2390f3056d4783a4ba7759eef0172db0fd926726
[oweals/busybox.git] / getopt.c
1 /*
2  * getopt.c - Enhanced implementation of BSD getopt(1)
3  *   Copyright (c) 1997, 1998, 1999, 2000  Frodo Looijaard <frodol@dds.nl>
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 as published by
7  *   the Free Software Foundation; either version 2 of the License, or
8  *   (at your option) any later version.
9  *
10  *   This program is distributed in the hope that it will be useful,
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *   GNU General Public License for more details.
14  *
15  *   You should have received a copy of the GNU General Public License
16  *   along with this program; if not, write to the Free Software
17  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 /*
21  * Version 1.0-b4: Tue Sep 23 1997. First public release.
22  * Version 1.0: Wed Nov 19 1997.
23  *   Bumped up the version number to 1.0
24  *   Fixed minor typo (CSH instead of TCSH)
25  * Version 1.0.1: Tue Jun 3 1998
26  *   Fixed sizeof instead of strlen bug
27  *   Bumped up the version number to 1.0.1
28  * Version 1.0.2: Thu Jun 11 1998 (not present)
29  *   Fixed gcc-2.8.1 warnings
30  *   Fixed --version/-V option (not present)
31  * Version 1.0.5: Tue Jun 22 1999
32  *   Make -u option work (not present)
33  * Version 1.0.6: Tue Jun 27 2000
34  *   No important changes
35  * Version 1.1.0: Tue Jun 30 2000
36  *   Added NLS support (partly written by Arkadiusz Mi<B6>kiewicz
37  *     <misiek@misiek.eu.org>)
38  * Ported to Busybox - Alfred M. Szmidt <ams@trillian.itslinux.org>
39  *  Removed --version/-V and --help/-h in
40  *  Removed prase_error(), using error_msg() from Busybox instead
41  *  Replaced our_malloc with xmalloc and our_realloc with xrealloc
42  *
43  */
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <ctype.h>
50 #include <getopt.h>
51
52 #include "busybox.h"
53
54 /* NON_OPT is the code that is returned when a non-option is found in '+'
55    mode */
56 static const int NON_OPT = 1;
57 /* LONG_OPT is the code that is returned when a long option is found. */
58 static const int LONG_OPT = 2;
59
60 /* The shells recognized. */
61 typedef enum {BASH,TCSH} shell_t;
62
63
64 /* Some global variables that tells us how to parse. */
65 static shell_t shell=BASH; /* The shell we generate output for. */
66 static int quiet_errors=0; /* 0 is not quiet. */
67 static int quiet_output=0; /* 0 is not quiet. */
68 static int quote=1; /* 1 is do quote. */
69 static int alternative=0; /* 0 is getopt_long, 1 is getopt_long_only */
70
71 /* Function prototypes */
72 static const char *normalize(const char *arg);
73 static int generate_output(char * argv[],int argc,const char *optstr,
74                     const struct option *longopts);
75 static void add_long_options(char *options);
76 static void add_longopt(const char *name,int has_arg);
77 static void set_shell(const char *new_shell);
78
79
80 /*
81  * This function 'normalizes' a single argument: it puts single quotes around
82  * it and escapes other special characters. If quote is false, it just
83  * returns its argument.
84  * Bash only needs special treatment for single quotes; tcsh also recognizes
85  * exclamation marks within single quotes, and nukes whitespace.
86  * This function returns a pointer to a buffer that is overwritten by
87  * each call.
88  */
89 const char *normalize(const char *arg)
90 {
91         static char *BUFFER=NULL;
92         const char *argptr=arg;
93         char *bufptr;
94
95         if (BUFFER != NULL)
96                 free(BUFFER);
97
98         if (!quote) { /* Just copy arg */
99                BUFFER=xstrdup(arg);
100                 return BUFFER;
101         }
102
103         /* Each character in arg may take upto four characters in the result:
104            For a quote we need a closing quote, a backslash, a quote and an
105            opening quote! We need also the global opening and closing quote,
106            and one extra character for '\0'. */
107         BUFFER=xmalloc(strlen(arg)*4+3);
108
109         bufptr=BUFFER;
110         *bufptr++='\'';
111
112         while (*argptr) {
113                 if (*argptr == '\'') {
114                         /* Quote: replace it with: '\'' */
115                         *bufptr++='\'';
116                         *bufptr++='\\';
117                         *bufptr++='\'';
118                         *bufptr++='\'';
119                 } else if (shell==TCSH && *argptr=='!') {
120                         /* Exclamation mark: replace it with: \! */
121                         *bufptr++='\'';
122                         *bufptr++='\\';
123                         *bufptr++='!';
124                         *bufptr++='\'';
125                 } else if (shell==TCSH && *argptr=='\n') {
126                         /* Newline: replace it with: \n */
127                         *bufptr++='\\';
128                         *bufptr++='n';
129                 } else if (shell==TCSH && isspace(*argptr)) {
130                         /* Non-newline whitespace: replace it with \<ws> */
131                         *bufptr++='\'';
132                         *bufptr++='\\';
133                         *bufptr++=*argptr;
134                         *bufptr++='\'';
135                 } else
136                         /* Just copy */
137                         *bufptr++=*argptr;
138                 argptr++;
139         }
140         *bufptr++='\'';
141         *bufptr++='\0';
142         return BUFFER;
143 }
144
145 /*
146  * Generate the output. argv[0] is the program name (used for reporting errors).
147  * argv[1..] contains the options to be parsed. argc must be the number of
148  * elements in argv (ie. 1 if there are no options, only the program name),
149  * optstr must contain the short options, and longopts the long options.
150  * Other settings are found in global variables.
151  */
152 int generate_output(char * argv[],int argc,const char *optstr,
153                     const struct option *longopts)
154 {
155         int exit_code = 0; /* We assume everything will be OK */
156         int opt;
157         int longindex;
158         const char *charptr;
159
160         if (quiet_errors) /* No error reporting from getopt(3) */
161                 opterr=0;
162         optind=0; /* Reset getopt(3) */
163
164         while ((opt = (alternative?
165                        getopt_long_only(argc,argv,optstr,longopts,&longindex):
166                        getopt_long(argc,argv,optstr,longopts,&longindex)))
167                != EOF)
168                 if (opt == '?' || opt == ':' )
169                         exit_code = 1;
170                 else if (!quiet_output) {
171                         if (opt == LONG_OPT) {
172                                 printf(" --%s",longopts[longindex].name);
173                                 if (longopts[longindex].has_arg)
174                                         printf(" %s",
175                                                normalize(optarg?optarg:""));
176                         } else if (opt == NON_OPT)
177                                 printf(" %s",normalize(optarg));
178                         else {
179                                 printf(" -%c",opt);
180                                 charptr = strchr(optstr,opt);
181                                 if (charptr != NULL && *++charptr == ':')
182                                         printf(" %s",
183                                                normalize(optarg?optarg:""));
184                         }
185                 }
186
187         if (! quiet_output) {
188                 printf(" --");
189                 while (optind < argc)
190                         printf(" %s",normalize(argv[optind++]));
191                 printf("\n");
192         }
193         return exit_code;
194 }
195
196 static struct option *long_options=NULL;
197 static int long_options_length=0; /* Length of array */
198 static int long_options_nr=0; /* Nr of used elements in array */
199 static const int LONG_OPTIONS_INCR = 10;
200 #define init_longopt() add_longopt(NULL,0)
201
202 /* Register a long option. The contents of name is copied. */
203 void add_longopt(const char *name,int has_arg)
204 {
205         if (!name) { /* init */
206                 free(long_options);
207                 long_options=NULL;
208                 long_options_length=0;
209                 long_options_nr=0;
210         }
211
212         if (long_options_nr == long_options_length) {
213                 long_options_length += LONG_OPTIONS_INCR;
214                 long_options=xrealloc(long_options,
215                                          sizeof(struct option) *
216                                          long_options_length);
217         }
218
219         long_options[long_options_nr].name=NULL;
220         long_options[long_options_nr].has_arg=0;
221         long_options[long_options_nr].flag=NULL;
222         long_options[long_options_nr].val=0;
223
224         if (long_options_nr) { /* Not for init! */
225                 long_options[long_options_nr-1].has_arg=has_arg;
226                 long_options[long_options_nr-1].flag=NULL;
227                 long_options[long_options_nr-1].val=LONG_OPT;
228                long_options[long_options_nr-1].name=xstrdup(name);
229         }
230         long_options_nr++;
231 }
232
233
234 /*
235  * Register several long options. options is a string of long options,
236  * separated by commas or whitespace.
237  * This nukes options!
238  */
239 void add_long_options(char *options)
240 {
241         int arg_opt, tlen;
242         char *tokptr=strtok(options,", \t\n");
243         while (tokptr) {
244                 arg_opt=no_argument;
245                 tlen=strlen(tokptr);
246                 if (tlen > 0) {
247                         if (tokptr[tlen-1] == ':') {
248                                 if (tlen > 1 && tokptr[tlen-2] == ':') {
249                                         tokptr[tlen-2]='\0';
250                                         tlen -= 2;
251                                         arg_opt=optional_argument;
252                                 } else {
253                                         tokptr[tlen-1]='\0';
254                                         tlen -= 1;
255                                         arg_opt=required_argument;
256                                 }
257                                 if (tlen == 0)
258                                         error_msg("empty long option after -l or --long argument");
259                         }
260                         add_longopt(tokptr,arg_opt);
261                 }
262                 tokptr=strtok(NULL,", \t\n");
263         }
264 }
265
266 void set_shell(const char *new_shell)
267 {
268         if (!strcmp(new_shell,"bash"))
269                 shell=BASH;
270         else if (!strcmp(new_shell,"tcsh"))
271                 shell=TCSH;
272         else if (!strcmp(new_shell,"sh"))
273                 shell=BASH;
274         else if (!strcmp(new_shell,"csh"))
275                 shell=TCSH;
276         else
277                 error_msg("unknown shell after -s or --shell argument");
278 }
279
280
281 /* Exit codes:
282  *   0) No errors, succesful operation.
283  *   1) getopt(3) returned an error.
284  *   2) A problem with parameter parsing for getopt(1).
285  *   3) Internal error, out of memory
286  *   4) Returned for -T
287  */
288
289 static struct option longopts[]=
290 {
291         {"options",required_argument,NULL,'o'},
292         {"longoptions",required_argument,NULL,'l'},
293         {"quiet",no_argument,NULL,'q'},
294         {"quiet-output",no_argument,NULL,'Q'},
295         {"shell",required_argument,NULL,'s'},
296         {"test",no_argument,NULL,'T'},
297         {"unquoted",no_argument,NULL,'u'},
298         {"alternative",no_argument,NULL,'a'},
299         {"name",required_argument,NULL,'n'},
300         {NULL,0,NULL,0}
301 };
302
303 /* Stop scanning as soon as a non-option argument is found! */
304 static const char *shortopts="+ao:l:n:qQs:Tu";
305
306
307 int getopt_main(int argc, char *argv[])
308 {
309         char *optstr=NULL;
310         char *name=NULL;
311         int opt;
312         int compatible=0;
313
314         init_longopt();
315
316         if (getenv("GETOPT_COMPATIBLE"))
317                 compatible=1;
318
319         if (argc == 1) {
320                 if (compatible) {
321                         /* For some reason, the original getopt gave no error
322                            when there were no arguments. */
323                         printf(" --\n");
324                        return 0;
325                 } else
326                         error_msg_and_die("missing optstring argument");
327         }
328
329         if (argv[1][0] != '-' || compatible) {
330                 quote=0;
331                 optstr=xmalloc(strlen(argv[1])+1);
332                 strcpy(optstr,argv[1]+strspn(argv[1],"-+"));
333                 argv[1]=argv[0];
334                return (generate_output(argv+1,argc-1,optstr,long_options));
335         }
336
337         while ((opt=getopt_long(argc,argv,shortopts,longopts,NULL)) != EOF)
338                 switch (opt) {
339                 case 'a':
340                         alternative=1;
341                         break;
342                 case 'o':
343                         if (optstr)
344                                 free(optstr);
345                        optstr=xstrdup(optarg);
346                         break;
347                 case 'l':
348                         add_long_options(optarg);
349                         break;
350                 case 'n':
351                         if (name)
352                                 free(name);
353                        name=xstrdup(optarg);
354                         break;
355                 case 'q':
356                         quiet_errors=1;
357                         break;
358                 case 'Q':
359                         quiet_output=1;
360                         break;
361                 case 's':
362                         set_shell(optarg);
363                         break;
364                 case 'T':
365                        return 4;
366                 case 'u':
367                         quote=0;
368                         break;
369                 default:
370                         show_usage();
371                 }
372
373         if (!optstr) {
374                 if (optind >= argc)
375                         error_msg_and_die("missing optstring argument");
376                 else {
377                        optstr=xstrdup(argv[optind]);
378                         optind++;
379                 }
380         }
381         if (name)
382                 argv[optind-1]=name;
383         else
384                 argv[optind-1]=argv[0];
385        return (generate_output(argv+optind-1,argc-optind+1,optstr,long_options));
386 }
387
388 /*
389   Local Variables:
390   c-file-style: "linux"
391   c-basic-offset: 4
392   tab-width: 4
393   End:
394 */