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