1 /* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $ */
2 /* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
3
4 /*
5 * Copyright (c) 2002 Todd C. Miller <[email protected]>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 * Sponsored in part by the Defense Advanced Research Projects
20 * Agency (DARPA) and Air Force Research Laboratory, Air Force
21 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
22 */
23 /*-
24 * Copyright (c) 2000 The NetBSD Foundation, Inc.
25 * All rights reserved.
26 *
27 * This code is derived from software contributed to The NetBSD Foundation
28 * by Dieter Baron and Thomas Klausner.
29 *
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
40 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
41 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
43 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
47 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49 * POSSIBILITY OF SUCH DAMAGE.
50 */
51
52 #include <errno.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <getopt.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #ifdef _WIN32
59 #include <windows.h>
60 #else
61 #include <err.h>
62 #endif
63
64 #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
65
66 #ifdef REPLACE_GETOPT
67 int opterr = 1; /* if error message should be printed */
68 int optind = 1; /* index into parent argv vector */
69 int optopt = '?'; /* character checked for validity */
70 #undef optreset /* see getopt.h */
71 #define optreset __mingw_optreset
72 int optreset; /* reset getopt */
73 char *optarg; /* argument associated with option */
74 #endif
75
76 #define PRINT_ERROR ((opterr) && (*options != ':'))
77
78 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
79 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
80 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
81
82 /* return values */
83 #define BADCH (int)'?'
84 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
85 #define INORDER (int)1
86
87 #ifdef __CYGWIN__
88 static char EMSG[] = "";
89 #else
90 #define EMSG ""
91 #endif
92
93 static int getopt_internal(int, char * const *, const char *,
94 const struct option *, int *, int);
95 static int parse_long_options(char * const *, const char *,
96 const struct option *, int *, int);
97 static int gcd(int, int);
98 static void permute_args(int, int, int, char * const *);
99
100 static char *place = EMSG; /* option letter processing */
101
102 /* XXX: set optreset to 1 rather than these two */
103 static int nonopt_start = -1; /* first non option argument (for permute) */
104 static int nonopt_end = -1; /* first option after non options (for permute) */
105
106 /* Error messages */
107 static const char recargchar[] = "option requires an argument -- %c";
108 static const char recargstring[] = "option requires an argument -- %s";
109 static const char ambig[] = "ambiguous option -- %.*s";
110 static const char noarg[] = "option doesn't take an argument -- %.*s";
111 static const char illoptchar[] = "unknown option -- %c";
112 static const char illoptstring[] = "unknown option -- %s";
113
114 #ifdef _WIN32
115 #ifndef __CYGWIN__
116 #define __progname __argv[0]
117 #else
118 extern char __declspec(dllimport) *__progname;
119 #endif
120
121 static void
_vwarnx(const char * fmt,va_list ap)122 _vwarnx(const char *fmt,va_list ap)
123 {
124 (void)fprintf(stderr,"%s: ",__progname);
125 if (fmt != NULL)
126 (void)vfprintf(stderr,fmt,ap);
127 (void)fprintf(stderr,"\n");
128 }
129
130 static void
warnx(const char * fmt,...)131 warnx(const char *fmt,...)
132 {
133 va_list ap;
134 va_start(ap,fmt);
135 _vwarnx(fmt,ap);
136 va_end(ap);
137 }
138 #endif
139
140 /*
141 * Compute the greatest common divisor of a and b.
142 */
143 static int
gcd(int a,int b)144 gcd(int a, int b)
145 {
146 int c;
147
148 c = a % b;
149 while (c != 0) {
150 a = b;
151 b = c;
152 c = a % b;
153 }
154
155 return (b);
156 }
157
158 /*
159 * Exchange the block from nonopt_start to nonopt_end with the block
160 * from nonopt_end to opt_end (keeping the same order of arguments
161 * in each block).
162 */
163 static void
permute_args(int panonopt_start,int panonopt_end,int opt_end,char * const * nargv)164 permute_args(int panonopt_start, int panonopt_end, int opt_end,
165 char * const *nargv)
166 {
167 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
168 char *swap;
169
170 /*
171 * compute lengths of blocks and number and size of cycles
172 */
173 nnonopts = panonopt_end - panonopt_start;
174 nopts = opt_end - panonopt_end;
175 ncycle = gcd(nnonopts, nopts);
176 cyclelen = (opt_end - panonopt_start) / ncycle;
177
178 for (i = 0; i < ncycle; i++) {
179 cstart = panonopt_end+i;
180 pos = cstart;
181 for (j = 0; j < cyclelen; j++) {
182 if (pos >= panonopt_end)
183 pos -= nnonopts;
184 else
185 pos += nopts;
186 swap = nargv[pos];
187 /* LINTED const cast */
188 ((char **) nargv)[pos] = nargv[cstart];
189 /* LINTED const cast */
190 ((char **)nargv)[cstart] = swap;
191 }
192 }
193 }
194
195 /*
196 * parse_long_options --
197 * Parse long options in argc/argv argument vector.
198 * Returns -1 if short_too is set and the option does not match long_options.
199 */
200 static int
parse_long_options(char * const * nargv,const char * options,const struct option * long_options,int * idx,int short_too)201 parse_long_options(char * const *nargv, const char *options,
202 const struct option *long_options, int *idx, int short_too)
203 {
204 char *current_argv, *has_equal;
205 size_t current_argv_len;
206 int i, ambiguous, match;
207
208 #define IDENTICAL_INTERPRETATION(_x, _y) \
209 (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
210 long_options[(_x)].flag == long_options[(_y)].flag && \
211 long_options[(_x)].val == long_options[(_y)].val)
212
213 current_argv = place;
214 match = -1;
215 ambiguous = 0;
216
217 optind++;
218
219 if ((has_equal = strchr(current_argv, '=')) != NULL) {
220 /* argument found (--option=arg) */
221 current_argv_len = has_equal - current_argv;
222 has_equal++;
223 } else
224 current_argv_len = strlen(current_argv);
225
226 for (i = 0; long_options[i].name; i++) {
227 /* find matching long option */
228 if (strncmp(current_argv, long_options[i].name,
229 current_argv_len))
230 continue;
231
232 if (strlen(long_options[i].name) == current_argv_len) {
233 /* exact match */
234 match = i;
235 ambiguous = 0;
236 break;
237 }
238 /*
239 * If this is a known short option, don't allow
240 * a partial match of a single character.
241 */
242 if (short_too && current_argv_len == 1)
243 continue;
244
245 if (match == -1) /* partial match */
246 match = i;
247 else if (!IDENTICAL_INTERPRETATION(i, match))
248 ambiguous = 1;
249 }
250 if (ambiguous) {
251 /* ambiguous abbreviation */
252 if (PRINT_ERROR)
253 warnx(ambig, (int)current_argv_len,
254 current_argv);
255 optopt = 0;
256 return (BADCH);
257 }
258 if (match != -1) { /* option found */
259 if (long_options[match].has_arg == no_argument
260 && has_equal) {
261 if (PRINT_ERROR)
262 warnx(noarg, (int)current_argv_len,
263 current_argv);
264 /*
265 * XXX: GNU sets optopt to val regardless of flag
266 */
267 if (long_options[match].flag == NULL)
268 optopt = long_options[match].val;
269 else
270 optopt = 0;
271 return (BADARG);
272 }
273 if (long_options[match].has_arg == required_argument ||
274 long_options[match].has_arg == optional_argument) {
275 if (has_equal)
276 optarg = has_equal;
277 else if (long_options[match].has_arg ==
278 required_argument) {
279 /*
280 * optional argument doesn't use next nargv
281 */
282 optarg = nargv[optind++];
283 }
284 }
285 if ((long_options[match].has_arg == required_argument)
286 && (optarg == NULL)) {
287 /*
288 * Missing argument; leading ':' indicates no error
289 * should be generated.
290 */
291 if (PRINT_ERROR)
292 warnx(recargstring,
293 current_argv);
294 /*
295 * XXX: GNU sets optopt to val regardless of flag
296 */
297 if (long_options[match].flag == NULL)
298 optopt = long_options[match].val;
299 else
300 optopt = 0;
301 --optind;
302 return (BADARG);
303 }
304 } else { /* unknown option */
305 if (short_too) {
306 --optind;
307 return (-1);
308 }
309 if (PRINT_ERROR)
310 warnx(illoptstring, current_argv);
311 optopt = 0;
312 return (BADCH);
313 }
314 if (idx)
315 *idx = match;
316 if (long_options[match].flag) {
317 *long_options[match].flag = long_options[match].val;
318 return (0);
319 } else
320 return (long_options[match].val);
321 #undef IDENTICAL_INTERPRETATION
322 }
323
324 /*
325 * getopt_internal --
326 * Parse argc/argv argument vector. Called by user level routines.
327 */
328 static int
getopt_internal(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx,int flags)329 getopt_internal(int nargc, char * const *nargv, const char *options,
330 const struct option *long_options, int *idx, int flags)
331 {
332 char *oli; /* option letter list index */
333 int optchar, short_too;
334 static int posixly_correct = -1;
335
336 if (options == NULL)
337 return (-1);
338
339 /*
340 * XXX Some GNU programs (like cvs) set optind to 0 instead of
341 * XXX using optreset. Work around this braindamage.
342 */
343 if (optind == 0)
344 optind = optreset = 1;
345
346 /*
347 * Disable GNU extensions if POSIXLY_CORRECT is set or options
348 * string begins with a '+'.
349 *
350 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
351 * optreset != 0 for GNU compatibility.
352 */
353 if (posixly_correct == -1 || optreset != 0)
354 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
355 if (*options == '-')
356 flags |= FLAG_ALLARGS;
357 else if (posixly_correct || *options == '+')
358 flags &= ~FLAG_PERMUTE;
359 if (*options == '+' || *options == '-')
360 options++;
361
362 optarg = NULL;
363 if (optreset)
364 nonopt_start = nonopt_end = -1;
365 start:
366 if (optreset || !*place) { /* update scanning pointer */
367 optreset = 0;
368 if (optind >= nargc) { /* end of argument vector */
369 place = EMSG;
370 if (nonopt_end != -1) {
371 /* do permutation, if we have to */
372 permute_args(nonopt_start, nonopt_end,
373 optind, nargv);
374 optind -= nonopt_end - nonopt_start;
375 }
376 else if (nonopt_start != -1) {
377 /*
378 * If we skipped non-options, set optind
379 * to the first of them.
380 */
381 optind = nonopt_start;
382 }
383 nonopt_start = nonopt_end = -1;
384 return (-1);
385 }
386 if (*(place = nargv[optind]) != '-' ||
387 (place[1] == '\0' && strchr(options, '-') == NULL)) {
388 place = EMSG; /* found non-option */
389 if (flags & FLAG_ALLARGS) {
390 /*
391 * GNU extension:
392 * return non-option as argument to option 1
393 */
394 optarg = nargv[optind++];
395 return (INORDER);
396 }
397 if (!(flags & FLAG_PERMUTE)) {
398 /*
399 * If no permutation wanted, stop parsing
400 * at first non-option.
401 */
402 return (-1);
403 }
404 /* do permutation */
405 if (nonopt_start == -1)
406 nonopt_start = optind;
407 else if (nonopt_end != -1) {
408 permute_args(nonopt_start, nonopt_end,
409 optind, nargv);
410 nonopt_start = optind -
411 (nonopt_end - nonopt_start);
412 nonopt_end = -1;
413 }
414 optind++;
415 /* process next argument */
416 goto start;
417 }
418 if (nonopt_start != -1 && nonopt_end == -1)
419 nonopt_end = optind;
420
421 /*
422 * If we have "-" do nothing, if "--" we are done.
423 */
424 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
425 optind++;
426 place = EMSG;
427 /*
428 * We found an option (--), so if we skipped
429 * non-options, we have to permute.
430 */
431 if (nonopt_end != -1) {
432 permute_args(nonopt_start, nonopt_end,
433 optind, nargv);
434 optind -= nonopt_end - nonopt_start;
435 }
436 nonopt_start = nonopt_end = -1;
437 return (-1);
438 }
439 }
440
441 /*
442 * Check long options if:
443 * 1) we were passed some
444 * 2) the arg is not just "-"
445 * 3) either the arg starts with -- we are getopt_long_only()
446 */
447 if (long_options != NULL && place != nargv[optind] &&
448 (*place == '-' || (flags & FLAG_LONGONLY))) {
449 short_too = 0;
450 if (*place == '-')
451 place++; /* --foo long option */
452 else if (*place != ':' && strchr(options, *place) != NULL)
453 short_too = 1; /* could be short option too */
454
455 optchar = parse_long_options(nargv, options, long_options,
456 idx, short_too);
457 if (optchar != -1) {
458 place = EMSG;
459 return (optchar);
460 }
461 }
462
463 if ((optchar = (int)*place++) == (int)':' ||
464 (optchar == (int)'-' && *place != '\0') ||
465 (oli = strchr(options, optchar)) == NULL) {
466 /*
467 * If the user specified "-" and '-' isn't listed in
468 * options, return -1 (non-option) as per POSIX.
469 * Otherwise, it is an unknown option character (or ':').
470 */
471 if (optchar == (int)'-' && *place == '\0')
472 return (-1);
473 if (!*place)
474 ++optind;
475 if (PRINT_ERROR)
476 warnx(illoptchar, optchar);
477 optopt = optchar;
478 return (BADCH);
479 }
480 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
481 /* -W long-option */
482 if (*place) /* no space */
483 /* NOTHING */;
484 else if (++optind >= nargc) { /* no arg */
485 place = EMSG;
486 if (PRINT_ERROR)
487 warnx(recargchar, optchar);
488 optopt = optchar;
489 return (BADARG);
490 } else /* white space */
491 place = nargv[optind];
492 optchar = parse_long_options(nargv, options, long_options,
493 idx, 0);
494 place = EMSG;
495 return (optchar);
496 }
497 if (*++oli != ':') { /* doesn't take argument */
498 if (!*place)
499 ++optind;
500 } else { /* takes (optional) argument */
501 optarg = NULL;
502 if (*place) /* no white space */
503 optarg = place;
504 else if (oli[1] != ':') { /* arg not optional */
505 if (++optind >= nargc) { /* no arg */
506 place = EMSG;
507 if (PRINT_ERROR)
508 warnx(recargchar, optchar);
509 optopt = optchar;
510 return (BADARG);
511 } else
512 optarg = nargv[optind];
513 }
514 place = EMSG;
515 ++optind;
516 }
517 /* dump back option letter */
518 return (optchar);
519 }
520
521 #ifdef REPLACE_GETOPT
522 /*
523 * getopt --
524 * Parse argc/argv argument vector.
525 *
526 * [eventually this will replace the BSD getopt]
527 */
528 int
getopt(int nargc,char * const * nargv,const char * options)529 getopt(int nargc, char * const *nargv, const char *options)
530 {
531
532 /*
533 * We don't pass FLAG_PERMUTE to getopt_internal() since
534 * the BSD getopt(3) (unlike GNU) has never done this.
535 *
536 * Furthermore, since many privileged programs call getopt()
537 * before dropping privileges it makes sense to keep things
538 * as simple (and bug-free) as possible.
539 */
540 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
541 }
542 #endif /* REPLACE_GETOPT */
543
544 /*
545 * getopt_long --
546 * Parse argc/argv argument vector.
547 */
548 int
getopt_long(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)549 getopt_long(int nargc, char * const *nargv, const char *options,
550 const struct option *long_options, int *idx)
551 {
552
553 return (getopt_internal(nargc, nargv, options, long_options, idx,
554 FLAG_PERMUTE));
555 }
556
557 /*
558 * getopt_long_only --
559 * Parse argc/argv argument vector.
560 */
561 int
getopt_long_only(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)562 getopt_long_only(int nargc, char * const *nargv, const char *options,
563 const struct option *long_options, int *idx)
564 {
565
566 return (getopt_internal(nargc, nargv, options, long_options, idx,
567 FLAG_PERMUTE|FLAG_LONGONLY));
568 }
569