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 (place[1] == '\0' && strchr(options, '-') == NULL)) { 417 place = EMSG; /* found non-option */ 418 if (flags & FLAG_ALLARGS) { 419 /* 420 * GNU extension: 421 * return non-option as argument to option 1 422 */ 423 optarg = nargv[optind++]; 424 return (INORDER); 425 } 426 if (!(flags & FLAG_PERMUTE)) { 427 /* 428 * If no permutation wanted, stop parsing 429 * at first non-option. 430 */ 431 return (-1); 432 } 433 /* do permutation */ 434 if (nonopt_start == -1) 435 nonopt_start = optind; 436 else if (nonopt_end != -1) { 437 permute_args(nonopt_start, nonopt_end, 438 optind, nargv); 439 nonopt_start = optind - 440 (nonopt_end - nonopt_start); 441 nonopt_end = -1; 442 } 443 optind++; 444 /* process next argument */ 445 goto start; 446 } 447 if (nonopt_start != -1 && nonopt_end == -1) 448 nonopt_end = optind; 449 450 /* 451 * If we have "-" do nothing, if "--" we are done. 452 */ 453 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { 454 optind++; 455 place = EMSG; 456 /* 457 * We found an option (--), so if we skipped 458 * non-options, we have to permute. 459 */ 460 if (nonopt_end != -1) { 461 permute_args(nonopt_start, nonopt_end, 462 optind, nargv); 463 optind -= nonopt_end - nonopt_start; 464 } 465 nonopt_start = nonopt_end = -1; 466 return (-1); 467 } 468 } 469 470 /* 471 * Check long options if: 472 * 1) we were passed some 473 * 2) the arg is not just "-" 474 * 3) either the arg starts with -- we are getopt_long_only() 475 */ 476 if (long_options != NULL && place != nargv[optind] && 477 (*place == '-' || (flags & FLAG_LONGONLY))) { 478 short_too = 0; 479 #ifdef GNU_COMPATIBLE 480 dash_prefix = D_PREFIX; 481 #endif 482 if (*place == '-') { 483 place++; /* --foo long option */ 484 #ifdef GNU_COMPATIBLE 485 dash_prefix = DD_PREFIX; 486 #endif 487 } else if (*place != ':' && strchr(options, *place) != NULL) 488 short_too = 1; /* could be short option too */ 489 490 optchar = parse_long_options(nargv, options, long_options, 491 idx, short_too); 492 if (optchar != -1) { 493 place = EMSG; 494 return (optchar); 495 } 496 } 497 498 if ((optchar = (int)*place++) == (int)':' || 499 (optchar == (int)'-' && *place != '\0') || 500 (oli = strchr(options, optchar)) == NULL) { 501 /* 502 * If the user specified "-" and '-' isn't listed in 503 * options, return -1 (non-option) as per POSIX. 504 * Otherwise, it is an unknown option character (or ':'). 505 */ 506 if (optchar == (int)'-' && *place == '\0') 507 return (-1); 508 if (!*place) 509 ++optind; 510 #ifdef GNU_COMPATIBLE 511 if (PRINT_ERROR) 512 warnx(posixly_correct ? illoptchar : gnuoptchar, 513 optchar); 514 #else 515 if (PRINT_ERROR) 516 warnx(illoptchar, optchar); 517 #endif 518 optopt = optchar; 519 return (BADCH); 520 } 521 if (long_options != NULL && optchar == 'W' && oli[1] == ';') { 522 /* -W long-option */ 523 if (*place) /* no space */ 524 /* NOTHING */; 525 else if (++optind >= nargc) { /* no arg */ 526 place = EMSG; 527 if (PRINT_ERROR) 528 warnx(recargchar, optchar); 529 optopt = optchar; 530 return (BADARG); 531 } else /* white space */ 532 place = nargv[optind]; 533 #ifdef GNU_COMPATIBLE 534 dash_prefix = W_PREFIX; 535 #endif 536 optchar = parse_long_options(nargv, options, long_options, 537 idx, 0); 538 place = EMSG; 539 return (optchar); 540 } 541 if (*++oli != ':') { /* doesn't take argument */ 542 if (!*place) 543 ++optind; 544 } else { /* takes (optional) argument */ 545 optarg = NULL; 546 if (*place) /* no white space */ 547 optarg = place; 548 /* XXX: disable test for :: if PC? (GNU doesn't) */ 549 else if (oli[1] != ':') { /* arg not optional */ 550 if (++optind >= nargc) { /* no arg */ 551 place = EMSG; 552 if (PRINT_ERROR) 553 warnx(recargchar, optchar); 554 optopt = optchar; 555 return (BADARG); 556 } else 557 optarg = nargv[optind]; 558 } else if (!(flags & FLAG_PERMUTE)) { 559 /* 560 * If permutation is disabled, we can accept an 561 * optional arg separated by whitespace. 562 */ 563 if (optind + 1 < nargc) 564 optarg = nargv[++optind]; 565 } 566 place = EMSG; 567 ++optind; 568 } 569 /* dump back option letter */ 570 return (optchar); 571 } 572 573 #ifdef REPLACE_GETOPT 574 /* 575 * getopt -- 576 * Parse argc/argv argument vector. 577 * 578 * [eventually this will replace the BSD getopt] 579 */ 580 int 581 getopt(int nargc, char * const *nargv, const char *options) 582 { 583 584 /* 585 * We don't pass FLAG_PERMUTE to getopt_internal() since 586 * the BSD getopt(3) (unlike GNU) has never done this. 587 * 588 * Furthermore, since many privileged programs call getopt() 589 * before dropping privileges it makes sense to keep things 590 * as simple (and bug-free) as possible. 591 */ 592 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); 593 } 594 #endif /* REPLACE_GETOPT */ 595 596 /* 597 * getopt_long -- 598 * Parse argc/argv argument vector. 599 */ 600 int 601 getopt_long(nargc, nargv, options, long_options, idx) 602 int nargc; 603 char * const *nargv; 604 const char *options; 605 const struct option *long_options; 606 int *idx; 607 { 608 609 return (getopt_internal(nargc, nargv, options, long_options, idx, 610 FLAG_PERMUTE)); 611 } 612 613 /* 614 * getopt_long_only -- 615 * Parse argc/argv argument vector. 616 */ 617 int 618 getopt_long_only(nargc, nargv, options, long_options, idx) 619 int nargc; 620 char * const *nargv; 621 const char *options; 622 const struct option *long_options; 623 int *idx; 624 { 625 626 return (getopt_internal(nargc, nargv, options, long_options, idx, 627 FLAG_PERMUTE|FLAG_LONGONLY)); 628 } 629