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