socket-util: closesocket() for Windows.
[sliver-openvswitch.git] / lib / getopt_long.c
1 /*-
2  * Copyright (c) 2000 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by Dieter Baron and Thomas Klausner.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <config.h>
31 #include <errno.h>
32 #include <getopt.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include "util.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(getopt_long);
39
40 int     opterr = 1;             /* if error message should be printed */
41 int     optind = 1;             /* index into parent argv vector */
42 int     optopt = '?';           /* character checked for validity */
43 int     optreset;               /* reset getopt */
44 char    *optarg;                /* argument associated with option */
45
46 #define IGNORE_FIRST    (*options == '-' || *options == '+')
47 #define PRINT_ERROR     ((opterr) && ((*options != ':') \
48                                       || (IGNORE_FIRST && options[1] != ':')))
49 #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
50 #define PERMUTE         (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
51 /* XXX: GNU ignores PC if *options == '-' */
52 #define IN_ORDER        (!IS_POSIXLY_CORRECT && *options == '-')
53
54 /* return values */
55 #define BADCH   (int)'?'
56 #define BADARG          ((IGNORE_FIRST && options[1] == ':') \
57                          || (*options == ':') ? (int)':' : (int)'?')
58 #define INORDER (int)1
59
60 #define EMSG    ""
61
62 #define __UNCONST(a)    ((void *)(unsigned long)(const void *)(a))
63 #define _DIAGASSERT(q) ovs_assert(q)
64
65 #define warnx VLOG_WARN
66
67 static int getopt_internal(int, char **, const char *);
68 static int gcd(int, int);
69 static void permute_args(int, int, int, char **);
70
71 static const char *place = EMSG; /* option letter processing */
72
73 /* XXX: set optreset to 1 rather than these two */
74 static int nonopt_start = -1; /* first non option argument (for permute) */
75 static int nonopt_end = -1;   /* first option after non options (for permute) */
76
77 /* Error messages */
78 static const char recargchar[] = "option requires an argument -- %c";
79 static const char recargstring[] = "option requires an argument -- %s";
80 static const char ambig[] = "ambiguous option -- %.*s";
81 static const char noarg[] = "option doesn't take an argument -- %.*s";
82 static const char illoptchar[] = "unknown option -- %c";
83 static const char illoptstring[] = "unknown option -- %s";
84
85
86 /*
87  * Compute the greatest common divisor of a and b.
88  */
89 static int
90 gcd(int a, int b)
91 {
92         int c;
93
94         c = a % b;
95         while (c != 0) {
96                 a = b;
97                 b = c;
98                 c = a % b;
99         }
100
101         return b;
102 }
103
104 /*
105  * Exchange the block from nonopt_start to nonopt_end with the block
106  * from nonopt_end to opt_end (keeping the same order of arguments
107  * in each block).
108  */
109 static void
110 permute_args(int panonopt_start, int panonopt_end, int opt_end, char **nargv)
111 {
112         int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
113         char *swap;
114
115         _DIAGASSERT(nargv != NULL);
116
117         /*
118          * compute lengths of blocks and number and size of cycles
119          */
120         nnonopts = panonopt_end - panonopt_start;
121         nopts = opt_end - panonopt_end;
122         ncycle = gcd(nnonopts, nopts);
123         cyclelen = (opt_end - panonopt_start) / ncycle;
124
125         for (i = 0; i < ncycle; i++) {
126                 cstart = panonopt_end+i;
127                 pos = cstart;
128                 for (j = 0; j < cyclelen; j++) {
129                         if (pos >= panonopt_end)
130                                 pos -= nnonopts;
131                         else
132                                 pos += nopts;
133                         swap = nargv[pos];
134                         nargv[pos] = nargv[cstart];
135                         nargv[cstart] = swap;
136                 }
137         }
138 }
139
140 /*
141  * getopt_internal --
142  *      Parse argc/argv argument vector.  Called by user level routines.
143  *  Returns -2 if -- is found (can be long option or end of options marker).
144  */
145 static int
146 getopt_internal(int nargc, char **nargv, const char *options)
147 {
148         char *oli;                              /* option letter list index */
149         int optchar;
150
151         _DIAGASSERT(nargv != NULL);
152         _DIAGASSERT(options != NULL);
153
154         optarg = NULL;
155
156         /*
157          * XXX Some programs (like rsyncd) expect to be able to
158          * XXX re-initialize optind to 0 and have getopt_long(3)
159          * XXX properly function again.  Work around this braindamage.
160          */
161         if (optind == 0)
162                 optind = 1;
163
164         if (optreset)
165                 nonopt_start = nonopt_end = -1;
166 start:
167         if (optreset || !*place) {              /* update scanning pointer */
168                 optreset = 0;
169                 if (optind >= nargc) {          /* end of argument vector */
170                         place = EMSG;
171                         if (nonopt_end != -1) {
172                                 /* do permutation, if we have to */
173                                 permute_args(nonopt_start, nonopt_end,
174                                     optind, nargv);
175                                 optind -= nonopt_end - nonopt_start;
176                         }
177                         else if (nonopt_start != -1) {
178                                 /*
179                                  * If we skipped non-options, set optind
180                                  * to the first of them.
181                                  */
182                                 optind = nonopt_start;
183                         }
184                         nonopt_start = nonopt_end = -1;
185                         return -1;
186                 }
187                 if ((*(place = nargv[optind]) != '-')
188                     || (place[1] == '\0')) {    /* found non-option */
189                         place = EMSG;
190                         if (IN_ORDER) {
191                                 /*
192                                  * GNU extension:
193                                  * return non-option as argument to option 1
194                                  */
195                                 optarg = nargv[optind++];
196                                 return INORDER;
197                         }
198                         if (!PERMUTE) {
199                                 /*
200                                  * if no permutation wanted, stop parsing
201                                  * at first non-option
202                                  */
203                                 return -1;
204                         }
205                         /* do permutation */
206                         if (nonopt_start == -1)
207                                 nonopt_start = optind;
208                         else if (nonopt_end != -1) {
209                                 permute_args(nonopt_start, nonopt_end,
210                                     optind, nargv);
211                                 nonopt_start = optind -
212                                     (nonopt_end - nonopt_start);
213                                 nonopt_end = -1;
214                         }
215                         optind++;
216                         /* process next argument */
217                         goto start;
218                 }
219                 if (nonopt_start != -1 && nonopt_end == -1)
220                         nonopt_end = optind;
221                 if (place[1] && *++place == '-') {      /* found "--" */
222                         place++;
223                         return -2;
224                 }
225         }
226         if ((optchar = (int)*place++) == (int)':' ||
227             (oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
228                 /* option letter unknown or ':' */
229                 if (!*place)
230                         ++optind;
231                 if (PRINT_ERROR)
232                         warnx(illoptchar, optchar);
233                 optopt = optchar;
234                 return BADCH;
235         }
236         if (optchar == 'W' && oli[1] == ';') {          /* -W long-option */
237                 /* XXX: what if no long options provided (called by getopt)? */
238                 if (*place)
239                         return -2;
240
241                 if (++optind >= nargc) {        /* no arg */
242                         place = EMSG;
243                         if (PRINT_ERROR)
244                                 warnx(recargchar, optchar);
245                         optopt = optchar;
246                         return BADARG;
247                 } else                          /* white space */
248                         place = nargv[optind];
249                 /*
250                  * Handle -W arg the same as --arg (which causes getopt to
251                  * stop parsing).
252                  */
253                 return -2;
254         }
255         if (*++oli != ':') {                    /* doesn't take argument */
256                 if (!*place)
257                         ++optind;
258         } else {                                /* takes (optional) argument */
259                 optarg = NULL;
260                 if (*place)                     /* no white space */
261                         optarg = __UNCONST(place);
262                 /* XXX: disable test for :: if PC? (GNU doesn't) */
263                 else if (oli[1] != ':') {       /* arg not optional */
264                         if (++optind >= nargc) {        /* no arg */
265                                 place = EMSG;
266                                 if (PRINT_ERROR)
267                                         warnx(recargchar, optchar);
268                                 optopt = optchar;
269                                 return BADARG;
270                         } else
271                                 optarg = nargv[optind];
272                 }
273                 place = EMSG;
274                 ++optind;
275         }
276         /* dump back option letter */
277         return optchar;
278 }
279
280 #ifdef REPLACE_GETOPT
281 /*
282  * getopt --
283  *      Parse argc/argv argument vector.
284  *
285  * [eventually this will replace the real getopt]
286  */
287 int
288 getopt(nargc, nargv, options)
289         int nargc;
290         char * const *nargv;
291         const char *options;
292 {
293         int retval;
294
295         _DIAGASSERT(nargv != NULL);
296         _DIAGASSERT(options != NULL);
297
298         retval = getopt_internal(nargc, __UNCONST(nargv), options);
299         if (retval == -2) {
300                 ++optind;
301                 /*
302                  * We found an option (--), so if we skipped non-options,
303                  * we have to permute.
304                  */
305                 if (nonopt_end != -1) {
306                         permute_args(nonopt_start, nonopt_end, optind,
307                                        nargv);
308                         optind -= nonopt_end - nonopt_start;
309                 }
310                 nonopt_start = nonopt_end = -1;
311                 retval = -1;
312         }
313         return retval;
314 }
315 #endif
316
317 /*
318  * getopt_long --
319  *      Parse argc/argv argument vector.
320  */
321 int
322 getopt_long(int nargc, char * const *nargv, const char *options,
323     const struct option *long_options, int *idx)
324 {
325         int retval;
326
327 #define IDENTICAL_INTERPRETATION(_x, _y)                                \
328         (long_options[(_x)].has_arg == long_options[(_y)].has_arg &&    \
329          long_options[(_x)].flag == long_options[(_y)].flag &&          \
330          long_options[(_x)].val == long_options[(_y)].val)
331
332         _DIAGASSERT(nargv != NULL);
333         _DIAGASSERT(options != NULL);
334         _DIAGASSERT(long_options != NULL);
335         /* idx may be NULL */
336
337         retval = getopt_internal(nargc, __UNCONST(nargv), options);
338         if (retval == -2) {
339                 char *current_argv, *has_equal;
340                 size_t current_argv_len;
341                 int i, ambiguous, match;
342
343                 current_argv = __UNCONST(place);
344                 match = -1;
345                 ambiguous = 0;
346
347                 optind++;
348                 place = EMSG;
349
350                 if (*current_argv == '\0') {            /* found "--" */
351                         /*
352                          * We found an option (--), so if we skipped
353                          * non-options, we have to permute.
354                          */
355                         if (nonopt_end != -1) {
356                                 permute_args(nonopt_start, nonopt_end,
357                                     optind, __UNCONST(nargv));
358                                 optind -= nonopt_end - nonopt_start;
359                         }
360                         nonopt_start = nonopt_end = -1;
361                         return -1;
362                 }
363                 if ((has_equal = strchr(current_argv, '=')) != NULL) {
364                         /* argument found (--option=arg) */
365                         current_argv_len = has_equal - current_argv;
366                         has_equal++;
367                 } else
368                         current_argv_len = strlen(current_argv);
369
370                 for (i = 0; long_options[i].name; i++) {
371                         /* find matching long option */
372                         if (strncmp(current_argv, long_options[i].name,
373                             current_argv_len))
374                                 continue;
375
376                         if (strlen(long_options[i].name) ==
377                             (unsigned)current_argv_len) {
378                                 /* exact match */
379                                 match = i;
380                                 ambiguous = 0;
381                                 break;
382                         }
383                         if (match == -1)                /* partial match */
384                                 match = i;
385                         else if (!IDENTICAL_INTERPRETATION(i, match))
386                                 ambiguous = 1;
387                 }
388                 if (ambiguous) {
389                         /* ambiguous abbreviation */
390                         if (PRINT_ERROR)
391                                 warnx(ambig, (int)current_argv_len,
392                                      current_argv);
393                         optopt = 0;
394                         return BADCH;
395                 }
396                 if (match != -1) {                      /* option found */
397                         if (long_options[match].has_arg == no_argument
398                             && has_equal) {
399                                 if (PRINT_ERROR)
400                                         warnx(noarg, (int)current_argv_len,
401                                              current_argv);
402                                 /*
403                                  * XXX: GNU sets optopt to val regardless of
404                                  * flag
405                                  */
406                                 if (long_options[match].flag == NULL)
407                                         optopt = long_options[match].val;
408                                 else
409                                         optopt = 0;
410                                 return BADARG;
411                         }
412                         if (long_options[match].has_arg == required_argument ||
413                             long_options[match].has_arg == optional_argument) {
414                                 if (has_equal)
415                                         optarg = has_equal;
416                                 else if (long_options[match].has_arg ==
417                                     required_argument) {
418                                         /*
419                                          * optional argument doesn't use
420                                          * next nargv
421                                          */
422                                         optarg = nargv[optind++];
423                                 }
424                         }
425                         if ((long_options[match].has_arg == required_argument)
426                             && (optarg == NULL)) {
427                                 /*
428                                  * Missing argument; leading ':'
429                                  * indicates no error should be generated
430                                  */
431                                 if (PRINT_ERROR)
432                                         warnx(recargstring, current_argv);
433                                 /*
434                                  * XXX: GNU sets optopt to val regardless
435                                  * of flag
436                                  */
437                                 if (long_options[match].flag == NULL)
438                                         optopt = long_options[match].val;
439                                 else
440                                         optopt = 0;
441                                 --optind;
442                                 return BADARG;
443                         }
444                 } else {                        /* unknown option */
445                         if (PRINT_ERROR)
446                                 warnx(illoptstring, current_argv);
447                         optopt = 0;
448                         return BADCH;
449                 }
450                 if (long_options[match].flag) {
451                         *long_options[match].flag = long_options[match].val;
452                         retval = 0;
453                 } else
454                         retval = long_options[match].val;
455                 if (idx)
456                         *idx = match;
457         }
458         return retval;
459 #undef IDENTICAL_INTERPRETATION
460 }