/* $OpenBSD: getopt_long.c,v 1.24 2010/07/22 19:31:53 blambert Exp $ */1/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */23/*4* Copyright (c) 2002 Todd C. Miller <[email protected]>5*6* Permission to use, copy, modify, and distribute this software for any7* purpose with or without fee is hereby granted, provided that the above8* copyright notice and this permission notice appear in all copies.9*10* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES11* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF12* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR13* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES14* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN15* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF16* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.17*18* Sponsored in part by the Defense Advanced Research Projects19* Agency (DARPA) and Air Force Research Laboratory, Air Force20* Materiel Command, USAF, under agreement number F39502-99-1-0512.21*/22/*-23* Copyright (c) 2000 The NetBSD Foundation, Inc.24* All rights reserved.25*26* This code is derived from software contributed to The NetBSD Foundation27* by Dieter Baron and Thomas Klausner.28*29* Redistribution and use in source and binary forms, with or without30* modification, are permitted provided that the following conditions31* are met:32* 1. Redistributions of source code must retain the above copyright33* notice, this list of conditions and the following disclaimer.34* 2. Redistributions in binary form must reproduce the above copyright35* notice, this list of conditions and the following disclaimer in the36* documentation and/or other materials provided with the distribution.37*38* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS39* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED40* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR41* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS42* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR43* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF44* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS45* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN46* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)47* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE48* POSSIBILITY OF SUCH DAMAGE.49*/5051#include <errno.h>52#include <getopt.h>53#include <stdio.h>54#include <stdlib.h>55#include <string.h>5657int opterr = 1; /* if error message should be printed */58int optind = 1; /* index into parent argv vector */59int optopt = '?'; /* character checked for validity */60int optreset; /* reset getopt */61char *optarg; /* argument associated with option */6263#define PRINT_ERROR ((opterr) && (*options != ':'))6465#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */66#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */67#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */6869/* return values */70#define BADCH (int)'?'71#define BADARG ((*options == ':') ? (int)':' : (int)'?')72#define INORDER (int)17374#define EMSG ""7576static int getopt_internal(int, char * const *, const char *,77const struct option *, int *, int);78static int parse_long_options(char * const *, const char *,79const struct option *, int *, int);80static int gcd(int, int);81static void permute_args(int, int, int, char * const *);8283static char *place = EMSG; /* option letter processing */8485/* XXX: set optreset to 1 rather than these two */86static int nonopt_start = -1; /* first non option argument (for permute) */87static int nonopt_end = -1; /* first option after non options (for permute) */8889/* Error messages */90static const char recargchar[] = "option requires an argument -- %c";91static const char recargstring[] = "option requires an argument -- %s";92static const char ambig[] = "ambiguous option -- %.*s";93static const char noarg[] = "option doesn't take an argument -- %.*s";94static const char illoptchar[] = "unknown option -- %c";95static const char illoptstring[] = "unknown option -- %s";9697/*98* Compute the greatest common divisor of a and b.99*/100static int101gcd(int a, int b)102{103int c;104105c = a % b;106while (c != 0) {107a = b;108b = c;109c = a % b;110}111112return (b);113}114115/*116* Exchange the block from nonopt_start to nonopt_end with the block117* from nonopt_end to opt_end (keeping the same order of arguments118* in each block).119*/120static void121permute_args(int panonopt_start, int panonopt_end, int opt_end,122char * const *nargv)123{124int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;125char *swap;126127/*128* compute lengths of blocks and number and size of cycles129*/130nnonopts = panonopt_end - panonopt_start;131nopts = opt_end - panonopt_end;132ncycle = gcd(nnonopts, nopts);133cyclelen = (opt_end - panonopt_start) / ncycle;134135for (i = 0; i < ncycle; i++) {136cstart = panonopt_end+i;137pos = cstart;138for (j = 0; j < cyclelen; j++) {139if (pos >= panonopt_end)140pos -= nnonopts;141else142pos += nopts;143swap = nargv[pos];144/* LINTED const cast */145((char **) nargv)[pos] = nargv[cstart];146/* LINTED const cast */147((char **)nargv)[cstart] = swap;148}149}150}151152/*153* parse_long_options --154* Parse long options in argc/argv argument vector.155* Returns -1 if short_too is set and the option does not match long_options.156*/157static int158parse_long_options(char * const *nargv, const char *options,159const struct option *long_options, int *idx, int short_too)160{161char *current_argv, *has_equal;162size_t current_argv_len;163int i, match;164165current_argv = place;166match = -1;167168optind++;169170if ((has_equal = strchr(current_argv, '=')) != NULL) {171/* argument found (--option=arg) */172current_argv_len = has_equal - current_argv;173has_equal++;174} else175current_argv_len = strlen(current_argv);176177for (i = 0; long_options[i].name; i++) {178/* find matching long option */179if (strncmp(current_argv, long_options[i].name,180current_argv_len))181continue;182183if (strlen(long_options[i].name) == current_argv_len) {184/* exact match */185match = i;186break;187}188/*189* If this is a known short option, don't allow190* a partial match of a single character.191*/192if (short_too && current_argv_len == 1)193continue;194195if (match == -1) /* partial match */196match = i;197else {198/* ambiguous abbreviation */199if (PRINT_ERROR)200fprintf(stderr, ambig, (int)current_argv_len,201current_argv);202optopt = 0;203return (BADCH);204}205}206if (match != -1) { /* option found */207if (long_options[match].has_arg == no_argument208&& has_equal) {209if (PRINT_ERROR)210fprintf(stderr, noarg, (int)current_argv_len,211current_argv);212/*213* XXX: GNU sets optopt to val regardless of flag214*/215if (long_options[match].flag == NULL)216optopt = long_options[match].val;217else218optopt = 0;219return (BADARG);220}221if (long_options[match].has_arg == required_argument ||222long_options[match].has_arg == optional_argument) {223if (has_equal)224optarg = has_equal;225else if (long_options[match].has_arg ==226required_argument) {227/*228* optional argument doesn't use next nargv229*/230optarg = nargv[optind++];231}232}233if ((long_options[match].has_arg == required_argument)234&& (optarg == NULL)) {235/*236* Missing argument; leading ':' indicates no error237* should be generated.238*/239if (PRINT_ERROR)240fprintf(stderr, recargstring,241current_argv);242/*243* XXX: GNU sets optopt to val regardless of flag244*/245if (long_options[match].flag == NULL)246optopt = long_options[match].val;247else248optopt = 0;249--optind;250return (BADARG);251}252} else { /* unknown option */253if (short_too) {254--optind;255return (-1);256}257if (PRINT_ERROR)258fprintf(stderr, illoptstring, current_argv);259optopt = 0;260return (BADCH);261}262if (idx)263*idx = match;264if (long_options[match].flag) {265*long_options[match].flag = long_options[match].val;266return (0);267} else268return (long_options[match].val);269}270271/*272* getopt_internal --273* Parse argc/argv argument vector. Called by user level routines.274*/275static int276getopt_internal(int nargc, char * const *nargv, const char *options,277const struct option *long_options, int *idx, int flags)278{279char *oli; /* option letter list index */280int optchar, short_too;281static int posixly_correct = -1;282283if (options == NULL)284return (-1);285286/*287* Disable GNU extensions if POSIXLY_CORRECT is set or options288* string begins with a '+'.289*/290if (posixly_correct == -1)291posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);292if (posixly_correct || *options == '+')293flags &= ~FLAG_PERMUTE;294else if (*options == '-')295flags |= FLAG_ALLARGS;296if (*options == '+' || *options == '-')297options++;298299/*300* XXX Some GNU programs (like cvs) set optind to 0 instead of301* XXX using optreset. Work around this braindamage.302*/303if (optind == 0)304optind = optreset = 1;305306optarg = NULL;307if (optreset)308nonopt_start = nonopt_end = -1;309start:310if (optreset || !*place) { /* update scanning pointer */311optreset = 0;312if (optind >= nargc) { /* end of argument vector */313place = EMSG;314if (nonopt_end != -1) {315/* do permutation, if we have to */316permute_args(nonopt_start, nonopt_end,317optind, nargv);318optind -= nonopt_end - nonopt_start;319}320else if (nonopt_start != -1) {321/*322* If we skipped non-options, set optind323* to the first of them.324*/325optind = nonopt_start;326}327nonopt_start = nonopt_end = -1;328return (-1);329}330if (*(place = nargv[optind]) != '-' ||331(place[1] == '\0' && strchr(options, '-') == NULL)) {332place = EMSG; /* found non-option */333if (flags & FLAG_ALLARGS) {334/*335* GNU extension:336* return non-option as argument to option 1337*/338optarg = nargv[optind++];339return (INORDER);340}341if (!(flags & FLAG_PERMUTE)) {342/*343* If no permutation wanted, stop parsing344* at first non-option.345*/346return (-1);347}348/* do permutation */349if (nonopt_start == -1)350nonopt_start = optind;351else if (nonopt_end != -1) {352permute_args(nonopt_start, nonopt_end,353optind, nargv);354nonopt_start = optind -355(nonopt_end - nonopt_start);356nonopt_end = -1;357}358optind++;359/* process next argument */360goto start;361}362if (nonopt_start != -1 && nonopt_end == -1)363nonopt_end = optind;364365/*366* If we have "-" do nothing, if "--" we are done.367*/368if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {369optind++;370place = EMSG;371/*372* We found an option (--), so if we skipped373* non-options, we have to permute.374*/375if (nonopt_end != -1) {376permute_args(nonopt_start, nonopt_end,377optind, nargv);378optind -= nonopt_end - nonopt_start;379}380nonopt_start = nonopt_end = -1;381return (-1);382}383}384385/*386* Check long options if:387* 1) we were passed some388* 2) the arg is not just "-"389* 3) either the arg starts with -- we are getopt_long_only()390*/391if (long_options != NULL && place != nargv[optind] &&392(*place == '-' || (flags & FLAG_LONGONLY))) {393short_too = 0;394if (*place == '-')395place++; /* --foo long option */396else if (*place != ':' && strchr(options, *place) != NULL)397short_too = 1; /* could be short option too */398399optchar = parse_long_options(nargv, options, long_options,400idx, short_too);401if (optchar != -1) {402place = EMSG;403return (optchar);404}405}406407if ((optchar = (int)*place++) == (int)':' ||408(optchar == (int)'-' && *place != '\0') ||409(oli = strchr(options, optchar)) == NULL) {410/*411* If the user specified "-" and '-' isn't listed in412* options, return -1 (non-option) as per POSIX.413* Otherwise, it is an unknown option character (or ':').414*/415if (optchar == (int)'-' && *place == '\0')416return (-1);417if (!*place)418++optind;419if (PRINT_ERROR)420fprintf(stderr, illoptchar, optchar);421optopt = optchar;422return (BADCH);423}424if (long_options != NULL && optchar == 'W' && oli[1] == ';') {425/* -W long-option */426if (*place) /* no space */427/* NOTHING */;428else if (++optind >= nargc) { /* no arg */429place = EMSG;430if (PRINT_ERROR)431fprintf(stderr, recargchar, optchar);432optopt = optchar;433return (BADARG);434} else /* white space */435place = nargv[optind];436optchar = parse_long_options(nargv, options, long_options,437idx, 0);438place = EMSG;439return (optchar);440}441if (*++oli != ':') { /* doesn't take argument */442if (!*place)443++optind;444} else { /* takes (optional) argument */445optarg = NULL;446if (*place) /* no white space */447optarg = place;448else if (oli[1] != ':') { /* arg not optional */449if (++optind >= nargc) { /* no arg */450place = EMSG;451if (PRINT_ERROR)452fprintf(stderr, recargchar, optchar);453optopt = optchar;454return (BADARG);455} else456optarg = nargv[optind];457}458place = EMSG;459++optind;460}461/* dump back option letter */462return (optchar);463}464465/*466* getopt --467* Parse argc/argv argument vector.468*469* [eventually this will replace the BSD getopt]470*/471int472getopt(int nargc, char * const *nargv, const char *options)473{474475/*476* We don't pass FLAG_PERMUTE to getopt_internal() since477* the BSD getopt(3) (unlike GNU) has never done this.478*479* Furthermore, since many privileged programs call getopt()480* before dropping privileges it makes sense to keep things481* as simple (and bug-free) as possible.482*/483return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));484}485486/*487* getopt_long --488* Parse argc/argv argument vector.489*/490int491getopt_long(int nargc, char * const *nargv, const char *options,492const struct option *long_options, int *idx)493{494495return (getopt_internal(nargc, nargv, options, long_options, idx,496FLAG_PERMUTE));497}498499/*500* getopt_long_only --501* Parse argc/argv argument vector.502*/503int504getopt_long_only(int nargc, char * const *nargv, const char *options,505const struct option *long_options, int *idx)506{507508return (getopt_internal(nargc, nargv, options, long_options, idx,509FLAG_PERMUTE|FLAG_LONGONLY));510}511512513