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