libubus: Fix deletion from context's object AVL tree when removing object
[project/ubus.git] / cli.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 <unistd.h>
15
16 #include <libubox/blobmsg_json.h>
17 #include "libubus.h"
18
19 static struct blob_buf b;
20 static int listen_timeout;
21 static int timeout = 30;
22 static bool simple_output = false;
23 static int verbose = 0;
24 static int monitor_dir = -1;
25 static uint32_t monitor_mask;
26 static const char * const monitor_types[] = {
27         [UBUS_MSG_HELLO] = "hello",
28         [UBUS_MSG_STATUS] = "status",
29         [UBUS_MSG_DATA] = "data",
30         [UBUS_MSG_PING] = "ping",
31         [UBUS_MSG_LOOKUP] = "lookup",
32         [UBUS_MSG_INVOKE] = "invoke",
33         [UBUS_MSG_ADD_OBJECT] = "add_object",
34         [UBUS_MSG_REMOVE_OBJECT] = "remove_object",
35         [UBUS_MSG_SUBSCRIBE] = "subscribe",
36         [UBUS_MSG_UNSUBSCRIBE] = "unsubscribe",
37         [UBUS_MSG_NOTIFY] = "notify",
38 };
39
40 static const char *format_type(void *priv, struct blob_attr *attr)
41 {
42         static const char * const attr_types[] = {
43                 [BLOBMSG_TYPE_INT8] = "\"Boolean\"",
44                 [BLOBMSG_TYPE_INT32] = "\"Integer\"",
45                 [BLOBMSG_TYPE_STRING] = "\"String\"",
46                 [BLOBMSG_TYPE_ARRAY] = "\"Array\"",
47                 [BLOBMSG_TYPE_TABLE] = "\"Table\"",
48         };
49         const char *type = NULL;
50         int typeid;
51
52         if (blob_id(attr) != BLOBMSG_TYPE_INT32)
53                 return NULL;
54
55         typeid = blobmsg_get_u32(attr);
56         if (typeid < ARRAY_SIZE(attr_types))
57                 type = attr_types[typeid];
58         if (!type)
59                 type = "\"(unknown)\"";
60
61         return type;
62 }
63
64 static void receive_list_result(struct ubus_context *ctx, struct ubus_object_data *obj, void *priv)
65 {
66         struct blob_attr *cur;
67         char *s;
68         int rem;
69
70         if (simple_output || !verbose) {
71                 printf("%s\n", obj->path);
72                 return;
73         }
74
75         printf("'%s' @%08x\n", obj->path, obj->id);
76
77         if (!obj->signature)
78                 return;
79
80         blob_for_each_attr(cur, obj->signature, rem) {
81                 s = blobmsg_format_json_with_cb(cur, false, format_type, NULL, -1);
82                 printf("\t%s\n", s);
83                 free(s);
84         }
85 }
86
87 static void receive_call_result_data(struct ubus_request *req, int type, struct blob_attr *msg)
88 {
89         char *str;
90         if (!msg)
91                 return;
92
93         str = blobmsg_format_json_indent(msg, true, simple_output ? -1 : 0);
94         printf("%s\n", str);
95         free(str);
96 }
97
98 static void print_event(const char *type, struct blob_attr *msg)
99 {
100         char *str;
101
102         str = blobmsg_format_json(msg, true);
103         printf("{ \"%s\": %s }\n", type, str);
104         fflush(stdout);
105         free(str);
106 }
107
108 static int receive_request(struct ubus_context *ctx, struct ubus_object *obj,
109                             struct ubus_request_data *req,
110                             const char *method, struct blob_attr *msg)
111 {
112         print_event(method, msg);
113         return 0;
114 }
115
116 static void receive_event(struct ubus_context *ctx, struct ubus_event_handler *ev,
117                           const char *type, struct blob_attr *msg)
118 {
119         print_event(type, msg);
120 }
121
122 static int ubus_cli_list(struct ubus_context *ctx, int argc, char **argv)
123 {
124         const char *path = NULL;
125
126         if (argc > 1)
127                 return -2;
128
129         if (argc == 1)
130                 path = argv[0];
131
132         return ubus_lookup(ctx, path, receive_list_result, NULL);
133 }
134
135 static int ubus_cli_call(struct ubus_context *ctx, int argc, char **argv)
136 {
137         uint32_t id;
138         int ret;
139
140         if (argc < 2 || argc > 3)
141                 return -2;
142
143         blob_buf_init(&b, 0);
144         if (argc == 3 && !blobmsg_add_json_from_string(&b, argv[2])) {
145                 if (!simple_output)
146                         fprintf(stderr, "Failed to parse message data\n");
147                 return -1;
148         }
149
150         ret = ubus_lookup_id(ctx, argv[0], &id);
151         if (ret)
152                 return ret;
153
154         return ubus_invoke(ctx, id, argv[1], b.head, receive_call_result_data, NULL, timeout * 1000);
155 }
156
157 struct cli_listen_data {
158         struct uloop_timeout timeout;
159         bool timed_out;
160 };
161
162 static void ubus_cli_listen_timeout(struct uloop_timeout *timeout)
163 {
164         struct cli_listen_data *data = container_of(timeout, struct cli_listen_data, timeout);
165         data->timed_out = true;
166         uloop_end();
167 }
168
169 static void do_listen(struct ubus_context *ctx, struct cli_listen_data *data)
170 {
171         memset(data, 0, sizeof(*data));
172         data->timeout.cb = ubus_cli_listen_timeout;
173         uloop_init();
174         ubus_add_uloop(ctx);
175         if (listen_timeout)
176                 uloop_timeout_set(&data->timeout, listen_timeout * 1000);
177         uloop_run();
178         uloop_done();
179 }
180
181 static int ubus_cli_listen(struct ubus_context *ctx, int argc, char **argv)
182 {
183         struct ubus_event_handler ev = {
184                 .cb = receive_event,
185         };
186         struct cli_listen_data data;
187         const char *event;
188         int ret = 0;
189
190         if (argc > 0) {
191                 event = argv[0];
192         } else {
193                 event = "*";
194                 argc = 1;
195         }
196
197         do {
198                 ret = ubus_register_event_handler(ctx, &ev, event);
199                 if (ret)
200                         break;
201
202                 argv++;
203                 argc--;
204                 if (argc <= 0)
205                         break;
206
207                 event = argv[0];
208         } while (1);
209
210         if (ret) {
211                 if (!simple_output)
212                         fprintf(stderr, "Error while registering for event '%s': %s\n",
213                                 event, ubus_strerror(ret));
214                 return -1;
215         }
216
217         do_listen(ctx, &data);
218
219         return 0;
220 }
221
222 static int ubus_cli_subscribe(struct ubus_context *ctx, int argc, char **argv)
223 {
224         struct ubus_subscriber sub = {
225                 .cb = receive_request,
226         };
227         struct cli_listen_data data;
228         const char *event;
229         int ret = 0;
230
231         if (argc > 0) {
232                 event = argv[0];
233         } else {
234                 if (!simple_output)
235                         fprintf(stderr, "You need to specify an object to subscribe to\n");
236                 return -1;
237         }
238
239         ret = ubus_register_subscriber(ctx, &sub);
240         for (; !ret && argc > 0; argc--, argv++) {
241                 uint32_t id;
242
243                 ret = ubus_lookup_id(ctx, argv[0], &id);
244                 if (ret)
245                         break;
246
247                 ret = ubus_subscribe(ctx, &sub, id);
248         }
249
250         if (ret) {
251                 if (!simple_output)
252                         fprintf(stderr, "Error while registering for event '%s': %s\n",
253                                 event, ubus_strerror(ret));
254                 return -1;
255         }
256
257         do_listen(ctx, &data);
258
259         return 0;
260 }
261
262
263 static int ubus_cli_send(struct ubus_context *ctx, int argc, char **argv)
264 {
265         if (argc < 1 || argc > 2)
266                 return -2;
267
268         blob_buf_init(&b, 0);
269
270         if (argc == 2 && !blobmsg_add_json_from_string(&b, argv[1])) {
271                 if (!simple_output)
272                         fprintf(stderr, "Failed to parse message data\n");
273                 return -1;
274         }
275
276         return ubus_send_event(ctx, argv[0], b.head);
277 }
278
279 struct cli_wait_data {
280         struct uloop_timeout timeout;
281         struct ubus_event_handler ev;
282         char **pending;
283         int n_pending;
284 };
285
286 static void wait_check_object(struct cli_wait_data *data, const char *path)
287 {
288         int i;
289
290         for (i = 0; i < data->n_pending; i++) {
291                 if (strcmp(path, data->pending[i]) != 0)
292                         continue;
293
294                 data->n_pending--;
295                 if (i == data->n_pending)
296                         break;
297
298                 memmove(&data->pending[i], &data->pending[i + 1],
299                         (data->n_pending - i) * sizeof(*data->pending));
300                 i--;
301         }
302
303         if (!data->n_pending)
304                 uloop_end();
305 }
306
307 static void wait_event_cb(struct ubus_context *ctx, struct ubus_event_handler *ev,
308                           const char *type, struct blob_attr *msg)
309 {
310         static const struct blobmsg_policy policy = {
311                 "path", BLOBMSG_TYPE_STRING
312         };
313         struct cli_wait_data *data = container_of(ev, struct cli_wait_data, ev);
314         struct blob_attr *attr;
315         const char *path;
316
317         if (strcmp(type, "ubus.object.add") != 0)
318                 return;
319
320         blobmsg_parse(&policy, 1, &attr, blob_data(msg), blob_len(msg));
321         if (!attr)
322                 return;
323
324         path = blobmsg_data(attr);
325         wait_check_object(data, path);
326 }
327
328 static void wait_list_cb(struct ubus_context *ctx, struct ubus_object_data *obj, void *priv)
329 {
330         struct cli_wait_data *data = priv;
331
332         wait_check_object(data, obj->path);
333 }
334
335
336 static void wait_timeout(struct uloop_timeout *timeout)
337 {
338         uloop_end();
339 }
340
341 static int ubus_cli_wait_for(struct ubus_context *ctx, int argc, char **argv)
342 {
343         struct cli_wait_data data = {
344                 .timeout.cb = wait_timeout,
345                 .ev.cb = wait_event_cb,
346                 .pending = argv,
347                 .n_pending = argc,
348         };
349         int ret;
350
351         if (argc < 1)
352                 return -2;
353
354         uloop_init();
355         ubus_add_uloop(ctx);
356
357         ret = ubus_register_event_handler(ctx, &data.ev, "ubus.object.add");
358         if (ret)
359                 return ret;
360
361         if (!data.n_pending)
362                 return ret;
363
364         ret = ubus_lookup(ctx, NULL, wait_list_cb, &data);
365         if (ret)
366                 return ret;
367
368         if (!data.n_pending)
369                 return ret;
370
371         uloop_timeout_set(&data.timeout, timeout * 1000);
372         uloop_run();
373         uloop_done();
374
375         if (data.n_pending)
376                 return UBUS_STATUS_TIMEOUT;
377
378         return ret;
379 }
380
381 static const char *
382 ubus_cli_msg_type(uint32_t type)
383 {
384         const char *ret = NULL;
385         static char unk_type[16];
386
387
388         if (type < ARRAY_SIZE(monitor_types))
389                 ret = monitor_types[type];
390
391         if (!ret) {
392                 snprintf(unk_type, sizeof(unk_type), "%d", type);
393                 ret = unk_type;
394         }
395
396         return ret;
397 }
398
399 static char *
400 ubus_cli_get_monitor_data(struct blob_attr *data)
401 {
402         static const struct blob_attr_info policy[UBUS_ATTR_MAX] = {
403                 [UBUS_ATTR_STATUS] = { .type = BLOB_ATTR_INT32 },
404                 [UBUS_ATTR_OBJPATH] = { .type = BLOB_ATTR_STRING },
405                 [UBUS_ATTR_OBJID] = { .type = BLOB_ATTR_INT32 },
406                 [UBUS_ATTR_METHOD] = { .type = BLOB_ATTR_STRING },
407                 [UBUS_ATTR_OBJTYPE] = { .type = BLOB_ATTR_INT32 },
408                 [UBUS_ATTR_SIGNATURE] = { .type = BLOB_ATTR_NESTED },
409                 [UBUS_ATTR_DATA] = { .type = BLOB_ATTR_NESTED },
410                 [UBUS_ATTR_ACTIVE] = { .type = BLOB_ATTR_INT8 },
411                 [UBUS_ATTR_NO_REPLY] = { .type = BLOB_ATTR_INT8 },
412                 [UBUS_ATTR_USER] = { .type = BLOB_ATTR_STRING },
413                 [UBUS_ATTR_GROUP] = { .type = BLOB_ATTR_STRING },
414         };
415         static const char * const names[UBUS_ATTR_MAX] = {
416                 [UBUS_ATTR_STATUS] = "status",
417                 [UBUS_ATTR_OBJPATH] = "objpath",
418                 [UBUS_ATTR_OBJID] = "objid",
419                 [UBUS_ATTR_METHOD] = "method",
420                 [UBUS_ATTR_OBJTYPE] = "objtype",
421                 [UBUS_ATTR_SIGNATURE] = "signature",
422                 [UBUS_ATTR_DATA] = "data",
423                 [UBUS_ATTR_ACTIVE] = "active",
424                 [UBUS_ATTR_NO_REPLY] = "no_reply",
425                 [UBUS_ATTR_USER] = "user",
426                 [UBUS_ATTR_GROUP] = "group",
427         };
428         struct blob_attr *tb[UBUS_ATTR_MAX];
429         int i;
430
431         blob_buf_init(&b, 0);
432         blob_parse(data, tb, policy, UBUS_ATTR_MAX);
433
434         for (i = 0; i < UBUS_ATTR_MAX; i++) {
435                 const char *n = names[i];
436                 struct blob_attr *v = tb[i];
437
438                 if (!tb[i] || !n)
439                         continue;
440
441                 switch(policy[i].type) {
442                 case BLOB_ATTR_INT32:
443                         blobmsg_add_u32(&b, n, blob_get_int32(v));
444                         break;
445                 case BLOB_ATTR_STRING:
446                         blobmsg_add_string(&b, n, blob_data(v));
447                         break;
448                 case BLOB_ATTR_INT8:
449                         blobmsg_add_u8(&b, n, !!blob_get_int8(v));
450                         break;
451                 case BLOB_ATTR_NESTED:
452                         blobmsg_add_field(&b, BLOBMSG_TYPE_TABLE, n, blobmsg_data(v), blobmsg_data_len(v));
453                         break;
454                 }
455         }
456
457         return blobmsg_format_json(b.head, true);
458 }
459
460 static void
461 ubus_cli_monitor_cb(struct ubus_context *ctx, uint32_t seq, struct blob_attr *msg)
462 {
463         static const struct blob_attr_info policy[UBUS_MONITOR_MAX] = {
464                 [UBUS_MONITOR_CLIENT] = { .type = BLOB_ATTR_INT32 },
465                 [UBUS_MONITOR_PEER] = { .type = BLOB_ATTR_INT32 },
466                 [UBUS_MONITOR_SEND] = { .type = BLOB_ATTR_INT8 },
467                 [UBUS_MONITOR_TYPE] = { .type = BLOB_ATTR_INT32 },
468                 [UBUS_MONITOR_DATA] = { .type = BLOB_ATTR_NESTED },
469         };
470         struct blob_attr *tb[UBUS_MONITOR_MAX];
471         uint32_t client, peer, type;
472         bool send;
473         char *data;
474
475         blob_parse(msg, tb, policy, UBUS_MONITOR_MAX);
476
477         if (!tb[UBUS_MONITOR_CLIENT] ||
478             !tb[UBUS_MONITOR_PEER] ||
479             !tb[UBUS_MONITOR_SEND] ||
480             !tb[UBUS_MONITOR_TYPE] ||
481             !tb[UBUS_MONITOR_DATA]) {
482                 printf("Invalid monitor msg\n");
483                 return;
484         }
485
486         send = blob_get_int32(tb[UBUS_MONITOR_SEND]);
487         client = blob_get_int32(tb[UBUS_MONITOR_CLIENT]);
488         peer = blob_get_int32(tb[UBUS_MONITOR_PEER]);
489         type = blob_get_int32(tb[UBUS_MONITOR_TYPE]);
490
491         if (monitor_mask && type < 32 && !(monitor_mask & (1 << type)))
492                 return;
493
494         if (monitor_dir >= 0 && send != monitor_dir)
495                 return;
496
497         data = ubus_cli_get_monitor_data(tb[UBUS_MONITOR_DATA]);
498         printf("%s %08x #%08x %14s: %s\n", send ? "->" : "<-", client, peer, ubus_cli_msg_type(type), data);
499         free(data);
500         fflush(stdout);
501 }
502
503 static int ubus_cli_monitor(struct ubus_context *ctx, int argc, char **argv)
504 {
505         int ret;
506
507         uloop_init();
508         ubus_add_uloop(ctx);
509         ctx->monitor_cb = ubus_cli_monitor_cb;
510         ret = ubus_monitor_start(ctx);
511         if (ret)
512                 return ret;
513
514         uloop_run();
515         uloop_done();
516
517         ubus_monitor_stop(ctx);
518         return 0;
519 }
520
521 static int add_monitor_type(const char *type)
522 {
523         int i;
524
525         for (i = 0; i < ARRAY_SIZE(monitor_types); i++) {
526                 if (!monitor_types[i] || strcmp(monitor_types[i], type) != 0)
527                         continue;
528
529                 monitor_mask |= 1 << i;
530                 return 0;
531         }
532
533         return -1;
534 }
535
536 static int usage(const char *prog)
537 {
538         fprintf(stderr,
539                 "Usage: %s [<options>] <command> [arguments...]\n"
540                 "Options:\n"
541                 " -s <socket>:          Set the unix domain socket to connect to\n"
542                 " -t <timeout>:         Set the timeout (in seconds) for a command to complete\n"
543                 " -S:                   Use simplified output (for scripts)\n"
544                 " -v:                   More verbose output\n"
545                 " -m <type>:            (for monitor): include a specific message type\n"
546                 "                       (can be used more than once)\n"
547                 " -M <r|t>              (for monitor): only capture received or transmitted traffic\n"
548                 "\n"
549                 "Commands:\n"
550                 " - list [<path>]                       List objects\n"
551                 " - call <path> <method> [<message>]    Call an object method\n"
552                 " - listen [<path>...]                  Listen for events\n"
553                 " - send <type> [<message>]             Send an event\n"
554                 " - wait_for <object> [<object>...]     Wait for multiple objects to appear on ubus\n"
555                 " - monitor                             Monitor ubus traffic\n"
556                 "\n", prog);
557         return 1;
558 }
559
560
561 static struct {
562         const char *name;
563         int (*cb)(struct ubus_context *ctx, int argc, char **argv);
564 } commands[] = {
565         { "list", ubus_cli_list },
566         { "call", ubus_cli_call },
567         { "listen", ubus_cli_listen },
568         { "subscribe", ubus_cli_subscribe },
569         { "send", ubus_cli_send },
570         { "wait_for", ubus_cli_wait_for },
571         { "monitor", ubus_cli_monitor },
572 };
573
574 int main(int argc, char **argv)
575 {
576         const char *progname, *ubus_socket = NULL;
577         struct ubus_context *ctx;
578         char *cmd;
579         int ret = 0;
580         int i, ch;
581
582         progname = argv[0];
583
584         while ((ch = getopt(argc, argv, "m:M:vs:t:S")) != -1) {
585                 switch (ch) {
586                 case 's':
587                         ubus_socket = optarg;
588                         break;
589                 case 't':
590                         listen_timeout = atoi(optarg);
591                         timeout = atoi(optarg);
592                         break;
593                 case 'S':
594                         simple_output = true;
595                         break;
596                 case 'v':
597                         verbose++;
598                         break;
599                 case 'm':
600                         if (add_monitor_type(optarg))
601                             return usage(progname);
602                         break;
603                 case 'M':
604                         switch (optarg[0]) {
605                         case 'r':
606                                 monitor_dir = 0;
607                                 break;
608                         case 't':
609                                 monitor_dir = 1;
610                                 break;
611                         default:
612                                 return usage(progname);
613                         }
614                         break;
615                 default:
616                         return usage(progname);
617                 }
618         }
619
620         argc -= optind;
621         argv += optind;
622
623         cmd = argv[0];
624         if (argc < 1)
625                 return usage(progname);
626
627         ctx = ubus_connect(ubus_socket);
628         if (!ctx) {
629                 if (!simple_output)
630                         fprintf(stderr, "Failed to connect to ubus\n");
631                 return -1;
632         }
633
634         argv++;
635         argc--;
636
637         ret = -2;
638         for (i = 0; i < ARRAY_SIZE(commands); i++) {
639                 if (strcmp(commands[i].name, cmd) != 0)
640                         continue;
641
642                 ret = commands[i].cb(ctx, argc, argv);
643                 break;
644         }
645
646         if (ret > 0 && !simple_output)
647                 fprintf(stderr, "Command failed: %s\n", ubus_strerror(ret));
648         else if (ret == -2)
649                 usage(progname);
650
651         ubus_free(ctx);
652         return ret;
653 }