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