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