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