39dca359028c453191def2323967b922663f7319
[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 4096
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_ARRAY },
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 struct blob_buf *buf;
77 };
78
79 enum rpc_error {
80 ERROR_PARSE,
81 ERROR_REQUEST,
82 ERROR_METHOD,
83 ERROR_PARAMS,
84 ERROR_INTERNAL,
85 ERROR_OBJECT,
86 ERROR_SESSION,
87 ERROR_ACCESS,
88 ERROR_TIMEOUT,
89 __ERROR_MAX
90 };
91
92 static const struct {
93 int code;
94 const char *msg;
95 } json_errors[__ERROR_MAX] = {
96 [ERROR_PARSE] = { -32700, "Parse error" },
97 [ERROR_REQUEST] = { -32600, "Invalid request" },
98 [ERROR_METHOD] = { -32601, "Method not found" },
99 [ERROR_PARAMS] = { -32602, "Invalid parameters" },
100 [ERROR_INTERNAL] = { -32603, "Internal error" },
101 [ERROR_OBJECT] = { -32000, "Object not found" },
102 [ERROR_SESSION] = { -32001, "Session not found" },
103 [ERROR_ACCESS] = { -32002, "Access denied" },
104 [ERROR_TIMEOUT] = { -32003, "ubus request timed out" },
105 };
106
107 static void __uh_ubus_next_batched_request(struct uloop_timeout *timeout);
108
109 static void uh_ubus_next_batched_request(struct client *cl)
110 {
111 struct dispatch_ubus *du = &cl->dispatch.ubus;
112
113 du->timeout.cb = __uh_ubus_next_batched_request;
114 uloop_timeout_set(&du->timeout, 1);
115 }
116
117 static void uh_ubus_send_header(struct client *cl)
118 {
119 ops->http_header(cl, 200, "OK");
120 ustream_printf(cl->us, "Content-Type: application/json\r\n\r\n");
121 }
122
123 static void uh_ubus_send_response(struct client *cl)
124 {
125 struct dispatch_ubus *du = &cl->dispatch.ubus;
126 const char *sep = "";
127 char *str;
128
129 if (du->array && du->array_idx > 1)
130 sep = ",";
131
132 str = blobmsg_format_json(buf.head, true);
133 ops->chunk_printf(cl, "%s%s", sep, str);
134 free(str);
135
136 du->jsobj_cur = NULL;
137 if (du->array)
138 uh_ubus_next_batched_request(cl);
139 else
140 return ops->request_done(cl);
141 }
142
143 static void uh_ubus_init_response(struct client *cl)
144 {
145 struct dispatch_ubus *du = &cl->dispatch.ubus;
146 struct json_object *obj = du->jsobj_cur;
147
148 blob_buf_init(&buf, 0);
149 blobmsg_add_string(&buf, "jsonrpc", "2.0");
150
151 if (obj)
152 obj = json_object_object_get(obj, "id");
153
154 if (obj)
155 blobmsg_add_json_element(&buf, "id", obj);
156 else
157 blobmsg_add_field(&buf, BLOBMSG_TYPE_UNSPEC, "id", NULL, 0);
158 }
159
160 static void uh_ubus_json_error(struct client *cl, enum rpc_error type)
161 {
162 void *c;
163
164 uh_ubus_init_response(cl);
165 c = blobmsg_open_table(&buf, "error");
166 blobmsg_add_u32(&buf, "code", json_errors[type].code);
167 blobmsg_add_string(&buf, "message", json_errors[type].msg);
168 blobmsg_close_table(&buf, c);
169 uh_ubus_send_response(cl);
170 }
171
172 static void
173 uh_ubus_request_data_cb(struct ubus_request *req, int type, struct blob_attr *msg)
174 {
175 struct dispatch_ubus *du = container_of(req, struct dispatch_ubus, req);
176
177 blobmsg_add_field(&du->buf, BLOBMSG_TYPE_TABLE, "", blob_data(msg), blob_len(msg));
178 }
179
180 static void
181 uh_ubus_request_cb(struct ubus_request *req, int ret)
182 {
183 struct dispatch_ubus *du = container_of(req, struct dispatch_ubus, req);
184 struct client *cl = container_of(du, struct client, dispatch.ubus);
185 struct blob_attr *cur;
186 void *r;
187 int rem;
188
189 uloop_timeout_cancel(&du->timeout);
190 uh_ubus_init_response(cl);
191 r = blobmsg_open_array(&buf, "result");
192 blobmsg_add_u32(&buf, "", ret);
193 blob_for_each_attr(cur, du->buf.head, rem)
194 blobmsg_add_blob(&buf, cur);
195 blobmsg_close_array(&buf, r);
196 uh_ubus_send_response(cl);
197 }
198
199 static void
200 uh_ubus_timeout_cb(struct uloop_timeout *timeout)
201 {
202 struct dispatch_ubus *du = container_of(timeout, struct dispatch_ubus, timeout);
203 struct client *cl = container_of(du, struct client, dispatch.ubus);
204
205 ubus_abort_request(ctx, &du->req);
206 uh_ubus_json_error(cl, ERROR_TIMEOUT);
207 }
208
209 static void uh_ubus_close_fds(struct client *cl)
210 {
211 if (ctx->sock.fd < 0)
212 return;
213
214 close(ctx->sock.fd);
215 ctx->sock.fd = -1;
216 }
217
218 static void uh_ubus_request_free(struct client *cl)
219 {
220 struct dispatch_ubus *du = &cl->dispatch.ubus;
221
222 blob_buf_free(&du->buf);
223 uloop_timeout_cancel(&du->timeout);
224
225 if (du->jsobj)
226 json_object_put(du->jsobj);
227
228 if (du->jstok)
229 json_tokener_free(du->jstok);
230
231 if (du->req_pending)
232 ubus_abort_request(ctx, &du->req);
233 }
234
235 static void uh_ubus_single_error(struct client *cl, enum rpc_error type)
236 {
237 uh_ubus_send_header(cl);
238 uh_ubus_json_error(cl, type);
239 ops->request_done(cl);
240 }
241
242 static void uh_ubus_send_request(struct client *cl, json_object *obj, const char *sid, struct blob_attr *args)
243 {
244 struct dispatch *d = &cl->dispatch;
245 struct dispatch_ubus *du = &d->ubus;
246 struct blob_attr *cur;
247 static struct blob_buf req;
248 int ret, rem;
249
250 blob_buf_init(&req, 0);
251 blobmsg_for_each_attr(cur, args, rem) {
252 if (!strcmp(blobmsg_name(cur), "ubus_rpc_session"))
253 return uh_ubus_json_error(cl, ERROR_PARAMS);
254 blobmsg_add_blob(&req, cur);
255 }
256
257 blobmsg_add_string(&req, "ubus_rpc_session", sid);
258
259 blob_buf_init(&du->buf, 0);
260 memset(&du->req, 0, sizeof(du->req));
261 ret = ubus_invoke_async(ctx, du->obj, du->func, req.head, &du->req);
262 if (ret)
263 return uh_ubus_json_error(cl, ERROR_INTERNAL);
264
265 du->req.data_cb = uh_ubus_request_data_cb;
266 du->req.complete_cb = uh_ubus_request_cb;
267 ubus_complete_request_async(ctx, &du->req);
268
269 du->timeout.cb = uh_ubus_timeout_cb;
270 uloop_timeout_set(&du->timeout, conf.script_timeout * 1000);
271
272 du->req_pending = true;
273 }
274
275 static void uh_ubus_list_cb(struct ubus_context *ctx, struct ubus_object_data *obj, void *priv)
276 {
277 struct blob_attr *sig, *attr;
278 struct list_data *data = priv;
279 int rem, rem2;
280 void *t, *o;
281
282 if (!data->verbose) {
283 blobmsg_add_string(data->buf, NULL, obj->path);
284 return;
285 }
286
287 if (!obj->signature)
288 return;
289
290 o = blobmsg_open_table(data->buf, obj->path);
291 blob_for_each_attr(sig, obj->signature, rem) {
292 t = blobmsg_open_table(data->buf, blobmsg_name(sig));
293 rem2 = blobmsg_data_len(sig);
294 __blob_for_each_attr(attr, blobmsg_data(sig), rem2) {
295 if (blob_id(attr) != BLOBMSG_TYPE_INT32)
296 continue;
297
298 switch (blobmsg_get_u32(attr)) {
299 case BLOBMSG_TYPE_INT8:
300 blobmsg_add_string(data->buf, blobmsg_name(attr), "boolean");
301 break;
302 case BLOBMSG_TYPE_INT32:
303 blobmsg_add_string(data->buf, blobmsg_name(attr), "number");
304 break;
305 case BLOBMSG_TYPE_STRING:
306 blobmsg_add_string(data->buf, blobmsg_name(attr), "string");
307 break;
308 case BLOBMSG_TYPE_ARRAY:
309 blobmsg_add_string(data->buf, blobmsg_name(attr), "array");
310 break;
311 case BLOBMSG_TYPE_TABLE:
312 blobmsg_add_string(data->buf, blobmsg_name(attr), "object");
313 break;
314 default:
315 blobmsg_add_string(data->buf, blobmsg_name(attr), "unknown");
316 break;
317 }
318 }
319 blobmsg_close_table(data->buf, t);
320 }
321 blobmsg_close_table(data->buf, o);
322 }
323
324 static void uh_ubus_send_list(struct client *cl, json_object *obj, struct blob_attr *params)
325 {
326 struct blob_attr *cur, *dup;
327 struct list_data data = { .buf = &cl->dispatch.ubus.buf, .verbose = false };
328 void *r;
329 int rem;
330
331 blob_buf_init(data.buf, 0);
332
333 uh_client_ref(cl);
334
335 if (!params || blob_id(params) != BLOBMSG_TYPE_ARRAY) {
336 r = blobmsg_open_array(data.buf, "result");
337 ubus_lookup(ctx, NULL, uh_ubus_list_cb, &data);
338 blobmsg_close_array(data.buf, r);
339 }
340 else {
341 r = blobmsg_open_table(data.buf, "result");
342 dup = blob_memdup(params);
343 if (dup)
344 {
345 rem = blobmsg_data_len(dup);
346 data.verbose = true;
347 __blob_for_each_attr(cur, blobmsg_data(dup), rem)
348 ubus_lookup(ctx, blobmsg_data(cur), uh_ubus_list_cb, &data);
349 free(dup);
350 }
351 blobmsg_close_table(data.buf, r);
352 }
353
354 uh_client_unref(cl);
355
356 uh_ubus_init_response(cl);
357 blobmsg_add_blob(&buf, blob_data(data.buf->head));
358 uh_ubus_send_response(cl);
359 }
360
361 static bool parse_json_rpc(struct rpc_data *d, struct blob_attr *data)
362 {
363 const struct blobmsg_policy data_policy[] = {
364 { .type = BLOBMSG_TYPE_STRING },
365 { .type = BLOBMSG_TYPE_STRING },
366 { .type = BLOBMSG_TYPE_STRING },
367 { .type = BLOBMSG_TYPE_TABLE },
368 };
369 struct blob_attr *tb[__RPC_MAX];
370 struct blob_attr *tb2[4];
371 struct blob_attr *cur;
372
373 blobmsg_parse(rpc_policy, __RPC_MAX, tb, blob_data(data), blob_len(data));
374
375 cur = tb[RPC_JSONRPC];
376 if (!cur || strcmp(blobmsg_data(cur), "2.0") != 0)
377 return false;
378
379 cur = tb[RPC_METHOD];
380 if (!cur)
381 return false;
382
383 d->id = tb[RPC_ID];
384 d->method = blobmsg_data(cur);
385
386 cur = tb[RPC_PARAMS];
387 if (!cur)
388 return true;
389
390 d->params = blob_memdup(cur);
391 if (!d->params)
392 return false;
393
394 blobmsg_parse_array(data_policy, ARRAY_SIZE(data_policy), tb2,
395 blobmsg_data(d->params), blobmsg_data_len(d->params));
396
397 if (tb2[0])
398 d->sid = blobmsg_data(tb2[0]);
399
400 if (conf.ubus_noauth && (!d->sid || !*d->sid))
401 d->sid = UH_UBUS_DEFAULT_SID;
402
403 if (tb2[1])
404 d->object = blobmsg_data(tb2[1]);
405
406 if (tb2[2])
407 d->function = blobmsg_data(tb2[2]);
408
409 d->data = tb2[3];
410
411 return true;
412 }
413
414 static void uh_ubus_init_batch(struct client *cl)
415 {
416 struct dispatch_ubus *du = &cl->dispatch.ubus;
417
418 du->array = true;
419 uh_ubus_send_header(cl);
420 ops->chunk_printf(cl, "[");
421 }
422
423 static void uh_ubus_complete_batch(struct client *cl)
424 {
425 ops->chunk_printf(cl, "]");
426 ops->request_done(cl);
427 }
428
429 static void uh_ubus_allowed_cb(struct ubus_request *req, int type, struct blob_attr *msg)
430 {
431 struct blob_attr *tb[__SES_MAX];
432 bool *allow = (bool *)req->priv;
433
434 if (!msg)
435 return;
436
437 blobmsg_parse(ses_policy, __SES_MAX, tb, blob_data(msg), blob_len(msg));
438
439 if (tb[SES_ACCESS])
440 *allow = blobmsg_get_bool(tb[SES_ACCESS]);
441 }
442
443 static bool uh_ubus_allowed(const char *sid, const char *obj, const char *fun)
444 {
445 uint32_t id;
446 bool allow = false;
447 static struct blob_buf req;
448
449 if (ubus_lookup_id(ctx, "session", &id))
450 return false;
451
452 blob_buf_init(&req, 0);
453 blobmsg_add_string(&req, "ubus_rpc_session", sid);
454 blobmsg_add_string(&req, "object", obj);
455 blobmsg_add_string(&req, "function", fun);
456
457 ubus_invoke(ctx, id, "access", req.head, uh_ubus_allowed_cb, &allow, conf.script_timeout * 500);
458
459 return allow;
460 }
461
462 static void uh_ubus_handle_request_object(struct client *cl, struct json_object *obj)
463 {
464 struct dispatch_ubus *du = &cl->dispatch.ubus;
465 struct rpc_data data = {};
466 enum rpc_error err = ERROR_PARSE;
467
468 uh_client_ref(cl);
469
470 if (json_object_get_type(obj) != json_type_object)
471 goto error;
472
473 du->jsobj_cur = obj;
474 blob_buf_init(&buf, 0);
475 if (!blobmsg_add_object(&buf, obj))
476 goto error;
477
478 if (!parse_json_rpc(&data, buf.head))
479 goto error;
480
481 if (!strcmp(data.method, "call")) {
482 if (!data.sid || !data.object || !data.function || !data.data)
483 goto error;
484
485 du->func = data.function;
486 if (ubus_lookup_id(ctx, data.object, &du->obj)) {
487 err = ERROR_OBJECT;
488 goto error;
489 }
490
491 if (!conf.ubus_noauth && !uh_ubus_allowed(data.sid, data.object, data.function)) {
492 err = ERROR_ACCESS;
493 goto error;
494 }
495
496 uh_ubus_send_request(cl, obj, data.sid, data.data);
497 goto out;
498 }
499 else if (!strcmp(data.method, "list")) {
500 uh_ubus_send_list(cl, obj, data.params);
501 goto out;
502 }
503 else {
504 err = ERROR_METHOD;
505 goto error;
506 }
507
508 error:
509 uh_ubus_json_error(cl, err);
510 out:
511 if (data.params)
512 free(data.params);
513
514 uh_client_unref(cl);
515 }
516
517 static void __uh_ubus_next_batched_request(struct uloop_timeout *timeout)
518 {
519 struct dispatch_ubus *du = container_of(timeout, struct dispatch_ubus, timeout);
520 struct client *cl = container_of(du, struct client, dispatch.ubus);
521 struct json_object *obj = du->jsobj;
522 int len;
523
524 len = json_object_array_length(obj);
525 if (du->array_idx >= len)
526 return uh_ubus_complete_batch(cl);
527
528 obj = json_object_array_get_idx(obj, du->array_idx++);
529 uh_ubus_handle_request_object(cl, obj);
530 }
531
532 static void uh_ubus_data_done(struct client *cl)
533 {
534 struct dispatch_ubus *du = &cl->dispatch.ubus;
535 struct json_object *obj = du->jsobj;
536
537 switch (obj ? json_object_get_type(obj) : json_type_null) {
538 case json_type_object:
539 uh_ubus_send_header(cl);
540 return uh_ubus_handle_request_object(cl, obj);
541 case json_type_array:
542 uh_ubus_init_batch(cl);
543 return uh_ubus_next_batched_request(cl);
544 default:
545 return uh_ubus_single_error(cl, ERROR_PARSE);
546 }
547 }
548
549 static int uh_ubus_data_send(struct client *cl, const char *data, int len)
550 {
551 struct dispatch_ubus *du = &cl->dispatch.ubus;
552
553 if (du->jsobj || !du->jstok)
554 goto error;
555
556 du->post_len += len;
557 if (du->post_len > UH_UBUS_MAX_POST_SIZE)
558 goto error;
559
560 du->jsobj = json_tokener_parse_ex(du->jstok, data, len);
561 return len;
562
563 error:
564 uh_ubus_single_error(cl, ERROR_PARSE);
565 return 0;
566 }
567
568 static void uh_ubus_handle_request(struct client *cl, char *url, struct path_info *pi)
569 {
570 struct dispatch *d = &cl->dispatch;
571
572 blob_buf_init(&buf, 0);
573
574 if (cl->request.method != UH_HTTP_MSG_POST)
575 return ops->client_error(cl, 400, "Bad Request", "Invalid Request");
576
577 d->close_fds = uh_ubus_close_fds;
578 d->free = uh_ubus_request_free;
579 d->data_send = uh_ubus_data_send;
580 d->data_done = uh_ubus_data_done;
581 d->ubus.jstok = json_tokener_new();
582 }
583
584 static bool
585 uh_ubus_check_url(const char *url)
586 {
587 return ops->path_match(conf.ubus_prefix, url);
588 }
589
590 static int
591 uh_ubus_init(void)
592 {
593 static struct dispatch_handler ubus_dispatch = {
594 .check_url = uh_ubus_check_url,
595 .handle_request = uh_ubus_handle_request,
596 };
597
598 ctx = ubus_connect(conf.ubus_socket);
599 if (!ctx) {
600 fprintf(stderr, "Unable to connect to ubus socket\n");
601 exit(1);
602 }
603
604 ops->dispatch_add(&ubus_dispatch);
605
606 uloop_done();
607 return 0;
608 }
609
610
611 static int uh_ubus_plugin_init(const struct uhttpd_ops *o, struct config *c)
612 {
613 ops = o;
614 _conf = c;
615 return uh_ubus_init();
616 }
617
618 static void uh_ubus_post_init(void)
619 {
620 ubus_add_uloop(ctx);
621 }
622
623 const struct uhttpd_plugin uhttpd_plugin = {
624 .init = uh_ubus_plugin_init,
625 .post_init = uh_ubus_post_init,
626 };