libbb: getopt32() should not ever touch argv[0] (even read)
[oweals/busybox.git] / libbb / getopt32.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * universal getopt32 implementation for busybox
4  *
5  * Copyright (C) 2003-2005  Vladimir Oleynik  <dzo@simtreas.ru>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 #include <getopt.h>
11 #include "libbb.h"
12
13 /*      Documentation
14
15 uint32_t
16 getopt32(char **argv, const char *applet_opts, ...)
17
18         The command line options must be declared in const char
19         *applet_opts as a string of chars, for example:
20
21         flags = getopt32(argv, "rnug");
22
23         If one of the given options is found, a flag value is added to
24         the return value (an unsigned long).
25
26         The flag value is determined by the position of the char in
27         applet_opts string.  For example, in the above case:
28
29         flags = getopt32(argv, "rnug");
30
31         "r" will add 1    (bit 0)
32         "n" will add 2    (bit 1)
33         "u" will add 4    (bit 2)
34         "g" will add 8    (bit 3)
35
36         and so on.  You can also look at the return value as a bit
37         field and each option sets one bit.
38
39         On exit, global variable optind is set so that if you
40         will do argc -= optind; argv += optind; then
41         argc will be equal to number of remaining non-option
42         arguments, first one would be in argv[0], next in argv[1] and so on
43         (options and their parameters will be moved into argv[]
44         positions prior to argv[optind]).
45
46  ":"    If one of the options requires an argument, then add a ":"
47         after the char in applet_opts and provide a pointer to store
48         the argument.  For example:
49
50         char *pointer_to_arg_for_a;
51         char *pointer_to_arg_for_b;
52         char *pointer_to_arg_for_c;
53         char *pointer_to_arg_for_d;
54
55         flags = getopt32(argv, "a:b:c:d:",
56                         &pointer_to_arg_for_a, &pointer_to_arg_for_b,
57                         &pointer_to_arg_for_c, &pointer_to_arg_for_d);
58
59         The type of the pointer (char* or llist_t*) may be controlled
60         by the "::" special separator that is set in the external string
61         opt_complementary (see below for more info).
62
63  "::"   If option can have an *optional* argument, then add a "::"
64         after its char in applet_opts and provide a pointer to store
65         the argument.  Note that optional arguments _must_
66         immediately follow the option: -oparam, not -o param.
67
68  "+"    If the first character in the applet_opts string is a plus,
69         then option processing will stop as soon as a non-option is
70         encountered in the argv array.  Useful for applets like env
71         which should not process arguments to subprograms:
72         env -i ls -d /
73         Here we want env to process just the '-i', not the '-d'.
74
75 const char *applet_long_options
76
77         This struct allows you to define long options:
78
79         static const char applet_longopts[] ALIGN1 =
80                 //"name\0" has_arg val
81                 "verbose\0" No_argument "v"
82                 ;
83         applet_long_options = applet_longopts;
84
85         The last member of struct option (val) typically is set to
86         matching short option from applet_opts. If there is no matching
87         char in applet_opts, then:
88         - return bit have next position after short options
89         - if has_arg is not "No_argument", use ptr for arg also
90         - opt_complementary affects it too
91
92         Note: a good applet will make long options configurable via the
93         config process and not a required feature.  The current standard
94         is to name the config option CONFIG_FEATURE_<applet>_LONG_OPTIONS.
95
96 const char *opt_complementary
97
98  ":"    The colon (":") is used to separate groups of two or more chars
99         and/or groups of chars and special characters (stating some
100         conditions to be checked).
101
102  "abc"  If groups of two or more chars are specified, the first char
103         is the main option and the other chars are secondary options.
104         Their flags will be turned on if the main option is found even
105         if they are not specifed on the command line.  For example:
106
107         opt_complementary = "abc";
108         flags = getopt32(argv, "abcd")
109
110         If getopt() finds "-a" on the command line, then
111         getopt32's return value will be as if "-a -b -c" were
112         found.
113
114  "ww"   Adjacent double options have a counter associated which indicates
115         the number of occurences of the option.
116         For example the ps applet needs:
117         if w is given once, GNU ps sets the width to 132,
118         if w is given more than once, it is "unlimited"
119
120         int w_counter = 0; // must be initialized!
121         opt_complementary = "ww";
122         getopt32(argv, "w", &w_counter);
123         if (w_counter)
124                 width = (w_counter == 1) ? 132 : INT_MAX;
125         else
126                 get_terminal_width(...&width...);
127
128         w_counter is a pointer to an integer. It has to be passed to
129         getopt32() after all other option argument sinks.
130
131         For example: accept multiple -v to indicate the level of verbosity
132         and for each -b optarg, add optarg to my_b. Finally, if b is given,
133         turn off c and vice versa:
134
135         llist_t *my_b = NULL;
136         int verbose_level = 0;
137         opt_complementary = "vv:b::b-c:c-b";
138         f = getopt32(argv, "vb:c", &my_b, &verbose_level);
139         if (f & 2)       // -c after -b unsets -b flag
140                 while (my_b) dosomething_with(llist_pop(&my_b));
141         if (my_b)        // but llist is stored if -b is specified
142                 free_llist(my_b);
143         if (verbose_level) printf("verbose level is %d\n", verbose_level);
144
145 Special characters:
146
147  "-"    A dash as the first char in a opt_complementary group forces
148         all arguments to be treated as options, even if they have
149         no leading dashes. Next char in this case can't be a digit (0-9),
150         use ':' or end of line. For example:
151
152         opt_complementary = "-:w-x:x-w";
153         getopt32(argv, "wx");
154
155         Allows any arguments to be given without a dash (./program w x)
156         as well as with a dash (./program -x).
157
158  "--"   A double dash at the beginning of opt_complementary means the
159         argv[1] string should always be treated as options, even if it isn't
160         prefixed with a "-".  This is useful for special syntax in applets
161         such as "ar" and "tar":
162         tar xvf foo.tar
163
164  "-N"   A dash as the first char in a opt_complementary group followed
165         by a single digit (0-9) means that at least N non-option
166         arguments must be present on the command line
167
168  "=N"   An equal sign as the first char in a opt_complementary group followed
169         by a single digit (0-9) means that exactly N non-option
170         arguments must be present on the command line
171
172  "?N"   A "?" as the first char in a opt_complementary group followed
173         by a single digit (0-9) means that at most N arguments must be present
174         on the command line.
175
176  "V-"   An option with dash before colon or end-of-line results in
177         bb_show_usage() being called if this option is encountered.
178         This is typically used to implement "print verbose usage message
179         and exit" option.
180
181  "a-b"  A dash between two options causes the second of the two
182         to be unset (and ignored) if it is given on the command line.
183
184         [FIXME: what if they are the same? like "x-x"? Is it ever useful?]
185
186         For example:
187         The du applet has the options "-s" and "-d depth".  If
188         getopt32 finds -s, then -d is unset or if it finds -d
189         then -s is unset.  (Note:  busybox implements the GNU
190         "--max-depth" option as "-d".)  To obtain this behavior, you
191         set opt_complementary = "s-d:d-s".  Only one flag value is
192         added to getopt32's return value depending on the
193         position of the options on the command line.  If one of the
194         two options requires an argument pointer (":" in applet_opts
195         as in "d:") optarg is set accordingly.
196
197         char *smax_print_depth;
198
199         opt_complementary = "s-d:d-s:x-x";
200         opt = getopt32(argv, "sd:x", &smax_print_depth);
201
202         if (opt & 2)
203                 max_print_depth = atoi(smax_print_depth);
204         if (opt & 4)
205                 printf("Detected odd -x usage\n");
206
207  "a--b" A double dash between two options, or between an option and a group
208         of options, means that they are mutually exclusive.  Unlike
209         the "-" case above, an error will be forced if the options
210         are used together.
211
212         For example:
213         The cut applet must have only one type of list specified, so
214         -b, -c and -f are mutually exclusive and should raise an error
215         if specified together.  In this case you must set
216         opt_complementary = "b--cf:c--bf:f--bc".  If two of the
217         mutually exclusive options are found, getopt32 will call
218         bb_show_usage() and die.
219
220  "x--x" Variation of the above, it means that -x option should occur
221         at most once.
222
223  "a+"   A plus after a char in opt_complementary means that the parameter
224         for this option is a nonnegative integer. It will be processed
225         with xatoi_u() - allowed range is 0..INT_MAX.
226
227         int param;  // "unsigned param;" will also work
228         opt_complementary = "p+";
229         getopt32(argv, "p:", &param);
230
231  "a::"  A double colon after a char in opt_complementary means that the
232         option can occur multiple times. Each occurrence will be saved as
233         a llist_t element instead of char*.
234
235         For example:
236         The grep applet can have one or more "-e pattern" arguments.
237         In this case you should use getopt32() as follows:
238
239         llist_t *patterns = NULL;
240
241         (this pointer must be initializated to NULL if the list is empty
242         as required by llist_add_to_end(llist_t **old_head, char *new_item).)
243
244         opt_complementary = "e::";
245
246         getopt32(argv, "e:", &patterns);
247         $ grep -e user -e root /etc/passwd
248         root:x:0:0:root:/root:/bin/bash
249         user:x:500:500::/home/user:/bin/bash
250
251  "a?b"  A "?" between an option and a group of options means that
252         at least one of them is required to occur if the first option
253         occurs in preceding command line arguments.
254
255         For example from "id" applet:
256
257         // Don't allow -n -r -rn -ug -rug -nug -rnug
258         opt_complementary = "r?ug:n?ug:u--g:g--u";
259         flags = getopt32(argv, "rnug");
260
261         This example allowed only:
262         $ id; id -u; id -g; id -ru; id -nu; id -rg; id -ng; id -rnu; id -rng
263
264  "X"    A opt_complementary group with just a single letter means
265         that this option is required. If more than one such group exists,
266         at least one option is required to occur (not all of them).
267         For example from "start-stop-daemon" applet:
268
269         // Don't allow -KS -SK, but -S or -K is required
270         opt_complementary = "K:S:K--S:S--K";
271         flags = getopt32(argv, "KS...);
272
273
274         Don't forget to use ':'. For example, "?322-22-23X-x-a"
275         is interpreted as "?3:22:-2:2-2:2-3Xa:2--x" -
276         max 3 args; count uses of '-2'; min 2 args; if there is
277         a '-2' option then unset '-3', '-X' and '-a'; if there is
278         a '-2' and after it a '-x' then error out.
279         But it's far too obfuscated. Use ':' to separate groups.
280 */
281
282 /* Code here assumes that 'unsigned' is at least 32 bits wide */
283
284 const char *const bb_argv_dash[] = { "-", NULL };
285
286 const char *opt_complementary;
287
288 enum {
289         PARAM_STRING,
290         PARAM_LIST,
291         PARAM_INT,
292 };
293
294 typedef struct {
295         unsigned char opt_char;
296         smallint param_type;
297         unsigned switch_on;
298         unsigned switch_off;
299         unsigned incongruously;
300         unsigned requires;
301         void **optarg;  /* char**, llist_t** or int *. */
302         int *counter;
303 } t_complementary;
304
305 /* You can set applet_long_options for parse called long options */
306 #if ENABLE_GETOPT_LONG
307 static const struct option bb_null_long_options[1] = {
308         { 0, 0, 0, 0 }
309 };
310 const char *applet_long_options;
311 #endif
312
313 uint32_t option_mask32;
314
315 uint32_t FAST_FUNC
316 getopt32(char **argv, const char *applet_opts, ...)
317 {
318         int argc;
319         unsigned flags = 0;
320         unsigned requires = 0;
321         t_complementary complementary[33]; /* last stays zero-filled */
322         int c;
323         const unsigned char *s;
324         t_complementary *on_off;
325         va_list p;
326 #if ENABLE_GETOPT_LONG
327         const struct option *l_o;
328         struct option *long_options = (struct option *) &bb_null_long_options;
329 #endif
330         unsigned trigger;
331         char **pargv;
332         int min_arg = 0;
333         int max_arg = -1;
334
335 #define SHOW_USAGE_IF_ERROR     1
336 #define ALL_ARGV_IS_OPTS        2
337 #define FIRST_ARGV_IS_OPT       4
338
339         int spec_flgs = 0;
340
341         /* skip 0: some applets cheat: they do not actually HAVE argv[0] */
342         argc = 1;
343         while (argv[argc])
344                 argc++;
345
346         va_start(p, applet_opts);
347
348         c = 0;
349         on_off = complementary;
350         memset(on_off, 0, sizeof(complementary));
351
352         /* skip GNU extension */
353         s = (const unsigned char *)applet_opts;
354         if (*s == '+' || *s == '-')
355                 s++;
356         while (*s) {
357                 if (c >= 32)
358                         break;
359                 on_off->opt_char = *s;
360                 on_off->switch_on = (1 << c);
361                 if (*++s == ':') {
362                         on_off->optarg = va_arg(p, void **);
363                         while (*++s == ':')
364                                 continue;
365                 }
366                 on_off++;
367                 c++;
368         }
369
370 #if ENABLE_GETOPT_LONG
371         if (applet_long_options) {
372                 const char *optstr;
373                 unsigned i, count;
374
375                 count = 1;
376                 optstr = applet_long_options;
377                 while (optstr[0]) {
378                         optstr += strlen(optstr) + 3; /* skip NUL, has_arg, val */
379                         count++;
380                 }
381                 /* count == no. of longopts + 1 */
382                 long_options = alloca(count * sizeof(*long_options));
383                 memset(long_options, 0, count * sizeof(*long_options));
384                 i = 0;
385                 optstr = applet_long_options;
386                 while (--count) {
387                         long_options[i].name = optstr;
388                         optstr += strlen(optstr) + 1;
389                         long_options[i].has_arg = (unsigned char)(*optstr++);
390                         /* long_options[i].flag = NULL; */
391                         long_options[i].val = (unsigned char)(*optstr++);
392                         i++;
393                 }
394                 for (l_o = long_options; l_o->name; l_o++) {
395                         if (l_o->flag)
396                                 continue;
397                         for (on_off = complementary; on_off->opt_char; on_off++)
398                                 if (on_off->opt_char == l_o->val)
399                                         goto next_long;
400                         if (c >= 32)
401                                 break;
402                         on_off->opt_char = l_o->val;
403                         on_off->switch_on = (1 << c);
404                         if (l_o->has_arg != no_argument)
405                                 on_off->optarg = va_arg(p, void **);
406                         c++;
407  next_long: ;
408                 }
409         }
410 #endif /* ENABLE_GETOPT_LONG */
411         for (s = (const unsigned char *)opt_complementary; s && *s; s++) {
412                 t_complementary *pair;
413                 unsigned *pair_switch;
414
415                 if (*s == ':')
416                         continue;
417                 c = s[1];
418                 if (*s == '?') {
419                         if (c < '0' || c > '9') {
420                                 spec_flgs |= SHOW_USAGE_IF_ERROR;
421                         } else {
422                                 max_arg = c - '0';
423                                 s++;
424                         }
425                         continue;
426                 }
427                 if (*s == '-') {
428                         if (c < '0' || c > '9') {
429                                 if (c == '-') {
430                                         spec_flgs |= FIRST_ARGV_IS_OPT;
431                                         s++;
432                                 } else
433                                         spec_flgs |= ALL_ARGV_IS_OPTS;
434                         } else {
435                                 min_arg = c - '0';
436                                 s++;
437                         }
438                         continue;
439                 }
440                 if (*s == '=') {
441                         min_arg = max_arg = c - '0';
442                         s++;
443                         continue;
444                 }
445                 for (on_off = complementary; on_off->opt_char; on_off++)
446                         if (on_off->opt_char == *s)
447                                 break;
448                 if (c == ':' && s[2] == ':') {
449                         on_off->param_type = PARAM_LIST;
450                         continue;
451                 }
452                 if (c == '+' && (s[2] == ':' || s[2] == '\0')) {
453                         on_off->param_type = PARAM_INT;
454                         continue;
455                 }
456                 if (c == ':' || c == '\0') {
457                         requires |= on_off->switch_on;
458                         continue;
459                 }
460                 if (c == '-' && (s[2] == ':' || s[2] == '\0')) {
461                         flags |= on_off->switch_on;
462                         on_off->incongruously |= on_off->switch_on;
463                         s++;
464                         continue;
465                 }
466                 if (c == *s) {
467                         on_off->counter = va_arg(p, int *);
468                         s++;
469                 }
470                 pair = on_off;
471                 pair_switch = &(pair->switch_on);
472                 for (s++; *s && *s != ':'; s++) {
473                         if (*s == '?') {
474                                 pair_switch = &(pair->requires);
475                         } else if (*s == '-') {
476                                 if (pair_switch == &(pair->switch_off))
477                                         pair_switch = &(pair->incongruously);
478                                 else
479                                         pair_switch = &(pair->switch_off);
480                         } else {
481                                 for (on_off = complementary; on_off->opt_char; on_off++)
482                                         if (on_off->opt_char == *s) {
483                                                 *pair_switch |= on_off->switch_on;
484                                                 break;
485                                         }
486                         }
487                 }
488                 s--;
489         }
490         va_end(p);
491
492         if (spec_flgs & (FIRST_ARGV_IS_OPT | ALL_ARGV_IS_OPTS)) {
493                 pargv = argv + 1;
494                 while (*pargv) {
495                         if (pargv[0][0] != '-' && pargv[0][0] != '\0') {
496                                 char *pp = alloca(strlen(*pargv) + 2);
497                                 *pp = '-';
498                                 strcpy(pp + 1, *pargv);
499                                 *pargv = pp;
500                         }
501                         if (!(spec_flgs & ALL_ARGV_IS_OPTS))
502                                 break; 
503                         pargv++;
504                 }
505         }
506
507         /* In case getopt32 was already called:
508          * reset the libc getopt() function, which keeps internal state.
509          *
510          * BSD-derived getopt() functions require that optind be set to 1 in
511          * order to reset getopt() state.  This used to be generally accepted
512          * way of resetting getopt().  However, glibc's getopt()
513          * has additional getopt() state beyond optind, and requires that
514          * optind be set to zero to reset its state.  So the unfortunate state of
515          * affairs is that BSD-derived versions of getopt() misbehave if
516          * optind is set to 0 in order to reset getopt(), and glibc's getopt()
517          * will core dump if optind is set 1 in order to reset getopt().
518          *
519          * More modern versions of BSD require that optreset be set to 1 in
520          * order to reset getopt().   Sigh.  Standards, anyone?
521          */
522 #ifdef __GLIBC__
523         optind = 0;
524 #else /* BSD style */
525         optind = 1;
526         /* optreset = 1; */
527 #endif
528         /* optarg = NULL; opterr = 0; optopt = 0; - do we need this?? */
529         pargv = NULL;
530
531         /* Note: just "getopt() <= 0" will not work well for
532          * "fake" short options, like this one:
533          * wget $'-\203' "Test: test" http://kernel.org/
534          * (supposed to act as --header, but doesn't) */
535 #if ENABLE_GETOPT_LONG
536         while ((c = getopt_long(argc, argv, applet_opts,
537                         long_options, NULL)) != -1) {
538 #else
539         while ((c = getopt(argc, argv, applet_opts)) != -1) {
540 #endif
541                 /* getopt prints "option requires an argument -- X"
542                  * and returns '?' if an option has no arg, but one is reqd */
543                 c &= 0xff; /* fight libc's sign extension */
544                 for (on_off = complementary; on_off->opt_char != c; on_off++) {
545                         /* c can be NUL if long opt has non-NULL ->flag,
546                          * but we construct long opts so that flag
547                          * is always NULL (see above) */
548                         if (on_off->opt_char == '\0' /* && c != '\0' */) {
549                                 /* c is probably '?' - "bad option" */
550                                 bb_show_usage();
551                         }
552                 }
553                 if (flags & on_off->incongruously)
554                         bb_show_usage();
555                 trigger = on_off->switch_on & on_off->switch_off;
556                 flags &= ~(on_off->switch_off ^ trigger);
557                 flags |= on_off->switch_on ^ trigger;
558                 flags ^= trigger;
559                 if (on_off->counter)
560                         (*(on_off->counter))++;
561                 if (on_off->param_type == PARAM_LIST) {
562                         if (optarg)
563                                 llist_add_to_end((llist_t **)(on_off->optarg), optarg);
564                 } else if (on_off->param_type == PARAM_INT) {
565                         if (optarg)
566 //TODO: xatoi_u indirectly pulls in printf machinery
567                                 *(unsigned*)(on_off->optarg) = xatoi_u(optarg);
568                 } else if (on_off->optarg) {
569                         if (optarg)
570                                 *(char **)(on_off->optarg) = optarg;
571                 }
572                 if (pargv != NULL)
573                         break;
574         }
575
576         /* check depending requires for given options */
577         for (on_off = complementary; on_off->opt_char; on_off++) {
578                 if (on_off->requires && (flags & on_off->switch_on) &&
579                                         (flags & on_off->requires) == 0)
580                         bb_show_usage();
581         }
582         if (requires && (flags & requires) == 0)
583                 bb_show_usage();
584         argc -= optind;
585         if (argc < min_arg || (max_arg >= 0 && argc > max_arg))
586                 bb_show_usage();
587
588         option_mask32 = flags;
589         return flags;
590 }