getopt_long.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
  5. *
  6. * Permission to use, copy, modify, and distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. *
  18. * Sponsored in part by the Defense Advanced Research Projects
  19. * Agency (DARPA) and Air Force Research Laboratory, Air Force
  20. * 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 Foundation
  27. * by Dieter Baron and Thomas Klausner.
  28. *
  29. * Redistribution and use in source and binary forms, with or without
  30. * modification, are permitted provided that the following conditions
  31. * are met:
  32. * 1. Redistributions of source code must retain the above copyright
  33. * notice, this list of conditions and the following disclaimer.
  34. * 2. Redistributions in binary form must reproduce the above copyright
  35. * notice, this list of conditions and the following disclaimer in the
  36. * documentation and/or other materials provided with the distribution.
  37. *
  38. * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
  39. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  40. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  41. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
  42. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  43. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  44. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  45. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  46. * 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 THE
  48. * POSSIBILITY OF SUCH DAMAGE.
  49. */
  50. /* OPENBSD ORIGINAL: lib/libc/stdlib/getopt_long.c */
  51. #include "includes.h"
  52. #if !defined(HAVE_GETOPT) || !defined(HAVE_GETOPT_OPTRESET)
  53. /*
  54. * Some defines to make it easier to keep the code in sync with upstream.
  55. * getopt opterr optind optopt optreset optarg are all in defines.h which is
  56. * pulled in by includes.h.
  57. */
  58. #define warnx logit
  59. #if 0
  60. #include <err.h>
  61. #include <getopt.h>
  62. #endif
  63. #include <errno.h>
  64. #include <stdlib.h>
  65. #include <string.h>
  66. #include <stdarg.h>
  67. #include "log.h"
  68. int opterr = 1; /* if error message should be printed */
  69. int optind = 1; /* index into parent argv vector */
  70. int optopt = '?'; /* character checked for validity */
  71. int optreset; /* reset getopt */
  72. char *optarg; /* argument associated with option */
  73. #define PRINT_ERROR ((opterr) && (*options != ':'))
  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. /* return values */
  78. #define BADCH (int)'?'
  79. #define BADARG ((*options == ':') ? (int)':' : (int)'?')
  80. #define INORDER (int)1
  81. #define EMSG ""
  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);
  86. static int gcd(int, int);
  87. static void permute_args(int, int, int, char * const *);
  88. static char *place = EMSG; /* option letter processing */
  89. /* XXX: set optreset to 1 rather than these two */
  90. static int nonopt_start = -1; /* first non option argument (for permute) */
  91. static int nonopt_end = -1; /* first option after non options (for permute) */
  92. /* Error messages */
  93. static const char recargchar[] = "option requires an argument -- %c";
  94. static const char recargstring[] = "option requires an argument -- %s";
  95. static const char ambig[] = "ambiguous option -- %.*s";
  96. static const char noarg[] = "option doesn't take an argument -- %.*s";
  97. static const char illoptchar[] = "unknown option -- %c";
  98. static const char illoptstring[] = "unknown option -- %s";
  99. /*
  100. * Compute the greatest common divisor of a and b.
  101. */
  102. static int
  103. gcd(int a, int b)
  104. {
  105. int c;
  106. c = a % b;
  107. while (c != 0) {
  108. a = b;
  109. b = c;
  110. c = a % b;
  111. }
  112. return (b);
  113. }
  114. /*
  115. * Exchange the block from nonopt_start to nonopt_end with the block
  116. * from nonopt_end to opt_end (keeping the same order of arguments
  117. * in each block).
  118. */
  119. static void
  120. permute_args(int panonopt_start, int panonopt_end, int opt_end,
  121. char * const *nargv)
  122. {
  123. int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
  124. char *swap;
  125. /*
  126. * compute lengths of blocks and number and size of cycles
  127. */
  128. nnonopts = panonopt_end - panonopt_start;
  129. nopts = opt_end - panonopt_end;
  130. ncycle = gcd(nnonopts, nopts);
  131. cyclelen = (opt_end - panonopt_start) / ncycle;
  132. for (i = 0; i < ncycle; i++) {
  133. cstart = panonopt_end+i;
  134. pos = cstart;
  135. for (j = 0; j < cyclelen; j++) {
  136. if (pos >= panonopt_end)
  137. pos -= nnonopts;
  138. else
  139. pos += nopts;
  140. swap = nargv[pos];
  141. /* LINTED const cast */
  142. ((char **) nargv)[pos] = nargv[cstart];
  143. /* LINTED const cast */
  144. ((char **)nargv)[cstart] = swap;
  145. }
  146. }
  147. }
  148. /*
  149. * parse_long_options --
  150. * Parse long options in argc/argv argument vector.
  151. * Returns -1 if short_too is set and the option does not match long_options.
  152. */
  153. static int
  154. parse_long_options(char * const *nargv, const char *options,
  155. const struct option *long_options, int *idx, int short_too)
  156. {
  157. char *current_argv, *has_equal;
  158. size_t current_argv_len;
  159. int i, match;
  160. current_argv = place;
  161. match = -1;
  162. optind++;
  163. if ((has_equal = strchr(current_argv, '=')) != NULL) {
  164. /* argument found (--option=arg) */
  165. current_argv_len = has_equal - current_argv;
  166. has_equal++;
  167. } else
  168. current_argv_len = strlen(current_argv);
  169. for (i = 0; long_options[i].name; i++) {
  170. /* find matching long option */
  171. if (strncmp(current_argv, long_options[i].name,
  172. current_argv_len))
  173. continue;
  174. if (strlen(long_options[i].name) == current_argv_len) {
  175. /* exact match */
  176. match = i;
  177. break;
  178. }
  179. /*
  180. * If this is a known short option, don't allow
  181. * a partial match of a single character.
  182. */
  183. if (short_too && current_argv_len == 1)
  184. continue;
  185. if (match == -1) /* partial match */
  186. match = i;
  187. else {
  188. /* ambiguous abbreviation */
  189. if (PRINT_ERROR)
  190. warnx(ambig, (int)current_argv_len,
  191. current_argv);
  192. optopt = 0;
  193. return (BADCH);
  194. }
  195. }
  196. if (match != -1) { /* option found */
  197. if (long_options[match].has_arg == no_argument
  198. && has_equal) {
  199. if (PRINT_ERROR)
  200. warnx(noarg, (int)current_argv_len,
  201. current_argv);
  202. /*
  203. * XXX: GNU sets optopt to val regardless of flag
  204. */
  205. if (long_options[match].flag == NULL)
  206. optopt = long_options[match].val;
  207. else
  208. optopt = 0;
  209. return (BADARG);
  210. }
  211. if (long_options[match].has_arg == required_argument ||
  212. long_options[match].has_arg == optional_argument) {
  213. if (has_equal)
  214. optarg = has_equal;
  215. else if (long_options[match].has_arg ==
  216. required_argument) {
  217. /*
  218. * optional argument doesn't use next nargv
  219. */
  220. optarg = nargv[optind++];
  221. }
  222. }
  223. if ((long_options[match].has_arg == required_argument)
  224. && (optarg == NULL)) {
  225. /*
  226. * Missing argument; leading ':' indicates no error
  227. * should be generated.
  228. */
  229. if (PRINT_ERROR)
  230. warnx(recargstring,
  231. current_argv);
  232. /*
  233. * XXX: GNU sets optopt to val regardless of flag
  234. */
  235. if (long_options[match].flag == NULL)
  236. optopt = long_options[match].val;
  237. else
  238. optopt = 0;
  239. --optind;
  240. return (BADARG);
  241. }
  242. } else { /* unknown option */
  243. if (short_too) {
  244. --optind;
  245. return (-1);
  246. }
  247. if (PRINT_ERROR)
  248. warnx(illoptstring, current_argv);
  249. optopt = 0;
  250. return (BADCH);
  251. }
  252. if (idx)
  253. *idx = match;
  254. if (long_options[match].flag) {
  255. *long_options[match].flag = long_options[match].val;
  256. return (0);
  257. } else
  258. return (long_options[match].val);
  259. }
  260. /*
  261. * getopt_internal --
  262. * Parse argc/argv argument vector. Called by user level routines.
  263. */
  264. static int
  265. getopt_internal(int nargc, char * const *nargv, const char *options,
  266. const struct option *long_options, int *idx, int flags)
  267. {
  268. char *oli; /* option letter list index */
  269. int optchar, short_too;
  270. static int posixly_correct = -1;
  271. if (options == NULL)
  272. return (-1);
  273. /*
  274. * XXX Some GNU programs (like cvs) set optind to 0 instead of
  275. * XXX using optreset. Work around this braindamage.
  276. */
  277. if (optind == 0)
  278. optind = optreset = 1;
  279. /*
  280. * Disable GNU extensions if POSIXLY_CORRECT is set or options
  281. * string begins with a '+'.
  282. */
  283. if (posixly_correct == -1 || optreset)
  284. posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
  285. if (*options == '-')
  286. flags |= FLAG_ALLARGS;
  287. else if (posixly_correct || *options == '+')
  288. flags &= ~FLAG_PERMUTE;
  289. if (*options == '+' || *options == '-')
  290. options++;
  291. optarg = NULL;
  292. if (optreset)
  293. nonopt_start = nonopt_end = -1;
  294. start:
  295. if (optreset || !*place) { /* update scanning pointer */
  296. optreset = 0;
  297. if (optind >= nargc) { /* end of argument vector */
  298. place = EMSG;
  299. if (nonopt_end != -1) {
  300. /* do permutation, if we have to */
  301. permute_args(nonopt_start, nonopt_end,
  302. optind, nargv);
  303. optind -= nonopt_end - nonopt_start;
  304. }
  305. else if (nonopt_start != -1) {
  306. /*
  307. * If we skipped non-options, set optind
  308. * to the first of them.
  309. */
  310. optind = nonopt_start;
  311. }
  312. nonopt_start = nonopt_end = -1;
  313. return (-1);
  314. }
  315. if (*(place = nargv[optind]) != '-' ||
  316. (place[1] == '\0' && strchr(options, '-') == NULL)) {
  317. place = EMSG; /* found non-option */
  318. if (flags & FLAG_ALLARGS) {
  319. /*
  320. * GNU extension:
  321. * return non-option as argument to option 1
  322. */
  323. optarg = nargv[optind++];
  324. return (INORDER);
  325. }
  326. if (!(flags & FLAG_PERMUTE)) {
  327. /*
  328. * If no permutation wanted, stop parsing
  329. * at first non-option.
  330. */
  331. return (-1);
  332. }
  333. /* do permutation */
  334. if (nonopt_start == -1)
  335. nonopt_start = optind;
  336. else if (nonopt_end != -1) {
  337. permute_args(nonopt_start, nonopt_end,
  338. optind, nargv);
  339. nonopt_start = optind -
  340. (nonopt_end - nonopt_start);
  341. nonopt_end = -1;
  342. }
  343. optind++;
  344. /* process next argument */
  345. goto start;
  346. }
  347. if (nonopt_start != -1 && nonopt_end == -1)
  348. nonopt_end = optind;
  349. /*
  350. * If we have "-" do nothing, if "--" we are done.
  351. */
  352. if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
  353. optind++;
  354. place = EMSG;
  355. /*
  356. * We found an option (--), so if we skipped
  357. * non-options, we have to permute.
  358. */
  359. if (nonopt_end != -1) {
  360. permute_args(nonopt_start, nonopt_end,
  361. optind, nargv);
  362. optind -= nonopt_end - nonopt_start;
  363. }
  364. nonopt_start = nonopt_end = -1;
  365. return (-1);
  366. }
  367. }
  368. /*
  369. * Check long options if:
  370. * 1) we were passed some
  371. * 2) the arg is not just "-"
  372. * 3) either the arg starts with -- we are getopt_long_only()
  373. */
  374. if (long_options != NULL && place != nargv[optind] &&
  375. (*place == '-' || (flags & FLAG_LONGONLY))) {
  376. short_too = 0;
  377. if (*place == '-')
  378. place++; /* --foo long option */
  379. else if (*place != ':' && strchr(options, *place) != NULL)
  380. short_too = 1; /* could be short option too */
  381. optchar = parse_long_options(nargv, options, long_options,
  382. idx, short_too);
  383. if (optchar != -1) {
  384. place = EMSG;
  385. return (optchar);
  386. }
  387. }
  388. if ((optchar = (int)*place++) == (int)':' ||
  389. (optchar == (int)'-' && *place != '\0') ||
  390. (oli = strchr(options, optchar)) == NULL) {
  391. /*
  392. * If the user specified "-" and '-' isn't listed in
  393. * options, return -1 (non-option) as per POSIX.
  394. * Otherwise, it is an unknown option character (or ':').
  395. */
  396. if (optchar == (int)'-' && *place == '\0')
  397. return (-1);
  398. if (!*place)
  399. ++optind;
  400. if (PRINT_ERROR)
  401. warnx(illoptchar, optchar);
  402. optopt = optchar;
  403. return (BADCH);
  404. }
  405. if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
  406. /* -W long-option */
  407. if (*place) /* no space */
  408. /* NOTHING */;
  409. else if (++optind >= nargc) { /* no arg */
  410. place = EMSG;
  411. if (PRINT_ERROR)
  412. warnx(recargchar, optchar);
  413. optopt = optchar;
  414. return (BADARG);
  415. } else /* white space */
  416. place = nargv[optind];
  417. optchar = parse_long_options(nargv, options, long_options,
  418. idx, 0);
  419. place = EMSG;
  420. return (optchar);
  421. }
  422. if (*++oli != ':') { /* doesn't take argument */
  423. if (!*place)
  424. ++optind;
  425. } else { /* takes (optional) argument */
  426. optarg = NULL;
  427. if (*place) /* no white space */
  428. optarg = place;
  429. else if (oli[1] != ':') { /* arg not optional */
  430. if (++optind >= nargc) { /* no arg */
  431. place = EMSG;
  432. if (PRINT_ERROR)
  433. warnx(recargchar, optchar);
  434. optopt = optchar;
  435. return (BADARG);
  436. } else
  437. optarg = nargv[optind];
  438. }
  439. place = EMSG;
  440. ++optind;
  441. }
  442. /* dump back option letter */
  443. return (optchar);
  444. }
  445. /*
  446. * getopt --
  447. * Parse argc/argv argument vector.
  448. *
  449. * [eventually this will replace the BSD getopt]
  450. */
  451. int
  452. getopt(int nargc, char * const *nargv, const char *options)
  453. {
  454. /*
  455. * We don't pass FLAG_PERMUTE to getopt_internal() since
  456. * the BSD getopt(3) (unlike GNU) has never done this.
  457. *
  458. * Furthermore, since many privileged programs call getopt()
  459. * before dropping privileges it makes sense to keep things
  460. * as simple (and bug-free) as possible.
  461. */
  462. return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
  463. }
  464. #if 0
  465. /*
  466. * getopt_long --
  467. * Parse argc/argv argument vector.
  468. */
  469. int
  470. getopt_long(int nargc, char * const *nargv, const char *options,
  471. const struct option *long_options, int *idx)
  472. {
  473. return (getopt_internal(nargc, nargv, options, long_options, idx,
  474. FLAG_PERMUTE));
  475. }
  476. /*
  477. * getopt_long_only --
  478. * Parse argc/argv argument vector.
  479. */
  480. int
  481. getopt_long_only(int nargc, char * const *nargv, const char *options,
  482. const struct option *long_options, int *idx)
  483. {
  484. return (getopt_internal(nargc, nargv, options, long_options, idx,
  485. FLAG_PERMUTE|FLAG_LONGONLY));
  486. }
  487. #endif
  488. #endif /* !defined(HAVE_GETOPT) || !defined(HAVE_OPTRESET) */