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