getopt: simple code shrink; expand help text
[platform/upstream/busybox.git] / util-linux / getopt.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * getopt.c - Enhanced implementation of BSD getopt(1)
4  *   Copyright (c) 1997, 1998, 1999, 2000  Frodo Looijaard <frodol@dds.nl>
5  *
6  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
7  */
8
9 /*
10  * Version 1.0-b4: Tue Sep 23 1997. First public release.
11  * Version 1.0: Wed Nov 19 1997.
12  *   Bumped up the version number to 1.0
13  *   Fixed minor typo (CSH instead of TCSH)
14  * Version 1.0.1: Tue Jun 3 1998
15  *   Fixed sizeof instead of strlen bug
16  *   Bumped up the version number to 1.0.1
17  * Version 1.0.2: Thu Jun 11 1998 (not present)
18  *   Fixed gcc-2.8.1 warnings
19  *   Fixed --version/-V option (not present)
20  * Version 1.0.5: Tue Jun 22 1999
21  *   Make -u option work (not present)
22  * Version 1.0.6: Tue Jun 27 2000
23  *   No important changes
24  * Version 1.1.0: Tue Jun 30 2000
25  *   Added NLS support (partly written by Arkadiusz Mickiewicz
26  *     <misiek@misiek.eu.org>)
27  * Ported to Busybox - Alfred M. Szmidt <ams@trillian.itslinux.org>
28  *  Removed --version/-V and --help/-h
29  *  Removed parse_error(), using bb_error_msg() from Busybox instead
30  *  Replaced our_malloc with xmalloc and our_realloc with xrealloc
31  *
32  */
33
34 //usage:#define getopt_trivial_usage
35 //usage:       "[OPTIONS] [--] OPTSTRING PARAMS"
36 //usage:#define getopt_full_usage "\n\n"
37 //usage:        IF_LONG_OPTS(
38 //usage:       "        -a,--alternative                Allow long options starting with single -"
39 //usage:     "\n        -l,--longoptions=LOPT[,...]     Long options to be recognized"
40 //usage:     "\n        -n,--name=PROGNAME              The name under which errors are reported"
41 //usage:     "\n        -o,--options=OPTSTRING          Short options to be recognized"
42 //usage:     "\n        -q,--quiet                      Disable error reporting by getopt(3)"
43 //usage:     "\n        -Q,--quiet-output               No normal output"
44 //usage:     "\n        -s,--shell=SHELL                Set shell quoting conventions"
45 //usage:     "\n        -T,--test                       Test for getopt(1) version"
46 //usage:     "\n        -u,--unquoted                   Don't quote the output"
47 //usage:        )
48 //usage:        IF_NOT_LONG_OPTS(
49 //usage:       "        -a              Allow long options starting with single -"
50 //usage:     "\n        -l LOPT[,...]   Long options to be recognized"
51 //usage:     "\n        -n PROGNAME     The name under which errors are reported"
52 //usage:     "\n        -o OPTSTRING    Short options to be recognized"
53 //usage:     "\n        -q              Disable error reporting by getopt(3)"
54 //usage:     "\n        -Q              No normal output"
55 //usage:     "\n        -s SHELL        Set shell quoting conventions"
56 //usage:     "\n        -T              Test for getopt(1) version"
57 //usage:     "\n        -u              Don't quote the output"
58 //usage:        )
59 //usage:     "\n"
60 //usage:     "\nExample:"
61 //usage:     "\n"
62 //usage:     "\nO=`getopt -l bb: -- ab:c:: \"$@\"`"
63 //usage:     "\n[ $? = 0 ] || exit 1"
64 //usage:     "\neval set -- \"$O\""
65 //usage:     "\nwhile true; do"
66 //usage:     "\n        case \"$1\" in"
67 //usage:     "\n        -a)     echo A; shift;;"
68 //usage:     "\n        -b|--bb) echo \"B:'$2'\"; shift 2;;"
69 //usage:     "\n        -c)     case \"$2\" in"
70 //usage:     "\n                \"\")   echo C; shift 2;;"
71 //usage:     "\n                *)      echo \"C:'$2'\"; shift 2;;"
72 //usage:     "\n                esac;;"
73 //usage:     "\n        --)     shift; break;;"
74 //usage:     "\n        *)      echo Error; exit 1;;"
75 //usage:     "\n        esac"
76 //usage:     "\ndone"
77 //usage:
78 //usage:#define getopt_example_usage
79 //usage:       "$ cat getopt.test\n"
80 //usage:       "#!/bin/sh\n"
81 //usage:       "GETOPT=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \\\n"
82 //usage:       "       -n 'example.busybox' -- \"$@\"`\n"
83 //usage:       "if [ $? != 0 ]; then exit 1; fi\n"
84 //usage:       "eval set -- \"$GETOPT\"\n"
85 //usage:       "while true; do\n"
86 //usage:       " case $1 in\n"
87 //usage:       "   -a|--a-long) echo \"Option a\"; shift;;\n"
88 //usage:       "   -b|--b-long) echo \"Option b, argument '$2'\"; shift 2;;\n"
89 //usage:       "   -c|--c-long)\n"
90 //usage:       "     case \"$2\" in\n"
91 //usage:       "       \"\") echo \"Option c, no argument\"; shift 2;;\n"
92 //usage:       "       *)  echo \"Option c, argument '$2'\"; shift 2;;\n"
93 //usage:       "     esac;;\n"
94 //usage:       "   --) shift; break;;\n"
95 //usage:       "   *) echo \"Internal error!\"; exit 1;;\n"
96 //usage:       " esac\n"
97 //usage:       "done\n"
98
99 #if ENABLE_FEATURE_GETOPT_LONG
100 # include <getopt.h>
101 #endif
102 #include "libbb.h"
103
104 /* NON_OPT is the code that is returned when a non-option is found in '+'
105    mode */
106 enum {
107         NON_OPT = 1,
108 #if ENABLE_FEATURE_GETOPT_LONG
109 /* LONG_OPT is the code that is returned when a long option is found. */
110         LONG_OPT = 2
111 #endif
112 };
113
114 /* For finding activated option flags. Must match getopt32 call! */
115 enum {
116         OPT_o   = 0x1,  // -o
117         OPT_n   = 0x2,  // -n
118         OPT_q   = 0x4,  // -q
119         OPT_Q   = 0x8,  // -Q
120         OPT_s   = 0x10, // -s
121         OPT_T   = 0x20, // -T
122         OPT_u   = 0x40, // -u
123 #if ENABLE_FEATURE_GETOPT_LONG
124         OPT_a   = 0x80, // -a
125         OPT_l   = 0x100, // -l
126 #endif
127         SHELL_IS_TCSH = 0x8000, /* hijack this bit for other purposes */
128 };
129
130 /* 0 is getopt_long, 1 is getopt_long_only */
131 #define alternative  (option_mask32 & OPT_a)
132
133 #define quiet_errors (option_mask32 & OPT_q)
134 #define quiet_output (option_mask32 & OPT_Q)
135 #define quote        (!(option_mask32 & OPT_u))
136 #define shell_TCSH   (option_mask32 & SHELL_IS_TCSH)
137
138 /*
139  * This function 'normalizes' a single argument: it puts single quotes around
140  * it and escapes other special characters. If quote is false, it just
141  * returns its argument.
142  * Bash only needs special treatment for single quotes; tcsh also recognizes
143  * exclamation marks within single quotes, and nukes whitespace.
144  * This function returns a pointer to a buffer that is overwritten by
145  * each call.
146  */
147 static const char *normalize(const char *arg)
148 {
149         char *bufptr;
150 #if ENABLE_FEATURE_CLEAN_UP
151         static char *BUFFER = NULL;
152         free(BUFFER);
153 #else
154         char *BUFFER;
155 #endif
156
157         if (!quote) { /* Just copy arg */
158                 BUFFER = xstrdup(arg);
159                 return BUFFER;
160         }
161
162         /* Each character in arg may take up to four characters in the result:
163            For a quote we need a closing quote, a backslash, a quote and an
164            opening quote! We need also the global opening and closing quote,
165            and one extra character for '\0'. */
166         BUFFER = xmalloc(strlen(arg)*4 + 3);
167
168         bufptr = BUFFER;
169         *bufptr ++= '\'';
170
171         while (*arg) {
172                 if (*arg == '\'') {
173                         /* Quote: replace it with: '\'' */
174                         *bufptr ++= '\'';
175                         *bufptr ++= '\\';
176                         *bufptr ++= '\'';
177                         *bufptr ++= '\'';
178                 } else if (shell_TCSH && *arg == '!') {
179                         /* Exclamation mark: replace it with: \! */
180                         *bufptr ++= '\'';
181                         *bufptr ++= '\\';
182                         *bufptr ++= '!';
183                         *bufptr ++= '\'';
184                 } else if (shell_TCSH && *arg == '\n') {
185                         /* Newline: replace it with: \n */
186                         *bufptr ++= '\\';
187                         *bufptr ++= 'n';
188                 } else if (shell_TCSH && isspace(*arg)) {
189                         /* Non-newline whitespace: replace it with \<ws> */
190                         *bufptr ++= '\'';
191                         *bufptr ++= '\\';
192                         *bufptr ++= *arg;
193                         *bufptr ++= '\'';
194                 } else
195                         /* Just copy */
196                         *bufptr ++= *arg;
197                 arg++;
198         }
199         *bufptr ++= '\'';
200         *bufptr ++= '\0';
201         return BUFFER;
202 }
203
204 /*
205  * Generate the output. argv[0] is the program name (used for reporting errors).
206  * argv[1..] contains the options to be parsed. argc must be the number of
207  * elements in argv (ie. 1 if there are no options, only the program name),
208  * optstr must contain the short options, and longopts the long options.
209  * Other settings are found in global variables.
210  */
211 #if !ENABLE_FEATURE_GETOPT_LONG
212 #define generate_output(argv,argc,optstr,longopts) \
213         generate_output(argv,argc,optstr)
214 #endif
215 static int generate_output(char **argv, int argc, const char *optstr, const struct option *longopts)
216 {
217         int exit_code = 0; /* We assume everything will be OK */
218         int opt;
219 #if ENABLE_FEATURE_GETOPT_LONG
220         int longindex;
221 #endif
222         const char *charptr;
223
224         if (quiet_errors) /* No error reporting from getopt(3) */
225                 opterr = 0;
226
227         /* We used it already in main() in getopt32(),
228          * we *must* reset getopt(3): */
229 #ifdef __GLIBC__
230         optind = 0;
231 #else /* BSD style */
232         optind = 1;
233         /* optreset = 1; */
234 #endif
235
236         while (1) {
237                 opt =
238 #if ENABLE_FEATURE_GETOPT_LONG
239                         alternative ?
240                         getopt_long_only(argc, argv, optstr, longopts, &longindex) :
241                         getopt_long(argc, argv, optstr, longopts, &longindex);
242 #else
243                         getopt(argc, argv, optstr);
244 #endif
245                 if (opt == -1)
246                         break;
247                 if (opt == '?' || opt == ':' )
248                         exit_code = 1;
249                 else if (!quiet_output) {
250 #if ENABLE_FEATURE_GETOPT_LONG
251                         if (opt == LONG_OPT) {
252                                 printf(" --%s", longopts[longindex].name);
253                                 if (longopts[longindex].has_arg)
254                                         printf(" %s",
255                                                 normalize(optarg ? optarg : ""));
256                         } else
257 #endif
258                         if (opt == NON_OPT)
259                                 printf(" %s", normalize(optarg));
260                         else {
261                                 printf(" -%c", opt);
262                                 charptr = strchr(optstr, opt);
263                                 if (charptr != NULL && *++charptr == ':')
264                                         printf(" %s",
265                                                 normalize(optarg ? optarg : ""));
266                         }
267                 }
268         }
269
270         if (!quiet_output) {
271                 printf(" --");
272                 while (optind < argc)
273                         printf(" %s", normalize(argv[optind++]));
274                 bb_putchar('\n');
275         }
276         return exit_code;
277 }
278
279 #if ENABLE_FEATURE_GETOPT_LONG
280 /*
281  * Register several long options. options is a string of long options,
282  * separated by commas or whitespace.
283  * This nukes options!
284  */
285 static struct option *add_long_options(struct option *long_options, char *options)
286 {
287         int long_nr = 0;
288         int arg_opt, tlen;
289         char *tokptr = strtok(options, ", \t\n");
290
291         if (long_options)
292                 while (long_options[long_nr].name)
293                         long_nr++;
294
295         while (tokptr) {
296                 arg_opt = no_argument;
297                 tlen = strlen(tokptr);
298                 if (tlen) {
299                         tlen--;
300                         if (tokptr[tlen] == ':') {
301                                 arg_opt = required_argument;
302                                 if (tlen && tokptr[tlen-1] == ':') {
303                                         tlen--;
304                                         arg_opt = optional_argument;
305                                 }
306                                 tokptr[tlen] = '\0';
307                                 if (tlen == 0)
308                                         bb_error_msg_and_die("empty long option specified");
309                         }
310                         long_options = xrealloc_vector(long_options, 4, long_nr);
311                         long_options[long_nr].has_arg = arg_opt;
312                         /*long_options[long_nr].flag = NULL; - xrealloc_vector did it */
313                         long_options[long_nr].val = LONG_OPT;
314                         long_options[long_nr].name = xstrdup(tokptr);
315                         long_nr++;
316                         /*memset(&long_options[long_nr], 0, sizeof(long_options[0])); - xrealloc_vector did it */
317                 }
318                 tokptr = strtok(NULL, ", \t\n");
319         }
320         return long_options;
321 }
322 #endif
323
324 static void set_shell(const char *new_shell)
325 {
326         if (!strcmp(new_shell, "bash") || !strcmp(new_shell, "sh"))
327                 return;
328         if (!strcmp(new_shell, "tcsh") || !strcmp(new_shell, "csh"))
329                 option_mask32 |= SHELL_IS_TCSH;
330         else
331                 bb_error_msg("unknown shell '%s', assuming bash", new_shell);
332 }
333
334
335 /* Exit codes:
336  *   0) No errors, successful operation.
337  *   1) getopt(3) returned an error.
338  *   2) A problem with parameter parsing for getopt(1).
339  *   3) Internal error, out of memory
340  *   4) Returned for -T
341  */
342
343 #if ENABLE_FEATURE_GETOPT_LONG
344 static const char getopt_longopts[] ALIGN1 =
345         "options\0"      Required_argument "o"
346         "longoptions\0"  Required_argument "l"
347         "quiet\0"        No_argument       "q"
348         "quiet-output\0" No_argument       "Q"
349         "shell\0"        Required_argument "s"
350         "test\0"         No_argument       "T"
351         "unquoted\0"     No_argument       "u"
352         "alternative\0"  No_argument       "a"
353         "name\0"         Required_argument "n"
354         ;
355 #endif
356
357 int getopt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
358 int getopt_main(int argc, char **argv)
359 {
360         int n;
361         char *optstr = NULL;
362         char *name = NULL;
363         unsigned opt;
364         const char *compatible;
365         char *s_arg;
366 #if ENABLE_FEATURE_GETOPT_LONG
367         struct option *long_options = NULL;
368         llist_t *l_arg = NULL;
369 #endif
370
371         compatible = getenv("GETOPT_COMPATIBLE"); /* used as yes/no flag */
372
373         if (!argv[1]) {
374                 if (compatible) {
375                         /* For some reason, the original getopt gave no error
376                            when there were no arguments. */
377                         printf(" --\n");
378                         return 0;
379                 }
380                 bb_error_msg_and_die("missing optstring argument");
381         }
382
383         if (argv[1][0] != '-' || compatible) {
384                 char *s = argv[1];
385
386                 option_mask32 |= OPT_u; /* quoting off */
387                 s = xstrdup(s + strspn(s, "-+"));
388                 argv[1] = argv[0];
389                 return generate_output(argv+1, argc-1, s, long_options);
390         }
391
392 #if !ENABLE_FEATURE_GETOPT_LONG
393         opt = getopt32(argv, "+o:n:qQs:Tu", &optstr, &name, &s_arg);
394 #else
395         applet_long_options = getopt_longopts;
396         opt_complementary = "l::";
397         opt = getopt32(argv, "+o:n:qQs:Tual:",
398                                         &optstr, &name, &s_arg, &l_arg);
399         /* Effectuate the read options for the applet itself */
400         while (l_arg) {
401                 long_options = add_long_options(long_options, llist_pop(&l_arg));
402         }
403 #endif
404
405         if (opt & OPT_s) {
406                 set_shell(s_arg);
407         }
408
409         if (opt & OPT_T) {
410                 return 4;
411         }
412
413         /* All options controlling the applet have now been parsed */
414         n = optind - 1;
415         if (!optstr) {
416                 optstr = argv[++n];
417                 if (!optstr)
418                         bb_error_msg_and_die("missing optstring argument");
419         }
420
421         argv[n] = name ? name : argv[0];
422         return generate_output(argv + n, argc - n, optstr, long_options);
423 }