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