8970f4f0b8cec1f0eed0804272e22bcfeb06d667
[oweals/uci.git] / cli.c
1 /*
2  * cli - Command Line Interface for the Unified Configuration Interface
3  * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14 #include <strings.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <stdarg.h>
18 #include <errno.h>
19 #include <unistd.h>
20 #include "uci.h"
21
22 #define MAX_ARGS        4 /* max command line arguments for batch mode */
23
24 static const char *delimiter = " ";
25 static const char *appname;
26 static enum {
27         CLI_FLAG_MERGE =    (1 << 0),
28         CLI_FLAG_QUIET =    (1 << 1),
29         CLI_FLAG_NOCOMMIT = (1 << 2),
30         CLI_FLAG_BATCH =    (1 << 3),
31         CLI_FLAG_SHOW_EXT = (1 << 4),
32 } flags;
33
34 static FILE *input;
35
36 static struct uci_context *ctx;
37 enum {
38         /* section cmds */
39         CMD_GET,
40         CMD_SET,
41         CMD_ADD_LIST,
42         CMD_DEL_LIST,
43         CMD_DEL,
44         CMD_RENAME,
45         CMD_REVERT,
46         CMD_REORDER,
47         /* package cmds */
48         CMD_SHOW,
49         CMD_CHANGES,
50         CMD_EXPORT,
51         CMD_COMMIT,
52         /* other cmds */
53         CMD_ADD,
54         CMD_IMPORT,
55         CMD_HELP,
56 };
57
58 struct uci_type_list {
59         unsigned int idx;
60         const char *name;
61         struct uci_type_list *next;
62 };
63
64 static struct uci_type_list *type_list = NULL;
65 static char *typestr = NULL;
66 static const char *cur_section_ref = NULL;
67
68 static int uci_cmd(int argc, char **argv);
69
70 static void
71 uci_reset_typelist(void)
72 {
73         struct uci_type_list *type;
74         while (type_list != NULL) {
75                         type = type_list;
76                         type_list = type_list->next;
77                         free(type);
78         }
79         if (typestr) {
80                 free(typestr);
81                 typestr = NULL;
82         }
83         cur_section_ref = NULL;
84 }
85
86 static char *
87 uci_lookup_section_ref(struct uci_section *s)
88 {
89         struct uci_type_list *ti = type_list;
90         char *ret;
91         int maxlen;
92
93         if (!(flags & CLI_FLAG_SHOW_EXT))
94                 return s->e.name;
95
96         /* look up in section type list */
97         while (ti) {
98                 if (strcmp(ti->name, s->type) == 0)
99                         break;
100                 ti = ti->next;
101         }
102         if (!ti) {
103                 ti = malloc(sizeof(struct uci_type_list));
104                 if (!ti)
105                         return NULL;
106                 memset(ti, 0, sizeof(struct uci_type_list));
107                 ti->next = type_list;
108                 type_list = ti;
109                 ti->name = s->type;
110         }
111
112         if (s->anonymous) {
113                 maxlen = strlen(s->type) + 1 + 2 + 10;
114                 if (!typestr) {
115                         typestr = malloc(maxlen);
116                         if (!typestr)
117                                 return NULL;
118                 } else {
119                         void *p = realloc(typestr, maxlen);
120                         if (!p) {
121                                 free(typestr);
122                                 return NULL;
123                         }
124
125                         typestr = p;
126                 }
127
128                 if (typestr)
129                         sprintf(typestr, "@%s[%d]", ti->name, ti->idx);
130
131                 ret = typestr;
132         } else {
133                 ret = s->e.name;
134         }
135
136         ti->idx++;
137
138         return ret;
139 }
140
141 static void uci_usage(void)
142 {
143         fprintf(stderr,
144                 "Usage: %s [<options>] <command> [<arguments>]\n\n"
145                 "Commands:\n"
146                 "\tbatch\n"
147                 "\texport     [<config>]\n"
148                 "\timport     [<config>]\n"
149                 "\tchanges    [<config>]\n"
150                 "\tcommit     [<config>]\n"
151                 "\tadd        <config> <section-type>\n"
152                 "\tadd_list   <config>.<section>.<option>=<string>\n"
153                 "\tdel_list   <config>.<section>.<option>=<string>\n"
154                 "\tshow       [<config>[.<section>[.<option>]]]\n"
155                 "\tget        <config>.<section>[.<option>]\n"
156                 "\tset        <config>.<section>[.<option>]=<value>\n"
157                 "\tdelete     <config>[.<section>[[.<option>][=<id>]]]\n"
158                 "\trename     <config>.<section>[.<option>]=<name>\n"
159                 "\trevert     <config>[.<section>[.<option>]]\n"
160                 "\treorder    <config>.<section>=<position>\n"
161                 "\n"
162                 "Options:\n"
163                 "\t-c <path>  set the search path for config files (default: /etc/config)\n"
164                 "\t-d <str>   set the delimiter for list values in uci show\n"
165                 "\t-f <file>  use <file> as input instead of stdin\n"
166                 "\t-m         when importing, merge data into an existing package\n"
167                 "\t-n         name unnamed sections on export (default)\n"
168                 "\t-N         don't name unnamed sections\n"
169                 "\t-p <path>  add a search path for config change files\n"
170                 "\t-P <path>  add a search path for config change files and use as default\n"
171                 "\t-q         quiet mode (don't print error messages)\n"
172                 "\t-s         force strict mode (stop on parser errors, default)\n"
173                 "\t-S         disable strict mode\n"
174                 "\t-X         do not use extended syntax on 'show'\n"
175                 "\n",
176                 appname
177         );
178 }
179
180 static void cli_perror(void)
181 {
182         if (flags & CLI_FLAG_QUIET)
183                 return;
184
185         uci_perror(ctx, appname);
186 }
187
188 static void cli_error(const char *fmt, ...)
189 {
190         va_list ap;
191
192         if (flags & CLI_FLAG_QUIET)
193                 return;
194
195         va_start(ap, fmt);
196         vfprintf(stderr, fmt, ap);
197         va_end(ap);
198 }
199
200 static void uci_print_value(FILE *f, const char *v)
201 {
202         fprintf(f, "'");
203         while (*v) {
204                 if (*v != '\'')
205                         fputc(*v, f);
206                 else
207                         fprintf(f, "'\\''");
208                 v++;
209         }
210         fprintf(f, "'");
211 }
212
213 static void uci_show_value(struct uci_option *o, bool quote)
214 {
215         struct uci_element *e;
216         bool sep = false;
217         char *space;
218
219         switch(o->type) {
220         case UCI_TYPE_STRING:
221                 if (quote)
222                         uci_print_value(stdout, o->v.string);
223                 else
224                         printf("%s", o->v.string);
225                 printf("\n");
226                 break;
227         case UCI_TYPE_LIST:
228                 uci_foreach_element(&o->v.list, e) {
229                         printf("%s", (sep ? delimiter : ""));
230                         space = strpbrk(e->name, " \t\r\n");
231                         if (!space && !quote)
232                                 printf("%s", e->name);
233                         else
234                                 uci_print_value(stdout, e->name);
235                         sep = true;
236                 }
237                 printf("\n");
238                 break;
239         default:
240                 printf("<unknown>\n");
241                 break;
242         }
243 }
244
245 static void uci_show_option(struct uci_option *o, bool quote)
246 {
247         printf("%s.%s.%s=",
248                 o->section->package->e.name,
249                 (cur_section_ref ? cur_section_ref : o->section->e.name),
250                 o->e.name);
251         uci_show_value(o, quote);
252 }
253
254 static void uci_show_section(struct uci_section *s)
255 {
256         struct uci_element *e;
257         const char *cname;
258         const char *sname;
259
260         cname = s->package->e.name;
261         sname = (cur_section_ref ? cur_section_ref : s->e.name);
262         printf("%s.%s=%s\n", cname, sname, s->type);
263         uci_foreach_element(&s->options, e) {
264                 uci_show_option(uci_to_option(e), true);
265         }
266 }
267
268 static void uci_show_package(struct uci_package *p)
269 {
270         struct uci_element *e;
271
272         uci_reset_typelist();
273         uci_foreach_element( &p->sections, e) {
274                 struct uci_section *s = uci_to_section(e);
275                 cur_section_ref = uci_lookup_section_ref(s);
276                 uci_show_section(s);
277         }
278         uci_reset_typelist();
279 }
280
281 static void uci_show_changes(struct uci_package *p)
282 {
283         struct uci_element *e;
284
285         uci_foreach_element(&p->saved_delta, e) {
286                 struct uci_delta *h = uci_to_delta(e);
287                 char *prefix = "";
288                 char *op = "=";
289
290                 switch(h->cmd) {
291                 case UCI_CMD_REMOVE:
292                         prefix = "-";
293                         break;
294                 case UCI_CMD_LIST_ADD:
295                         op = "+=";
296                         break;
297                 case UCI_CMD_LIST_DEL:
298                         op = "-=";
299                         break;
300                 default:
301                         break;
302                 }
303                 printf("%s%s.%s", prefix, p->e.name, h->section);
304                 if (e->name)
305                         printf(".%s", e->name);
306                 if (h->cmd != UCI_CMD_REMOVE) {
307                         printf("%s", op);
308                         uci_print_value(stdout, h->value);
309                 }
310                 printf("\n");
311         }
312 }
313
314 static int package_cmd(int cmd, char *tuple)
315 {
316         struct uci_element *e = NULL;
317         struct uci_ptr ptr;
318         int ret = 1;
319
320         if (uci_lookup_ptr(ctx, &ptr, tuple, true) != UCI_OK) {
321                 cli_perror();
322                 return 1;
323         }
324
325         e = ptr.last;
326         switch(cmd) {
327         case CMD_CHANGES:
328                 uci_show_changes(ptr.p);
329                 break;
330         case CMD_COMMIT:
331                 if (flags & CLI_FLAG_NOCOMMIT) {
332                         ret = 0;
333                         goto out;
334                 }
335                 if (uci_commit(ctx, &ptr.p, false) != UCI_OK) {
336                         cli_perror();
337                         goto out;
338                 }
339                 break;
340         case CMD_EXPORT:
341                 if (uci_export(ctx, stdout, ptr.p, true) != UCI_OK) {
342                         goto out;
343                 }
344                 break;
345         case CMD_SHOW:
346                 if (!(ptr.flags & UCI_LOOKUP_COMPLETE)) {
347                         ctx->err = UCI_ERR_NOTFOUND;
348                         cli_perror();
349                         goto out;
350                 }
351                 switch(e->type) {
352                         case UCI_TYPE_PACKAGE:
353                                 uci_show_package(ptr.p);
354                                 break;
355                         case UCI_TYPE_SECTION:
356                                 uci_show_section(ptr.s);
357                                 break;
358                         case UCI_TYPE_OPTION:
359                                 uci_show_option(ptr.o, true);
360                                 break;
361                         default:
362                                 /* should not happen */
363                                 goto out;
364                 }
365                 break;
366         }
367
368         ret = 0;
369
370 out:
371         if (ptr.p)
372                 uci_unload(ctx, ptr.p);
373         return ret;
374 }
375
376 static int uci_do_import(int argc, char **argv)
377 {
378         struct uci_package *package = NULL;
379         char *name = NULL;
380         int ret = UCI_OK;
381         bool merge = false;
382
383         if (argc > 2)
384                 return 255;
385
386         if (argc == 2)
387                 name = argv[1];
388         else if (flags & CLI_FLAG_MERGE)
389                 /* need a package to merge */
390                 return 255;
391
392         if (flags & CLI_FLAG_MERGE) {
393                 if (uci_load(ctx, name, &package) != UCI_OK)
394                         package = NULL;
395                 else
396                         merge = true;
397         }
398         ret = uci_import(ctx, input, name, &package, (name != NULL));
399         if (ret == UCI_OK) {
400                 if (merge) {
401                         ret = uci_save(ctx, package);
402                 } else {
403                         struct uci_element *e;
404                         /* loop through all config sections and overwrite existing data */
405                         uci_foreach_element(&ctx->root, e) {
406                                 struct uci_package *p = uci_to_package(e);
407                                 ret = uci_commit(ctx, &p, true);
408                         }
409                 }
410         }
411
412         if (ret != UCI_OK) {
413                 cli_perror();
414                 return 1;
415         }
416
417         return 0;
418 }
419
420 static int uci_do_package_cmd(int cmd, int argc, char **argv)
421 {
422         char **configs = NULL;
423         char **p;
424         int ret = 1;
425
426         if (argc > 2)
427                 return 255;
428
429         if (argc == 2)
430                 return package_cmd(cmd, argv[1]);
431
432         if ((uci_list_configs(ctx, &configs) != UCI_OK) || !configs) {
433                 cli_perror();
434                 goto out;
435         }
436
437         for (p = configs; *p; p++) {
438                 package_cmd(cmd, *p);
439         }
440
441         ret = 0;
442 out:
443         free(configs);
444         return ret;
445 }
446
447 static int uci_do_add(int argc, char **argv)
448 {
449         struct uci_package *p = NULL;
450         struct uci_section *s = NULL;
451         int ret;
452
453         if (argc != 3)
454                 return 255;
455
456         ret = uci_load(ctx, argv[1], &p);
457         if (ret != UCI_OK)
458                 goto done;
459
460         ret = uci_add_section(ctx, p, argv[2], &s);
461         if (ret != UCI_OK)
462                 goto done;
463
464         ret = uci_save(ctx, p);
465
466 done:
467         if (ret != UCI_OK)
468                 cli_perror();
469         else if (s)
470                 fprintf(stdout, "%s\n", s->e.name);
471
472         return ret;
473 }
474
475 static int uci_do_section_cmd(int cmd, int argc, char **argv)
476 {
477         struct uci_element *e;
478         struct uci_ptr ptr;
479         int ret = UCI_OK;
480         int dummy;
481
482         if (argc != 2)
483                 return 255;
484
485         if (uci_lookup_ptr(ctx, &ptr, argv[1], true) != UCI_OK) {
486                 cli_perror();
487                 return 1;
488         }
489
490         if (ptr.value && (cmd != CMD_SET) && (cmd != CMD_DEL) &&
491             (cmd != CMD_ADD_LIST) && (cmd != CMD_DEL_LIST) &&
492             (cmd != CMD_RENAME) && (cmd != CMD_REORDER))
493                 return 1;
494
495         e = ptr.last;
496         switch(cmd) {
497         case CMD_GET:
498                 if (!(ptr.flags & UCI_LOOKUP_COMPLETE)) {
499                         ctx->err = UCI_ERR_NOTFOUND;
500                         cli_perror();
501                         return 1;
502                 }
503                 switch(e->type) {
504                 case UCI_TYPE_SECTION:
505                         printf("%s\n", ptr.s->type);
506                         break;
507                 case UCI_TYPE_OPTION:
508                         uci_show_value(ptr.o, false);
509                         break;
510                 default:
511                         break;
512                 }
513                 /* throw the value to stdout */
514                 break;
515         case CMD_RENAME:
516                 ret = uci_rename(ctx, &ptr);
517                 break;
518         case CMD_REVERT:
519                 ret = uci_revert(ctx, &ptr);
520                 break;
521         case CMD_SET:
522                 ret = uci_set(ctx, &ptr);
523                 break;
524         case CMD_ADD_LIST:
525                 ret = uci_add_list(ctx, &ptr);
526                 break;
527         case CMD_DEL_LIST:
528                 ret = uci_del_list(ctx, &ptr);
529                 break;
530         case CMD_REORDER:
531                 if (!ptr.s || !ptr.value) {
532                         ctx->err = UCI_ERR_NOTFOUND;
533                         cli_perror();
534                         return 1;
535                 }
536                 ret = uci_reorder_section(ctx, ptr.s, strtoul(ptr.value, NULL, 10));
537                 break;
538         case CMD_DEL:
539                 if (ptr.value && !sscanf(ptr.value, "%d", &dummy))
540                         return 1;
541                 ret = uci_delete(ctx, &ptr);
542                 break;
543         }
544
545         /* no save necessary for get */
546         if ((cmd == CMD_GET) || (cmd == CMD_REVERT))
547                 return 0;
548
549         /* save changes, but don't commit them yet */
550         if (ret == UCI_OK)
551                 ret = uci_save(ctx, ptr.p);
552
553         if (ret != UCI_OK) {
554                 cli_perror();
555                 return 1;
556         }
557
558         return 0;
559 }
560
561 static int uci_batch_cmd(void)
562 {
563         char *argv[MAX_ARGS + 2];
564         char *str = NULL;
565         int ret = 0;
566         int i, j;
567
568         for(i = 0; i <= MAX_ARGS; i++) {
569                 if (i == MAX_ARGS) {
570                         cli_error("Too many arguments\n");
571                         return 1;
572                 }
573                 argv[i] = NULL;
574                 if (uci_parse_argument(ctx, input, &str, &argv[i]) != UCI_OK) {
575                         cli_perror();
576                         i = 0;
577                         break;
578                 }
579                 if (!argv[i][0])
580                         break;
581                 argv[i] = strdup(argv[i]);
582                 if (!argv[i]) {
583                         cli_error("uci: %s", strerror(errno));
584                         return 1;
585                 }
586         }
587         argv[i] = NULL;
588
589         if (i > 0) {
590                 if (!strcasecmp(argv[0], "exit"))
591                         return 254;
592                 ret = uci_cmd(i, argv);
593         } else
594                 return 0;
595
596         for (j = 0; j < i; j++) {
597                 free(argv[j]);
598         }
599
600         return ret;
601 }
602
603 static int uci_batch(void)
604 {
605         int ret = 0;
606
607         flags |= CLI_FLAG_BATCH;
608         while (!feof(input)) {
609                 struct uci_element *e, *tmp;
610
611                 ret = uci_batch_cmd();
612                 if (ret == 254)
613                         return 0;
614                 else if (ret == 255)
615                         cli_error("Unknown command\n");
616
617                 /* clean up */
618                 uci_foreach_element_safe(&ctx->root, tmp, e) {
619                         uci_unload(ctx, uci_to_package(e));
620                 }
621         }
622         flags &= ~CLI_FLAG_BATCH;
623
624         return 0;
625 }
626
627 static int uci_cmd(int argc, char **argv)
628 {
629         int cmd = 0;
630
631         if (!strcasecmp(argv[0], "batch") && !(flags & CLI_FLAG_BATCH))
632                 return uci_batch();
633         else if (!strcasecmp(argv[0], "show"))
634                 cmd = CMD_SHOW;
635         else if (!strcasecmp(argv[0], "changes"))
636                 cmd = CMD_CHANGES;
637         else if (!strcasecmp(argv[0], "export"))
638                 cmd = CMD_EXPORT;
639         else if (!strcasecmp(argv[0], "commit"))
640                 cmd = CMD_COMMIT;
641         else if (!strcasecmp(argv[0], "get"))
642                 cmd = CMD_GET;
643         else if (!strcasecmp(argv[0], "set"))
644                 cmd = CMD_SET;
645         else if (!strcasecmp(argv[0], "ren") ||
646                  !strcasecmp(argv[0], "rename"))
647                 cmd = CMD_RENAME;
648         else if (!strcasecmp(argv[0], "revert"))
649                 cmd = CMD_REVERT;
650         else if (!strcasecmp(argv[0], "reorder"))
651                 cmd = CMD_REORDER;
652         else if (!strcasecmp(argv[0], "del") ||
653                  !strcasecmp(argv[0], "delete"))
654                 cmd = CMD_DEL;
655         else if (!strcasecmp(argv[0], "import"))
656                 cmd = CMD_IMPORT;
657         else if (!strcasecmp(argv[0], "help"))
658                 cmd = CMD_HELP;
659         else if (!strcasecmp(argv[0], "add"))
660                 cmd = CMD_ADD;
661         else if (!strcasecmp(argv[0], "add_list"))
662                 cmd = CMD_ADD_LIST;
663         else if (!strcasecmp(argv[0], "del_list"))
664                 cmd = CMD_DEL_LIST;
665         else
666                 cmd = -1;
667
668         switch(cmd) {
669                 case CMD_ADD_LIST:
670                 case CMD_DEL_LIST:
671                 case CMD_GET:
672                 case CMD_SET:
673                 case CMD_DEL:
674                 case CMD_RENAME:
675                 case CMD_REVERT:
676                 case CMD_REORDER:
677                         return uci_do_section_cmd(cmd, argc, argv);
678                 case CMD_SHOW:
679                 case CMD_EXPORT:
680                 case CMD_COMMIT:
681                 case CMD_CHANGES:
682                         return uci_do_package_cmd(cmd, argc, argv);
683                 case CMD_IMPORT:
684                         return uci_do_import(argc, argv);
685                 case CMD_ADD:
686                         return uci_do_add(argc, argv);
687                 case CMD_HELP:
688                         uci_usage();
689                         return 0;
690                 default:
691                         return 255;
692         }
693 }
694
695 int main(int argc, char **argv)
696 {
697         int ret;
698         int c;
699
700         flags = CLI_FLAG_SHOW_EXT;
701         appname = argv[0];
702         input = stdin;
703         ctx = uci_alloc_context();
704         if (!ctx) {
705                 cli_error("Out of memory\n");
706                 return 1;
707         }
708
709         while((c = getopt(argc, argv, "c:d:f:LmnNp:P:sSqX")) != -1) {
710                 switch(c) {
711                         case 'c':
712                                 uci_set_confdir(ctx, optarg);
713                                 break;
714                         case 'd':
715                                 delimiter = optarg;
716                                 break;
717                         case 'f':
718                                 if (input != stdin) {
719                                         fclose(input);
720                                         cli_error("Too many input files.\n");
721                                         return 1;
722                                 }
723
724                                 input = fopen(optarg, "r");
725                                 if (!input) {
726                                         cli_error("uci: %s", strerror(errno));
727                                         return 1;
728                                 }
729                                 break;
730                         case 'm':
731                                 flags |= CLI_FLAG_MERGE;
732                                 break;
733                         case 's':
734                                 ctx->flags |= UCI_FLAG_STRICT;
735                                 break;
736                         case 'S':
737                                 ctx->flags &= ~UCI_FLAG_STRICT;
738                                 ctx->flags |= UCI_FLAG_PERROR;
739                                 break;
740                         case 'n':
741                                 ctx->flags |= UCI_FLAG_EXPORT_NAME;
742                                 break;
743                         case 'N':
744                                 ctx->flags &= ~UCI_FLAG_EXPORT_NAME;
745                                 break;
746                         case 'p':
747                                 uci_add_delta_path(ctx, optarg);
748                                 break;
749                         case 'P':
750                                 uci_add_delta_path(ctx, ctx->savedir);
751                                 uci_set_savedir(ctx, optarg);
752                                 flags |= CLI_FLAG_NOCOMMIT;
753                                 break;
754                         case 'q':
755                                 flags |= CLI_FLAG_QUIET;
756                                 break;
757                         case 'X':
758                                 flags &= ~CLI_FLAG_SHOW_EXT;
759                                 break;
760                         default:
761                                 uci_usage();
762                                 return 0;
763                 }
764         }
765         if (optind > 1)
766                 argv[optind - 1] = argv[0];
767         argv += optind - 1;
768         argc -= optind - 1;
769
770         if (argc < 2) {
771                 uci_usage();
772                 return 0;
773         }
774
775         ret = uci_cmd(argc - 1, argv + 1);
776         if (input != stdin)
777                 fclose(input);
778
779         if (ret == 255)
780                 uci_usage();
781
782         uci_free_context(ctx);
783
784         return ret;
785 }