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