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