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