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 "wingetopt.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 #ifndef _WIN32
348 	if (posixly_correct == -1 || optreset != 0)
349 		posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
350 #endif
351 	if (*options == '-')
352 		flags |= FLAG_ALLARGS;
353 	else if (posixly_correct || *options == '+')
354 		flags &= ~FLAG_PERMUTE;
355 	if (*options == '+' || *options == '-')
356 		options++;
357 
358 	optarg = NULL;
359 	if (optreset)
360 		nonopt_start = nonopt_end = -1;
361 start:
362 	if (optreset || !*place) {		/* update scanning pointer */
363 		optreset = 0;
364 		if (optind >= nargc) {          /* end of argument vector */
365 			place = EMSG;
366 			if (nonopt_end != -1) {
367 				/* do permutation, if we have to */
368 				permute_args(nonopt_start, nonopt_end,
369 				    optind, nargv);
370 				optind -= nonopt_end - nonopt_start;
371 			}
372 			else if (nonopt_start != -1) {
373 				/*
374 				 * If we skipped non-options, set optind
375 				 * to the first of them.
376 				 */
377 				optind = nonopt_start;
378 			}
379 			nonopt_start = nonopt_end = -1;
380 			return (-1);
381 		}
382 		if (*(place = nargv[optind]) != '-' ||
383 		    (place[1] == '\0' && strchr(options, '-') == NULL)) {
384 			place = EMSG;		/* found non-option */
385 			if (flags & FLAG_ALLARGS) {
386 				/*
387 				 * GNU extension:
388 				 * return non-option as argument to option 1
389 				 */
390 				optarg = nargv[optind++];
391 				return (INORDER);
392 			}
393 			if (!(flags & FLAG_PERMUTE)) {
394 				/*
395 				 * If no permutation wanted, stop parsing
396 				 * at first non-option.
397 				 */
398 				return (-1);
399 			}
400 			/* do permutation */
401 			if (nonopt_start == -1)
402 				nonopt_start = optind;
403 			else if (nonopt_end != -1) {
404 				permute_args(nonopt_start, nonopt_end,
405 				    optind, nargv);
406 				nonopt_start = optind -
407 				    (nonopt_end - nonopt_start);
408 				nonopt_end = -1;
409 			}
410 			optind++;
411 			/* process next argument */
412 			goto start;
413 		}
414 		if (nonopt_start != -1 && nonopt_end == -1)
415 			nonopt_end = optind;
416 
417 		/*
418 		 * If we have "-" do nothing, if "--" we are done.
419 		 */
420 		if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
421 			optind++;
422 			place = EMSG;
423 			/*
424 			 * We found an option (--), so if we skipped
425 			 * non-options, we have to permute.
426 			 */
427 			if (nonopt_end != -1) {
428 				permute_args(nonopt_start, nonopt_end,
429 				    optind, nargv);
430 				optind -= nonopt_end - nonopt_start;
431 			}
432 			nonopt_start = nonopt_end = -1;
433 			return (-1);
434 		}
435 	}
436 
437 	/*
438 	 * Check long options if:
439 	 *  1) we were passed some
440 	 *  2) the arg is not just "-"
441 	 *  3) either the arg starts with -- we are getopt_long_only()
442 	 */
443 	if (long_options != NULL && place != nargv[optind] &&
444 	    (*place == '-' || (flags & FLAG_LONGONLY))) {
445 		short_too = 0;
446 		if (*place == '-')
447 			place++;		/* --foo long option */
448 		else if (*place != ':' && strchr(options, *place) != NULL)
449 			short_too = 1;		/* could be short option too */
450 
451 		optchar = parse_long_options(nargv, options, long_options,
452 		    idx, short_too);
453 		if (optchar != -1) {
454 			place = EMSG;
455 			return (optchar);
456 		}
457 	}
458 
459 	if ((optchar = (int)*place++) == (int)':' ||
460 	    (optchar == (int)'-' && *place != '\0') ||
461 	    (oli = strchr(options, optchar)) == NULL) {
462 		/*
463 		 * If the user specified "-" and  '-' isn't listed in
464 		 * options, return -1 (non-option) as per POSIX.
465 		 * Otherwise, it is an unknown option character (or ':').
466 		 */
467 		if (optchar == (int)'-' && *place == '\0')
468 			return (-1);
469 		if (!*place)
470 			++optind;
471 		if (PRINT_ERROR)
472 			warnx(illoptchar, optchar);
473 		optopt = optchar;
474 		return (BADCH);
475 	}
476 	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
477 		/* -W long-option */
478 		if (*place)			/* no space */
479 			/* NOTHING */;
480 		else if (++optind >= nargc) {	/* no arg */
481 			place = EMSG;
482 			if (PRINT_ERROR)
483 				warnx(recargchar, optchar);
484 			optopt = optchar;
485 			return (BADARG);
486 		} else				/* white space */
487 			place = nargv[optind];
488 		optchar = parse_long_options(nargv, options, long_options,
489 		    idx, 0);
490 		place = EMSG;
491 		return (optchar);
492 	}
493 	if (*++oli != ':') {			/* doesn't take argument */
494 		if (!*place)
495 			++optind;
496 	} else {				/* takes (optional) argument */
497 		optarg = NULL;
498 		if (*place)			/* no white space */
499 			optarg = place;
500 		else if (oli[1] != ':') {	/* arg not optional */
501 			if (++optind >= nargc) {	/* no arg */
502 				place = EMSG;
503 				if (PRINT_ERROR)
504 					warnx(recargchar, optchar);
505 				optopt = optchar;
506 				return (BADARG);
507 			} else
508 				optarg = nargv[optind];
509 		}
510 		place = EMSG;
511 		++optind;
512 	}
513 	/* dump back option letter */
514 	return (optchar);
515 }
516 
517 #ifdef REPLACE_GETOPT
518 /*
519  * getopt --
520  *	Parse argc/argv argument vector.
521  *
522  * [eventually this will replace the BSD getopt]
523  */
524 int
getopt(int nargc,char * const * nargv,const char * options)525 getopt(int nargc, char * const *nargv, const char *options)
526 {
527 
528 	/*
529 	 * We don't pass FLAG_PERMUTE to getopt_internal() since
530 	 * the BSD getopt(3) (unlike GNU) has never done this.
531 	 *
532 	 * Furthermore, since many privileged programs call getopt()
533 	 * before dropping privileges it makes sense to keep things
534 	 * as simple (and bug-free) as possible.
535 	 */
536 	return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
537 }
538 #endif /* REPLACE_GETOPT */
539 
540 /*
541  * getopt_long --
542  *	Parse argc/argv argument vector.
543  */
544 int
getopt_long(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)545 getopt_long(int nargc, char * const *nargv, const char *options,
546     const struct option *long_options, int *idx)
547 {
548 
549 	return (getopt_internal(nargc, nargv, options, long_options, idx,
550 	    FLAG_PERMUTE));
551 }
552 
553 /*
554  * getopt_long_only --
555  *	Parse argc/argv argument vector.
556  */
557 int
getopt_long_only(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)558 getopt_long_only(int nargc, char * const *nargv, const char *options,
559     const struct option *long_options, int *idx)
560 {
561 
562 	return (getopt_internal(nargc, nargv, options, long_options, idx,
563 	    FLAG_PERMUTE|FLAG_LONGONLY));
564 }
565