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