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