]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.c
7bd427a4ca14136a6e23d2cdeed45515522b8365
[libucw.git] / ucw / opt.c
1 /*
2  *      UCW Library -- Parsing of command line options
3  *
4  *      (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
5  *      (c) 2014 Martin Mares <mj@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include <ucw/lib.h>
12 #include <ucw/opt.h>
13 #include <ucw/conf.h>
14 #include <ucw/conf-internal.h>
15 #include <ucw/fastbuf.h>
16 #include <ucw/stkstring.h>
17 #include <ucw/strtonum.h>
18
19 #include <alloca.h>
20 #include <math.h>
21
22 /***
23  * Value flags defaults
24  * ~~~~~~~~~~~~~~~~~~~~
25  *
26  * OPT_NO_VALUE for OPT_BOOL, OPT_SWITCH and OPT_INC
27  * OPT_MAYBE_VALUE for OPT_STRING, OPT_UNS, OPT_INT
28  * Some of the value flags (OPT_NO_VALUE, OPT_MAYBE_VALUE, OPT_REQUIRED_VALUE)
29  * must be specified for OPT_CALL and OPT_USER.
30  ***/
31 static uns opt_default_value_flags[] = {
32     [OPT_CL_BOOL] = OPT_NO_VALUE,
33     [OPT_CL_STATIC] = OPT_MAYBE_VALUE,
34     [OPT_CL_SWITCH] = OPT_NO_VALUE,
35     [OPT_CL_INC] = OPT_NO_VALUE,
36     [OPT_CL_CALL] = 0,
37     [OPT_CL_USER] = 0,
38     [OPT_CL_SECTION] = 0,
39     [OPT_CL_HELP] = 0
40 };
41
42 struct opt_precomputed {
43   struct opt_item * item;
44   const char * name;
45   short flags;
46   short count;
47 };
48
49 struct opt_context {
50   struct opt_precomputed * opts;
51   struct opt_precomputed ** shortopt;
52   struct opt_item ** hooks_before_arg;
53   struct opt_item ** hooks_before_value;
54   struct opt_item ** hooks_after_value;
55   short opt_count;
56   short hooks_before_arg_count;
57   short hooks_before_value_count;
58   short hooks_after_value_count;
59   int positional_max;
60   int positional_count;
61 };
62
63 static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2) NONRET;
64 static void opt_failure(const char * mesg, ...) {
65   va_list args;
66   va_start(args, mesg);
67   vfprintf(stderr, mesg, args);
68   fprintf(stderr, "\n");
69   opt_usage();
70   exit(OPT_EXIT_BAD_ARGS);
71   va_end(args);         // FIXME: Does this make a sense after exit()?
72 }
73
74 #define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
75
76 static inline uns uns_min(uns x, uns y)
77 {
78   return MIN(x, y);
79 }
80
81 void opt_help(const struct opt_section * help) {
82   int sections_cnt = 0;
83   int lines_cnt = 0;
84
85   for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
86     if (item->flags & OPT_NO_HELP) continue;
87     if (item->cls == OPT_CL_SECTION) {
88       sections_cnt++;
89       continue;
90     }
91     if (!*(item->help)) {
92       lines_cnt++;
93       continue;
94     }
95     FOREACHLINE(item->help)
96       lines_cnt++;
97   }
98
99   struct opt_sectlist {
100     int pos;
101     struct opt_section * sect;
102   } sections[sections_cnt];
103   int s = 0;
104
105   const char *lines[lines_cnt][3];
106   memset(lines, 0, sizeof(lines));
107   int line = 0;
108
109   int linelengths[3] = { -1, -1, -1 };
110
111   for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
112     if (item->flags & OPT_NO_HELP) continue;
113
114     if (item->cls == OPT_CL_HELP) {
115       if (!*(item->help)) {
116         line++;
117         continue;
118       }
119 #define SPLITLINES(text) do { \
120       FOREACHLINE(text) { \
121         int cell = 0; \
122         for (const char * b = begin, * e = begin; (e < end) && (e = strchrnul(b, '\t')) && (e > end ? (e = end) : end); b = e+1) { \
123           lines[line][cell] = b; \
124           if (cell >= 2) \
125             break; \
126           else \
127             if (*e == '\t' && linelengths[cell] < (e - b)) \
128               linelengths[cell] = e-b; \
129           cell++; \
130         } \
131         line++; \
132       } } while (0)
133       SPLITLINES(item->help);
134       continue;
135     }
136
137     if (item->cls == OPT_CL_SECTION) {
138       sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
139       continue;
140     }
141
142     uns valoff = strchrnul(item->help, '\t') - item->help;
143     uns eol = strchrnul(item->help, '\n') - item->help;
144     if (valoff > eol)
145       valoff = eol;
146 #define VAL(it) ((it->flags & OPT_REQUIRED_VALUE) ? stk_printf("=%.*s", valoff, item->help)  : ((it->flags & OPT_NO_VALUE) ? "" : stk_printf("(=%.*s)", valoff, item->help)))
147     if (item->name) {
148       lines[line][1] = stk_printf("--%s%s", item->name, VAL(item));
149       if (linelengths[1] < (int) strlen(lines[line][1]))
150         linelengths[1] = strlen(lines[line][1]);
151       lines[line][0] = "";
152       if (linelengths[0] < 0)
153         linelengths[0] = 0;
154     }
155     if (item->letter) {
156       lines[line][0] = stk_printf("-%c,", item->letter);
157       if (linelengths[0] < (int) strlen(lines[line][0]))
158         linelengths[0] = strlen(lines[line][0]);
159     }
160 #undef VAL
161
162     if (eol > valoff) {
163       lines[line][2] = item->help + valoff + 1;
164     }
165
166     line++;
167
168     if (*(item->help + eol))
169       SPLITLINES(item->help + eol + 1);
170   }
171 #undef SPLITLINES
172
173   s = 0;
174 #define FIELD(k) linelengths[k], uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
175 #define LASTFIELD(k) uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
176   for (int i=0;i<line;i++) {
177     while (s < sections_cnt && sections[s].pos == i) {
178       opt_help(sections[s].sect);
179       s++;
180     }
181     if (lines[i][0] == NULL)
182       printf("\n");
183     else if (linelengths[0] == -1 || lines[i][1] == NULL)
184       printf("%.*s\n", LASTFIELD(0));
185     else if (linelengths[1] == -1 || lines[i][2] == NULL)
186       printf("%-*.*s  %.*s\n", FIELD(0), LASTFIELD(1));
187     else
188       printf("%-*.*s  %-*.*s  %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
189   }
190   while (s < sections_cnt && sections[s].pos == line) {
191     opt_help(sections[s].sect);
192     s++;
193   }
194 }
195
196 static struct opt_precomputed * opt_find_item_longopt(struct opt_context * oc, char * str) {
197   uns len = strlen(str);
198   struct opt_precomputed * candidate = NULL;
199
200   for (int i = 0; i < oc->opt_count; i++) {
201     struct opt_precomputed *opt = &oc->opts[i];
202     if (!opt->name)
203       continue;
204
205     if (!strncmp(opt->name, str, len)) {
206       if (strlen(opt->name) == len)
207         return opt;
208     } else if (opt->item->cls == OPT_CL_BOOL && !strncmp("no-", str, 3) && !strncmp(opt->name, str+3, len-3)) {
209       if (strlen(opt->name) == len-3)
210         return opt;
211     } else
212       continue;
213
214     if (candidate)
215       opt_failure("Ambiguous option --%s: matches both --%s and --%s.", str, candidate->name, opt->name);
216     else
217       candidate = opt;
218   }
219
220   if (candidate)
221     return candidate;
222
223   opt_failure("Invalid option --%s.", str);
224 }
225
226 #define OPT_PTR(type) ({ \
227   type * ptr; \
228   if (item->flags & OPT_MULTIPLE) { \
229     struct { \
230       cnode n; \
231       type v; \
232     } * n = xmalloc(sizeof(*n)); \
233     clist_add_tail(item->ptr, &(n->n)); \
234     ptr = &(n->v); \
235   } else \
236     ptr = item->ptr; \
237   ptr; })
238
239 #define OPT_NAME (longopt == 2 ? stk_printf("positional arg #%d", oc->positional_count) : (longopt == 1 ? stk_printf("--%s", opt->name) : stk_printf("-%c", item->letter)))
240 static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value, int longopt) {
241   struct opt_item * item = opt->item;
242   for (int i=0;i<oc->hooks_before_value_count;i++)
243     oc->hooks_before_value[i]->u.call(item, value, oc->hooks_before_value[i]->ptr);
244
245   switch (item->cls) {
246     case OPT_CL_BOOL:
247       if (!value || !strcasecmp(value, "y") || !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "1"))
248         *((int *) item->ptr) = 1 ^ (!!(opt->flags & OPT_NEGATIVE));
249       else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
250         *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
251       else
252         opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
253       break;
254     case OPT_CL_STATIC:
255       {
256         char * e = NULL;
257         switch (item->type) {
258           case CT_INT:
259             if (!value)
260               *OPT_PTR(int) = 0;
261             else
262               e = cf_parse_int(value, OPT_PTR(int));
263             if (e)
264               opt_failure("Integer value parsing failed for %s: %s", OPT_NAME, e);
265             break;
266           case CT_U64:
267             if (!value)
268               *OPT_PTR(u64) = 0;
269             else
270               e = cf_parse_u64(value, OPT_PTR(u64));
271             if (e)
272               opt_failure("Unsigned 64-bit value parsing failed for %s: %s", OPT_NAME, e);
273             break;
274           case CT_DOUBLE:
275             if (!value)
276               *OPT_PTR(double) = NAN;
277             else
278               e = cf_parse_double(value, OPT_PTR(double));
279             if (e)
280               opt_failure("Double value parsing failed for %s: %s", OPT_NAME, e);
281             break;
282           case CT_IP:
283             if (!value)
284               e = cf_parse_ip("0.0.0.0", OPT_PTR(u32));
285             else
286               e = cf_parse_ip(value, OPT_PTR(u32));
287             if (e)
288               opt_failure("IP parsing failed for %s: %s", OPT_NAME, e);
289             break;
290           case CT_STRING:
291             if (!value)
292               *OPT_PTR(const char *) = NULL;
293             else
294               *OPT_PTR(const char *) = xstrdup(value);
295             break;
296           default:
297             ASSERT(0);
298         }
299         break;
300       }
301     case OPT_CL_SWITCH:
302       if (*((int *)item->ptr) != -1)
303         opt_failure("Multiple switches: %s", OPT_NAME);
304       else
305         *((int *)item->ptr) = item->u.value;
306       break;
307     case OPT_CL_INC:
308       if (opt->flags & OPT_NEGATIVE)
309         (*((int *)item->ptr))--;
310       else
311         (*((int *)item->ptr))++;
312       break;
313     case OPT_CL_CALL:
314       item->u.call(item, value, item->ptr);
315       break;
316     case OPT_CL_USER:
317       {
318         char * e = NULL;
319         e = item->u.utype->parser(value, OPT_PTR(void*));
320         if (e)
321           opt_failure("User defined type value parsing failed for %s: %s", OPT_NAME, e);
322         break;
323       }
324     default:
325       ASSERT(0);
326   }
327
328   for (int i=0;i<oc->hooks_after_value_count;i++)
329     oc->hooks_after_value[i]->u.call(item, value, oc->hooks_after_value[i]->ptr);
330 }
331 #undef OPT_NAME
332
333 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
334   int eaten = 0;
335   char * name_in = argv[index] + 2; // skipping the -- on the beginning
336   uns pos = strchrnul(name_in, '=') - name_in;
337   struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos));
338   char * value = NULL;
339
340   // FIXME: Move to opt_parse_value()?
341   if (opt->count++ && (opt->flags & OPT_SINGLE))
342     opt_failure("Option --%s must be specified at most once.", opt->name);
343
344   if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3)) {
345     if (name_in[pos])
346       opt_failure("Option --%s must not have any value.", name_in);
347     value = "n";
348   } else if (opt->flags & OPT_REQUIRED_VALUE) {
349     if (name_in[pos])
350       value = name_in + pos + 1;
351     else {
352       value = argv[index+1];
353       if (!value)
354         opt_failure("Option --%s must have a value, but nothing supplied.", opt->name);
355       eaten++;
356     }
357   } else if (opt->flags & OPT_MAYBE_VALUE) {
358     if (name_in[pos])
359       value = name_in + pos + 1;
360   } else {
361     if (name_in[pos])
362       opt_failure("Option --%s must have no value.", opt->name);
363   }
364   opt_parse_value(oc, opt, value, 1);
365   return eaten;
366 }
367
368 static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
369   int chr = 0;
370   struct opt_precomputed * opt;
371   int o;
372
373   while (o = argv[index][++chr]) {
374     if (o < 0 || o >= 128)
375       opt_failure("Invalid character 0x%02x in option name. Only ASCII is allowed.", o & 0xff);
376     opt = oc->shortopt[o];
377
378     if (!opt)
379       opt_failure("Unknown option -%c.", o);
380
381     if (opt->count && (opt->flags & OPT_SINGLE))
382       opt_failure("Option -%c must be specified at most once.", o);
383     opt->count++;
384
385     if (opt->flags & OPT_NO_VALUE)
386       opt_parse_value(oc, opt, NULL, 0);
387     else if (opt->flags & OPT_REQUIRED_VALUE) {
388       if (argv[index][chr+1]) {
389         opt_parse_value(oc, opt, argv[index] + chr + 1, 0);
390         return 0;
391       } else if (!argv[index+1])
392         opt_failure("Option -%c must have a value, but nothing supplied.", o);
393       else {
394         opt_parse_value(oc, opt, argv[index+1], 0);
395         return 1;
396       }
397     } else if (opt->flags & OPT_MAYBE_VALUE) {
398       if (argv[index][chr+1]) {
399         opt_parse_value(oc, opt, argv[index] + chr + 1, 0);
400         return 0;
401       } else
402         opt_parse_value(oc, opt, NULL, 0);
403     } else {
404       ASSERT(0);
405     }
406   }
407
408   return 0;
409 }
410
411 static void opt_positional(struct opt_context * oc, char * value) {
412   oc->positional_count++;
413   uns id = oc->positional_count > oc->positional_max ? OPT_POSITIONAL_TAIL : OPT_POSITIONAL(oc->positional_count);
414   struct opt_precomputed * opt = oc->shortopt[id];
415   if (!opt || (opt->flags & OPT_SINGLE) && opt->count)
416     opt_failure("Too many positional arguments.");
417   else {
418     opt->count++;
419     opt_parse_value(oc, opt, value, 2);
420   }
421 }
422
423 static void opt_count_items(struct opt_context *oc, const struct opt_section *sec)
424 {
425   for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
426     if (item->cls == OPT_CL_SECTION)
427       opt_count_items(oc, item->u.section);
428     else if (item->cls == OPT_CL_HOOK) {
429       if (item->flags & OPT_HOOK_BEFORE_ARG)
430         oc->hooks_before_arg_count++;
431       else if (item->flags & OPT_HOOK_BEFORE_VALUE)
432         oc->hooks_before_value_count++;
433       else if (item->flags & OPT_HOOK_AFTER_VALUE)
434         oc->hooks_after_value_count++;
435       else
436         ASSERT(0);
437     } else if (item->letter || item->name) {
438       oc->opt_count++;
439       if (item->letter > OPT_POSITIONAL_TAIL)
440         oc->positional_max++;
441     }
442   }
443 }
444
445 static void opt_add_default_flags(struct opt_precomputed *opt)
446 {
447   struct opt_item *item = opt->item;
448   uns flags = opt->flags;
449
450   if (item->letter >= OPT_POSITIONAL_TAIL) {
451     flags &= ~OPT_VALUE_FLAGS;
452     flags |= OPT_REQUIRED_VALUE;
453   }
454   if (!(flags & OPT_VALUE_FLAGS)) {
455     ASSERT(item->cls != OPT_CL_CALL && item->cls != OPT_CL_USER);
456     flags |= opt_default_value_flags[item->cls];
457   }
458
459   opt->flags = flags;
460 }
461
462 static void opt_prepare_items(struct opt_context *oc, const struct opt_section *sec)
463 {
464   for (struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
465     if (item->cls == OPT_CL_SECTION)
466       opt_prepare_items(oc, item->u.section);
467     else if (item->cls == OPT_CL_HOOK) {
468       if (item->flags & OPT_HOOK_BEFORE_ARG)
469         oc->hooks_before_arg[oc->hooks_before_arg_count++] = item;
470       else if (item->flags & OPT_HOOK_BEFORE_VALUE)
471         oc->hooks_before_value[oc->hooks_before_value_count++] = item;
472       else if (item->flags & OPT_HOOK_AFTER_VALUE)
473         oc->hooks_after_value[oc->hooks_after_value_count++] = item;
474       else
475         ASSERT(0);
476     } else if (item->letter || item->name) {
477       struct opt_precomputed * opt = &oc->opts[oc->opt_count++];
478       opt->item = item;
479       opt->flags = item->flags;
480       opt->count = 0;
481       opt->name = item->name;
482       if (item->letter)
483         oc->shortopt[(int) item->letter] = opt;
484       opt_add_default_flags(opt);
485     }
486   }
487 }
488
489 static void opt_check_required(struct opt_context *oc)
490 {
491   for (int i = 0; i < oc->opt_count; i++) {
492     struct opt_precomputed *opt = &oc->opts[i];
493     if (!opt->count && (opt->flags & OPT_REQUIRED)) {
494       struct opt_item *item = opt->item;
495       if (item->letter > OPT_POSITIONAL_TAIL)
496         opt_failure("Required positional argument #%d not found.", i - OPT_POSITIONAL_TAIL);
497       else if (item->letter == OPT_POSITIONAL_TAIL)
498         opt_failure("Required positional argument not found.");
499       else if (item->letter && item->name)
500         opt_failure("Required option -%c/--%s not found.", item->letter, item->name);
501       else if (item->letter)
502         opt_failure("Required option -%c not found.", item->letter);
503       else
504         opt_failure("Required option --%s not found.", item->name);
505     }
506   }
507 }
508
509 void opt_parse(const struct opt_section * options, char ** argv) {
510   struct opt_context * oc = alloca(sizeof(*oc));
511   memset(oc, 0, sizeof (*oc));
512
513   opt_count_items(oc, options);
514   oc->opts = alloca(sizeof(*oc->opts) * oc->opt_count);
515   oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + 257));
516   memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + 257));
517   oc->hooks_before_arg = alloca(sizeof (*oc->hooks_before_arg) * oc->hooks_before_arg_count);
518   oc->hooks_before_value = alloca(sizeof (*oc->hooks_before_value) * oc->hooks_before_value_count);
519   oc->hooks_after_value = alloca(sizeof (*oc->hooks_after_value) * oc->hooks_after_value_count);
520
521   oc->opt_count = 0;
522   oc->hooks_before_arg_count = 0;
523   oc->hooks_before_value_count = 0;
524   oc->hooks_after_value_count = 0;
525   opt_prepare_items(oc, options);
526
527   int force_positional = 0;
528   for (int i = 0; argv[i]; i++) {
529     char *arg = argv[i];
530     for (int j = 0; j < oc->hooks_before_arg_count; j++)
531       oc->hooks_before_arg[j]->u.call(NULL, NULL, oc->hooks_before_arg[j]->ptr);
532     if (arg[0] != '-' || force_positional)
533       opt_positional(oc, arg);
534     else {
535       if (arg[1] == '-') {
536         if (arg[2] == '\0')
537           force_positional++;
538         else
539           i += opt_longopt(oc, argv, i);
540       } else if (arg[1])
541         i += opt_shortopt(oc, argv, i);
542       else
543         opt_positional(oc, arg);
544     }
545   }
546
547   opt_check_required(oc);
548 }
549
550 static void opt_conf_end_of_options(struct cf_context *cc) {
551   cf_load_default(cc);
552   if (cc->postpone_commit && cf_close_group())
553     opt_failure("Loading of configuration failed");
554 }
555
556 void opt_conf_internal(struct opt_item * opt, const char * value, void * data UNUSED) {
557   struct cf_context *cc = cf_get_context();
558   switch (opt->letter) {
559     case 'S':
560       cf_load_default(cc);
561       if (cf_set(value))
562         opt_failure("Cannot set %s", value);
563       break;
564     case 'C':
565       if (cf_load(value))
566         opt_failure("Cannot load config file %s", value);
567       break;
568 #ifdef CONFIG_UCW_DEBUG
569     case '0':
570       opt_conf_end_of_options(cc);
571       struct fastbuf *b = bfdopen(1, 4096);
572       cf_dump_sections(b);
573       bclose(b);
574       exit(0);
575       break;
576 #endif
577   }
578 }
579
580 void opt_conf_hook_internal(struct opt_item * opt, const char * value UNUSED, void * data UNUSED) {
581   static enum {
582     OPT_CONF_HOOK_BEGIN,
583     OPT_CONF_HOOK_CONFIG,
584     OPT_CONF_HOOK_OTHERS
585   } state = OPT_CONF_HOOK_BEGIN;
586
587   int confopt = 0;
588
589   if (opt->letter == 'S' || opt->letter == 'C' || (opt->name && !strcmp(opt->name, "dumpconfig")))
590     confopt = 1;
591
592   switch (state) {
593     case OPT_CONF_HOOK_BEGIN:
594       if (confopt)
595         state = OPT_CONF_HOOK_CONFIG;
596       else {
597         opt_conf_end_of_options(cf_get_context());
598         state = OPT_CONF_HOOK_OTHERS;
599       }
600       break;
601     case OPT_CONF_HOOK_CONFIG:
602       if (!confopt) {
603         opt_conf_end_of_options(cf_get_context());
604         state = OPT_CONF_HOOK_OTHERS;
605       }
606       break;
607     case OPT_CONF_HOOK_OTHERS:
608       if (confopt)
609         opt_failure("Config options (-C, -S) must stand before other options.");
610       break;
611     default:
612       ASSERT(0);
613   }
614 }