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