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