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 <Todd.Miller@courtesan.com>
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 #include <windows.h>
59 
60 #define	REPLACE_GETOPT		/* use this getopt as the system getopt(3) */
61 
62 #ifdef REPLACE_GETOPT
63 int	opterr = 1;		/* if error message should be printed */
64 int	optind = 1;		/* index into parent argv vector */
65 int	optopt = '?';		/* character checked for validity */
66 #undef	optreset		/* see getopt.h */
67 #define	optreset		__mingw_optreset
68 int	optreset;		/* reset getopt */
69 char    *optarg;		/* argument associated with option */
70 #endif
71 
72 #define PRINT_ERROR	((opterr) && (*options != ':'))
73 
74 #define FLAG_PERMUTE	0x01	/* permute non-options to the end of argv */
75 #define FLAG_ALLARGS	0x02	/* treat non-options as args to option "-1" */
76 #define FLAG_LONGONLY	0x04	/* operate as getopt_long_only */
77 
78 /* return values */
79 #define	BADCH		(int)'?'
80 #define	BADARG		((*options == ':') ? (int)':' : (int)'?')
81 #define	INORDER 	(int)1
82 
83 #ifndef __CYGWIN__
84 #define __progname __argv[0]
85 #else
86 extern char __declspec(dllimport) *__progname;
87 #endif
88 
89 #ifdef __CYGWIN__
90 static char EMSG[] = "";
91 #else
92 #define	EMSG		""
93 #endif
94 
95 static int getopt_internal(int, char * const *, const char *,
96 			   const struct option *, int *, int);
97 static int parse_long_options(char * const *, const char *,
98 			      const struct option *, int *, int);
99 static int gcd(int, int);
100 static void permute_args(int, int, int, char * const *);
101 
102 static char *place = EMSG; /* option letter processing */
103 
104 /* XXX: set optreset to 1 rather than these two */
105 static int nonopt_start = -1; /* first non option argument (for permute) */
106 static int nonopt_end = -1;   /* first option after non options (for permute) */
107 
108 /* Error messages */
109 static const char recargchar[] = "option requires an argument -- %c";
110 static const char recargstring[] = "option requires an argument -- %s";
111 static const char ambig[] = "ambiguous option -- %.*s";
112 static const char noarg[] = "option doesn't take an argument -- %.*s";
113 static const char illoptchar[] = "unknown option -- %c";
114 static const char illoptstring[] = "unknown option -- %s";
115 
116 static void
_vwarnx(const char * fmt,va_list ap)117 _vwarnx(const char *fmt,va_list ap)
118 {
119   (void)fprintf(stderr,"%s: ",__progname);
120   if (fmt != NULL)
121     (void)vfprintf(stderr,fmt,ap);
122   (void)fprintf(stderr,"\n");
123 }
124 
125 static void
warnx(const char * fmt,...)126 warnx(const char *fmt,...)
127 {
128   va_list ap;
129   va_start(ap,fmt);
130   _vwarnx(fmt,ap);
131   va_end(ap);
132 }
133 
134 /*
135  * Compute the greatest common divisor of a and b.
136  */
137 static int
gcd(int a,int b)138 gcd(int a, int b)
139 {
140 	int c;
141 
142 	c = a % b;
143 	while (c != 0) {
144 		a = b;
145 		b = c;
146 		c = a % b;
147 	}
148 
149 	return (b);
150 }
151 
152 /*
153  * Exchange the block from nonopt_start to nonopt_end with the block
154  * from nonopt_end to opt_end (keeping the same order of arguments
155  * in each block).
156  */
157 static void
permute_args(int panonopt_start,int panonopt_end,int opt_end,char * const * nargv)158 permute_args(int panonopt_start, int panonopt_end, int opt_end,
159 	char * const *nargv)
160 {
161 	int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
162 	char *swap;
163 
164 	/*
165 	 * compute lengths of blocks and number and size of cycles
166 	 */
167 	nnonopts = panonopt_end - panonopt_start;
168 	nopts = opt_end - panonopt_end;
169 	ncycle = gcd(nnonopts, nopts);
170 	cyclelen = (opt_end - panonopt_start) / ncycle;
171 
172 	for (i = 0; i < ncycle; i++) {
173 		cstart = panonopt_end+i;
174 		pos = cstart;
175 		for (j = 0; j < cyclelen; j++) {
176 			if (pos >= panonopt_end)
177 				pos -= nnonopts;
178 			else
179 				pos += nopts;
180 			swap = nargv[pos];
181 			/* LINTED const cast */
182 			((char **) nargv)[pos] = nargv[cstart];
183 			/* LINTED const cast */
184 			((char **)nargv)[cstart] = swap;
185 		}
186 	}
187 }
188 
189 /*
190  * parse_long_options --
191  *	Parse long options in argc/argv argument vector.
192  * Returns -1 if short_too is set and the option does not match long_options.
193  */
194 static int
parse_long_options(char * const * nargv,const char * options,const struct option * long_options,int * idx,int short_too)195 parse_long_options(char * const *nargv, const char *options,
196 	const struct option *long_options, int *idx, int short_too)
197 {
198 	char *current_argv, *has_equal;
199 	size_t current_argv_len;
200 	int i, ambiguous, match;
201 
202 #define IDENTICAL_INTERPRETATION(_x, _y)                                \
203 	(long_options[(_x)].has_arg == long_options[(_y)].has_arg &&    \
204 	 long_options[(_x)].flag == long_options[(_y)].flag &&          \
205 	 long_options[(_x)].val == long_options[(_y)].val)
206 
207 	current_argv = place;
208 	match = -1;
209 	ambiguous = 0;
210 
211 	optind++;
212 
213 	if ((has_equal = strchr(current_argv, '=')) != NULL) {
214 		/* argument found (--option=arg) */
215 		current_argv_len = has_equal - current_argv;
216 		has_equal++;
217 	} else
218 		current_argv_len = strlen(current_argv);
219 
220 	for (i = 0; long_options[i].name; i++) {
221 		/* find matching long option */
222 		if (strncmp(current_argv, long_options[i].name,
223 		    current_argv_len))
224 			continue;
225 
226 		if (strlen(long_options[i].name) == current_argv_len) {
227 			/* exact match */
228 			match = i;
229 			ambiguous = 0;
230 			break;
231 		}
232 		/*
233 		 * If this is a known short option, don't allow
234 		 * a partial match of a single character.
235 		 */
236 		if (short_too && current_argv_len == 1)
237 			continue;
238 
239 		if (match == -1)	/* partial match */
240 			match = i;
241 		else if (!IDENTICAL_INTERPRETATION(i, match))
242 			ambiguous = 1;
243 	}
244 	if (ambiguous) {
245 		/* ambiguous abbreviation */
246 		if (PRINT_ERROR)
247 			warnx(ambig, (int)current_argv_len,
248 			     current_argv);
249 		optopt = 0;
250 		return (BADCH);
251 	}
252 	if (match != -1) {		/* option found */
253 		if (long_options[match].has_arg == no_argument
254 		    && has_equal) {
255 			if (PRINT_ERROR)
256 				warnx(noarg, (int)current_argv_len,
257 				     current_argv);
258 			/*
259 			 * XXX: GNU sets optopt to val regardless of flag
260 			 */
261 			if (long_options[match].flag == NULL)
262 				optopt = long_options[match].val;
263 			else
264 				optopt = 0;
265 			return (BADARG);
266 		}
267 		if (long_options[match].has_arg == required_argument ||
268 		    long_options[match].has_arg == optional_argument) {
269 			if (has_equal)
270 				optarg = has_equal;
271 			else if (long_options[match].has_arg ==
272 			    required_argument) {
273 				/*
274 				 * optional argument doesn't use next nargv
275 				 */
276 				optarg = nargv[optind++];
277 			}
278 		}
279 		if ((long_options[match].has_arg == required_argument)
280 		    && (optarg == NULL)) {
281 			/*
282 			 * Missing argument; leading ':' indicates no error
283 			 * should be generated.
284 			 */
285 			if (PRINT_ERROR)
286 				warnx(recargstring,
287 				    current_argv);
288 			/*
289 			 * XXX: GNU sets optopt to val regardless of flag
290 			 */
291 			if (long_options[match].flag == NULL)
292 				optopt = long_options[match].val;
293 			else
294 				optopt = 0;
295 			--optind;
296 			return (BADARG);
297 		}
298 	} else {			/* unknown option */
299 		if (short_too) {
300 			--optind;
301 			return (-1);
302 		}
303 		if (PRINT_ERROR)
304 			warnx(illoptstring, current_argv);
305 		optopt = 0;
306 		return (BADCH);
307 	}
308 	if (idx)
309 		*idx = match;
310 	if (long_options[match].flag) {
311 		*long_options[match].flag = long_options[match].val;
312 		return (0);
313 	} else
314 		return (long_options[match].val);
315 #undef IDENTICAL_INTERPRETATION
316 }
317 
318 /*
319  * getopt_internal --
320  *	Parse argc/argv argument vector.  Called by user level routines.
321  */
322 static int
getopt_internal(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx,int flags)323 getopt_internal(int nargc, char * const *nargv, const char *options,
324 	const struct option *long_options, int *idx, int flags)
325 {
326 	char *oli;				/* option letter list index */
327 	int optchar, short_too;
328 	static int posixly_correct = -1;
329 
330 	if (options == NULL)
331 		return (-1);
332 
333 	/*
334 	 * XXX Some GNU programs (like cvs) set optind to 0 instead of
335 	 * XXX using optreset.  Work around this braindamage.
336 	 */
337 	if (optind == 0)
338 		optind = optreset = 1;
339 
340 	/*
341 	 * Disable GNU extensions if POSIXLY_CORRECT is set or options
342 	 * string begins with a '+'.
343 	 *
344 	 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
345 	 *                 optreset != 0 for GNU compatibility.
346 	 */
347 	if (posixly_correct == -1 || optreset != 0)
348 		posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
349 	if (*options == '-')
350 		flags |= FLAG_ALLARGS;
351 	else if (posixly_correct || *options == '+')
352 		flags &= ~FLAG_PERMUTE;
353 	if (*options == '+' || *options == '-')
354 		options++;
355 
356 	optarg = NULL;
357 	if (optreset)
358 		nonopt_start = nonopt_end = -1;
359 start:
360 	if (optreset || !*place) {		/* update scanning pointer */
361 		optreset = 0;
362 		if (optind >= nargc) {          /* end of argument vector */
363 			place = EMSG;
364 			if (nonopt_end != -1) {
365 				/* do permutation, if we have to */
366 				permute_args(nonopt_start, nonopt_end,
367 				    optind, nargv);
368 				optind -= nonopt_end - nonopt_start;
369 			}
370 			else if (nonopt_start != -1) {
371 				/*
372 				 * If we skipped non-options, set optind
373 				 * to the first of them.
374 				 */
375 				optind = nonopt_start;
376 			}
377 			nonopt_start = nonopt_end = -1;
378 			return (-1);
379 		}
380 		if (*(place = nargv[optind]) != '-' ||
381 		    (place[1] == '\0' && strchr(options, '-') == NULL)) {
382 			place = EMSG;		/* found non-option */
383 			if (flags & FLAG_ALLARGS) {
384 				/*
385 				 * GNU extension:
386 				 * return non-option as argument to option 1
387 				 */
388 				optarg = nargv[optind++];
389 				return (INORDER);
390 			}
391 			if (!(flags & FLAG_PERMUTE)) {
392 				/*
393 				 * If no permutation wanted, stop parsing
394 				 * at first non-option.
395 				 */
396 				return (-1);
397 			}
398 			/* do permutation */
399 			if (nonopt_start == -1)
400 				nonopt_start = optind;
401 			else if (nonopt_end != -1) {
402 				permute_args(nonopt_start, nonopt_end,
403 				    optind, nargv);
404 				nonopt_start = optind -
405 				    (nonopt_end - nonopt_start);
406 				nonopt_end = -1;
407 			}
408 			optind++;
409 			/* process next argument */
410 			goto start;
411 		}
412 		if (nonopt_start != -1 && nonopt_end == -1)
413 			nonopt_end = optind;
414 
415 		/*
416 		 * If we have "-" do nothing, if "--" we are done.
417 		 */
418 		if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
419 			optind++;
420 			place = EMSG;
421 			/*
422 			 * We found an option (--), so if we skipped
423 			 * non-options, we have to permute.
424 			 */
425 			if (nonopt_end != -1) {
426 				permute_args(nonopt_start, nonopt_end,
427 				    optind, nargv);
428 				optind -= nonopt_end - nonopt_start;
429 			}
430 			nonopt_start = nonopt_end = -1;
431 			return (-1);
432 		}
433 	}
434 
435 	/*
436 	 * Check long options if:
437 	 *  1) we were passed some
438 	 *  2) the arg is not just "-"
439 	 *  3) either the arg starts with -- we are getopt_long_only()
440 	 */
441 	if (long_options != NULL && place != nargv[optind] &&
442 	    (*place == '-' || (flags & FLAG_LONGONLY))) {
443 		short_too = 0;
444 		if (*place == '-')
445 			place++;		/* --foo long option */
446 		else if (*place != ':' && strchr(options, *place) != NULL)
447 			short_too = 1;		/* could be short option too */
448 
449 		optchar = parse_long_options(nargv, options, long_options,
450 		    idx, short_too);
451 		if (optchar != -1) {
452 			place = EMSG;
453 			return (optchar);
454 		}
455 	}
456 
457 	if ((optchar = (int)*place++) == (int)':' ||
458 	    (optchar == (int)'-' && *place != '\0') ||
459 	    (oli = strchr(options, optchar)) == NULL) {
460 		/*
461 		 * If the user specified "-" and  '-' isn't listed in
462 		 * options, return -1 (non-option) as per POSIX.
463 		 * Otherwise, it is an unknown option character (or ':').
464 		 */
465 		if (optchar == (int)'-' && *place == '\0')
466 			return (-1);
467 		if (!*place)
468 			++optind;
469 		if (PRINT_ERROR)
470 			warnx(illoptchar, optchar);
471 		optopt = optchar;
472 		return (BADCH);
473 	}
474 	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
475 		/* -W long-option */
476 		if (*place)			/* no space */
477 			/* NOTHING */;
478 		else if (++optind >= nargc) {	/* no arg */
479 			place = EMSG;
480 			if (PRINT_ERROR)
481 				warnx(recargchar, optchar);
482 			optopt = optchar;
483 			return (BADARG);
484 		} else				/* white space */
485 			place = nargv[optind];
486 		optchar = parse_long_options(nargv, options, long_options,
487 		    idx, 0);
488 		place = EMSG;
489 		return (optchar);
490 	}
491 	if (*++oli != ':') {			/* doesn't take argument */
492 		if (!*place)
493 			++optind;
494 	} else {				/* takes (optional) argument */
495 		optarg = NULL;
496 		if (*place)			/* no white space */
497 			optarg = place;
498 		else if (oli[1] != ':') {	/* arg not optional */
499 			if (++optind >= nargc) {	/* no arg */
500 				place = EMSG;
501 				if (PRINT_ERROR)
502 					warnx(recargchar, optchar);
503 				optopt = optchar;
504 				return (BADARG);
505 			} else
506 				optarg = nargv[optind];
507 		}
508 		place = EMSG;
509 		++optind;
510 	}
511 	/* dump back option letter */
512 	return (optchar);
513 }
514 
515 #ifdef REPLACE_GETOPT
516 /*
517  * getopt --
518  *	Parse argc/argv argument vector.
519  *
520  * [eventually this will replace the BSD getopt]
521  */
522 int
getopt(int nargc,char * const * nargv,const char * options)523 getopt(int nargc, char * const *nargv, const char *options)
524 {
525 
526 	/*
527 	 * We don't pass FLAG_PERMUTE to getopt_internal() since
528 	 * the BSD getopt(3) (unlike GNU) has never done this.
529 	 *
530 	 * Furthermore, since many privileged programs call getopt()
531 	 * before dropping privileges it makes sense to keep things
532 	 * as simple (and bug-free) as possible.
533 	 */
534 	return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
535 }
536 #endif /* REPLACE_GETOPT */
537 
538 /*
539  * getopt_long --
540  *	Parse argc/argv argument vector.
541  */
542 int
getopt_long(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)543 getopt_long(int nargc, char * const *nargv, const char *options,
544     const struct option *long_options, int *idx)
545 {
546 
547 	return (getopt_internal(nargc, nargv, options, long_options, idx,
548 	    FLAG_PERMUTE));
549 }
550 
551 /*
552  * getopt_long_only --
553  *	Parse argc/argv argument vector.
554  */
555 int
getopt_long_only(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)556 getopt_long_only(int nargc, char * const *nargv, const char *options,
557     const struct option *long_options, int *idx)
558 {
559 
560 	return (getopt_internal(nargc, nargv, options, long_options, idx,
561 	    FLAG_PERMUTE|FLAG_LONGONLY));
562 }
563