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