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