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