ubus: add new RESTful API
[project/uhttpd.git] / ubus.c
1 /*
2 * uhttpd - Tiny single-threaded httpd
3 *
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20 #include <libubox/blobmsg.h>
21 #include <libubox/blobmsg_json.h>
22 #include <libubox/avl.h>
23 #include <libubox/avl-cmp.h>
24 #include <stdio.h>
25 #include <poll.h>
26
27 #include "uhttpd.h"
28 #include "plugin.h"
29
30 static const struct uhttpd_ops *ops;
31 static struct config *_conf;
32 #define conf (*_conf)
33
34 static struct ubus_context *ctx;
35 static struct blob_buf buf;
36
37 #define UH_UBUS_MAX_POST_SIZE 65536
38 #define UH_UBUS_DEFAULT_SID "00000000000000000000000000000000"
39
40 enum {
41 RPC_JSONRPC,
42 RPC_METHOD,
43 RPC_PARAMS,
44 RPC_ID,
45 __RPC_MAX,
46 };
47
48 static const struct blobmsg_policy rpc_policy[__RPC_MAX] = {
49 [RPC_JSONRPC] = { .name = "jsonrpc", .type = BLOBMSG_TYPE_STRING },
50 [RPC_METHOD] = { .name = "method", .type = BLOBMSG_TYPE_STRING },
51 [RPC_PARAMS] = { .name = "params", .type = BLOBMSG_TYPE_UNSPEC },
52 [RPC_ID] = { .name = "id", .type = BLOBMSG_TYPE_UNSPEC },
53 };
54
55 enum {
56 SES_ACCESS,
57 __SES_MAX,
58 };
59
60 static const struct blobmsg_policy ses_policy[__SES_MAX] = {
61 [SES_ACCESS] = { .name = "access", .type = BLOBMSG_TYPE_BOOL },
62 };
63
64 struct rpc_data {
65 struct blob_attr *id;
66 const char *sid;
67 const char *method;
68 const char *object;
69 const char *function;
70 struct blob_attr *data;
71 struct blob_attr *params;
72 };
73
74 struct list_data {
75 bool verbose;
76 bool add_object;
77 struct blob_buf *buf;
78 };
79
80 enum rpc_error {
81 ERROR_PARSE,
82 ERROR_REQUEST,
83 ERROR_METHOD,
84 ERROR_PARAMS,
85 ERROR_INTERNAL,
86 ERROR_OBJECT,
87 ERROR_SESSION,
88 ERROR_ACCESS,
89 ERROR_TIMEOUT,
90 __ERROR_MAX
91 };
92
93 static const struct {
94 int code;
95 const char *msg;
96 } json_errors[__ERROR_MAX] = {
97 [ERROR_PARSE] = { -32700, "Parse error" },
98 [ERROR_REQUEST] = { -32600, "Invalid request" },
99 [ERROR_METHOD] = { -32601, "Method not found" },
100 [ERROR_PARAMS] = { -32602, "Invalid parameters" },
101 [ERROR_INTERNAL] = { -32603, "Internal error" },
102 [ERROR_OBJECT] = { -32000, "Object not found" },
103 [ERROR_SESSION] = { -32001, "Session not found" },
104 [ERROR_ACCESS] = { -32002, "Access denied" },
105 [ERROR_TIMEOUT] = { -32003, "ubus request timed out" },
106 };
107
108 enum cors_hdr {
109 HDR_ORIGIN,
110 HDR_ACCESS_CONTROL_REQUEST_METHOD,
111 HDR_ACCESS_CONTROL_REQUEST_HEADERS,
112 __HDR_MAX
113 };
114
115 static void __uh_ubus_next_batched_request(struct uloop_timeout *timeout);
116
117 static void uh_ubus_next_batched_request(struct client *cl)
118 {
119 struct dispatch_ubus *du = &cl->dispatch.ubus;
120
121 du->timeout.cb = __uh_ubus_next_batched_request;
122 uloop_timeout_set(&du->timeout, 1);
123 }
124
125 static void uh_ubus_add_cors_headers(struct client *cl)
126 {
127 struct blob_attr *tb[__HDR_MAX];
128 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
129 [HDR_ORIGIN] = { "origin", BLOBMSG_TYPE_STRING },
130 [HDR_ACCESS_CONTROL_REQUEST_METHOD] = { "access-control-request-method", BLOBMSG_TYPE_STRING },
131 [HDR_ACCESS_CONTROL_REQUEST_HEADERS] = { "access-control-request-headers", BLOBMSG_TYPE_STRING },
132 };
133
134 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
135
136 if (!tb[HDR_ORIGIN])
137 return;
138
139 if (tb[HDR_ACCESS_CONTROL_REQUEST_METHOD])
140 {
141 char *hdr = (char *) blobmsg_data(tb[HDR_ACCESS_CONTROL_REQUEST_METHOD]);
142
143 if (strcmp(hdr, "POST") && strcmp(hdr, "OPTIONS"))
144 return;
145 }
146
147 ustream_printf(cl->us, "Access-Control-Allow-Origin: %s\r\n",
148 blobmsg_get_string(tb[HDR_ORIGIN]));
149
150 if (tb[HDR_ACCESS_CONTROL_REQUEST_HEADERS])
151 ustream_printf(cl->us, "Access-Control-Allow-Headers: %s\r\n",
152 blobmsg_get_string(tb[HDR_ACCESS_CONTROL_REQUEST_HEADERS]));
153
154 ustream_printf(cl->us, "Access-Control-Allow-Methods: POST, OPTIONS\r\n");
155 ustream_printf(cl->us, "Access-Control-Allow-Credentials: true\r\n");
156 }
157
158 static void uh_ubus_send_header(struct client *cl, int code, const char *summary, const char *content_type)
159 {
160 ops->http_header(cl, code, summary);
161
162 if (conf.ubus_cors)
163 uh_ubus_add_cors_headers(cl);
164
165 ustream_printf(cl->us, "Content-Type: %s\r\n", content_type);
166
167 if (cl->request.method == UH_HTTP_MSG_OPTIONS)
168 ustream_printf(cl->us, "Content-Length: 0\r\n");
169
170 ustream_printf(cl->us, "\r\n");
171 }
172
173 static void uh_ubus_send_response(struct client *cl, struct blob_buf *buf)
174 {
175 struct dispatch_ubus *du = &cl->dispatch.ubus;
176 const char *sep = "";
177 char *str;
178
179 if (du->array && du->array_idx > 1)
180 sep = ",";
181
182 str = blobmsg_format_json(buf->head, true);
183 ops->chunk_printf(cl, "%s%s", sep, str);
184 free(str);
185
186 du->jsobj_cur = NULL;
187 if (du->array)
188 uh_ubus_next_batched_request(cl);
189 else
190 return ops->request_done(cl);
191 }
192
193 static void uh_ubus_init_json_rpc_response(struct client *cl, struct blob_buf *buf)
194 {
195 struct dispatch_ubus *du = &cl->dispatch.ubus;
196 struct json_object *obj = du->jsobj_cur, *obj2 = NULL;
197
198 blobmsg_add_string(buf, "jsonrpc", "2.0");
199
200 if (obj)
201 json_object_object_get_ex(obj, "id", &obj2);
202
203 if (obj2)
204 blobmsg_add_json_element(buf, "id", obj2);
205 else
206 blobmsg_add_field(buf, BLOBMSG_TYPE_UNSPEC, "id", NULL, 0);
207 }
208
209 static void uh_ubus_json_rpc_error(struct client *cl, enum rpc_error type)
210 {
211 void *c;
212
213 blob_buf_init(&buf, 0);
214
215 uh_ubus_init_json_rpc_response(cl, &buf);
216 c = blobmsg_open_table(&buf, "error");
217 blobmsg_add_u32(&buf, "code", json_errors[type].code);
218 blobmsg_add_string(&buf, "message", json_errors[type].msg);
219 blobmsg_close_table(&buf, c);
220 uh_ubus_send_response(cl, &buf);
221 }
222
223 static void uh_ubus_error(struct client *cl, int code, const char *message)
224 {
225 blob_buf_init(&buf, 0);
226
227 blobmsg_add_u32(&buf, "code", code);
228 blobmsg_add_string(&buf, "message", message);
229 uh_ubus_send_response(cl, &buf);
230 }
231
232 static void uh_ubus_posix_error(struct client *cl, int err)
233 {
234 uh_ubus_error(cl, -err, strerror(err));
235 }
236
237 static void uh_ubus_ubus_error(struct client *cl, int err)
238 {
239 uh_ubus_error(cl, err, ubus_strerror(err));
240 }
241
242 /* GET requests handling */
243
244 static void uh_ubus_list_cb(struct ubus_context *ctx, struct ubus_object_data *obj, void *priv);
245
246 static void uh_ubus_handle_get_list(struct client *cl, const char *path)
247 {
248 static struct blob_buf tmp;
249 struct list_data data = { .verbose = true, .add_object = !path, .buf = &tmp};
250 struct blob_attr *cur;
251 int rem;
252 int err;
253
254 blob_buf_init(&tmp, 0);
255
256 err = ubus_lookup(ctx, path, uh_ubus_list_cb, &data);
257 if (err) {
258 uh_ubus_send_header(cl, 500, "Ubus Protocol Error", "application/json");
259 uh_ubus_ubus_error(cl, err);
260 return;
261 }
262
263 blob_buf_init(&buf, 0);
264 blob_for_each_attr(cur, tmp.head, rem)
265 blobmsg_add_blob(&buf, cur);
266
267 uh_ubus_send_header(cl, 200, "OK", "application/json");
268 uh_ubus_send_response(cl, &buf);
269 }
270
271 static int uh_ubus_subscription_notification_cb(struct ubus_context *ctx,
272 struct ubus_object *obj,
273 struct ubus_request_data *req,
274 const char *method,
275 struct blob_attr *msg)
276 {
277 struct ubus_subscriber *s;
278 struct dispatch_ubus *du;
279 struct client *cl;
280 char *json;
281
282 s = container_of(obj, struct ubus_subscriber, obj);
283 du = container_of(s, struct dispatch_ubus, sub);
284 cl = container_of(du, struct client, dispatch.ubus);
285
286 json = blobmsg_format_json(msg, true);
287 if (json) {
288 ops->chunk_printf(cl, "event: %s\ndata: %s\n\n", method, json);
289 free(json);
290 }
291
292 return 0;
293 }
294
295 static void uh_ubus_subscription_notification_remove_cb(struct ubus_context *ctx, struct ubus_subscriber *s, uint32_t id)
296 {
297 struct dispatch_ubus *du;
298 struct client *cl;
299
300 du = container_of(s, struct dispatch_ubus, sub);
301 cl = container_of(du, struct client, dispatch.ubus);
302
303 ops->request_done(cl);
304 }
305
306 static void uh_ubus_handle_get_subscribe(struct client *cl, const char *sid, const char *path)
307 {
308 struct dispatch_ubus *du = &cl->dispatch.ubus;
309 uint32_t id;
310 int err;
311
312 /* TODO: add ACL support */
313 if (!conf.ubus_noauth) {
314 uh_ubus_send_header(cl, 200, "OK", "application/json");
315 uh_ubus_posix_error(cl, EACCES);
316 return;
317 }
318
319 du->sub.cb = uh_ubus_subscription_notification_cb;
320 du->sub.remove_cb = uh_ubus_subscription_notification_remove_cb;
321
322 uh_client_ref(cl);
323
324 err = ubus_register_subscriber(ctx, &du->sub);
325 if (err)
326 goto err_unref;
327
328 err = ubus_lookup_id(ctx, path, &id);
329 if (err)
330 goto err_unregister;
331
332 err = ubus_subscribe(ctx, &du->sub, id);
333 if (err)
334 goto err_unregister;
335
336 uh_ubus_send_header(cl, 200, "OK", "text/event-stream");
337
338 if (conf.events_retry)
339 ops->chunk_printf(cl, "retry: %d\n", conf.events_retry);
340
341 return;
342
343 err_unregister:
344 ubus_unregister_subscriber(ctx, &du->sub);
345 err_unref:
346 uh_client_unref(cl);
347 if (err) {
348 uh_ubus_send_header(cl, 200, "OK", "application/json");
349 uh_ubus_ubus_error(cl, err);
350 }
351 }
352
353 static void uh_ubus_handle_get(struct client *cl)
354 {
355 struct dispatch_ubus *du = &cl->dispatch.ubus;
356 const char *url = du->url_path;
357
358 url += strlen(conf.ubus_prefix);
359
360 if (!strcmp(url, "/list") || !strncmp(url, "/list/", strlen("/list/"))) {
361 url += strlen("/list");
362
363 uh_ubus_handle_get_list(cl, *url ? url + 1 : NULL);
364 } else if (!strncmp(url, "/subscribe/", strlen("/subscribe/"))) {
365 url += strlen("/subscribe");
366
367 uh_ubus_handle_get_subscribe(cl, NULL, url + 1);
368 } else {
369 ops->http_header(cl, 404, "Not Found");
370 ustream_printf(cl->us, "\r\n");
371 ops->request_done(cl);
372 }
373 }
374
375 /* POST requests handling */
376
377 static void
378 uh_ubus_request_data_cb(struct ubus_request *req, int type, struct blob_attr *msg)
379 {
380 struct dispatch_ubus *du = container_of(req, struct dispatch_ubus, req);
381 struct blob_attr *cur;
382 int len;
383
384 blob_for_each_attr(cur, msg, len)
385 blobmsg_add_blob(&du->buf, cur);
386 }
387
388 static void
389 uh_ubus_request_cb(struct ubus_request *req, int ret)
390 {
391 struct dispatch_ubus *du = container_of(req, struct dispatch_ubus, req);
392 struct client *cl = container_of(du, struct client, dispatch.ubus);
393 struct blob_attr *cur;
394 void *r;
395 int rem;
396
397 blob_buf_init(&buf, 0);
398
399 uloop_timeout_cancel(&du->timeout);
400
401 /* Legacy format always uses "result" array - even for errors and empty
402 * results. */
403 if (du->legacy) {
404 void *c;
405
406 uh_ubus_init_json_rpc_response(cl, &buf);
407 r = blobmsg_open_array(&buf, "result");
408 blobmsg_add_u32(&buf, "", ret);
409 c = blobmsg_open_table(&buf, NULL);
410 blob_for_each_attr(cur, du->buf.head, rem)
411 blobmsg_add_blob(&buf, cur);
412 blobmsg_close_table(&buf, c);
413 blobmsg_close_array(&buf, r);
414 uh_ubus_send_response(cl, &buf);
415 return;
416 }
417
418 if (ret) {
419 void *c;
420
421 uh_ubus_init_json_rpc_response(cl, &buf);
422 c = blobmsg_open_table(&buf, "error");
423 blobmsg_add_u32(&buf, "code", ret);
424 blobmsg_add_string(&buf, "message", ubus_strerror(ret));
425 blobmsg_close_table(&buf, c);
426 uh_ubus_send_response(cl, &buf);
427 } else {
428 uh_ubus_init_json_rpc_response(cl, &buf);
429 if (blob_len(du->buf.head)) {
430 r = blobmsg_open_table(&buf, "result");
431 blob_for_each_attr(cur, du->buf.head, rem)
432 blobmsg_add_blob(&buf, cur);
433 blobmsg_close_table(&buf, r);
434 } else {
435 blobmsg_add_field(&buf, BLOBMSG_TYPE_UNSPEC, "result", NULL, 0);
436 }
437 uh_ubus_send_response(cl, &buf);
438 }
439
440 }
441
442 static void
443 uh_ubus_timeout_cb(struct uloop_timeout *timeout)
444 {
445 struct dispatch_ubus *du = container_of(timeout, struct dispatch_ubus, timeout);
446 struct client *cl = container_of(du, struct client, dispatch.ubus);
447
448 ubus_abort_request(ctx, &du->req);
449 uh_ubus_json_rpc_error(cl, ERROR_TIMEOUT);
450 }
451
452 static void uh_ubus_close_fds(struct client *cl)
453 {
454 if (ctx->sock.fd < 0)
455 return;
456
457 close(ctx->sock.fd);
458 ctx->sock.fd = -1;
459 }
460
461 static void uh_ubus_request_free(struct client *cl)
462 {
463 struct dispatch_ubus *du = &cl->dispatch.ubus;
464
465 blob_buf_free(&du->buf);
466 uloop_timeout_cancel(&du->timeout);
467
468 if (du->jsobj)
469 json_object_put(du->jsobj);
470
471 if (du->jstok)
472 json_tokener_free(du->jstok);
473
474 if (du->req_pending)
475 ubus_abort_request(ctx, &du->req);
476
477 free(du->url_path);
478 du->url_path = NULL;
479 }
480
481 static void uh_ubus_single_error(struct client *cl, enum rpc_error type)
482 {
483 uh_ubus_send_header(cl, 200, "OK", "application/json");
484 uh_ubus_json_rpc_error(cl, type);
485 ops->request_done(cl);
486 }
487
488 static void uh_ubus_send_request(struct client *cl, const char *sid, struct blob_attr *args)
489 {
490 struct dispatch *d = &cl->dispatch;
491 struct dispatch_ubus *du = &d->ubus;
492 struct blob_attr *cur;
493 static struct blob_buf req;
494 int ret, rem;
495
496 blob_buf_init(&req, 0);
497 blobmsg_for_each_attr(cur, args, rem) {
498 if (!strcmp(blobmsg_name(cur), "ubus_rpc_session"))
499 return uh_ubus_json_rpc_error(cl, ERROR_PARAMS);
500 blobmsg_add_blob(&req, cur);
501 }
502
503 blobmsg_add_string(&req, "ubus_rpc_session", sid);
504
505 blob_buf_init(&du->buf, 0);
506 memset(&du->req, 0, sizeof(du->req));
507 ret = ubus_invoke_async(ctx, du->obj, du->func, req.head, &du->req);
508 if (ret)
509 return uh_ubus_json_rpc_error(cl, ERROR_INTERNAL);
510
511 du->req.data_cb = uh_ubus_request_data_cb;
512 du->req.complete_cb = uh_ubus_request_cb;
513 ubus_complete_request_async(ctx, &du->req);
514
515 du->timeout.cb = uh_ubus_timeout_cb;
516 uloop_timeout_set(&du->timeout, conf.script_timeout * 1000);
517
518 du->req_pending = true;
519 }
520
521 static void uh_ubus_list_cb(struct ubus_context *ctx, struct ubus_object_data *obj, void *priv)
522 {
523 struct blob_attr *sig, *attr;
524 struct list_data *data = priv;
525 int rem, rem2;
526 void *t, *o;
527
528 if (!data->verbose) {
529 blobmsg_add_string(data->buf, NULL, obj->path);
530 return;
531 }
532
533 if (!obj->signature)
534 return;
535
536 if (data->add_object)
537 o = blobmsg_open_table(data->buf, obj->path);
538 blob_for_each_attr(sig, obj->signature, rem) {
539 t = blobmsg_open_table(data->buf, blobmsg_name(sig));
540 rem2 = blobmsg_data_len(sig);
541 __blob_for_each_attr(attr, blobmsg_data(sig), rem2) {
542 if (blob_id(attr) != BLOBMSG_TYPE_INT32)
543 continue;
544
545 switch (blobmsg_get_u32(attr)) {
546 case BLOBMSG_TYPE_INT8:
547 blobmsg_add_string(data->buf, blobmsg_name(attr), "boolean");
548 break;
549 case BLOBMSG_TYPE_INT32:
550 blobmsg_add_string(data->buf, blobmsg_name(attr), "number");
551 break;
552 case BLOBMSG_TYPE_STRING:
553 blobmsg_add_string(data->buf, blobmsg_name(attr), "string");
554 break;
555 case BLOBMSG_TYPE_ARRAY:
556 blobmsg_add_string(data->buf, blobmsg_name(attr), "array");
557 break;
558 case BLOBMSG_TYPE_TABLE:
559 blobmsg_add_string(data->buf, blobmsg_name(attr), "object");
560 break;
561 default:
562 blobmsg_add_string(data->buf, blobmsg_name(attr), "unknown");
563 break;
564 }
565 }
566 blobmsg_close_table(data->buf, t);
567 }
568 if (data->add_object)
569 blobmsg_close_table(data->buf, o);
570 }
571
572 static void uh_ubus_send_list(struct client *cl, struct blob_attr *params)
573 {
574 struct blob_attr *cur, *dup;
575 struct list_data data = { .buf = &cl->dispatch.ubus.buf, .verbose = false, .add_object = true };
576 void *r;
577 int rem;
578
579 blob_buf_init(data.buf, 0);
580
581 uh_client_ref(cl);
582
583 if (!params || blob_id(params) != BLOBMSG_TYPE_ARRAY) {
584 r = blobmsg_open_array(data.buf, "result");
585 ubus_lookup(ctx, NULL, uh_ubus_list_cb, &data);
586 blobmsg_close_array(data.buf, r);
587 }
588 else {
589 r = blobmsg_open_table(data.buf, "result");
590 dup = blob_memdup(params);
591 if (dup)
592 {
593 rem = blobmsg_data_len(dup);
594 data.verbose = true;
595 __blob_for_each_attr(cur, blobmsg_data(dup), rem)
596 ubus_lookup(ctx, blobmsg_data(cur), uh_ubus_list_cb, &data);
597 free(dup);
598 }
599 blobmsg_close_table(data.buf, r);
600 }
601
602 uh_client_unref(cl);
603
604 blob_buf_init(&buf, 0);
605 uh_ubus_init_json_rpc_response(cl, &buf);
606 blobmsg_add_blob(&buf, blob_data(data.buf->head));
607 uh_ubus_send_response(cl, &buf);
608 }
609
610 static bool parse_json_rpc(struct rpc_data *d, struct blob_attr *data)
611 {
612 struct blob_attr *tb[__RPC_MAX];
613 struct blob_attr *cur;
614
615 blobmsg_parse(rpc_policy, __RPC_MAX, tb, blob_data(data), blob_len(data));
616
617 cur = tb[RPC_JSONRPC];
618 if (!cur || strcmp(blobmsg_data(cur), "2.0") != 0)
619 return false;
620
621 cur = tb[RPC_METHOD];
622 if (!cur)
623 return false;
624
625 d->id = tb[RPC_ID];
626 d->method = blobmsg_data(cur);
627
628 cur = tb[RPC_PARAMS];
629 if (!cur)
630 return true;
631
632 d->params = blob_memdup(cur);
633 if (!d->params)
634 return false;
635
636 return true;
637 }
638
639 static void parse_call_params(struct rpc_data *d)
640 {
641 const struct blobmsg_policy data_policy[] = {
642 { .type = BLOBMSG_TYPE_STRING },
643 { .type = BLOBMSG_TYPE_STRING },
644 { .type = BLOBMSG_TYPE_STRING },
645 { .type = BLOBMSG_TYPE_TABLE },
646 };
647 struct blob_attr *tb[4];
648
649 if (!d->params || blobmsg_type(d->params) != BLOBMSG_TYPE_ARRAY)
650 return;
651
652 blobmsg_parse_array(data_policy, ARRAY_SIZE(data_policy), tb,
653 blobmsg_data(d->params), blobmsg_data_len(d->params));
654
655 if (tb[0])
656 d->sid = blobmsg_data(tb[0]);
657
658 if (conf.ubus_noauth && (!d->sid || !*d->sid))
659 d->sid = UH_UBUS_DEFAULT_SID;
660
661 if (tb[1])
662 d->object = blobmsg_data(tb[1]);
663
664 if (tb[2])
665 d->function = blobmsg_data(tb[2]);
666
667 d->data = tb[3];
668 }
669
670 static void uh_ubus_init_batch(struct client *cl)
671 {
672 struct dispatch_ubus *du = &cl->dispatch.ubus;
673
674 du->array = true;
675 uh_ubus_send_header(cl, 200, "OK", "application/json");
676 ops->chunk_printf(cl, "[");
677 }
678
679 static void uh_ubus_complete_batch(struct client *cl)
680 {
681 ops->chunk_printf(cl, "]");
682 ops->request_done(cl);
683 }
684
685 static void uh_ubus_allowed_cb(struct ubus_request *req, int type, struct blob_attr *msg)
686 {
687 struct blob_attr *tb[__SES_MAX];
688 bool *allow = (bool *)req->priv;
689
690 if (!msg)
691 return;
692
693 blobmsg_parse(ses_policy, __SES_MAX, tb, blob_data(msg), blob_len(msg));
694
695 if (tb[SES_ACCESS])
696 *allow = blobmsg_get_bool(tb[SES_ACCESS]);
697 }
698
699 static bool uh_ubus_allowed(const char *sid, const char *obj, const char *fun)
700 {
701 uint32_t id;
702 bool allow = false;
703 static struct blob_buf req;
704
705 if (ubus_lookup_id(ctx, "session", &id))
706 return false;
707
708 blob_buf_init(&req, 0);
709 blobmsg_add_string(&req, "ubus_rpc_session", sid);
710 blobmsg_add_string(&req, "object", obj);
711 blobmsg_add_string(&req, "function", fun);
712
713 ubus_invoke(ctx, id, "access", req.head, uh_ubus_allowed_cb, &allow, conf.script_timeout * 500);
714
715 return allow;
716 }
717
718 static void uh_ubus_handle_request_object(struct client *cl, struct json_object *obj)
719 {
720 struct dispatch_ubus *du = &cl->dispatch.ubus;
721 struct rpc_data data = {};
722 enum rpc_error err = ERROR_PARSE;
723 static struct blob_buf req;
724
725 uh_client_ref(cl);
726
727 if (json_object_get_type(obj) != json_type_object)
728 goto error;
729
730 du->jsobj_cur = obj;
731 blob_buf_init(&req, 0);
732 if (!blobmsg_add_object(&req, obj))
733 goto error;
734
735 if (!parse_json_rpc(&data, req.head))
736 goto error;
737
738 if (!strcmp(data.method, "call")) {
739 parse_call_params(&data);
740
741 if (!data.sid || !data.object || !data.function || !data.data)
742 goto error;
743
744 du->func = data.function;
745 if (ubus_lookup_id(ctx, data.object, &du->obj)) {
746 err = ERROR_OBJECT;
747 goto error;
748 }
749
750 if (!conf.ubus_noauth && !uh_ubus_allowed(data.sid, data.object, data.function)) {
751 err = ERROR_ACCESS;
752 goto error;
753 }
754
755 uh_ubus_send_request(cl, data.sid, data.data);
756 goto out;
757 }
758 else if (!strcmp(data.method, "list")) {
759 uh_ubus_send_list(cl, data.params);
760 goto out;
761 }
762 else {
763 err = ERROR_METHOD;
764 goto error;
765 }
766
767 error:
768 uh_ubus_json_rpc_error(cl, err);
769 out:
770 if (data.params)
771 free(data.params);
772
773 uh_client_unref(cl);
774 }
775
776 static void __uh_ubus_next_batched_request(struct uloop_timeout *timeout)
777 {
778 struct dispatch_ubus *du = container_of(timeout, struct dispatch_ubus, timeout);
779 struct client *cl = container_of(du, struct client, dispatch.ubus);
780 struct json_object *obj = du->jsobj;
781 int len;
782
783 len = json_object_array_length(obj);
784 if (du->array_idx >= len)
785 return uh_ubus_complete_batch(cl);
786
787 obj = json_object_array_get_idx(obj, du->array_idx++);
788 uh_ubus_handle_request_object(cl, obj);
789 }
790
791 static void uh_ubus_data_done(struct client *cl)
792 {
793 struct dispatch_ubus *du = &cl->dispatch.ubus;
794 struct json_object *obj = du->jsobj;
795
796 switch (obj ? json_object_get_type(obj) : json_type_null) {
797 case json_type_object:
798 uh_ubus_send_header(cl, 200, "OK", "application/json");
799 return uh_ubus_handle_request_object(cl, obj);
800 case json_type_array:
801 uh_ubus_init_batch(cl);
802 return uh_ubus_next_batched_request(cl);
803 default:
804 return uh_ubus_single_error(cl, ERROR_PARSE);
805 }
806 }
807
808 static void uh_ubus_call(struct client *cl, const char *path, const char *sid)
809 {
810 struct dispatch_ubus *du = &cl->dispatch.ubus;
811 struct json_object *obj = du->jsobj;
812 struct rpc_data data = {};
813 enum rpc_error err = ERROR_PARSE;
814 static struct blob_buf req;
815
816 uh_client_ref(cl);
817
818 if (!obj || json_object_get_type(obj) != json_type_object)
819 goto error;
820
821 uh_ubus_send_header(cl, 200, "OK", "application/json");
822
823 du->jsobj_cur = obj;
824 blob_buf_init(&req, 0);
825 if (!blobmsg_add_object(&req, obj))
826 goto error;
827
828 if (!parse_json_rpc(&data, req.head))
829 goto error;
830
831 du->func = data.method;
832 if (ubus_lookup_id(ctx, path, &du->obj)) {
833 err = ERROR_OBJECT;
834 goto error;
835 }
836
837 if (!conf.ubus_noauth && !uh_ubus_allowed(sid, path, data.method)) {
838 err = ERROR_ACCESS;
839 goto error;
840 }
841
842 uh_ubus_send_request(cl, sid, data.params);
843 goto out;
844
845 error:
846 uh_ubus_json_rpc_error(cl, err);
847 out:
848 if (data.params)
849 free(data.params);
850
851 uh_client_unref(cl);
852 }
853
854 enum ubus_hdr {
855 HDR_AUTHORIZATION,
856 __HDR_UBUS_MAX
857 };
858
859 static void uh_ubus_handle_post(struct client *cl)
860 {
861 static const struct blobmsg_policy hdr_policy[__HDR_UBUS_MAX] = {
862 [HDR_AUTHORIZATION] = { "authorization", BLOBMSG_TYPE_STRING },
863 };
864 struct dispatch_ubus *du = &cl->dispatch.ubus;
865 struct blob_attr *tb[__HDR_UBUS_MAX];
866 const char *url = du->url_path;
867 const char *auth;
868
869 /* Treat both: /foo AND /foo/ as legacy requests. */
870 if (ops->path_match(conf.ubus_prefix, url) && strlen(url) - strlen(conf.ubus_prefix) <= 1) {
871 du->legacy = true;
872 uh_ubus_data_done(cl);
873 return;
874 }
875
876 blobmsg_parse(hdr_policy, __HDR_UBUS_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
877
878 auth = UH_UBUS_DEFAULT_SID;
879 if (tb[HDR_AUTHORIZATION]) {
880 const char *tmp = blobmsg_get_string(tb[HDR_AUTHORIZATION]);
881
882 if (!strncasecmp(tmp, "Bearer ", 7))
883 auth = tmp + 7;
884 }
885
886 url += strlen(conf.ubus_prefix);
887
888 if (!strncmp(url, "/call/", strlen("/call/"))) {
889 url += strlen("/call/");
890
891 uh_ubus_call(cl, url, auth);
892 } else {
893 ops->http_header(cl, 404, "Not Found");
894 ustream_printf(cl->us, "\r\n");
895 ops->request_done(cl);
896 }
897 }
898
899 static int uh_ubus_data_send(struct client *cl, const char *data, int len)
900 {
901 struct dispatch_ubus *du = &cl->dispatch.ubus;
902
903 if (du->jsobj || !du->jstok)
904 goto error;
905
906 du->post_len += len;
907 if (du->post_len > UH_UBUS_MAX_POST_SIZE)
908 goto error;
909
910 du->jsobj = json_tokener_parse_ex(du->jstok, data, len);
911 return len;
912
913 error:
914 uh_ubus_single_error(cl, ERROR_PARSE);
915 return 0;
916 }
917
918 static void uh_ubus_handle_request(struct client *cl, char *url, struct path_info *pi)
919 {
920 struct dispatch *d = &cl->dispatch;
921 struct dispatch_ubus *du = &d->ubus;
922 char *chr;
923
924 du->url_path = strdup(url);
925 if (!du->url_path) {
926 ops->client_error(cl, 500, "Internal Server Error", "Failed to allocate resources");
927 return;
928 }
929 chr = strchr(du->url_path, '?');
930 if (chr)
931 chr[0] = '\0';
932
933 du->legacy = false;
934
935 switch (cl->request.method)
936 {
937 case UH_HTTP_MSG_GET:
938 uh_ubus_handle_get(cl);
939 break;
940 case UH_HTTP_MSG_POST:
941 d->data_send = uh_ubus_data_send;
942 d->data_done = uh_ubus_handle_post;
943 d->close_fds = uh_ubus_close_fds;
944 d->free = uh_ubus_request_free;
945 du->jstok = json_tokener_new();
946 return;
947
948 case UH_HTTP_MSG_OPTIONS:
949 uh_ubus_send_header(cl, 200, "OK", "application/json");
950 ops->request_done(cl);
951 break;
952
953 default:
954 ops->client_error(cl, 400, "Bad Request", "Invalid Request");
955 }
956
957 free(du->url_path);
958 du->url_path = NULL;
959 }
960
961 static bool
962 uh_ubus_check_url(const char *url)
963 {
964 return ops->path_match(conf.ubus_prefix, url);
965 }
966
967 static int
968 uh_ubus_init(void)
969 {
970 static struct dispatch_handler ubus_dispatch = {
971 .check_url = uh_ubus_check_url,
972 .handle_request = uh_ubus_handle_request,
973 };
974
975 ctx = ubus_connect(conf.ubus_socket);
976 if (!ctx) {
977 fprintf(stderr, "Unable to connect to ubus socket\n");
978 exit(1);
979 }
980
981 ops->dispatch_add(&ubus_dispatch);
982
983 uloop_done();
984 return 0;
985 }
986
987
988 static int uh_ubus_plugin_init(const struct uhttpd_ops *o, struct config *c)
989 {
990 ops = o;
991 _conf = c;
992 return uh_ubus_init();
993 }
994
995 static void uh_ubus_post_init(void)
996 {
997 ubus_add_uloop(ctx);
998 }
999
1000 struct uhttpd_plugin uhttpd_plugin = {
1001 .init = uh_ubus_plugin_init,
1002 .post_init = uh_ubus_post_init,
1003 };