]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/getopt.c
9e94452e7840a7f21521015741e66662be46a885
[thirdparty/util-linux.git] / misc-utils / getopt.c
1 /*
2 * getopt.c - Enhanced implementation of BSD getopt(1)
3 * Copyright (c) 1997-2005 Frodo Looijaard <frodo@frodo.looijaard.name>
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 along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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@pld.org.pl>)
38 * Version 1.1.4: Mon Nov 7 2005
39 * Fixed a few type's in the manpage
40 */
41
42 /* Exit codes:
43 * 0) No errors, successful operation.
44 * 1) getopt(3) returned an error.
45 * 2) A problem with parameter parsing for getopt(1).
46 * 3) Internal error, out of memory
47 * 4) Returned for -T
48 */
49 #define GETOPT_EXIT_CODE 1
50 #define PARAMETER_EXIT_CODE 2
51 #define XALLOC_EXIT_CODE 3
52 #define TEST_EXIT_CODE 4
53
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <ctype.h>
59 #include <getopt.h>
60
61 #include "closestream.h"
62 #include "nls.h"
63 #include "xalloc.h"
64
65 /* NON_OPT is the code that is returned when a non-option is found in '+'
66 * mode */
67 #define NON_OPT 1
68 /* LONG_OPT is the code that is returned when a long option is found. */
69 #define LONG_OPT 2
70
71 /* The shells recognized. */
72 typedef enum { BASH, TCSH } shell_t;
73
74
75 /* Some global variables that tells us how to parse. */
76 static shell_t shell = BASH; /* The shell we generate output for. */
77 static int quiet_errors = 0; /* 0 is not quiet. */
78 static int quiet_output = 0; /* 0 is not quiet. */
79 static int quote = 1; /* 1 is do quote. */
80
81 /* Allow changing which getopt is in use with function pointer */
82 int (*getopt_long_fp) (int argc, char *const *argv, const char *optstr,
83 const struct option * longopts, int *longindex);
84
85 /* Function prototypes */
86 static const char *normalize(const char *arg);
87 static int generate_output(char *argv[], int argc, const char *optstr,
88 const struct option *longopts);
89 static void parse_error(const char *message);
90 static void add_long_options(char *options);
91 static void add_longopt(const char *name, int has_arg);
92 static void print_help(void);
93 static void set_shell(const char *new_shell);
94
95 /*
96 * This function 'normalizes' a single argument: it puts single quotes
97 * around it and escapes other special characters. If quote is false, it
98 * just returns its argument.
99 *
100 * Bash only needs special treatment for single quotes; tcsh also recognizes
101 * exclamation marks within single quotes, and nukes whitespace. This
102 * function returns a pointer to a buffer that is overwritten by each call.
103 */
104 static const char *normalize(const char *arg)
105 {
106 static char *BUFFER = NULL;
107 const char *argptr = arg;
108 char *bufptr;
109
110 if (!quote) {
111 /* Just copy arg */
112 BUFFER = xmalloc(strlen(arg) + 1);
113 strcpy(BUFFER, arg);
114 return BUFFER;
115 }
116
117 /*
118 * Each character in arg may take up to four characters in the
119 * result: For a quote we need a closing quote, a backslash, a quote
120 * and an opening quote! We need also the global opening and closing
121 * quote, and one extra character for '\0'.
122 */
123 BUFFER = xmalloc(strlen(arg) * 4 + 3);
124
125 bufptr = BUFFER;
126 *bufptr++ = '\'';
127
128 while (*argptr) {
129 if (*argptr == '\'') {
130 /* Quote: replace it with: '\'' */
131 *bufptr++ = '\'';
132 *bufptr++ = '\\';
133 *bufptr++ = '\'';
134 *bufptr++ = '\'';
135 } else if (shell == TCSH && *argptr == '!') {
136 /* Exclamation mark: replace it with: \! */
137 *bufptr++ = '\'';
138 *bufptr++ = '\\';
139 *bufptr++ = '!';
140 *bufptr++ = '\'';
141 } else if (shell == TCSH && *argptr == '\n') {
142 /* Newline: replace it with: \n */
143 *bufptr++ = '\\';
144 *bufptr++ = 'n';
145 } else if (shell == TCSH && isspace(*argptr)) {
146 /* Non-newline whitespace: replace it with \<ws> */
147 *bufptr++ = '\'';
148 *bufptr++ = '\\';
149 *bufptr++ = *argptr;
150 *bufptr++ = '\'';
151 } else
152 /* Just copy */
153 *bufptr++ = *argptr;
154 argptr++;
155 }
156 *bufptr++ = '\'';
157 *bufptr++ = '\0';
158 return BUFFER;
159 }
160
161 /*
162 * Generate the output. argv[0] is the program name (used for reporting errors).
163 * argv[1..] contains the options to be parsed. argc must be the number of
164 * elements in argv (ie. 1 if there are no options, only the program name),
165 * optstr must contain the short options, and longopts the long options.
166 * Other settings are found in global variables.
167 */
168 static int generate_output(char *argv[], int argc, const char *optstr,
169 const struct option *longopts)
170 {
171 int exit_code = EXIT_SUCCESS; /* Assume everything will be OK */
172 int opt;
173 int longindex;
174 const char *charptr;
175
176 if (quiet_errors)
177 /* No error reporting from getopt(3) */
178 opterr = 0;
179 /* Reset getopt(3) */
180 optind = 0;
181
182 while ((opt =
183 (getopt_long_fp(argc, argv, optstr, longopts, &longindex)))
184 != EOF)
185 if (opt == '?' || opt == ':')
186 exit_code = GETOPT_EXIT_CODE;
187 else if (!quiet_output) {
188 if (opt == LONG_OPT) {
189 printf(" --%s", longopts[longindex].name);
190 if (longopts[longindex].has_arg)
191 printf(" %s", normalize(optarg ? optarg : ""));
192 } else if (opt == NON_OPT)
193 printf(" %s", normalize(optarg));
194 else {
195 printf(" -%c", opt);
196 charptr = strchr(optstr, opt);
197 if (charptr != NULL && *++charptr == ':')
198 printf(" %s", normalize(optarg ? optarg : ""));
199 }
200 }
201
202 if (!quiet_output) {
203 printf(" --");
204 while (optind < argc)
205 printf(" %s", normalize(argv[optind++]));
206 printf("\n");
207 }
208 return exit_code;
209 }
210
211 /*
212 * Report an error when parsing getopt's own arguments. If message is NULL,
213 * we already sent a message, we just exit with a helpful hint.
214 */
215 static void __attribute__ ((__noreturn__)) parse_error(const char *message)
216 {
217 if (message)
218 warnx("%s", message);
219 fprintf(stderr, _("Try `%s --help' for more information.\n"),
220 program_invocation_short_name);
221 exit(PARAMETER_EXIT_CODE);
222 }
223
224 static struct option *long_options = NULL;
225 static int long_options_length = 0; /* Length of array */
226 static int long_options_nr = 0; /* Nr of used elements in array */
227 #define LONG_OPTIONS_INCR 10
228 #define init_longopt() add_longopt(NULL,0)
229
230 /* Register a long option. The contents of name is copied. */
231 static void add_longopt(const char *name, int has_arg)
232 {
233 char *tmp;
234 if (!name) {
235 /* init */
236 free(long_options);
237 long_options = NULL;
238 long_options_length = 0;
239 long_options_nr = 0;
240 }
241
242 if (long_options_nr == long_options_length) {
243 long_options_length += LONG_OPTIONS_INCR;
244 long_options = xrealloc(long_options,
245 sizeof(struct option) *
246 long_options_length);
247 }
248
249 long_options[long_options_nr].name = NULL;
250 long_options[long_options_nr].has_arg = 0;
251 long_options[long_options_nr].flag = NULL;
252 long_options[long_options_nr].val = 0;
253
254 if (long_options_nr && name) {
255 /* Not for init! */
256 long_options[long_options_nr - 1].has_arg = has_arg;
257 long_options[long_options_nr - 1].flag = NULL;
258 long_options[long_options_nr - 1].val = LONG_OPT;
259 tmp = xmalloc(strlen(name) + 1);
260 strcpy(tmp, name);
261 long_options[long_options_nr - 1].name = tmp;
262 }
263 long_options_nr++;
264 }
265
266
267 /*
268 * Register several long options. options is a string of long options,
269 * separated by commas or whitespace. This nukes options!
270 */
271 static void add_long_options(char *options)
272 {
273 int arg_opt;
274 char *tokptr = strtok(options, ", \t\n");
275 while (tokptr) {
276 arg_opt = no_argument;
277 if (strlen(tokptr) > 0) {
278 if (tokptr[strlen(tokptr) - 1] == ':') {
279 if (tokptr[strlen(tokptr) - 2] == ':') {
280 tokptr[strlen(tokptr) - 2] = '\0';
281 arg_opt = optional_argument;
282 } else {
283 tokptr[strlen(tokptr) - 1] = '\0';
284 arg_opt = required_argument;
285 }
286 if (strlen(tokptr) == 0)
287 parse_error(_
288 ("empty long option after "
289 "-l or --long argument"));
290 }
291 add_longopt(tokptr, arg_opt);
292 }
293 tokptr = strtok(NULL, ", \t\n");
294 }
295 }
296
297 static void set_shell(const char *new_shell)
298 {
299 if (!strcmp(new_shell, "bash"))
300 shell = BASH;
301 else if (!strcmp(new_shell, "tcsh"))
302 shell = TCSH;
303 else if (!strcmp(new_shell, "sh"))
304 shell = BASH;
305 else if (!strcmp(new_shell, "csh"))
306 shell = TCSH;
307 else
308 parse_error(_
309 ("unknown shell after -s or --shell argument"));
310 }
311
312 static void __attribute__ ((__noreturn__)) print_help(void)
313 {
314 fputs(_("\nUsage:\n"), stderr);
315
316 fprintf(stderr, _(
317 " %1$s optstring parameters\n"
318 " %1$s [options] [--] optstring parameters\n"
319 " %1$s [options] -o|--options optstring [options] [--] parameters\n"),
320 program_invocation_short_name);
321
322 fputs(_("\nOptions:\n"), stderr);
323 fputs(_(" -a, --alternative Allow long options starting with single -\n"), stderr);
324 fputs(_(" -h, --help This small usage guide\n"), stderr);
325 fputs(_(" -l, --longoptions <longopts> Long options to be recognized\n"), stderr);
326 fputs(_(" -n, --name <progname> The name under which errors are reported\n"), stderr);
327 fputs(_(" -o, --options <optstring> Short options to be recognized\n"), stderr);
328 fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"), stderr);
329 fputs(_(" -Q, --quiet-output No normal output\n"), stderr);
330 fputs(_(" -s, --shell <shell> Set shell quoting conventions\n"), stderr);
331 fputs(_(" -T, --test Test for getopt(1) version\n"), stderr);
332 fputs(_(" -u, --unquote Do not quote the output\n"), stderr);
333 fputs(_(" -V, --version Output version information\n"), stderr);
334 fputc('\n', stderr);
335
336 exit(PARAMETER_EXIT_CODE);
337 }
338
339 int main(int argc, char *argv[])
340 {
341 char *optstr = NULL;
342 char *name = NULL;
343 int opt;
344 int compatible = 0;
345
346 /* Stop scanning as soon as a non-option argument is found! */
347 static const char *shortopts = "+ao:l:n:qQs:TuhV";
348 static const struct option longopts[] = {
349 {"options", required_argument, NULL, 'o'},
350 {"longoptions", required_argument, NULL, 'l'},
351 {"quiet", no_argument, NULL, 'q'},
352 {"quiet-output", no_argument, NULL, 'Q'},
353 {"shell", required_argument, NULL, 's'},
354 {"test", no_argument, NULL, 'T'},
355 {"unquoted", no_argument, NULL, 'u'},
356 {"help", no_argument, NULL, 'h'},
357 {"alternative", no_argument, NULL, 'a'},
358 {"name", required_argument, NULL, 'n'},
359 {"version", no_argument, NULL, 'V'},
360 {NULL, 0, NULL, 0}
361 };
362
363 setlocale(LC_ALL, "");
364 bindtextdomain(PACKAGE, LOCALEDIR);
365 textdomain(PACKAGE);
366 atexit(close_stdout);
367
368 init_longopt();
369 getopt_long_fp = getopt_long;
370
371 if (getenv("GETOPT_COMPATIBLE"))
372 compatible = 1;
373
374 if (argc == 1) {
375 if (compatible) {
376 /*
377 * For some reason, the original getopt gave no
378 * error when there were no arguments.
379 */
380 printf(" --\n");
381 return EXIT_SUCCESS;
382 } else
383 parse_error(_("missing optstring argument"));
384 }
385
386 if (argv[1][0] != '-' || compatible) {
387 quote = 0;
388 optstr = xmalloc(strlen(argv[1]) + 1);
389 strcpy(optstr, argv[1] + strspn(argv[1], "-+"));
390 argv[1] = argv[0];
391 return generate_output(argv + 1, argc - 1, optstr,
392 long_options);
393 }
394
395 while ((opt =
396 getopt_long(argc, argv, shortopts, longopts, NULL)) != EOF)
397 switch (opt) {
398 case 'a':
399 getopt_long_fp = getopt_long_only;
400 break;
401 case 'h':
402 print_help();
403 case 'o':
404 free(optstr);
405 optstr = xmalloc(strlen(optarg) + 1);
406 strcpy(optstr, optarg);
407 break;
408 case 'l':
409 add_long_options(optarg);
410 break;
411 case 'n':
412 free(name);
413 name = xmalloc(strlen(optarg) + 1);
414 strcpy(name, optarg);
415 break;
416 case 'q':
417 quiet_errors = 1;
418 break;
419 case 'Q':
420 quiet_output = 1;
421 break;
422 case 's':
423 set_shell(optarg);
424 break;
425 case 'T':
426 return TEST_EXIT_CODE;
427 case 'u':
428 quote = 0;
429 break;
430 case 'V':
431 printf(UTIL_LINUX_VERSION);
432 return EXIT_SUCCESS;
433 case '?':
434 case ':':
435 parse_error(NULL);
436 default:
437 parse_error(_("internal error, contact the author."));
438 }
439
440 if (!optstr) {
441 if (optind >= argc)
442 parse_error(_("missing optstring argument"));
443 else {
444 optstr = xmalloc(strlen(argv[optind]) + 1);
445 strcpy(optstr, argv[optind]);
446 optind++;
447 }
448 }
449 if (name)
450 argv[optind - 1] = name;
451 else
452 argv[optind - 1] = argv[0];
453
454 return generate_output(argv + optind - 1, argc-optind + 1,
455 optstr, long_options);
456 }