getopt.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. /* Getopt for GNU.
  2. NOTE: getopt is now part of the C library, so if you don't know what
  3. "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
  4. before changing it!
  5. Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97
  6. Free Software Foundation, Inc.
  7. NOTE: The canonical source of this file is maintained with the GNU C Library.
  8. Bugs can be reported to bug-glibc@prep.ai.mit.edu.
  9. This program is free software; you can redistribute it and/or modify it
  10. under the terms of the GNU General Public License as published by the
  11. Free Software Foundation; either version 3, or (at your option) any
  12. later version.
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License
  18. along with this program; if not, write to the Free Software
  19. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  20. USA.
  21. This code was heavily modified for GNUnet.
  22. Copyright (C) 2006, 2017 Christian Grothoff
  23. */
  24. /**
  25. * @file util/getopt.c
  26. * @brief GNU style option parsing
  27. *
  28. * TODO: get rid of statics (make reentrant) and
  29. * replace main GNU getopt parser with one that
  30. * actually fits our API.
  31. */
  32. #include "platform.h"
  33. #include "gnunet_util_lib.h"
  34. #ifdef VMS
  35. #include <unixlib.h>
  36. #if HAVE_STRING_H - 0
  37. #include <string.h>
  38. #endif
  39. #endif
  40. #define LOG(kind, ...) GNUNET_log_from (kind, "util-getopt", __VA_ARGS__)
  41. #define LOG_STRERROR(kind, syscall) \
  42. GNUNET_log_from_strerror (kind, "util-getopt", syscall)
  43. #ifndef _
  44. /* This is for other GNU distributions with internationalized messages.
  45. When compiling libc, the _ macro is predefined. */
  46. #ifdef HAVE_LIBINTL_H
  47. #include <libintl.h>
  48. #define _(msgid) gettext (msgid)
  49. #else
  50. #define _(msgid) (msgid)
  51. #endif
  52. #endif
  53. /* Describe the long-named options requested by the application.
  54. The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
  55. of `struct GNoption' terminated by an element containing a name which is
  56. zero.
  57. The field `has_arg' is:
  58. no_argument (or 0) if the option does not take an argument,
  59. required_argument (or 1) if the option requires an argument,
  60. optional_argument (or 2) if the option takes an optional argument.
  61. If the field `flag' is not NULL, it points to a variable that is set
  62. to the value given in the field `val' when the option is found, but
  63. left unchanged if the option is not found.
  64. To have a long-named option do something other than set an `int' to
  65. a compiled-in constant, such as set a value from `GNoptarg', set the
  66. option's `flag' field to zero and its `val' field to a nonzero
  67. value (the equivalent single-letter option character, if there is
  68. one). For long options that have a zero `flag' field, `getopt'
  69. returns the contents of the `val' field. */
  70. struct GNoption
  71. {
  72. const char *name;
  73. /* has_arg can't be an enum because some compilers complain about
  74. * type mismatches in all the code that assumes it is an int. */
  75. int has_arg;
  76. int *flag;
  77. int val;
  78. };
  79. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  80. but it behaves differently for the user, since it allows the user
  81. to intersperse the options with the other arguments.
  82. As `getopt' works, it permutes the elements of ARGV so that,
  83. when it is done, all the options precede everything else. Thus
  84. all application programs are extended to handle flexible argument order.
  85. Setting the environment variable POSIXLY_CORRECT disables permutation.
  86. Then the behavior is completely standard.
  87. GNU application programs can use a third alternative mode in which
  88. they can distinguish the relative order of options and other arguments. */
  89. /* For communication from `getopt' to the caller.
  90. When `getopt' finds an option that takes an argument,
  91. the argument value is returned here.
  92. Also, when `ordering' is RETURN_IN_ORDER,
  93. each non-option ARGV-element is returned here. */
  94. static char *GNoptarg = NULL;
  95. /* Index in ARGV of the next element to be scanned.
  96. This is used for communication to and from the caller
  97. and for communication between successive calls to `getopt'.
  98. On entry to `getopt', zero means this is the first call; initialize.
  99. When `getopt' returns -1, this is the index of the first of the
  100. non-option elements that the caller should itself scan.
  101. Otherwise, `GNoptind' communicates from one call to the next
  102. how much of ARGV has been scanned so far. */
  103. /* 1003.2 says this must be 1 before any call. */
  104. static int GNoptind = 1;
  105. /* The next char to be scanned in the option-element
  106. in which the last option character we returned was found.
  107. This allows us to pick up the scan where we left off.
  108. If this is zero, or a null string, it means resume the scan
  109. by advancing to the next ARGV-element. */
  110. static char *nextchar;
  111. /* Describe how to deal with options that follow non-option ARGV-elements.
  112. If the caller did not specify anything,
  113. the default is REQUIRE_ORDER if the environment variable
  114. POSIXLY_CORRECT is defined, PERMUTE otherwise.
  115. REQUIRE_ORDER means don't recognize them as options;
  116. stop option processing when the first non-option is seen.
  117. This is what Unix does.
  118. This mode of operation is selected by either setting the environment
  119. variable POSIXLY_CORRECT, or using `+' as the first character
  120. of the list of option characters.
  121. PERMUTE is the default. We GNUNET_CRYPTO_random_permute the contents of ARGV as we scan,
  122. so that eventually all the non-options are at the end. This allows options
  123. to be given in any order, even with programs that were not written to
  124. expect this.
  125. RETURN_IN_ORDER is an option available to programs that were written
  126. to expect GNoptions and other ARGV-elements in any order and that care about
  127. the ordering of the two. We describe each non-option ARGV-element
  128. as if it were the argument of an option with character code 1.
  129. Using `-' as the first character of the list of option characters
  130. selects this mode of operation.
  131. The special argument `--' forces an end of option-scanning regardless
  132. of the value of `ordering'. In the case of RETURN_IN_ORDER, only
  133. `--' can cause `getopt' to return -1 with `GNoptind' != ARGC. */
  134. static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
  135. /* Value of POSIXLY_CORRECT environment variable. */
  136. static char *posixly_correct;
  137. #ifdef __GNU_LIBRARY__
  138. /* We want to avoid inclusion of string.h with non-GNU libraries
  139. because there are many ways it can cause trouble.
  140. On some systems, it contains special magic macros that don't work
  141. in GCC. */
  142. #include <string.h>
  143. #define my_index strchr
  144. #else
  145. /* Avoid depending on library functions or files
  146. whose names are inconsistent. */
  147. char *
  148. getenv ();
  149. static char *
  150. my_index (const char *str, int chr)
  151. {
  152. while (*str)
  153. {
  154. if (*str == chr)
  155. return (char *) str;
  156. str++;
  157. }
  158. return 0;
  159. }
  160. /* If using GCC, we can safely declare strlen this way.
  161. If not using GCC, it is ok not to declare it. */
  162. #ifdef __GNUC__
  163. /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
  164. That was relevant to code that was here before. */
  165. #if ! defined(__STDC__) || ! __STDC__
  166. /* gcc with -traditional declares the built-in strlen to return int,
  167. and has done so at least since version 2.4.5. -- rms. */
  168. extern int
  169. strlen (const char *);
  170. #endif /* not __STDC__ */
  171. #endif /* __GNUC__ */
  172. #endif /* not __GNU_LIBRARY__ */
  173. /* Handle permutation of arguments. */
  174. /* Describe the part of ARGV that contains non-options that have
  175. been skipped. `first_nonopt' is the index in ARGV of the first of them;
  176. `last_nonopt' is the index after the last of them. */
  177. static int first_nonopt;
  178. static int last_nonopt;
  179. #define SWAP_FLAGS(ch1, ch2)
  180. /* Exchange two adjacent subsequences of ARGV.
  181. One subsequence is elements [first_nonopt,last_nonopt)
  182. which contains all the non-options that have been skipped so far.
  183. The other is elements [last_nonopt,GNoptind), which contains all
  184. the options processed since those non-options were skipped.
  185. `first_nonopt' and `last_nonopt' are relocated so that they describe
  186. the new indices of the non-options in ARGV after they are moved. */
  187. #if defined(__STDC__) && __STDC__
  188. static void
  189. exchange (char **);
  190. #endif
  191. static void
  192. exchange (char **argv)
  193. {
  194. int bottom = first_nonopt;
  195. int middle = last_nonopt;
  196. int top = GNoptind;
  197. char *tem;
  198. /* Exchange the shorter segment with the far end of the longer segment.
  199. * That puts the shorter segment into the right place.
  200. * It leaves the longer segment in the right place overall,
  201. * but it consists of two parts that need to be swapped next. */
  202. while (top > middle && middle > bottom)
  203. {
  204. if (top - middle > middle - bottom)
  205. {
  206. /* Bottom segment is the short one. */
  207. int len = middle - bottom;
  208. register int i;
  209. /* Swap it with the top part of the top segment. */
  210. for (i = 0; i < len; i++)
  211. {
  212. tem = argv[bottom + i];
  213. argv[bottom + i] = argv[top - (middle - bottom) + i];
  214. argv[top - (middle - bottom) + i] = tem;
  215. SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  216. }
  217. /* Exclude the moved bottom segment from further swapping. */
  218. top -= len;
  219. }
  220. else
  221. {
  222. /* Top segment is the short one. */
  223. int len = top - middle;
  224. register int i;
  225. /* Swap it with the bottom part of the bottom segment. */
  226. for (i = 0; i < len; i++)
  227. {
  228. tem = argv[bottom + i];
  229. argv[bottom + i] = argv[middle + i];
  230. argv[middle + i] = tem;
  231. SWAP_FLAGS (bottom + i, middle + i);
  232. }
  233. /* Exclude the moved top segment from further swapping. */
  234. bottom += len;
  235. }
  236. }
  237. /* Update records for the slots the non-options now occupy. */
  238. first_nonopt += (GNoptind - last_nonopt);
  239. last_nonopt = GNoptind;
  240. }
  241. /* Initialize the internal data when the first call is made. */
  242. #if defined(__STDC__) && __STDC__
  243. static const char *
  244. _getopt_initialize (int, char *const *, const char *);
  245. #endif
  246. static const char *
  247. _getopt_initialize (int argc, char *const *argv, const char *optstring)
  248. {
  249. /* Start processing options with ARGV-element 1 (since ARGV-element 0
  250. * is the program name); the sequence of previously skipped
  251. * non-option ARGV-elements is empty. */
  252. first_nonopt = last_nonopt = GNoptind;
  253. nextchar = NULL;
  254. posixly_correct = getenv ("POSIXLY_CORRECT");
  255. /* Determine how to handle the ordering of options and nonoptions. */
  256. if (optstring[0] == '-')
  257. {
  258. ordering = RETURN_IN_ORDER;
  259. ++optstring;
  260. }
  261. else if (optstring[0] == '+')
  262. {
  263. ordering = REQUIRE_ORDER;
  264. ++optstring;
  265. }
  266. else if (posixly_correct != NULL)
  267. ordering = REQUIRE_ORDER;
  268. else
  269. ordering = PERMUTE;
  270. return optstring;
  271. }
  272. /* Scan elements of ARGV (whose length is ARGC) for option characters
  273. given in OPTSTRING.
  274. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  275. then it is an option element. The characters of this element
  276. (aside from the initial '-') are option characters. If `getopt'
  277. is called repeatedly, it returns successively each of the option characters
  278. from each of the option elements.
  279. If `getopt' finds another option character, it returns that character,
  280. updating `GNoptind' and `nextchar' so that the next call to `getopt' can
  281. resume the scan with the following option character or ARGV-element.
  282. If there are no more option characters, `getopt' returns -1.
  283. Then `GNoptind' is the index in ARGV of the first ARGV-element
  284. that is not an option. (The ARGV-elements have been permuted
  285. so that those that are not options now come last.)
  286. OPTSTRING is a string containing the legitimate option characters.
  287. If an option character is seen that is not listed in OPTSTRING,
  288. return '?' after printing an error message. If you set `GNopterr' to
  289. zero, the error message is suppressed but we still return '?'.
  290. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  291. so the following text in the same ARGV-element, or the text of the following
  292. ARGV-element, is returned in `GNoptarg'. Two colons mean an option that
  293. wants an optional arg; if there is text in the current ARGV-element,
  294. it is returned in `GNoptarg', otherwise `GNoptarg' is set to zero.
  295. If OPTSTRING starts with `-' or `+', it requests different methods of
  296. handling the non-option ARGV-elements.
  297. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  298. Long-named options begin with `--' instead of `-'.
  299. Their names may be abbreviated as long as the abbreviation is unique
  300. or is an exact match for some defined option. If they have an
  301. argument, it follows the option name in the same ARGV-element, separated
  302. from the option name by a `=', or else the in next ARGV-element.
  303. When `getopt' finds a long-named option, it returns 0 if that option's
  304. `flag' field is nonzero, the value of the option's `val' field
  305. if the `flag' field is zero.
  306. The elements of ARGV aren't really const, because we GNUNET_CRYPTO_random_permute them.
  307. But we pretend they're const in the prototype to be compatible
  308. with other systems.
  309. LONGOPTS is a vector of `struct GNoption' terminated by an
  310. element containing a name which is zero.
  311. LONGIND returns the index in LONGOPT of the long-named option found.
  312. It is only valid when a long-named option has been found by the most
  313. recent call.
  314. If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  315. long-named options. */
  316. static int
  317. GN_getopt_internal (int argc,
  318. char *const *argv,
  319. const char *optstring,
  320. const struct GNoption *longopts,
  321. int *longind,
  322. int long_only)
  323. {
  324. static int __getopt_initialized = 0;
  325. static int GNopterr = 1;
  326. GNoptarg = NULL;
  327. if ((GNoptind == 0) || ! __getopt_initialized)
  328. {
  329. if (GNoptind == 0)
  330. GNoptind = 1; /* Don't scan ARGV[0], the program name. */
  331. optstring = _getopt_initialize (argc, argv, optstring);
  332. __getopt_initialized = 1;
  333. }
  334. /* Test whether ARGV[GNoptind] points to a non-option argument.
  335. * Either it does not have option syntax, or there is an environment flag
  336. * from the shell indicating it is not an option. The later information
  337. * is only used when the used in the GNU libc. */
  338. #define NONOPTION_P (argv[GNoptind][0] != '-' || argv[GNoptind][1] == '\0')
  339. if ((nextchar == NULL) || (*nextchar == '\0'))
  340. {
  341. /* Advance to the next ARGV-element. */
  342. /* Give FIRST_NONOPT & LAST_NONOPT rational values if GNoptind has been
  343. * moved back by the user (who may also have changed the arguments). */
  344. if (last_nonopt > GNoptind)
  345. last_nonopt = GNoptind;
  346. if (first_nonopt > GNoptind)
  347. first_nonopt = GNoptind;
  348. if (ordering == PERMUTE)
  349. {
  350. /* If we have just processed some options following some non-options,
  351. * exchange them so that the options come first. */
  352. if ((first_nonopt != last_nonopt) && (last_nonopt != GNoptind) )
  353. exchange ((char **) argv);
  354. else if (last_nonopt != GNoptind)
  355. first_nonopt = GNoptind;
  356. /* Skip any additional non-options
  357. * and extend the range of non-options previously skipped. */
  358. while (GNoptind < argc && NONOPTION_P)
  359. GNoptind++;
  360. last_nonopt = GNoptind;
  361. }
  362. /* The special ARGV-element `--' means premature end of options.
  363. * Skip it like a null option,
  364. * then exchange with previous non-options as if it were an option,
  365. * then skip everything else like a non-option. */
  366. if ((GNoptind != argc) && ! strcmp (argv[GNoptind], "--"))
  367. {
  368. GNoptind++;
  369. if ((first_nonopt != last_nonopt) && (last_nonopt != GNoptind) )
  370. exchange ((char **) argv);
  371. else if (first_nonopt == last_nonopt)
  372. first_nonopt = GNoptind;
  373. last_nonopt = argc;
  374. GNoptind = argc;
  375. }
  376. /* If we have done all the ARGV-elements, stop the scan
  377. * and back over any non-options that we skipped and permuted. */
  378. if (GNoptind == argc)
  379. {
  380. /* Set the next-arg-index to point at the non-options
  381. * that we previously skipped, so the caller will digest them. */
  382. if (first_nonopt != last_nonopt)
  383. GNoptind = first_nonopt;
  384. return -1;
  385. }
  386. /* If we have come to a non-option and did not permute it,
  387. * either stop the scan or describe it to the caller and pass it by. */
  388. if (NONOPTION_P)
  389. {
  390. if (ordering == REQUIRE_ORDER)
  391. return -1;
  392. GNoptarg = argv[GNoptind++];
  393. return 1;
  394. }
  395. /* We have found another option-ARGV-element.
  396. * Skip the initial punctuation. */
  397. nextchar =
  398. (argv[GNoptind] + 1 + (longopts != NULL && argv[GNoptind][1] == '-'));
  399. }
  400. /* Decode the current option-ARGV-element. */
  401. /* Check whether the ARGV-element is a long option.
  402. *
  403. * If long_only and the ARGV-element has the form "-f", where f is
  404. * a valid short option, don't consider it an abbreviated form of
  405. * a long option that starts with f. Otherwise there would be no
  406. * way to give the -f short option.
  407. *
  408. * On the other hand, if there's a long option "fubar" and
  409. * the ARGV-element is "-fu", do consider that an abbreviation of
  410. * the long option, just like "--fu", and not "-f" with arg "u".
  411. *
  412. * This distinction seems to be the most useful approach. */if ((longopts != NULL) &&
  413. ((argv[GNoptind][1] == '-') ||
  414. (long_only &&
  415. (argv[GNoptind][2] || ! my_index (optstring, argv[GNoptind][1])))))
  416. {
  417. char *nameend;
  418. const struct GNoption *p;
  419. const struct GNoption *pfound = NULL;
  420. int exact = 0;
  421. int ambig = 0;
  422. int indfound = -1;
  423. int option_index;
  424. for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
  425. /* Do nothing. */;
  426. /* Test all long options for either exact match
  427. * or abbreviated matches. */
  428. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  429. if (! strncmp (p->name, nextchar, nameend - nextchar))
  430. {
  431. if ((unsigned int) (nameend - nextchar) ==
  432. (unsigned int) strlen (p->name))
  433. {
  434. /* Exact match found. */
  435. pfound = p;
  436. indfound = option_index;
  437. exact = 1;
  438. break;
  439. }
  440. else if (pfound == NULL)
  441. {
  442. /* First nonexact match found. */
  443. pfound = p;
  444. indfound = option_index;
  445. }
  446. else
  447. /* Second or later nonexact match found. */
  448. ambig = 1;
  449. }
  450. if (ambig && ! exact)
  451. {
  452. if (GNopterr)
  453. fprintf (stderr,
  454. _ ("%s: option `%s' is ambiguous\n"),
  455. argv[0],
  456. argv[GNoptind]);
  457. nextchar += strlen (nextchar);
  458. GNoptind++;
  459. return '?';
  460. }
  461. if (pfound != NULL)
  462. {
  463. option_index = indfound;
  464. GNoptind++;
  465. if (*nameend)
  466. {
  467. /* Don't test has_arg with >, because some C compilers don't
  468. * allow it to be used on enums. */
  469. if (pfound->has_arg)
  470. GNoptarg = nameend + 1;
  471. else
  472. {
  473. if (GNopterr)
  474. {
  475. if (argv[GNoptind - 1][1] == '-')
  476. /* --option */
  477. fprintf (stderr,
  478. _ ("%s: option `--%s' does not allow an argument\n"),
  479. argv[0],
  480. pfound->name);
  481. else
  482. /* +option or -option */
  483. fprintf (stderr,
  484. _ ("%s: option `%c%s' does not allow an argument\n"),
  485. argv[0],
  486. argv[GNoptind - 1][0],
  487. pfound->name);
  488. }
  489. nextchar += strlen (nextchar);
  490. return '?';
  491. }
  492. }
  493. else if (pfound->has_arg == 1)
  494. {
  495. if (GNoptind < argc)
  496. {
  497. GNoptarg = argv[GNoptind++];
  498. }
  499. else
  500. {
  501. if (GNopterr)
  502. {
  503. fprintf (stderr,
  504. _ ("%s: option `%s' requires an argument\n"),
  505. argv[0],
  506. argv[GNoptind - 1]);
  507. }
  508. nextchar += strlen (nextchar);
  509. return (optstring[0] == ':') ? ':' : '?';
  510. }
  511. }
  512. nextchar += strlen (nextchar);
  513. if (longind != NULL)
  514. *longind = option_index;
  515. if (pfound->flag)
  516. {
  517. *(pfound->flag) = pfound->val;
  518. return 0;
  519. }
  520. return pfound->val;
  521. }
  522. /* Can't find it as a long option. If this is not getopt_long_only,
  523. * or the option starts with '--' or is not a valid short
  524. * option, then it's an error.
  525. * Otherwise interpret it as a short option. */
  526. if (! long_only || (argv[GNoptind][1] == '-') ||
  527. (my_index (optstring, *nextchar) == NULL) )
  528. {
  529. if (GNopterr)
  530. {
  531. if (argv[GNoptind][1] == '-')
  532. /* --option */
  533. fprintf (stderr,
  534. _ ("%s: unrecognized option `--%s'\n"),
  535. argv[0],
  536. nextchar);
  537. else
  538. /* +option or -option */
  539. fprintf (stderr,
  540. _ ("%s: unrecognized option `%c%s'\n"),
  541. argv[0],
  542. argv[GNoptind][0],
  543. nextchar);
  544. }
  545. nextchar = (char *) "";
  546. GNoptind++;
  547. return '?';
  548. }
  549. }
  550. /* Look at and handle the next short option-character. */
  551. {
  552. char c = *nextchar++;
  553. char *temp = my_index (optstring, c);
  554. /* Increment `GNoptind' when we start to process its last character. */
  555. if (*nextchar == '\0')
  556. ++GNoptind;
  557. if ((temp == NULL) || (c == ':'))
  558. {
  559. if (GNopterr)
  560. {
  561. if (posixly_correct)
  562. /* 1003.2 specifies the format of this message. */
  563. fprintf (stderr, _ ("%s: illegal option -- %c\n"), argv[0], c);
  564. else
  565. fprintf (stderr, _ ("%s: invalid option -- %c\n"), argv[0], c);
  566. }
  567. return '?';
  568. }
  569. /* Convenience. Treat POSIX -W foo same as long option --foo */
  570. if ((temp[0] == 'W') && (temp[1] == ';'))
  571. {
  572. char *nameend;
  573. const struct GNoption *p;
  574. const struct GNoption *pfound = NULL;
  575. int exact = 0;
  576. int ambig = 0;
  577. int indfound = 0;
  578. int option_index;
  579. /* This is an option that requires an argument. */
  580. if (*nextchar != '\0')
  581. {
  582. GNoptarg = nextchar;
  583. /* If we end this ARGV-element by taking the rest as an arg,
  584. * we must advance to the next element now. */
  585. GNoptind++;
  586. }
  587. else if (GNoptind == argc)
  588. {
  589. if (GNopterr)
  590. {
  591. /* 1003.2 specifies the format of this message. */
  592. fprintf (stderr,
  593. _ ("%s: option requires an argument -- %c\n"),
  594. argv[0],
  595. c);
  596. }
  597. if (optstring[0] == ':')
  598. c = ':';
  599. else
  600. c = '?';
  601. return c;
  602. }
  603. else
  604. /* We already incremented `GNoptind' once;
  605. * increment it again when taking next ARGV-elt as argument. */
  606. GNoptarg = argv[GNoptind++];
  607. /* GNoptarg is now the argument, see if it's in the
  608. * table of longopts. */
  609. for (nextchar = nameend = GNoptarg; *nameend && *nameend != '=';
  610. nameend++)
  611. /* Do nothing. */;
  612. /* Test all long options for either exact match
  613. * or abbreviated matches. */
  614. if (longopts != NULL)
  615. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  616. if (! strncmp (p->name, nextchar, nameend - nextchar))
  617. {
  618. if ((unsigned int) (nameend - nextchar) == strlen (p->name))
  619. {
  620. /* Exact match found. */
  621. pfound = p;
  622. indfound = option_index;
  623. exact = 1;
  624. break;
  625. }
  626. else if (pfound == NULL)
  627. {
  628. /* First nonexact match found. */
  629. pfound = p;
  630. indfound = option_index;
  631. }
  632. else
  633. /* Second or later nonexact match found. */
  634. ambig = 1;
  635. }
  636. if (ambig && ! exact)
  637. {
  638. if (GNopterr)
  639. fprintf (stderr,
  640. _ ("%s: option `-W %s' is ambiguous\n"),
  641. argv[0],
  642. argv[GNoptind]);
  643. nextchar += strlen (nextchar);
  644. GNoptind++;
  645. return '?';
  646. }
  647. if (pfound != NULL)
  648. {
  649. option_index = indfound;
  650. if (*nameend)
  651. {
  652. /* Don't test has_arg with >, because some C compilers don't
  653. * allow it to be used on enums. */
  654. if (pfound->has_arg)
  655. GNoptarg = nameend + 1;
  656. else
  657. {
  658. if (GNopterr)
  659. fprintf (stderr,
  660. _ ("%s: option `-W %s' does not allow an argument\n"),
  661. argv[0],
  662. pfound->name);
  663. nextchar += strlen (nextchar);
  664. return '?';
  665. }
  666. }
  667. else if (pfound->has_arg == 1)
  668. {
  669. if (GNoptind < argc)
  670. GNoptarg = argv[GNoptind++];
  671. else
  672. {
  673. if (GNopterr)
  674. fprintf (stderr,
  675. _ ("%s: option `%s' requires an argument\n"),
  676. argv[0],
  677. argv[GNoptind - 1]);
  678. nextchar += strlen (nextchar);
  679. return optstring[0] == ':' ? ':' : '?';
  680. }
  681. }
  682. nextchar += strlen (nextchar);
  683. if (longind != NULL)
  684. *longind = option_index;
  685. if (pfound->flag)
  686. {
  687. *(pfound->flag) = pfound->val;
  688. return 0;
  689. }
  690. return pfound->val;
  691. }
  692. nextchar = NULL;
  693. return 'W'; /* Let the application handle it. */
  694. }
  695. if (temp[1] == ':')
  696. {
  697. if (temp[2] == ':')
  698. {
  699. /* This is an option that accepts an argument optionally. */
  700. if (*nextchar != '\0')
  701. {
  702. GNoptarg = nextchar;
  703. GNoptind++;
  704. }
  705. else
  706. GNoptarg = NULL;
  707. nextchar = NULL;
  708. }
  709. else
  710. {
  711. /* This is an option that requires an argument. */
  712. if (*nextchar != '\0')
  713. {
  714. GNoptarg = nextchar;
  715. /* If we end this ARGV-element by taking the rest as an arg,
  716. * we must advance to the next element now. */
  717. GNoptind++;
  718. }
  719. else if (GNoptind == argc)
  720. {
  721. if (GNopterr)
  722. {
  723. /* 1003.2 specifies the format of this message. */
  724. fprintf (stderr,
  725. _ ("%s: option requires an argument -- %c\n"),
  726. argv[0],
  727. c);
  728. }
  729. if (optstring[0] == ':')
  730. c = ':';
  731. else
  732. c = '?';
  733. }
  734. else
  735. /* We already incremented `GNoptind' once;
  736. * increment it again when taking next ARGV-elt as argument. */
  737. GNoptarg = argv[GNoptind++];
  738. nextchar = NULL;
  739. }
  740. }
  741. return c;
  742. }
  743. }
  744. static int
  745. GNgetopt_long (int argc,
  746. char *const *argv,
  747. const char *options,
  748. const struct GNoption *long_options,
  749. int *opt_index)
  750. {
  751. return GN_getopt_internal (argc, argv, options, long_options, opt_index, 0);
  752. }
  753. /* ******************** now the GNUnet specific modifications... ********************* */
  754. /**
  755. * Parse the command line.
  756. *
  757. * @param binaryOptions Name of application with option summary
  758. * @param allOptions defined options and handlers
  759. * @param argc number of arguments
  760. * @param argv actual arguments
  761. * @return index into argv with first non-option
  762. * argument, or #GNUNET_SYSERR on error
  763. */
  764. int
  765. GNUNET_GETOPT_run (const char *binaryOptions,
  766. const struct GNUNET_GETOPT_CommandLineOption *allOptions,
  767. unsigned int argc,
  768. char *const *argv)
  769. {
  770. struct GNoption *long_options;
  771. struct GNUNET_GETOPT_CommandLineProcessorContext clpc;
  772. int count;
  773. char *shorts;
  774. int spos;
  775. int cont;
  776. uint8_t *seen;
  777. unsigned int optmatch = 0;
  778. const char *have_exclusive = NULL;
  779. GNUNET_assert (argc > 0);
  780. GNoptind = 0;
  781. clpc.binaryName = argv[0];
  782. clpc.binaryOptions = binaryOptions;
  783. clpc.allOptions = allOptions;
  784. clpc.argv = argv;
  785. clpc.argc = argc;
  786. for (count = 0; NULL != allOptions[count].name; count++)
  787. ;
  788. /* transform our option representation into the format
  789. used by the GNU getopt copylib */
  790. long_options = GNUNET_new_array (count + 1, struct GNoption);
  791. seen = GNUNET_new_array (count, uint8_t);
  792. shorts = GNUNET_malloc (count * 2 + 1);
  793. spos = 0;
  794. for (unsigned i = 0; i < count; i++)
  795. {
  796. long_options[i].name = allOptions[i].name;
  797. long_options[i].has_arg = allOptions[i].require_argument;
  798. long_options[i].flag = NULL;
  799. long_options[i].val = allOptions[i].shortName;
  800. shorts[spos++] = allOptions[i].shortName;
  801. if (allOptions[i].require_argument != 0)
  802. shorts[spos++] = ':';
  803. }
  804. long_options[count].name = NULL;
  805. long_options[count].has_arg = 0;
  806. long_options[count].flag = NULL;
  807. long_options[count].val = '\0';
  808. shorts[spos] = '\0';
  809. cont = GNUNET_OK;
  810. /* main getopt loop */
  811. while (1)
  812. {
  813. int option_index = 0;
  814. unsigned int i;
  815. int c;
  816. c = GNgetopt_long (argc, argv, shorts, long_options, &option_index);
  817. if (c == GNUNET_SYSERR)
  818. break; /* No more flags to process */
  819. /* Check which of our program's options was given by the user */
  820. for (i = 0; i < count; i++)
  821. {
  822. clpc.currentArgument = GNoptind - 1;
  823. if ((char) c == allOptions[i].shortName)
  824. {
  825. optmatch++;
  826. if (allOptions[i].option_exclusive)
  827. have_exclusive = allOptions[i].name;
  828. if (GNUNET_OK == cont)
  829. {
  830. /* parse the option using the option-specific processor */
  831. cont = allOptions[i].processor (&clpc,
  832. allOptions[i].scls,
  833. allOptions[i].name,
  834. GNoptarg);
  835. }
  836. seen[i] = 1;
  837. break;
  838. }
  839. }
  840. if (i == count)
  841. {
  842. fprintf (stderr, _ ("Use %s to get a list of options.\n"), "--help");
  843. cont = GNUNET_SYSERR;
  844. }
  845. }
  846. GNUNET_free (shorts);
  847. GNUNET_free (long_options);
  848. /* check that if any option that was marked as exclusive
  849. is the only option that was provided */
  850. if ((NULL != have_exclusive) && (optmatch > 1))
  851. {
  852. fprintf (stderr,
  853. _ ("Option `%s' can't be used with other options.\n"),
  854. have_exclusive);
  855. cont = GNUNET_SYSERR;
  856. }
  857. if (GNUNET_YES == cont)
  858. {
  859. /* check that all mandatory options are present */
  860. for (count = 0; NULL != allOptions[count].name; count++)
  861. {
  862. if ((0 == seen[count]) && (allOptions[count].option_mandatory))
  863. {
  864. fprintf (stderr,
  865. _ ("Missing mandatory option `%s'.\n"),
  866. allOptions[count].name);
  867. cont = GNUNET_SYSERR;
  868. }
  869. }
  870. }
  871. GNUNET_free (seen);
  872. /* call cleaners, if available */
  873. for (unsigned int i = 0; NULL != allOptions[i].name; i++)
  874. if (NULL != allOptions[i].cleaner)
  875. allOptions[i].cleaner (allOptions[i].scls);
  876. if (GNUNET_OK != cont)
  877. return cont;
  878. return GNoptind;
  879. }
  880. /* end of getopt.c */