libubus.h: add ubus_auto_shutdown()
[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 static int ubus_cli_listen(struct ubus_context *ctx, int argc, char **argv)
144 {
145         static struct ubus_event_handler listener;
146         const char *event;
147         int ret = 0;
148
149         memset(&listener, 0, sizeof(listener));
150         listener.cb = receive_event;
151
152         if (argc > 0) {
153                 event = argv[0];
154         } else {
155                 event = "*";
156                 argc = 1;
157         }
158
159         do {
160                 ret = ubus_register_event_handler(ctx, &listener, event);
161                 if (ret)
162                         break;
163
164                 argv++;
165                 argc--;
166                 if (argc <= 0)
167                         break;
168
169                 event = argv[0];
170         } while (1);
171
172         if (ret) {
173                 if (!simple_output)
174                         fprintf(stderr, "Error while registering for event '%s': %s\n",
175                                 event, ubus_strerror(ret));
176                 return -1;
177         }
178
179         uloop_init();
180         ubus_add_uloop(ctx);
181         uloop_run();
182         uloop_done();
183
184         return 0;
185 }
186
187 static int ubus_cli_send(struct ubus_context *ctx, int argc, char **argv)
188 {
189         if (argc < 1 || argc > 2)
190                 return -2;
191
192         blob_buf_init(&b, 0);
193
194         if (argc == 2 && !blobmsg_add_json_from_string(&b, argv[1])) {
195                 if (!simple_output)
196                         fprintf(stderr, "Failed to parse message data\n");
197                 return -1;
198         }
199
200         return ubus_send_event(ctx, argv[0], b.head);
201 }
202
203 struct cli_wait_data {
204         struct uloop_timeout timeout;
205         struct ubus_event_handler ev;
206         char **pending;
207         int n_pending;
208 };
209
210 static void wait_check_object(struct cli_wait_data *data, const char *path)
211 {
212         int i;
213
214         for (i = 0; i < data->n_pending; i++) {
215                 if (strcmp(path, data->pending[i]) != 0)
216                         continue;
217
218                 data->n_pending--;
219                 if (i == data->n_pending)
220                         break;
221
222                 memmove(&data->pending[i], &data->pending[i + 1],
223                         (data->n_pending - i) * sizeof(*data->pending));
224                 i--;
225         }
226
227         if (!data->n_pending)
228                 uloop_end();
229 }
230
231 static void wait_event_cb(struct ubus_context *ctx, struct ubus_event_handler *ev,
232                           const char *type, struct blob_attr *msg)
233 {
234         static const struct blobmsg_policy policy = {
235                 "path", BLOBMSG_TYPE_STRING
236         };
237         struct cli_wait_data *data = container_of(ev, struct cli_wait_data, ev);
238         struct blob_attr *attr;
239         const char *path;
240
241         if (strcmp(type, "ubus.object.add") != 0)
242                 return;
243
244         blobmsg_parse(&policy, 1, &attr, blob_data(msg), blob_len(msg));
245         if (!attr)
246                 return;
247
248         path = blobmsg_data(attr);
249         wait_check_object(data, path);
250 }
251
252 static void wait_list_cb(struct ubus_context *ctx, struct ubus_object_data *obj, void *priv)
253 {
254         struct cli_wait_data *data = priv;
255
256         wait_check_object(data, obj->path);
257 }
258
259
260 static void wait_timeout(struct uloop_timeout *timeout)
261 {
262         uloop_end();
263 }
264
265 static int ubus_cli_wait_for(struct ubus_context *ctx, int argc, char **argv)
266 {
267         struct cli_wait_data data = {
268                 .timeout.cb = wait_timeout,
269                 .ev.cb = wait_event_cb,
270                 .pending = argv,
271                 .n_pending = argc,
272         };
273         int ret;
274
275         if (argc < 1)
276                 return -2;
277
278         uloop_init();
279         ubus_add_uloop(ctx);
280
281         ret = ubus_lookup(ctx, NULL, wait_list_cb, &data);
282         if (ret)
283                 return ret;
284
285         if (!data.n_pending)
286                 return ret;
287
288         ret = ubus_register_event_handler(ctx, &data.ev, "ubus.object.add");
289         if (ret)
290                 return ret;
291
292         uloop_timeout_set(&data.timeout, timeout * 1000);
293         uloop_run();
294         uloop_done();
295
296         if (data.n_pending)
297                 return UBUS_STATUS_TIMEOUT;
298
299         return ret;
300 }
301
302 static const char *
303 ubus_cli_msg_type(uint32_t type)
304 {
305         const char *ret = NULL;
306         static char unk_type[16];
307
308
309         if (type < ARRAY_SIZE(monitor_types))
310                 ret = monitor_types[type];
311
312         if (!ret) {
313                 snprintf(unk_type, sizeof(unk_type), "%d", type);
314                 ret = unk_type;
315         }
316
317         return ret;
318 }
319
320 static char *
321 ubus_cli_get_monitor_data(struct blob_attr *data)
322 {
323         static const struct blob_attr_info policy[UBUS_ATTR_MAX] = {
324                 [UBUS_ATTR_STATUS] = { .type = BLOB_ATTR_INT32 },
325                 [UBUS_ATTR_OBJPATH] = { .type = BLOB_ATTR_STRING },
326                 [UBUS_ATTR_OBJID] = { .type = BLOB_ATTR_INT32 },
327                 [UBUS_ATTR_METHOD] = { .type = BLOB_ATTR_STRING },
328                 [UBUS_ATTR_OBJTYPE] = { .type = BLOB_ATTR_INT32 },
329                 [UBUS_ATTR_SIGNATURE] = { .type = BLOB_ATTR_NESTED },
330                 [UBUS_ATTR_DATA] = { .type = BLOB_ATTR_NESTED },
331                 [UBUS_ATTR_ACTIVE] = { .type = BLOB_ATTR_INT8 },
332                 [UBUS_ATTR_NO_REPLY] = { .type = BLOB_ATTR_INT8 },
333                 [UBUS_ATTR_USER] = { .type = BLOB_ATTR_STRING },
334                 [UBUS_ATTR_GROUP] = { .type = BLOB_ATTR_STRING },
335         };
336         static const char * const names[UBUS_ATTR_MAX] = {
337                 [UBUS_ATTR_STATUS] = "status",
338                 [UBUS_ATTR_OBJPATH] = "objpath",
339                 [UBUS_ATTR_OBJID] = "objid",
340                 [UBUS_ATTR_METHOD] = "method",
341                 [UBUS_ATTR_OBJTYPE] = "objtype",
342                 [UBUS_ATTR_SIGNATURE] = "signature",
343                 [UBUS_ATTR_DATA] = "data",
344                 [UBUS_ATTR_ACTIVE] = "active",
345                 [UBUS_ATTR_NO_REPLY] = "no_reply",
346                 [UBUS_ATTR_USER] = "user",
347                 [UBUS_ATTR_GROUP] = "group",
348         };
349         struct blob_attr *tb[UBUS_ATTR_MAX];
350         int i;
351
352         blob_buf_init(&b, 0);
353         blob_parse(data, tb, policy, UBUS_ATTR_MAX);
354
355         for (i = 0; i < UBUS_ATTR_MAX; i++) {
356                 const char *n = names[i];
357                 struct blob_attr *v = tb[i];
358
359                 if (!tb[i] || !n)
360                         continue;
361
362                 switch(policy[i].type) {
363                 case BLOB_ATTR_INT32:
364                         blobmsg_add_u32(&b, n, blob_get_int32(v));
365                         break;
366                 case BLOB_ATTR_STRING:
367                         blobmsg_add_string(&b, n, blob_data(v));
368                         break;
369                 case BLOB_ATTR_INT8:
370                         blobmsg_add_u8(&b, n, !!blob_get_int8(v));
371                         break;
372                 case BLOB_ATTR_NESTED:
373                         blobmsg_add_field(&b, BLOBMSG_TYPE_TABLE, n, blobmsg_data(v), blobmsg_data_len(v));
374                         break;
375                 }
376         }
377
378         return blobmsg_format_json(b.head, true);
379 }
380
381 static void
382 ubus_cli_monitor_cb(struct ubus_context *ctx, uint32_t seq, struct blob_attr *msg)
383 {
384         static const struct blob_attr_info policy[UBUS_MONITOR_MAX] = {
385                 [UBUS_MONITOR_CLIENT] = { .type = BLOB_ATTR_INT32 },
386                 [UBUS_MONITOR_PEER] = { .type = BLOB_ATTR_INT32 },
387                 [UBUS_MONITOR_SEND] = { .type = BLOB_ATTR_INT8 },
388                 [UBUS_MONITOR_TYPE] = { .type = BLOB_ATTR_INT32 },
389                 [UBUS_MONITOR_DATA] = { .type = BLOB_ATTR_NESTED },
390         };
391         struct blob_attr *tb[UBUS_MONITOR_MAX];
392         uint32_t client, peer, type;
393         bool send;
394         char *data;
395
396         blob_parse(msg, tb, policy, UBUS_MONITOR_MAX);
397
398         if (!tb[UBUS_MONITOR_CLIENT] ||
399             !tb[UBUS_MONITOR_PEER] ||
400             !tb[UBUS_MONITOR_SEND] ||
401             !tb[UBUS_MONITOR_TYPE] ||
402             !tb[UBUS_MONITOR_DATA]) {
403                 printf("Invalid monitor msg\n");
404                 return;
405         }
406
407         send = blob_get_int32(tb[UBUS_MONITOR_SEND]);
408         client = blob_get_int32(tb[UBUS_MONITOR_CLIENT]);
409         peer = blob_get_int32(tb[UBUS_MONITOR_PEER]);
410         type = blob_get_int32(tb[UBUS_MONITOR_TYPE]);
411
412         if (monitor_mask && type < 32 && !(monitor_mask & (1 << type)))
413                 return;
414
415         if (monitor_dir >= 0 && send != monitor_dir)
416                 return;
417
418         data = ubus_cli_get_monitor_data(tb[UBUS_MONITOR_DATA]);
419         printf("%s %08x #%08x %14s: %s\n", send ? "->" : "<-", client, peer, ubus_cli_msg_type(type), data);
420         free(data);
421         fflush(stdout);
422 }
423
424 static int ubus_cli_monitor(struct ubus_context *ctx, int argc, char **argv)
425 {
426         int ret;
427
428         uloop_init();
429         ubus_add_uloop(ctx);
430         ctx->monitor_cb = ubus_cli_monitor_cb;
431         ret = ubus_monitor_start(ctx);
432         if (ret)
433                 return ret;
434
435         uloop_run();
436         uloop_done();
437
438         ubus_monitor_stop(ctx);
439         return 0;
440 }
441
442 static int add_monitor_type(const char *type)
443 {
444         int i;
445
446         for (i = 0; i < ARRAY_SIZE(monitor_types); i++) {
447                 if (!monitor_types[i] || strcmp(monitor_types[i], type) != 0)
448                         continue;
449
450                 monitor_mask |= 1 << i;
451                 return 0;
452         }
453
454         return -1;
455 }
456
457 static int usage(const char *prog)
458 {
459         fprintf(stderr,
460                 "Usage: %s [<options>] <command> [arguments...]\n"
461                 "Options:\n"
462                 " -s <socket>:          Set the unix domain socket to connect to\n"
463                 " -t <timeout>:         Set the timeout (in seconds) for a command to complete\n"
464                 " -S:                   Use simplified output (for scripts)\n"
465                 " -v:                   More verbose output\n"
466                 " -m <type>:            (for monitor): include a specific message type\n"
467                 "                       (can be used more than once)\n"
468                 " -M <r|t>              (for monitor): only capture received or transmitted traffic\n"
469                 "\n"
470                 "Commands:\n"
471                 " - list [<path>]                       List objects\n"
472                 " - call <path> <method> [<message>]    Call an object method\n"
473                 " - listen [<path>...]                  Listen for events\n"
474                 " - send <type> [<message>]             Send an event\n"
475                 " - wait_for <object> [<object>...]     Wait for multiple objects to appear on ubus\n"
476                 " - monitor                             Monitor ubus traffic\n"
477                 "\n", prog);
478         return 1;
479 }
480
481
482 struct {
483         const char *name;
484         int (*cb)(struct ubus_context *ctx, int argc, char **argv);
485 } commands[] = {
486         { "list", ubus_cli_list },
487         { "call", ubus_cli_call },
488         { "listen", ubus_cli_listen },
489         { "send", ubus_cli_send },
490         { "wait_for", ubus_cli_wait_for },
491         { "monitor", ubus_cli_monitor },
492 };
493
494 int main(int argc, char **argv)
495 {
496         const char *progname, *ubus_socket = NULL;
497         static struct ubus_context *ctx;
498         char *cmd;
499         int ret = 0;
500         int i, ch;
501
502         progname = argv[0];
503
504         while ((ch = getopt(argc, argv, "m:M:vs:t:S")) != -1) {
505                 switch (ch) {
506                 case 's':
507                         ubus_socket = optarg;
508                         break;
509                 case 't':
510                         timeout = atoi(optarg);
511                         break;
512                 case 'S':
513                         simple_output = true;
514                         break;
515                 case 'v':
516                         verbose++;
517                         break;
518                 case 'm':
519                         if (add_monitor_type(optarg))
520                             return usage(progname);
521                         break;
522                 case 'M':
523                         switch (optarg[0]) {
524                         case 'r':
525                                 monitor_dir = 0;
526                                 break;
527                         case 't':
528                                 monitor_dir = 1;
529                                 break;
530                         default:
531                                 return usage(progname);
532                         }
533                         break;
534                 default:
535                         return usage(progname);
536                 }
537         }
538
539         argc -= optind;
540         argv += optind;
541
542         cmd = argv[0];
543         if (argc < 1)
544                 return usage(progname);
545
546         ctx = ubus_connect(ubus_socket);
547         if (!ctx) {
548                 if (!simple_output)
549                         fprintf(stderr, "Failed to connect to ubus\n");
550                 return -1;
551         }
552
553         argv++;
554         argc--;
555
556         ret = -2;
557         for (i = 0; i < ARRAY_SIZE(commands); i++) {
558                 if (strcmp(commands[i].name, cmd) != 0)
559                         continue;
560
561                 ret = commands[i].cb(ctx, argc, argv);
562                 break;
563         }
564
565         if (ret > 0 && !simple_output)
566                 fprintf(stderr, "Command failed: %s\n", ubus_strerror(ret));
567         else if (ret == -2)
568                 usage(progname);
569
570         ubus_free(ctx);
571         return ret;
572 }