move example to examples/
[project/ubus.git] / libubus.c
1 /*
2  * Copyright (C) 2011 Felix Fietkau <nbd@openwrt.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License version 2.1
6  * as published by the Free Software Foundation
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  */
13
14 #include <sys/types.h>
15 #include <sys/uio.h>
16 #include <sys/socket.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <poll.h>
20
21 #include <libubox/blob.h>
22 #include <libubox/blobmsg.h>
23 #include <libubox/usock.h>
24
25 #include "libubus.h"
26 #include "ubusmsg.h"
27
28 #define STATIC_IOV(_var) { .iov_base = (char *) &(_var), .iov_len = sizeof(_var) }
29
30 const char *__ubus_strerror[__UBUS_STATUS_LAST] = {
31         [UBUS_STATUS_OK] = "Success",
32         [UBUS_STATUS_INVALID_COMMAND] = "Invalid command",
33         [UBUS_STATUS_INVALID_ARGUMENT] = "Invalid argument",
34         [UBUS_STATUS_METHOD_NOT_FOUND] = "Method not found",
35         [UBUS_STATUS_NOT_FOUND] = "Not found",
36         [UBUS_STATUS_NO_DATA] = "No response",
37         [UBUS_STATUS_PERMISSION_DENIED] = "Permission denied",
38         [UBUS_STATUS_TIMEOUT] = "Request timed out",
39         [UBUS_STATUS_NOT_SUPPORTED] = "Operation not supported",
40         [UBUS_STATUS_UNKNOWN_ERROR] = "Unknown error",
41         [UBUS_STATUS_CONNECTION_FAILED] = "Connection failed",
42 };
43
44 static struct blob_buf b;
45
46 static const struct blob_attr_info ubus_policy[UBUS_ATTR_MAX] = {
47         [UBUS_ATTR_STATUS] = { .type = BLOB_ATTR_INT32 },
48         [UBUS_ATTR_OBJID] = { .type = BLOB_ATTR_INT32 },
49         [UBUS_ATTR_OBJPATH] = { .type = BLOB_ATTR_STRING },
50         [UBUS_ATTR_METHOD] = { .type = BLOB_ATTR_STRING },
51 };
52 static struct blob_attr *attrbuf[UBUS_ATTR_MAX];
53
54 struct ubus_pending_data {
55         struct list_head list;
56         int type;
57         struct blob_attr data[];
58 };
59
60 struct ubus_pending_invoke {
61         struct list_head list;
62         struct ubus_msghdr hdr;
63 };
64
65 static void ubus_process_pending_invoke(struct ubus_context *ctx);
66
67 static int ubus_cmp_id(const void *k1, const void *k2, void *ptr)
68 {
69         const uint32_t *id1 = k1, *id2 = k2;
70
71         if (*id1 < *id2)
72                 return -1;
73         else
74                 return *id1 > *id2;
75 }
76
77 static struct blob_attr **ubus_parse_msg(struct blob_attr *msg)
78 {
79         blob_parse(msg, attrbuf, ubus_policy, UBUS_ATTR_MAX);
80         return attrbuf;
81 }
82
83 const char *ubus_strerror(int error)
84 {
85         static char err[32];
86
87         if (error < 0 || error >= __UBUS_STATUS_LAST)
88                 goto out;
89
90         if (!__ubus_strerror[error])
91                 goto out;
92
93         return __ubus_strerror[error];
94
95 out:
96         sprintf(err, "Unknown error: %d", error);
97         return err;
98 }
99
100 static void wait_data(int fd, bool write)
101 {
102         struct pollfd pfd = { .fd = fd };
103
104         pfd.events = write ? POLLOUT : POLLIN;
105         poll(&pfd, 1, 0);
106 }
107
108 static int writev_retry(int fd, struct iovec *iov, int iov_len)
109 {
110         int len = 0;
111
112         do {
113                 int cur_len = writev(fd, iov, iov_len);
114                 if (cur_len < 0) {
115                         switch(errno) {
116                         case EAGAIN:
117                                 wait_data(fd, true);
118                                 break;
119                         case EINTR:
120                                 break;
121                         default:
122                                 return -1;
123                         }
124                         continue;
125                 }
126                 len += cur_len;
127                 while (cur_len >= iov->iov_len) {
128                         cur_len -= iov->iov_len;
129                         iov_len--;
130                         iov++;
131                         if (!cur_len || !iov_len)
132                                 return len;
133                 }
134                 iov->iov_len -= cur_len;
135         } while (1);
136 }
137
138 static int ubus_send_msg(struct ubus_context *ctx, uint32_t seq,
139                          struct blob_attr *msg, int cmd, uint32_t peer)
140 {
141         struct ubus_msghdr hdr;
142         struct iovec iov[2] = {
143                 STATIC_IOV(hdr)
144         };
145
146         hdr.version = 0;
147         hdr.type = cmd;
148         hdr.seq = seq;
149         hdr.peer = peer;
150
151         if (!msg) {
152                 blob_buf_init(&b, 0);
153                 msg = b.head;
154         }
155
156         iov[1].iov_base = (char *) msg;
157         iov[1].iov_len = blob_raw_len(msg);
158
159         return writev_retry(ctx->sock.fd, iov, ARRAY_SIZE(iov));
160 }
161
162 static int ubus_start_request(struct ubus_context *ctx, struct ubus_request *req,
163                               struct blob_attr *msg, int cmd, uint32_t peer)
164 {
165         memset(req, 0, sizeof(*req));
166
167         if (msg && blob_pad_len(msg) > UBUS_MAX_MSGLEN)
168                 return -1;
169
170         INIT_LIST_HEAD(&req->list);
171         INIT_LIST_HEAD(&req->pending);
172         req->ctx = ctx;
173         req->peer = peer;
174         req->seq = ++ctx->request_seq;
175         return ubus_send_msg(ctx, req->seq, msg, cmd, peer);
176 }
177
178 static bool recv_retry(int fd, struct iovec *iov, bool wait)
179 {
180         int bytes;
181
182         while (iov->iov_len > 0) {
183                 if (wait)
184                         wait_data(fd, false);
185
186                 bytes = read(fd, iov->iov_base, iov->iov_len);
187                 if (bytes < 0) {
188                         bytes = 0;
189                         if (uloop_cancelled)
190                                 return false;
191                         if (errno == EINTR)
192                                 continue;
193
194                         if (errno != EAGAIN)
195                                 return false;
196                 }
197                 if (!wait && !bytes)
198                         return false;
199
200                 wait = true;
201                 iov->iov_len -= bytes;
202                 iov->iov_base += bytes;
203         }
204
205         return true;
206 }
207
208 static bool ubus_validate_hdr(struct ubus_msghdr *hdr)
209 {
210         if (hdr->version != 0)
211                 return false;
212
213         if (blob_raw_len(hdr->data) < sizeof(*hdr->data))
214                 return false;
215
216         if (blob_pad_len(hdr->data) > UBUS_MAX_MSGLEN)
217                 return false;
218
219         return true;
220 }
221
222 static bool get_next_msg(struct ubus_context *ctx)
223 {
224         struct iovec iov = STATIC_IOV(ctx->msgbuf.hdr);
225
226         /* receive header + start attribute */
227         iov.iov_len += sizeof(struct blob_attr);
228         if (!recv_retry(ctx->sock.fd, &iov, false))
229                 return false;
230
231         iov.iov_len = blob_len(ctx->msgbuf.hdr.data);
232         if (iov.iov_len > 0 && !recv_retry(ctx->sock.fd, &iov, true))
233                 return false;
234
235         return ubus_validate_hdr(&ctx->msgbuf.hdr);
236 }
237
238 static bool ubus_get_status(struct ubus_msghdr *hdr, int *ret)
239 {
240         ubus_parse_msg(hdr->data);
241
242         if (!attrbuf[UBUS_ATTR_STATUS])
243                 return false;
244
245         *ret = blob_get_u32(attrbuf[UBUS_ATTR_STATUS]);
246         return true;
247 }
248
249 static void req_data_cb(struct ubus_request *req, int type, struct blob_attr *data)
250 {
251         struct blob_attr **attr;
252
253         if (req->raw_data_cb)
254                 req->raw_data_cb(req, type, data);
255
256         if (!req->data_cb)
257                 return;
258
259         attr = ubus_parse_msg(data);
260         req->data_cb(req, type, attr[UBUS_ATTR_DATA]);
261 }
262
263 static void ubus_process_req_data(struct ubus_request *req)
264 {
265         struct ubus_pending_data *data;
266
267         while (!list_empty(&req->pending)) {
268                 data = list_first_entry(&req->pending,
269                         struct ubus_pending_data, list);
270                 list_del(&data->list);
271                 if (!req->cancelled)
272                         req_data_cb(req, data->type, data->data);
273                 free(data);
274         }
275 }
276
277 static void ubus_req_complete_cb(struct ubus_request *req)
278 {
279         ubus_complete_handler_t cb = req->complete_cb;
280
281         if (!cb)
282                 return;
283
284         req->complete_cb = NULL;
285         cb(req, req->status_code);
286 }
287
288 static int ubus_process_req_status(struct ubus_request *req, struct ubus_msghdr *hdr)
289 {
290         int ret = UBUS_STATUS_INVALID_ARGUMENT;
291
292         if (!list_empty(&req->list))
293                 list_del_init(&req->list);
294
295         ubus_get_status(hdr, &ret);
296         req->peer = hdr->peer;
297         req->status_msg = true;
298         req->status_code = ret;
299         if (!req->blocked)
300                 ubus_req_complete_cb(req);
301
302         return ret;
303 }
304
305 static void ubus_req_data(struct ubus_request *req, struct ubus_msghdr *hdr)
306 {
307         struct ubus_pending_data *data;
308         int len;
309
310         if (!req->blocked) {
311                 req->blocked = true;
312                 req_data_cb(req, hdr->type, hdr->data);
313                 ubus_process_req_data(req);
314                 req->blocked = false;
315
316                 if (req->status_msg)
317                         ubus_req_complete_cb(req);
318
319                 return;
320         }
321
322         len = blob_raw_len(hdr->data);
323         data = calloc(1, sizeof(*data) + len);
324         if (!data)
325                 return;
326
327         data->type = hdr->type;
328         memcpy(data->data, hdr->data, len);
329         list_add(&data->list, &req->pending);
330 }
331
332 static struct ubus_request *ubus_find_request(struct ubus_context *ctx, uint32_t seq, uint32_t peer)
333 {
334         struct ubus_request *req;
335
336         list_for_each_entry(req, &ctx->requests, list) {
337                 if (seq != req->seq || peer != req->peer)
338                         continue;
339
340                 return req;
341         }
342         return NULL;
343 }
344
345 void ubus_complete_deferred_request(struct ubus_context *ctx, struct ubus_request_data *req, int ret)
346 {
347         blob_buf_init(&b, 0);
348         blob_put_int32(&b, UBUS_ATTR_STATUS, ret);
349         blob_put_int32(&b, UBUS_ATTR_OBJID, req->object);
350         ubus_send_msg(ctx, req->seq, b.head, UBUS_MSG_STATUS, req->peer);
351 }
352
353 static void ubus_process_invoke(struct ubus_context *ctx, struct ubus_msghdr *hdr)
354 {
355         struct ubus_request_data req;
356         struct ubus_object *obj;
357         int method;
358         int ret = 0;
359
360         req.peer = hdr->peer;
361         req.seq = hdr->seq;
362         ubus_parse_msg(hdr->data);
363
364         if (!attrbuf[UBUS_ATTR_OBJID])
365                 return;
366
367         req.object = blob_get_u32(attrbuf[UBUS_ATTR_OBJID]);
368
369         if (!attrbuf[UBUS_ATTR_METHOD]) {
370                 ret = UBUS_STATUS_INVALID_ARGUMENT;
371                 goto send;
372         }
373
374         obj = avl_find_element(&ctx->objects, &req.object, obj, avl);
375         if (!obj) {
376                 ret = UBUS_STATUS_NOT_FOUND;
377                 goto send;
378         }
379
380         for (method = 0; method < obj->n_methods; method++)
381                 if (!obj->methods[method].name ||
382                     !strcmp(obj->methods[method].name,
383                             blob_data(attrbuf[UBUS_ATTR_METHOD])))
384                         goto found;
385
386         /* not found */
387         ret = UBUS_STATUS_METHOD_NOT_FOUND;
388         goto send;
389
390 found:
391         ret = obj->methods[method].handler(ctx, obj, &req,
392                                            blob_data(attrbuf[UBUS_ATTR_METHOD]),
393                                            attrbuf[UBUS_ATTR_DATA]);
394         if (req.deferred)
395                 return;
396
397 send:
398         ubus_complete_deferred_request(ctx, &req, ret);
399 }
400
401 static void ubus_process_msg(struct ubus_context *ctx, struct ubus_msghdr *hdr)
402 {
403         struct ubus_pending_invoke *pending;
404         struct ubus_request *req;
405
406         switch(hdr->type) {
407         case UBUS_MSG_STATUS:
408                 req = ubus_find_request(ctx, hdr->seq, hdr->peer);
409                 if (!req)
410                         break;
411
412                 ubus_process_req_status(req, hdr);
413                 break;
414
415         case UBUS_MSG_DATA:
416                 req = ubus_find_request(ctx, hdr->seq, hdr->peer);
417                 if (req && (req->data_cb || req->raw_data_cb))
418                         ubus_req_data(req, hdr);
419                 break;
420
421         case UBUS_MSG_INVOKE:
422                 if (ctx->stack_depth > 2) {
423                         pending = calloc(1, sizeof(*pending) +
424                                 blob_raw_len(hdr->data));
425
426                         if (!pending)
427                                 return;
428
429                         memcpy(&pending->hdr, hdr, sizeof(*hdr) +
430                                 blob_raw_len(hdr->data));
431                         list_add(&pending->list, &ctx->pending);
432                 } else {
433                         ubus_process_invoke(ctx, hdr);
434                 }
435                 break;
436         }
437 }
438
439 static void ubus_process_pending_invoke(struct ubus_context *ctx)
440 {
441         struct ubus_pending_invoke *pending, *tmp;
442
443         list_for_each_entry_safe(pending, tmp, &ctx->pending, list) {
444                 list_del(&pending->list);
445                 ubus_process_msg(ctx, &pending->hdr);
446                 free(pending);
447                 if (ctx->stack_depth > 2)
448                         break;
449         }
450 }
451
452 void ubus_abort_request(struct ubus_context *ctx, struct ubus_request *req)
453 {
454         if (!list_empty(&req->list))
455                 return;
456
457         req->cancelled = true;
458         ubus_process_req_data(req);
459         list_del_init(&req->list);
460 }
461
462 void ubus_complete_request_async(struct ubus_context *ctx, struct ubus_request *req)
463 {
464         if (!list_empty(&req->list))
465                 return;
466
467         list_add(&req->list, &ctx->requests);
468 }
469
470 static void ubus_handle_data(struct uloop_fd *u, unsigned int events)
471 {
472         struct ubus_context *ctx = container_of(u, struct ubus_context, sock);
473         struct ubus_msghdr *hdr = &ctx->msgbuf.hdr;
474
475         while (get_next_msg(ctx)) {
476                 ubus_process_msg(ctx, hdr);
477                 if (uloop_cancelled)
478                         break;
479         }
480
481         if (u->eof)
482                 ctx->connection_lost(ctx);
483 }
484
485 static void ubus_sync_req_cb(struct ubus_request *req, int ret)
486 {
487         req->status_msg = true;
488         req->status_code = ret;
489         uloop_end();
490 }
491
492 struct ubus_sync_req_cb {
493         struct uloop_timeout timeout;
494         struct ubus_request *req;
495 };
496
497 static void ubus_sync_req_timeout_cb(struct uloop_timeout *timeout)
498 {
499         struct ubus_sync_req_cb *cb;
500
501         cb = container_of(timeout, struct ubus_sync_req_cb, timeout);
502         ubus_sync_req_cb(cb->req, UBUS_STATUS_TIMEOUT);
503 }
504
505 int ubus_complete_request(struct ubus_context *ctx, struct ubus_request *req,
506                           int timeout)
507 {
508         struct ubus_sync_req_cb cb;
509         ubus_complete_handler_t complete_cb = req->complete_cb;
510         bool registered = ctx->sock.registered;
511         int status = UBUS_STATUS_NO_DATA;
512
513         if (!registered) {
514                 uloop_init();
515                 ubus_add_uloop(ctx);
516         }
517
518         if (timeout) {
519                 memset(&cb, 0, sizeof(cb));
520                 cb.req = req;
521                 cb.timeout.cb = ubus_sync_req_timeout_cb;
522                 uloop_timeout_set(&cb.timeout, timeout);
523         }
524
525         ubus_complete_request_async(ctx, req);
526         req->complete_cb = ubus_sync_req_cb;
527
528         ctx->stack_depth++;
529         while (!req->status_msg) {
530                 bool cancelled = uloop_cancelled;
531                 uloop_cancelled = false;
532                 uloop_run();
533                 uloop_cancelled = cancelled;
534         }
535         ctx->stack_depth--;
536
537         if (timeout)
538                 uloop_timeout_cancel(&cb.timeout);
539
540         if (req->status_msg)
541                 status = req->status_code;
542
543         req->complete_cb = complete_cb;
544         if (req->complete_cb)
545                 req->complete_cb(req, status);
546
547         if (!registered)
548                 uloop_fd_delete(&ctx->sock);
549
550         if (!ctx->stack_depth)
551                 ubus_process_pending_invoke(ctx);
552
553         return status;
554 }
555
556 struct ubus_lookup_request {
557         struct ubus_request req;
558         ubus_lookup_handler_t cb;
559 };
560
561 static void ubus_lookup_cb(struct ubus_request *ureq, int type, struct blob_attr *msg)
562 {
563         struct ubus_lookup_request *req;
564         struct ubus_object_data obj;
565         struct blob_attr **attr;
566
567         req = container_of(ureq, struct ubus_lookup_request, req);
568         attr = ubus_parse_msg(msg);
569
570         if (!attr[UBUS_ATTR_OBJID] || !attr[UBUS_ATTR_OBJPATH] ||
571             !attr[UBUS_ATTR_OBJTYPE])
572                 return;
573
574         memset(&obj, 0, sizeof(obj));
575         obj.id = blob_get_u32(attr[UBUS_ATTR_OBJID]);
576         obj.path = blob_data(attr[UBUS_ATTR_OBJPATH]);
577         obj.type_id = blob_get_u32(attr[UBUS_ATTR_OBJTYPE]);
578         obj.signature = attr[UBUS_ATTR_SIGNATURE];
579         req->cb(ureq->ctx, &obj, ureq->priv);
580 }
581
582 int ubus_lookup(struct ubus_context *ctx, const char *path,
583                 ubus_lookup_handler_t cb, void *priv)
584 {
585         struct ubus_lookup_request lookup;
586
587         blob_buf_init(&b, 0);
588         if (path)
589                 blob_put_string(&b, UBUS_ATTR_OBJPATH, path);
590
591         if (ubus_start_request(ctx, &lookup.req, b.head, UBUS_MSG_LOOKUP, 0) < 0)
592                 return UBUS_STATUS_INVALID_ARGUMENT;
593
594         lookup.req.raw_data_cb = ubus_lookup_cb;
595         lookup.req.priv = priv;
596         lookup.cb = cb;
597         return ubus_complete_request(ctx, &lookup.req, 0);
598 }
599
600 static void ubus_lookup_id_cb(struct ubus_request *req, int type, struct blob_attr *msg)
601 {
602         struct blob_attr **attr;
603         uint32_t *id = req->priv;
604
605         attr = ubus_parse_msg(msg);
606
607         if (!attr[UBUS_ATTR_OBJID])
608                 return;
609
610         *id = blob_get_u32(attr[UBUS_ATTR_OBJID]);
611 }
612
613 int ubus_lookup_id(struct ubus_context *ctx, const char *path, uint32_t *id)
614 {
615         struct ubus_request req;
616
617         blob_buf_init(&b, 0);
618         if (path)
619                 blob_put_string(&b, UBUS_ATTR_OBJPATH, path);
620
621         if (ubus_start_request(ctx, &req, b.head, UBUS_MSG_LOOKUP, 0) < 0)
622                 return UBUS_STATUS_INVALID_ARGUMENT;
623
624         req.raw_data_cb = ubus_lookup_id_cb;
625         req.priv = id;
626
627         return ubus_complete_request(ctx, &req, 0);
628 }
629
630 int ubus_send_reply(struct ubus_context *ctx, struct ubus_request_data *req,
631                     struct blob_attr *msg)
632 {
633         int ret;
634
635         blob_buf_init(&b, 0);
636         blob_put_int32(&b, UBUS_ATTR_OBJID, req->object);
637         blob_put(&b, UBUS_ATTR_DATA, blob_data(msg), blob_len(msg));
638         ret = ubus_send_msg(ctx, req->seq, b.head, UBUS_MSG_DATA, req->peer);
639         if (ret < 0)
640                 return UBUS_STATUS_NO_DATA;
641
642         return 0;
643 }
644
645 int ubus_invoke_async(struct ubus_context *ctx, uint32_t obj, const char *method,
646                        struct blob_attr *msg, struct ubus_request *req)
647 {
648         blob_buf_init(&b, 0);
649         blob_put_int32(&b, UBUS_ATTR_OBJID, obj);
650         blob_put_string(&b, UBUS_ATTR_METHOD, method);
651         if (msg)
652                 blob_put(&b, UBUS_ATTR_DATA, blob_data(msg), blob_len(msg));
653
654         if (ubus_start_request(ctx, req, b.head, UBUS_MSG_INVOKE, obj) < 0)
655                 return UBUS_STATUS_INVALID_ARGUMENT;
656
657         return 0;
658 }
659
660 int ubus_invoke(struct ubus_context *ctx, uint32_t obj, const char *method,
661                 struct blob_attr *msg, ubus_data_handler_t cb, void *priv,
662                 int timeout)
663 {
664         struct ubus_request req;
665
666         ubus_invoke_async(ctx, obj, method, msg, &req);
667         req.data_cb = cb;
668         req.priv = priv;
669         return ubus_complete_request(ctx, &req, timeout);
670 }
671
672 static void ubus_add_object_cb(struct ubus_request *req, int type, struct blob_attr *msg)
673 {
674         struct ubus_object *obj = req->priv;
675
676         ubus_parse_msg(msg);
677
678         if (!attrbuf[UBUS_ATTR_OBJID])
679                 return;
680
681         obj->id = blob_get_u32(attrbuf[UBUS_ATTR_OBJID]);
682
683         if (attrbuf[UBUS_ATTR_OBJTYPE])
684                 obj->type->id = blob_get_u32(attrbuf[UBUS_ATTR_OBJTYPE]);
685
686         obj->avl.key = &obj->id;
687         avl_insert(&req->ctx->objects, &obj->avl);
688 }
689
690 static void ubus_push_method_data(const struct ubus_method *m)
691 {
692         void *mtbl;
693         int i;
694
695         mtbl = blobmsg_open_table(&b, m->name);
696
697         for (i = 0; i < m->n_policy; i++)
698                 blobmsg_add_u32(&b, m->policy[i].name, m->policy[i].type);
699
700         blobmsg_close_table(&b, mtbl);
701 }
702
703 static bool ubus_push_object_type(const struct ubus_object_type *type)
704 {
705         void *s;
706         int i;
707
708         s = blob_nest_start(&b, UBUS_ATTR_SIGNATURE);
709
710         for (i = 0; i < type->n_methods; i++)
711                 ubus_push_method_data(&type->methods[i]);
712
713         blob_nest_end(&b, s);
714
715         return true;
716 }
717
718 int ubus_add_object(struct ubus_context *ctx, struct ubus_object *obj)
719 {
720         struct ubus_request req;
721         int ret;
722
723         blob_buf_init(&b, 0);
724
725         if (obj->name && obj->type) {
726                 blob_put_string(&b, UBUS_ATTR_OBJPATH, obj->name);
727
728                 if (obj->type->id)
729                         blob_put_int32(&b, UBUS_ATTR_OBJTYPE, obj->type->id);
730                 else if (!ubus_push_object_type(obj->type))
731                         return UBUS_STATUS_INVALID_ARGUMENT;
732         }
733
734         if (ubus_start_request(ctx, &req, b.head, UBUS_MSG_ADD_OBJECT, 0) < 0)
735                 return UBUS_STATUS_INVALID_ARGUMENT;
736
737         req.raw_data_cb = ubus_add_object_cb;
738         req.priv = obj;
739         ret = ubus_complete_request(ctx, &req, 0);
740         if (ret)
741                 return ret;
742
743         if (!obj->id)
744                 return UBUS_STATUS_NO_DATA;
745
746         return 0;
747 }
748
749 static void ubus_remove_object_cb(struct ubus_request *req, int type, struct blob_attr *msg)
750 {
751         struct ubus_object *obj = req->priv;
752
753         ubus_parse_msg(msg);
754
755         if (!attrbuf[UBUS_ATTR_OBJID])
756                 return;
757
758         obj->id = 0;
759
760         if (attrbuf[UBUS_ATTR_OBJTYPE] && obj->type)
761                 obj->type->id = 0;
762
763         avl_delete(&req->ctx->objects, &obj->avl);
764 }
765
766 int ubus_remove_object(struct ubus_context *ctx, struct ubus_object *obj)
767 {
768         struct ubus_request req;
769         int ret;
770
771         blob_buf_init(&b, 0);
772         blob_put_int32(&b, UBUS_ATTR_OBJID, obj->id);
773
774         if (ubus_start_request(ctx, &req, b.head, UBUS_MSG_REMOVE_OBJECT, 0) < 0)
775                 return UBUS_STATUS_INVALID_ARGUMENT;
776
777         req.raw_data_cb = ubus_remove_object_cb;
778         req.priv = obj;
779         ret = ubus_complete_request(ctx, &req, 0);
780         if (ret)
781                 return ret;
782
783         if (obj->id)
784                 return UBUS_STATUS_NO_DATA;
785
786         return 0;
787 }
788
789 static int ubus_event_cb(struct ubus_context *ctx, struct ubus_object *obj,
790                          struct ubus_request_data *req,
791                          const char *method, struct blob_attr *msg)
792 {
793         struct ubus_event_handler *ev;
794
795         ev = container_of(obj, struct ubus_event_handler, obj);
796         ev->cb(ctx, ev, method, msg);
797         return 0;
798 }
799
800 static const struct ubus_method event_method = {
801         .name = NULL,
802         .handler = ubus_event_cb,
803 };
804
805 int ubus_register_event_handler(struct ubus_context *ctx,
806                                 struct ubus_event_handler *ev,
807                                 const char *pattern)
808 {
809         struct ubus_object *obj = &ev->obj;
810         struct blob_buf b2;
811         int ret;
812
813         if (!obj->id) {
814                 obj->methods = &event_method;
815                 obj->n_methods = 1;
816
817                 if (!!obj->name ^ !!obj->type)
818                         return UBUS_STATUS_INVALID_ARGUMENT;
819
820                 ret = ubus_add_object(ctx, obj);
821                 if (ret)
822                         return ret;
823         }
824
825         /* use a second buffer, ubus_invoke() overwrites the primary one */
826         memset(&b2, 0, sizeof(b2));
827         blob_buf_init(&b2, 0);
828         blobmsg_add_u32(&b2, "object", obj->id);
829         if (pattern)
830                 blobmsg_add_string(&b2, "pattern", pattern);
831
832         return ubus_invoke(ctx, UBUS_SYSTEM_OBJECT_EVENT, "register", b2.head,
833                           NULL, NULL, 0);
834 }
835
836 enum {
837         WATCH_ID,
838         WATCH_NOTIFY,
839         __WATCH_MAX
840 };
841
842 static const struct blobmsg_policy watch_policy[] = {
843         [WATCH_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
844         [WATCH_NOTIFY] = { .name = "notify", .type = BLOBMSG_TYPE_STRING },
845 };
846
847
848 static int ubus_watch_cb(struct ubus_context *ctx, struct ubus_object *obj,
849                          struct ubus_request_data *req,
850                          const char *method, struct blob_attr *msg)
851 {
852         struct ubus_watch_object *w;
853         struct blob_attr *tb[__WATCH_MAX];
854
855         blobmsg_parse(watch_policy, ARRAY_SIZE(watch_policy), tb, blob_data(msg), blob_len(msg));
856
857         if (!tb[WATCH_ID] || !tb[WATCH_NOTIFY])
858                 return UBUS_STATUS_INVALID_ARGUMENT;
859
860         if (req->peer)
861                 return UBUS_STATUS_INVALID_ARGUMENT;
862
863         w = container_of(obj, struct ubus_watch_object, obj);
864         w->cb(ctx, w, blobmsg_get_u32(tb[WATCH_ID]));
865         return 0;
866 }
867
868 static const struct ubus_method watch_method = {
869         .name = NULL,
870         .handler = ubus_watch_cb,
871 };
872
873 int ubus_register_watch_object(struct ubus_context *ctx, struct ubus_watch_object *w_obj)
874 {
875         struct ubus_object *obj = &w_obj->obj;
876
877         obj->methods = &watch_method;
878         obj->n_methods = 1;
879
880         return ubus_add_object(ctx, obj);
881 }
882
883 static int
884 __ubus_watch_request(struct ubus_context *ctx, struct ubus_object *obj, uint32_t id, const char *method, int type)
885 {
886         struct ubus_request req;
887
888         blob_buf_init(&b, 0);
889         blob_put_int32(&b, UBUS_ATTR_OBJID, obj->id);
890         blob_put_int32(&b, UBUS_ATTR_TARGET, id);
891         if (method)
892                 blob_put_string(&b, UBUS_ATTR_METHOD, method);
893
894         if (ubus_start_request(ctx, &req, b.head, type, 0) < 0)
895                 return UBUS_STATUS_INVALID_ARGUMENT;
896
897         return ubus_complete_request(ctx, &req, 0);
898
899 }
900
901 int ubus_watch_object_add(struct ubus_context *ctx, struct ubus_watch_object *obj, uint32_t id)
902 {
903         return __ubus_watch_request(ctx, &obj->obj, id, "event", UBUS_MSG_ADD_WATCH);
904 }
905
906 int ubus_watch_object_remove(struct ubus_context *ctx, struct ubus_watch_object *obj, uint32_t id)
907 {
908         return __ubus_watch_request(ctx, &obj->obj, id, NULL, UBUS_MSG_REMOVE_WATCH);
909 }
910
911 int ubus_send_event(struct ubus_context *ctx, const char *id,
912                     struct blob_attr *data)
913 {
914         struct ubus_request req;
915         void *s;
916
917         blob_buf_init(&b, 0);
918         blob_put_int32(&b, UBUS_ATTR_OBJID, UBUS_SYSTEM_OBJECT_EVENT);
919         blob_put_string(&b, UBUS_ATTR_METHOD, "send");
920         s = blob_nest_start(&b, UBUS_ATTR_DATA);
921         blobmsg_add_string(&b, "id", id);
922         blobmsg_add_field(&b, BLOBMSG_TYPE_TABLE, "data", blob_data(data), blob_len(data));
923         blob_nest_end(&b, s);
924
925         if (ubus_start_request(ctx, &req, b.head, UBUS_MSG_INVOKE, UBUS_SYSTEM_OBJECT_EVENT) < 0)
926                 return UBUS_STATUS_INVALID_ARGUMENT;
927
928         return ubus_complete_request(ctx, &req, 0);
929 }
930
931 static void
932 ubus_refresh_state(struct ubus_context *ctx)
933 {
934         struct ubus_object *obj, *tmp;
935
936         /* clear all type IDs, they need to be registered again */
937         avl_for_each_element(&ctx->objects, obj, avl)
938                 obj->type->id = 0;
939
940         /* push out all objects again */
941         avl_for_each_element_safe(&ctx->objects, obj, avl, tmp) {
942                 obj->id = 0;
943                 avl_delete(&ctx->objects, &obj->avl);
944                 ubus_add_object(ctx, obj);
945         }
946 }
947
948 int ubus_reconnect(struct ubus_context *ctx, const char *path)
949 {
950         struct {
951                 struct ubus_msghdr hdr;
952                 struct blob_attr data;
953         } hdr;
954         struct blob_attr *buf;
955         int ret = UBUS_STATUS_UNKNOWN_ERROR;
956
957         if (!path)
958                 path = UBUS_UNIX_SOCKET;
959
960         if (ctx->sock.fd >= 0) {
961                 if (ctx->sock.registered)
962                         uloop_fd_delete(&ctx->sock);
963
964                 close(ctx->sock.fd);
965         }
966
967         ctx->sock.fd = usock(USOCK_UNIX, path, NULL);
968         if (ctx->sock.fd < 0)
969                 return UBUS_STATUS_CONNECTION_FAILED;
970
971         if (read(ctx->sock.fd, &hdr, sizeof(hdr)) != sizeof(hdr))
972                 goto out_close;
973
974         if (!ubus_validate_hdr(&hdr.hdr))
975                 goto out_close;
976
977         if (hdr.hdr.type != UBUS_MSG_HELLO)
978                 goto out_close;
979
980         buf = calloc(1, blob_raw_len(&hdr.data));
981         if (!buf)
982                 goto out_close;
983
984         memcpy(buf, &hdr.data, sizeof(hdr.data));
985         if (read(ctx->sock.fd, blob_data(buf), blob_len(buf)) != blob_len(buf))
986                 goto out_free;
987
988         ctx->local_id = hdr.hdr.peer;
989         if (!ctx->local_id)
990                 goto out_free;
991
992         ret = UBUS_STATUS_OK;
993         fcntl(ctx->sock.fd, F_SETFL, fcntl(ctx->sock.fd, F_GETFL) | O_NONBLOCK);
994
995         ubus_refresh_state(ctx);
996
997 out_free:
998         free(buf);
999 out_close:
1000         if (ret)
1001                 close(ctx->sock.fd);
1002
1003         return ret;
1004 }
1005
1006 static void ubus_default_connection_lost(struct ubus_context *ctx)
1007 {
1008         if (ctx->sock.registered)
1009                 uloop_end();
1010 }
1011
1012 struct ubus_context *ubus_connect(const char *path)
1013 {
1014         struct ubus_context *ctx;
1015
1016         ctx = calloc(1, sizeof(*ctx));
1017         if (!ctx)
1018                 return NULL;
1019
1020         ctx->sock.fd = -1;
1021         ctx->sock.cb = ubus_handle_data;
1022         ctx->connection_lost = ubus_default_connection_lost;
1023
1024         INIT_LIST_HEAD(&ctx->requests);
1025         INIT_LIST_HEAD(&ctx->pending);
1026         avl_init(&ctx->objects, ubus_cmp_id, false, NULL);
1027         if (ubus_reconnect(ctx, path)) {
1028                 free(ctx);
1029                 ctx = NULL;
1030         }
1031
1032         return ctx;
1033 }
1034
1035 void ubus_free(struct ubus_context *ctx)
1036 {
1037         close(ctx->sock.fd);
1038         free(ctx);
1039 }