Standardize on the vi editing directives being on the first line.
[oweals/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 tarball for details.
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 Mi<B6>kiewicz
26  *     <misiek@misiek.eu.org>)
27  * Ported to Busybox - Alfred M. Szmidt <ams@trillian.itslinux.org>
28  *  Removed --version/-V and --help/-h in
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 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <getopt.h>
40
41 #include "busybox.h"
42
43 /* NON_OPT is the code that is returned when a non-option is found in '+'
44    mode */
45 enum {
46         NON_OPT = 1,
47 /* LONG_OPT is the code that is returned when a long option is found. */
48         LONG_OPT = 2
49 };
50
51 /* The shells recognized. */
52 typedef enum {BASH,TCSH} shell_t;
53
54
55 /* Some global variables that tells us how to parse. */
56 static shell_t shell=BASH; /* The shell we generate output for. */
57 static int quiet_errors; /* 0 is not quiet. */
58 static int quiet_output; /* 0 is not quiet. */
59 static int quote=1; /* 1 is do quote. */
60 static int alternative; /* 0 is getopt_long, 1 is getopt_long_only */
61
62 /* Function prototypes */
63 static const char *normalize(const char *arg);
64 static int generate_output(char * argv[],int argc,const char *optstr,
65                     const struct option *longopts);
66 static void add_long_options(char *options);
67 static void add_longopt(const char *name,int has_arg);
68 static void set_shell(const char *new_shell);
69
70
71 /*
72  * This function 'normalizes' a single argument: it puts single quotes around
73  * it and escapes other special characters. If quote is false, it just
74  * returns its argument.
75  * Bash only needs special treatment for single quotes; tcsh also recognizes
76  * exclamation marks within single quotes, and nukes whitespace.
77  * This function returns a pointer to a buffer that is overwritten by
78  * each call.
79  */
80 const char *normalize(const char *arg)
81 {
82         static char *BUFFER=NULL;
83         const char *argptr=arg;
84         char *bufptr;
85
86         free(BUFFER);
87
88         if (!quote) { /* Just copy arg */
89                BUFFER=bb_xstrdup(arg);
90                 return BUFFER;
91         }
92
93         /* Each character in arg may take up to four characters in the result:
94            For a quote we need a closing quote, a backslash, a quote and an
95            opening quote! We need also the global opening and closing quote,
96            and one extra character for '\0'. */
97         BUFFER=xmalloc(strlen(arg)*4+3);
98
99         bufptr=BUFFER;
100         *bufptr++='\'';
101
102         while (*argptr) {
103                 if (*argptr == '\'') {
104                         /* Quote: replace it with: '\'' */
105                         *bufptr++='\'';
106                         *bufptr++='\\';
107                         *bufptr++='\'';
108                         *bufptr++='\'';
109                 } else if (shell==TCSH && *argptr=='!') {
110                         /* Exclamation mark: replace it with: \! */
111                         *bufptr++='\'';
112                         *bufptr++='\\';
113                         *bufptr++='!';
114                         *bufptr++='\'';
115                 } else if (shell==TCSH && *argptr=='\n') {
116                         /* Newline: replace it with: \n */
117                         *bufptr++='\\';
118                         *bufptr++='n';
119                 } else if (shell==TCSH && isspace(*argptr)) {
120                         /* Non-newline whitespace: replace it with \<ws> */
121                         *bufptr++='\'';
122                         *bufptr++='\\';
123                         *bufptr++=*argptr;
124                         *bufptr++='\'';
125                 } else
126                         /* Just copy */
127                         *bufptr++=*argptr;
128                 argptr++;
129         }
130         *bufptr++='\'';
131         *bufptr++='\0';
132         return BUFFER;
133 }
134
135 /*
136  * Generate the output. argv[0] is the program name (used for reporting errors).
137  * argv[1..] contains the options to be parsed. argc must be the number of
138  * elements in argv (ie. 1 if there are no options, only the program name),
139  * optstr must contain the short options, and longopts the long options.
140  * Other settings are found in global variables.
141  */
142 int generate_output(char * argv[],int argc,const char *optstr,
143                     const struct option *longopts)
144 {
145         int exit_code = 0; /* We assume everything will be OK */
146         int opt;
147         int longindex;
148         const char *charptr;
149
150         if (quiet_errors) /* No error reporting from getopt(3) */
151                 opterr=0;
152         optind=0; /* Reset getopt(3) */
153
154         while ((opt = (alternative?
155                        getopt_long_only(argc,argv,optstr,longopts,&longindex):
156                        getopt_long(argc,argv,optstr,longopts,&longindex)))
157                != EOF)
158                 if (opt == '?' || opt == ':' )
159                         exit_code = 1;
160                 else if (!quiet_output) {
161                         if (opt == LONG_OPT) {
162                                 printf(" --%s",longopts[longindex].name);
163                                 if (longopts[longindex].has_arg)
164                                         printf(" %s",
165                                                normalize(optarg?optarg:""));
166                         } else if (opt == NON_OPT)
167                                 printf(" %s",normalize(optarg));
168                         else {
169                                 printf(" -%c",opt);
170                                 charptr = strchr(optstr,opt);
171                                 if (charptr != NULL && *++charptr == ':')
172                                         printf(" %s",
173                                                normalize(optarg?optarg:""));
174                         }
175                 }
176
177         if (! quiet_output) {
178                 printf(" --");
179                 while (optind < argc)
180                         printf(" %s",normalize(argv[optind++]));
181                 printf("\n");
182         }
183         return exit_code;
184 }
185
186 static struct option *long_options;
187 static int long_options_length; /* Length of array */
188 static int long_options_nr; /* Nr of used elements in array */
189 enum { LONG_OPTIONS_INCR = 10 };
190 #define init_longopt() add_longopt(NULL,0)
191
192 /* Register a long option. The contents of name is copied. */
193 void add_longopt(const char *name,int has_arg)
194 {
195         if (!name) { /* init */
196                 free(long_options);
197                 long_options=NULL;
198                 long_options_length=0;
199                 long_options_nr=0;
200         }
201
202         if (long_options_nr == long_options_length) {
203                 long_options_length += LONG_OPTIONS_INCR;
204                 long_options=xrealloc(long_options,
205                                          sizeof(struct option) *
206                                          long_options_length);
207         }
208
209         long_options[long_options_nr].name=NULL;
210         long_options[long_options_nr].has_arg=0;
211         long_options[long_options_nr].flag=NULL;
212         long_options[long_options_nr].val=0;
213
214         if (long_options_nr) { /* Not for init! */
215                 long_options[long_options_nr-1].has_arg=has_arg;
216                 long_options[long_options_nr-1].flag=NULL;
217                 long_options[long_options_nr-1].val=LONG_OPT;
218                long_options[long_options_nr-1].name=bb_xstrdup(name);
219         }
220         long_options_nr++;
221 }
222
223
224 /*
225  * Register several long options. options is a string of long options,
226  * separated by commas or whitespace.
227  * This nukes options!
228  */
229 void add_long_options(char *options)
230 {
231         int arg_opt, tlen;
232         char *tokptr=strtok(options,", \t\n");
233         while (tokptr) {
234                 arg_opt=no_argument;
235                 tlen=strlen(tokptr);
236                 if (tlen > 0) {
237                         if (tokptr[tlen-1] == ':') {
238                                 if (tlen > 1 && tokptr[tlen-2] == ':') {
239                                         tokptr[tlen-2]='\0';
240                                         tlen -= 2;
241                                         arg_opt=optional_argument;
242                                 } else {
243                                         tokptr[tlen-1]='\0';
244                                         tlen -= 1;
245                                         arg_opt=required_argument;
246                                 }
247                                 if (tlen == 0)
248                                         bb_error_msg("empty long option after -l or --long argument");
249                         }
250                         add_longopt(tokptr,arg_opt);
251                 }
252                 tokptr=strtok(NULL,", \t\n");
253         }
254 }
255
256 void set_shell(const char *new_shell)
257 {
258         if (!strcmp(new_shell,"bash"))
259                 shell=BASH;
260         else if (!strcmp(new_shell,"tcsh"))
261                 shell=TCSH;
262         else if (!strcmp(new_shell,"sh"))
263                 shell=BASH;
264         else if (!strcmp(new_shell,"csh"))
265                 shell=TCSH;
266         else
267                 bb_error_msg("unknown shell after -s or --shell argument");
268 }
269
270
271 /* Exit codes:
272  *   0) No errors, successful operation.
273  *   1) getopt(3) returned an error.
274  *   2) A problem with parameter parsing for getopt(1).
275  *   3) Internal error, out of memory
276  *   4) Returned for -T
277  */
278
279 static const struct option longopts[]=
280 {
281         {"options",required_argument,NULL,'o'},
282         {"longoptions",required_argument,NULL,'l'},
283         {"quiet",no_argument,NULL,'q'},
284         {"quiet-output",no_argument,NULL,'Q'},
285         {"shell",required_argument,NULL,'s'},
286         {"test",no_argument,NULL,'T'},
287         {"unquoted",no_argument,NULL,'u'},
288         {"alternative",no_argument,NULL,'a'},
289         {"name",required_argument,NULL,'n'},
290         {NULL,0,NULL,0}
291 };
292
293 /* Stop scanning as soon as a non-option argument is found! */
294 static const char shortopts[]="+ao:l:n:qQs:Tu";
295
296
297 int getopt_main(int argc, char *argv[])
298 {
299         const char *optstr = NULL;
300         char *name = NULL;
301         int opt;
302         int compatible=0;
303
304         init_longopt();
305
306         if (getenv("GETOPT_COMPATIBLE"))
307                 compatible=1;
308
309         if (argc == 1) {
310                 if (compatible) {
311                         /* For some reason, the original getopt gave no error
312                            when there were no arguments. */
313                         printf(" --\n");
314                        return 0;
315                 } else
316                         bb_error_msg_and_die("missing optstring argument");
317         }
318
319         if (argv[1][0] != '-' || compatible) {
320                 char *s;
321
322                 quote=0;
323                 s=xmalloc(strlen(argv[1])+1);
324                 strcpy(s,argv[1]+strspn(argv[1],"-+"));
325                 argv[1]=argv[0];
326                return (generate_output(argv+1,argc-1,s,long_options));
327         }
328
329         while ((opt=getopt_long(argc,argv,shortopts,longopts,NULL)) != EOF)
330                 switch (opt) {
331                 case 'a':
332                         alternative=1;
333                         break;
334                 case 'o':
335                        optstr = optarg;
336                         break;
337                 case 'l':
338                         add_long_options(optarg);
339                         break;
340                 case 'n':
341                        name = optarg;
342                         break;
343                 case 'q':
344                         quiet_errors=1;
345                         break;
346                 case 'Q':
347                         quiet_output=1;
348                         break;
349                 case 's':
350                         set_shell(optarg);
351                         break;
352                 case 'T':
353                        return 4;
354                 case 'u':
355                         quote=0;
356                         break;
357                 default:
358                         bb_show_usage();
359                 }
360
361         if (!optstr) {
362                 if (optind >= argc)
363                         bb_error_msg_and_die("missing optstring argument");
364                 else optstr=argv[optind++];
365         }
366         if (name)
367                 argv[optind-1]=name;
368         else
369                 argv[optind-1]=argv[0];
370        return (generate_output(argv+optind-1,argc-optind+1,optstr,long_options));
371 }