1 /* $OpenBSD: getopt_long.c,v 1.16 2004/02/04 18:17:25 millert 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 * 3. All advertising materials mentioning features or use of this software 39 * must display the following acknowledgement: 40 * This product includes software developed by the NetBSD 41 * Foundation, Inc. and its contributors. 42 * 4. Neither the name of The NetBSD Foundation nor the names of its 43 * contributors may be used to endorse or promote products derived 44 * from this software without specific prior written permission. 45 * 46 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 47 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 48 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 49 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 50 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 51 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 52 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 53 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 54 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 55 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 56 * POSSIBILITY OF SUCH DAMAGE. 57 */ 58 59 #if 0 60 #if defined(LIBC_SCCS) && !defined(lint) 61 static char *rcsid = "$OpenBSD: getopt_long.c,v 1.16 2004/02/04 18:17:25 millert Exp $"; 62 #endif /* LIBC_SCCS and not lint */ 63 #endif 64 #include <sys/cdefs.h> 65 __FBSDID("$FreeBSD$"); 66 67 #include <err.h> 68 #include <errno.h> 69 #include <getopt.h> 70 #include <stdlib.h> 71 #include <string.h> 72 73 #define GNU_COMPATIBLE /* Be more compatible, configure's use us! */ 74 75 #ifndef GNU_COMPATIBLE 76 #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ 77 #endif 78 79 #ifdef REPLACE_GETOPT 80 int opterr = 1; /* if error message should be printed */ 81 int optind = 1; /* index into parent argv vector */ 82 int optopt = '?'; /* character checked for validity */ 83 int optreset; /* reset getopt */ 84 char *optarg; /* argument associated with option */ 85 #endif 86 87 #define PRINT_ERROR ((opterr) && (*options != ':')) 88 89 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ 90 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ 91 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ 92 93 /* return values */ 94 #define BADCH (int)'?' 95 #define BADARG ((*options == ':') ? (int)':' : (int)'?') 96 #define INORDER (int)1 97 98 #define EMSG "" 99 100 #ifdef GNU_COMPATIBLE 101 #define NO_PREFIX (-1) 102 #define D_PREFIX 0 103 #define DD_PREFIX 1 104 #define W_PREFIX 2 105 #endif 106 107 static int getopt_internal(int, char * const *, const char *, 108 const struct option *, int *, int); 109 static int parse_long_options(char * const *, const char *, 110 const struct option *, int *, int); 111 static int gcd(int, int); 112 static void permute_args(int, int, int, char * const *); 113 114 static char *place = EMSG; /* option letter processing */ 115 116 /* XXX: set optreset to 1 rather than these two */ 117 static int nonopt_start = -1; /* first non option argument (for permute) */ 118 static int nonopt_end = -1; /* first option after non options (for permute) */ 119 120 /* Error messages */ 121 static const char recargchar[] = "option requires an argument -- %c"; 122 static const char illoptchar[] = "illegal option -- %c"; /* From P1003.2 */ 123 #ifdef GNU_COMPATIBLE 124 static int dash_prefix = NO_PREFIX; 125 static const char gnuoptchar[] = "invalid option -- %c"; 126 127 static const char recargstring[] = "option `%s%s' requires an argument"; 128 static const char ambig[] = "option `%s%.*s' is ambiguous"; 129 static const char noarg[] = "option `%s%.*s' doesn't allow an argument"; 130 static const char illoptstring[] = "unrecognized option `%s%s'"; 131 #else 132 static const char recargstring[] = "option requires an argument -- %s"; 133 static const char ambig[] = "ambiguous option -- %.*s"; 134 static const char noarg[] = "option doesn't take an argument -- %.*s"; 135 static const char illoptstring[] = "unknown option -- %s"; 136 #endif 137 138 /* 139 * Compute the greatest common divisor of a and b. 140 */ 141 static int 142 gcd(int a, int b) 143 { 144 int c; 145 146 c = a % b; 147 while (c != 0) { 148 a = b; 149 b = c; 150 c = a % b; 151 } 152 153 return (b); 154 } 155 156 /* 157 * Exchange the block from nonopt_start to nonopt_end with the block 158 * from nonopt_end to opt_end (keeping the same order of arguments 159 * in each block). 160 */ 161 static void 162 permute_args(int panonopt_start, int panonopt_end, int opt_end, 163 char * const *nargv) 164 { 165 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; 166 char *swap; 167 168 /* 169 * compute lengths of blocks and number and size of cycles 170 */ 171 nnonopts = panonopt_end - panonopt_start; 172 nopts = opt_end - panonopt_end; 173 ncycle = gcd(nnonopts, nopts); 174 cyclelen = (opt_end - panonopt_start) / ncycle; 175 176 for (i = 0; i < ncycle; i++) { 177 cstart = panonopt_end+i; 178 pos = cstart; 179 for (j = 0; j < cyclelen; j++) { 180 if (pos >= panonopt_end) 181 pos -= nnonopts; 182 else 183 pos += nopts; 184 swap = nargv[pos]; 185 /* LINTED const cast */ 186 ((char **) nargv)[pos] = nargv[cstart]; 187 /* LINTED const cast */ 188 ((char **)nargv)[cstart] = swap; 189 } 190 } 191 } 192 193 /* 194 * parse_long_options -- 195 * Parse long options in argc/argv argument vector. 196 * Returns -1 if short_too is set and the option does not match long_options. 197 */ 198 static int 199 parse_long_options(char * const *nargv, const char *options, 200 const struct option *long_options, int *idx, int short_too) 201 { 202 char *current_argv, *has_equal; 203 #ifdef GNU_COMPATIBLE 204 char *current_dash; 205 #endif 206 size_t current_argv_len; 207 int i, match; 208 209 current_argv = place; 210 #ifdef GNU_COMPATIBLE 211 switch (dash_prefix) { 212 case D_PREFIX: 213 current_dash = "-"; 214 break; 215 case DD_PREFIX: 216 current_dash = "--"; 217 break; 218 case W_PREFIX: 219 current_dash = "-W "; 220 break; 221 default: 222 current_dash = ""; 223 break; 224 } 225 #endif 226 match = -1; 227 228 optind++; 229 230 if ((has_equal = strchr(current_argv, '=')) != NULL) { 231 /* argument found (--option=arg) */ 232 current_argv_len = has_equal - current_argv; 233 has_equal++; 234 } else 235 current_argv_len = strlen(current_argv); 236 237 for (i = 0; long_options[i].name; i++) { 238 /* find matching long option */ 239 if (strncmp(current_argv, long_options[i].name, 240 current_argv_len)) 241 continue; 242 243 if (strlen(long_options[i].name) == current_argv_len) { 244 /* exact match */ 245 match = i; 246 break; 247 } 248 /* 249 * If this is a known short option, don't allow 250 * a partial match of a single character. 251 */ 252 if (short_too && current_argv_len == 1) 253 continue; 254 255 if (match == -1) /* partial match */ 256 match = i; 257 else { 258 /* ambiguous abbreviation */ 259 if (PRINT_ERROR) 260 warnx(ambig, 261 #ifdef GNU_COMPATIBLE 262 current_dash, 263 #endif 264 (int)current_argv_len, 265 current_argv); 266 optopt = 0; 267 return (BADCH); 268 } 269 } 270 if (match != -1) { /* option found */ 271 if (long_options[match].has_arg == no_argument 272 && has_equal) { 273 if (PRINT_ERROR) 274 warnx(noarg, 275 #ifdef GNU_COMPATIBLE 276 current_dash, 277 #endif 278 (int)current_argv_len, 279 current_argv); 280 /* 281 * XXX: GNU sets optopt to val regardless of flag 282 */ 283 if (long_options[match].flag == NULL) 284 optopt = long_options[match].val; 285 else 286 optopt = 0; 287 #ifdef GNU_COMPATIBLE 288 return (BADCH); 289 #else 290 return (BADARG); 291 #endif 292 } 293 if (long_options[match].has_arg == required_argument || 294 long_options[match].has_arg == optional_argument) { 295 if (has_equal) 296 optarg = has_equal; 297 else if (long_options[match].has_arg == 298 required_argument) { 299 /* 300 * optional argument doesn't use next nargv 301 */ 302 optarg = nargv[optind++]; 303 } 304 } 305 if ((long_options[match].has_arg == required_argument) 306 && (optarg == NULL)) { 307 /* 308 * Missing argument; leading ':' indicates no error 309 * should be generated. 310 */ 311 if (PRINT_ERROR) 312 warnx(recargstring, 313 #ifdef GNU_COMPATIBLE 314 current_dash, 315 #endif 316 current_argv); 317 /* 318 * XXX: GNU sets optopt to val regardless of flag 319 */ 320 if (long_options[match].flag == NULL) 321 optopt = long_options[match].val; 322 else 323 optopt = 0; 324 --optind; 325 return (BADARG); 326 } 327 } else { /* unknown option */ 328 if (short_too) { 329 --optind; 330 return (-1); 331 } 332 if (PRINT_ERROR) 333 warnx(illoptstring, 334 #ifdef GNU_COMPATIBLE 335 current_dash, 336 #endif 337 current_argv); 338 optopt = 0; 339 return (BADCH); 340 } 341 if (idx) 342 *idx = match; 343 if (long_options[match].flag) { 344 *long_options[match].flag = long_options[match].val; 345 return (0); 346 } else 347 return (long_options[match].val); 348 } 349 350 /* 351 * getopt_internal -- 352 * Parse argc/argv argument vector. Called by user level routines. 353 */ 354 static int 355 getopt_internal(int nargc, char * const *nargv, const char *options, 356 const struct option *long_options, int *idx, int flags) 357 { 358 char *oli; /* option letter list index */ 359 int optchar, short_too; 360 int posixly_correct; 361 362 if (options == NULL) 363 return (-1); 364 365 /* 366 * Disable GNU extensions if POSIXLY_CORRECT is set or options 367 * string begins with a '+'. 368 */ 369 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); 370 #ifdef GNU_COMPATIBLE 371 if (*options == '-') 372 flags |= FLAG_ALLARGS; 373 else if (posixly_correct || *options == '+') 374 flags &= ~FLAG_PERMUTE; 375 #else 376 if (posixly_correct || *options == '+') 377 flags &= ~FLAG_PERMUTE; 378 else if (*options == '-') 379 flags |= FLAG_ALLARGS; 380 #endif 381 if (*options == '+' || *options == '-') 382 options++; 383 384 /* 385 * XXX Some GNU programs (like cvs) set optind to 0 instead of 386 * XXX using optreset. Work around this braindamage. 387 */ 388 if (optind == 0) 389 optind = optreset = 1; 390 391 optarg = NULL; 392 if (optreset) 393 nonopt_start = nonopt_end = -1; 394 start: 395 if (optreset || !*place) { /* update scanning pointer */ 396 optreset = 0; 397 if (optind >= nargc) { /* end of argument vector */ 398 place = EMSG; 399 if (nonopt_end != -1) { 400 /* do permutation, if we have to */ 401 permute_args(nonopt_start, nonopt_end, 402 optind, nargv); 403 optind -= nonopt_end - nonopt_start; 404 } 405 else if (nonopt_start != -1) { 406 /* 407 * If we skipped non-options, set optind 408 * to the first of them. 409 */ 410 optind = nonopt_start; 411 } 412 nonopt_start = nonopt_end = -1; 413 return (-1); 414 } 415 if (*(place = nargv[optind]) != '-' || 416 #ifdef GNU_COMPATIBLE 417 place[1] == '\0') { 418 #else 419 (place[1] == '\0' && strchr(options, '-') == NULL)) { 420 #endif 421 place = EMSG; /* found non-option */ 422 if (flags & FLAG_ALLARGS) { 423 /* 424 * GNU extension: 425 * return non-option as argument to option 1 426 */ 427 optarg = nargv[optind++]; 428 return (INORDER); 429 } 430 if (!(flags & FLAG_PERMUTE)) { 431 /* 432 * If no permutation wanted, stop parsing 433 * at first non-option. 434 */ 435 return (-1); 436 } 437 /* do permutation */ 438 if (nonopt_start == -1) 439 nonopt_start = optind; 440 else if (nonopt_end != -1) { 441 permute_args(nonopt_start, nonopt_end, 442 optind, nargv); 443 nonopt_start = optind - 444 (nonopt_end - nonopt_start); 445 nonopt_end = -1; 446 } 447 optind++; 448 /* process next argument */ 449 goto start; 450 } 451 if (nonopt_start != -1 && nonopt_end == -1) 452 nonopt_end = optind; 453 454 /* 455 * If we have "-" do nothing, if "--" we are done. 456 */ 457 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { 458 optind++; 459 place = EMSG; 460 /* 461 * We found an option (--), so if we skipped 462 * non-options, we have to permute. 463 */ 464 if (nonopt_end != -1) { 465 permute_args(nonopt_start, nonopt_end, 466 optind, nargv); 467 optind -= nonopt_end - nonopt_start; 468 } 469 nonopt_start = nonopt_end = -1; 470 return (-1); 471 } 472 } 473 474 /* 475 * Check long options if: 476 * 1) we were passed some 477 * 2) the arg is not just "-" 478 * 3) either the arg starts with -- we are getopt_long_only() 479 */ 480 if (long_options != NULL && place != nargv[optind] && 481 (*place == '-' || (flags & FLAG_LONGONLY))) { 482 short_too = 0; 483 #ifdef GNU_COMPATIBLE 484 dash_prefix = D_PREFIX; 485 #endif 486 if (*place == '-') { 487 place++; /* --foo long option */ 488 #ifdef GNU_COMPATIBLE 489 dash_prefix = DD_PREFIX; 490 #endif 491 } else if (*place != ':' && strchr(options, *place) != NULL) 492 short_too = 1; /* could be short option too */ 493 494 optchar = parse_long_options(nargv, options, long_options, 495 idx, short_too); 496 if (optchar != -1) { 497 place = EMSG; 498 return (optchar); 499 } 500 } 501 502 if ((optchar = (int)*place++) == (int)':' || 503 (optchar == (int)'-' && *place != '\0') || 504 (oli = strchr(options, optchar)) == NULL) { 505 /* 506 * If the user specified "-" and '-' isn't listed in 507 * options, return -1 (non-option) as per POSIX. 508 * Otherwise, it is an unknown option character (or ':'). 509 */ 510 if (optchar == (int)'-' && *place == '\0') 511 return (-1); 512 if (!*place) 513 ++optind; 514 #ifdef GNU_COMPATIBLE 515 if (PRINT_ERROR) 516 warnx(posixly_correct ? illoptchar : gnuoptchar, 517 optchar); 518 #else 519 if (PRINT_ERROR) 520 warnx(illoptchar, optchar); 521 #endif 522 optopt = optchar; 523 return (BADCH); 524 } 525 if (long_options != NULL && optchar == 'W' && oli[1] == ';') { 526 /* -W long-option */ 527 if (*place) /* no space */ 528 /* NOTHING */; 529 else if (++optind >= nargc) { /* no arg */ 530 place = EMSG; 531 if (PRINT_ERROR) 532 warnx(recargchar, optchar); 533 optopt = optchar; 534 return (BADARG); 535 } else /* white space */ 536 place = nargv[optind]; 537 #ifdef GNU_COMPATIBLE 538 dash_prefix = W_PREFIX; 539 #endif 540 optchar = parse_long_options(nargv, options, long_options, 541 idx, 0); 542 place = EMSG; 543 return (optchar); 544 } 545 if (*++oli != ':') { /* doesn't take argument */ 546 if (!*place) 547 ++optind; 548 } else { /* takes (optional) argument */ 549 optarg = NULL; 550 if (*place) /* no white space */ 551 optarg = place; 552 /* XXX: disable test for :: if PC? (GNU doesn't) */ 553 else if (oli[1] != ':') { /* arg not optional */ 554 if (++optind >= nargc) { /* no arg */ 555 place = EMSG; 556 if (PRINT_ERROR) 557 warnx(recargchar, optchar); 558 optopt = optchar; 559 return (BADARG); 560 } else 561 optarg = nargv[optind]; 562 } else if (!(flags & FLAG_PERMUTE)) { 563 /* 564 * If permutation is disabled, we can accept an 565 * optional arg separated by whitespace. 566 */ 567 if (optind + 1 < nargc) 568 optarg = nargv[++optind]; 569 } 570 place = EMSG; 571 ++optind; 572 } 573 /* dump back option letter */ 574 return (optchar); 575 } 576 577 #ifdef REPLACE_GETOPT 578 /* 579 * getopt -- 580 * Parse argc/argv argument vector. 581 * 582 * [eventually this will replace the BSD getopt] 583 */ 584 int 585 getopt(int nargc, char * const *nargv, const char *options) 586 { 587 588 /* 589 * We don't pass FLAG_PERMUTE to getopt_internal() since 590 * the BSD getopt(3) (unlike GNU) has never done this. 591 * 592 * Furthermore, since many privileged programs call getopt() 593 * before dropping privileges it makes sense to keep things 594 * as simple (and bug-free) as possible. 595 */ 596 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); 597 } 598 #endif /* REPLACE_GETOPT */ 599 600 /* 601 * getopt_long -- 602 * Parse argc/argv argument vector. 603 */ 604 int 605 getopt_long(nargc, nargv, options, long_options, idx) 606 int nargc; 607 char * const *nargv; 608 const char *options; 609 const struct option *long_options; 610 int *idx; 611 { 612 613 return (getopt_internal(nargc, nargv, options, long_options, idx, 614 FLAG_PERMUTE)); 615 } 616 617 /* 618 * getopt_long_only -- 619 * Parse argc/argv argument vector. 620 */ 621 int 622 getopt_long_only(nargc, nargv, options, long_options, idx) 623 int nargc; 624 char * const *nargv; 625 const char *options; 626 const struct option *long_options; 627 int *idx; 628 { 629 630 return (getopt_internal(nargc, nargv, options, long_options, idx, 631 FLAG_PERMUTE|FLAG_LONGONLY)); 632 } 633