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