Merge branch 'master' of ssh://git.samba.org/data/git/samba into wmi
[metze/samba/wip.git] / source4 / lib / popt / popt.c
1 /** \ingroup popt
2  * \file popt/popt.c
3  */
4
5 /* (C) 1998-2002 Red Hat, Inc. -- Licensing details are in the COPYING
6    file accompanying popt source distributions, available from
7    ftp://ftp.rpm.org/pub/rpm/dist */
8
9 #undef  MYDEBUG
10
11 #include "system.h"
12
13 #if HAVE_MATH_H
14 #include <math.h>
15 #endif
16 #if HAVE_FLOAT_H
17 #include <float.h>
18 #endif
19
20 #include "findme.h"
21 #include "poptint.h"
22
23 #ifdef  MYDEBUG
24 /*@unchecked@*/
25 int _popt_debug = 0;
26 #endif
27
28 #ifndef HAVE_STRERROR
29 static char * strerror(int errno) {
30     extern int sys_nerr;
31     extern char * sys_errlist[];
32
33     if ((0 <= errno) && (errno < sys_nerr))
34         return sys_errlist[errno];
35     else
36         return POPT_("unknown errno");
37 }
38 #endif
39
40 #ifdef MYDEBUG
41 /*@unused@*/ static void prtcon(const char *msg, poptContext con)
42 {
43     if (msg) fprintf(stderr, "%s", msg);
44     fprintf(stderr, "\tcon %p os %p nextCharArg \"%s\" nextArg \"%s\" argv[%d] \"%s\"\n",
45         con, con->os,
46         (con->os->nextCharArg ? con->os->nextCharArg : ""),
47         (con->os->nextArg ? con->os->nextArg : ""),
48         con->os->next,
49         (con->os->argv && con->os->argv[con->os->next]
50                 ? con->os->argv[con->os->next] : ""));
51 }
52 #endif
53
54 void poptSetExecPath(poptContext con, const char * path, int allowAbsolute)
55 {
56     con->execPath = _free(con->execPath);
57     con->execPath = xstrdup(path);
58     con->execAbsolute = allowAbsolute;
59     /*@-nullstate@*/ /* LCL: con->execPath can be NULL? */
60     return;
61     /*@=nullstate@*/
62 }
63
64 static void invokeCallbacksPRE(poptContext con, const struct poptOption * opt)
65         /*@globals internalState@*/
66         /*@modifies internalState@*/
67 {
68     if (opt != NULL)
69     for (; opt->longName || opt->shortName || opt->arg; opt++) {
70         if (opt->arg == NULL) continue;         /* XXX program error. */
71         if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
72             /* Recurse on included sub-tables. */
73             invokeCallbacksPRE(con, opt->arg);
74         } else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_CALLBACK &&
75                    (opt->argInfo & POPT_CBFLAG_PRE))
76         {   /*@-castfcnptr@*/
77             poptCallbackType cb = (poptCallbackType)opt->arg;
78             /*@=castfcnptr@*/
79             /* Perform callback. */
80             /*@-moduncon -noeffectuncon @*/
81             cb(con, POPT_CALLBACK_REASON_PRE, NULL, NULL, opt->descrip);
82             /*@=moduncon =noeffectuncon @*/
83         }
84     }
85 }
86
87 static void invokeCallbacksPOST(poptContext con, const struct poptOption * opt)
88         /*@globals internalState@*/
89         /*@modifies internalState@*/
90 {
91     if (opt != NULL)
92     for (; opt->longName || opt->shortName || opt->arg; opt++) {
93         if (opt->arg == NULL) continue;         /* XXX program error. */
94         if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
95             /* Recurse on included sub-tables. */
96             invokeCallbacksPOST(con, opt->arg);
97         } else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_CALLBACK &&
98                    (opt->argInfo & POPT_CBFLAG_POST))
99         {   /*@-castfcnptr@*/
100             poptCallbackType cb = (poptCallbackType)opt->arg;
101             /*@=castfcnptr@*/
102             /* Perform callback. */
103             /*@-moduncon -noeffectuncon @*/
104             cb(con, POPT_CALLBACK_REASON_POST, NULL, NULL, opt->descrip);
105             /*@=moduncon =noeffectuncon @*/
106         }
107     }
108 }
109
110 static void invokeCallbacksOPTION(poptContext con,
111                                   const struct poptOption * opt,
112                                   const struct poptOption * myOpt,
113                                   /*@null@*/ const void * myData, int shorty)
114         /*@globals internalState@*/
115         /*@modifies internalState@*/
116 {
117     const struct poptOption * cbopt = NULL;
118
119     if (opt != NULL)
120     for (; opt->longName || opt->shortName || opt->arg; opt++) {
121         if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
122             /* Recurse on included sub-tables. */
123             if (opt->arg != NULL)       /* XXX program error */
124                 invokeCallbacksOPTION(con, opt->arg, myOpt, myData, shorty);
125         } else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_CALLBACK &&
126                   !(opt->argInfo & POPT_CBFLAG_SKIPOPTION)) {
127             /* Save callback info. */
128             cbopt = opt;
129         } else if (cbopt != NULL &&
130                    ((myOpt->shortName && opt->shortName && shorty &&
131                         myOpt->shortName == opt->shortName) ||
132                     (myOpt->longName && opt->longName &&
133                 /*@-nullpass@*/         /* LCL: opt->longName != NULL */
134                         !strcmp(myOpt->longName, opt->longName)))
135                 /*@=nullpass@*/
136                    )
137         {   /*@-castfcnptr@*/
138             poptCallbackType cb = (poptCallbackType)cbopt->arg;
139             /*@=castfcnptr@*/
140             const void * cbData = (cbopt->descrip ? cbopt->descrip : myData);
141             /* Perform callback. */
142             if (cb != NULL) {   /* XXX program error */
143                 /*@-moduncon -noeffectuncon @*/
144                 cb(con, POPT_CALLBACK_REASON_OPTION, myOpt,
145                         con->os->nextArg, cbData);
146                 /*@=moduncon =noeffectuncon @*/
147             }
148             /* Terminate (unless explcitly continuing). */
149             if (!(cbopt->argInfo & POPT_CBFLAG_CONTINUE))
150                 return;
151         }
152     }
153 }
154
155 poptContext poptGetContext(const char * name, int argc, const char ** argv,
156                            const struct poptOption * options, int flags)
157 {
158     poptContext con = malloc(sizeof(*con));
159
160     if (con == NULL) return NULL;       /* XXX can't happen */
161     memset(con, 0, sizeof(*con));
162
163     con->os = con->optionStack;
164     con->os->argc = argc;
165     /*@-dependenttrans -assignexpose@*/ /* FIX: W2DO? */
166     con->os->argv = argv;
167     /*@=dependenttrans =assignexpose@*/
168     con->os->argb = NULL;
169
170     if (!(flags & POPT_CONTEXT_KEEP_FIRST))
171         con->os->next = 1;                      /* skip argv[0] */
172
173     con->leftovers = calloc( (argc + 1), sizeof(*con->leftovers) );
174     /*@-dependenttrans -assignexpose@*/ /* FIX: W2DO? */
175     con->options = options;
176     /*@=dependenttrans =assignexpose@*/
177     con->aliases = NULL;
178     con->numAliases = 0;
179     con->flags = flags;
180     con->execs = NULL;
181     con->numExecs = 0;
182     con->finalArgvAlloced = argc * 2;
183     con->finalArgv = calloc( con->finalArgvAlloced, sizeof(*con->finalArgv) );
184     con->execAbsolute = 1;
185     con->arg_strip = NULL;
186
187     if (getenv("POSIXLY_CORRECT") || getenv("POSIX_ME_HARDER"))
188         con->flags |= POPT_CONTEXT_POSIXMEHARDER;
189
190     if (name) {
191         char * t = malloc(strlen(name) + 1);
192         if (t) con->appName = strcpy(t, name);
193     }
194
195     /*@-internalglobs@*/
196     invokeCallbacksPRE(con, con->options);
197     /*@=internalglobs@*/
198
199     return con;
200 }
201
202 static void cleanOSE(/*@special@*/ struct optionStackEntry *os)
203         /*@uses os @*/
204         /*@releases os->nextArg, os->argv, os->argb @*/
205         /*@modifies os @*/
206 {
207     os->nextArg = _free(os->nextArg);
208     os->argv = _free(os->argv);
209     os->argb = PBM_FREE(os->argb);
210 }
211
212 /*@-boundswrite@*/
213 void poptResetContext(poptContext con)
214 {
215     int i;
216
217     if (con == NULL) return;
218     while (con->os > con->optionStack) {
219         cleanOSE(con->os--);
220     }
221     con->os->argb = PBM_FREE(con->os->argb);
222     con->os->currAlias = NULL;
223     con->os->nextCharArg = NULL;
224     con->os->nextArg = NULL;
225     con->os->next = 1;                  /* skip argv[0] */
226
227     con->numLeftovers = 0;
228     con->nextLeftover = 0;
229     con->restLeftover = 0;
230     con->doExec = NULL;
231
232     if (con->finalArgv != NULL)
233     for (i = 0; i < con->finalArgvCount; i++) {
234         /*@-unqualifiedtrans@*/         /* FIX: typedef double indirection. */
235         con->finalArgv[i] = _free(con->finalArgv[i]);
236         /*@=unqualifiedtrans@*/
237     }
238
239     con->finalArgvCount = 0;
240     con->arg_strip = PBM_FREE(con->arg_strip);
241     /*@-nullstate@*/    /* FIX: con->finalArgv != NULL */
242     return;
243     /*@=nullstate@*/
244 }
245 /*@=boundswrite@*/
246
247 /* Only one of longName, shortName should be set, not both. */
248 /*@-boundswrite@*/
249 static int handleExec(/*@special@*/ poptContext con,
250                 /*@null@*/ const char * longName, char shortName)
251         /*@uses con->execs, con->numExecs, con->flags, con->doExec,
252                 con->finalArgv, con->finalArgvAlloced, con->finalArgvCount @*/
253         /*@modifies con @*/
254 {
255     poptItem item;
256     int i;
257
258     if (con->execs == NULL || con->numExecs <= 0) /* XXX can't happen */
259         return 0;
260
261     for (i = con->numExecs - 1; i >= 0; i--) {
262         item = con->execs + i;
263         if (longName && !(item->option.longName &&
264                         !strcmp(longName, item->option.longName)))
265             continue;
266         else if (shortName != item->option.shortName)
267             continue;
268         break;
269     }
270     if (i < 0) return 0;
271
272
273     if (con->flags & POPT_CONTEXT_NO_EXEC)
274         return 1;
275
276     if (con->doExec == NULL) {
277         con->doExec = con->execs + i;
278         return 1;
279     }
280
281     /* We already have an exec to do; remember this option for next
282        time 'round */
283     if ((con->finalArgvCount + 1) >= (con->finalArgvAlloced)) {
284         con->finalArgvAlloced += 10;
285         con->finalArgv = realloc(con->finalArgv,
286                         sizeof(*con->finalArgv) * con->finalArgvAlloced);
287     }
288
289     i = con->finalArgvCount++;
290     if (con->finalArgv != NULL) /* XXX can't happen */
291     {   char *s  = malloc((longName ? strlen(longName) : 0) + 3);
292         if (s != NULL) {        /* XXX can't happen */
293             if (longName)
294                 sprintf(s, "--%s", longName);
295             else
296                 sprintf(s, "-%c", shortName);
297             con->finalArgv[i] = s;
298         } else
299             con->finalArgv[i] = NULL;
300     }
301
302     /*@-nullstate@*/    /* FIX: con->finalArgv[] == NULL */
303     return 1;
304     /*@=nullstate@*/
305 }
306 /*@=boundswrite@*/
307
308 /* Only one of longName, shortName may be set at a time */
309 static int handleAlias(/*@special@*/ poptContext con,
310                 /*@null@*/ const char * longName, char shortName,
311                 /*@exposed@*/ /*@null@*/ const char * nextCharArg)
312         /*@uses con->aliases, con->numAliases, con->optionStack, con->os,
313                 con->os->currAlias, con->os->currAlias->option.longName @*/
314         /*@modifies con @*/
315 {
316     poptItem item = con->os->currAlias;
317     int rc;
318     int i;
319
320     if (item) {
321         if (longName && (item->option.longName &&
322                 !strcmp(longName, item->option.longName)))
323             return 0;
324         if (shortName && shortName == item->option.shortName)
325             return 0;
326     }
327
328     if (con->aliases == NULL || con->numAliases <= 0) /* XXX can't happen */
329         return 0;
330
331     for (i = con->numAliases - 1; i >= 0; i--) {
332         item = con->aliases + i;
333         if (longName && !(item->option.longName &&
334                         !strcmp(longName, item->option.longName)))
335             continue;
336         else if (shortName != item->option.shortName)
337             continue;
338         break;
339     }
340     if (i < 0) return 0;
341
342     if ((con->os - con->optionStack + 1) == POPT_OPTION_DEPTH)
343         return POPT_ERROR_OPTSTOODEEP;
344
345 /*@-boundsread@*/
346     if (nextCharArg && *nextCharArg)
347         con->os->nextCharArg = nextCharArg;
348 /*@=boundsread@*/
349
350     con->os++;
351     con->os->next = 0;
352     con->os->stuffed = 0;
353     con->os->nextArg = NULL;
354     con->os->nextCharArg = NULL;
355     con->os->currAlias = con->aliases + i;
356     rc = poptDupArgv(con->os->currAlias->argc, con->os->currAlias->argv,
357                 &con->os->argc, &con->os->argv);
358     con->os->argb = NULL;
359
360     return (rc ? rc : 1);
361 }
362
363 /*@-bounds -boundswrite @*/
364 static int execCommand(poptContext con)
365         /*@globals internalState @*/
366         /*@modifies internalState @*/
367 {
368     poptItem item = con->doExec;
369     const char ** argv;
370     int argc = 0;
371     int rc;
372
373     if (item == NULL) /*XXX can't happen*/
374         return POPT_ERROR_NOARG;
375
376     if (item->argv == NULL || item->argc < 1 ||
377         (!con->execAbsolute && strchr(item->argv[0], '/')))
378             return POPT_ERROR_NOARG;
379
380     argv = malloc(sizeof(*argv) *
381                         (6 + item->argc + con->numLeftovers + con->finalArgvCount));
382     if (argv == NULL) return POPT_ERROR_MALLOC; /* XXX can't happen */
383
384     if (!strchr(item->argv[0], '/') && con->execPath) {
385         char *s = alloca(strlen(con->execPath) + strlen(item->argv[0]) + sizeof("/"));
386         sprintf(s, "%s/%s", con->execPath, item->argv[0]);
387         argv[argc] = s;
388     } else {
389         argv[argc] = findProgramPath(item->argv[0]);
390     }
391     if (argv[argc++] == NULL) return POPT_ERROR_NOARG;
392
393     if (item->argc > 1) {
394         memcpy(argv + argc, item->argv + 1, sizeof(*argv) * (item->argc - 1));
395         argc += (item->argc - 1);
396     }
397
398     if (con->finalArgv != NULL && con->finalArgvCount > 0) {
399         memcpy(argv + argc, con->finalArgv,
400                 sizeof(*argv) * con->finalArgvCount);
401         argc += con->finalArgvCount;
402     }
403
404     if (con->leftovers != NULL && con->numLeftovers > 0) {
405 #if 0
406         argv[argc++] = "--";
407 #endif
408         memcpy(argv + argc, con->leftovers, sizeof(*argv) * con->numLeftovers);
409         argc += con->numLeftovers;
410     }
411
412     argv[argc] = NULL;
413
414 #ifdef __hpux
415     rc = setresuid(getuid(), getuid(),-1);
416     if (rc) return POPT_ERROR_ERRNO;
417 #else
418 /*
419  * XXX " ... on BSD systems setuid() should be preferred over setreuid()"
420  * XXX  sez' Timur Bakeyev <mc@bat.ru>
421  * XXX  from Norbert Warmuth <nwarmuth@privat.circular.de>
422  */
423 #if defined(HAVE_SETUID)
424     rc = setuid(getuid());
425     if (rc) return POPT_ERROR_ERRNO;
426 #elif defined (HAVE_SETREUID)
427     rc = setreuid(getuid(), getuid()); /*hlauer: not portable to hpux9.01 */
428     if (rc) return POPT_ERROR_ERRNO;
429 #else
430     ; /* Can't drop privileges */
431 #endif
432 #endif
433
434     if (argv[0] == NULL)
435         return POPT_ERROR_NOARG;
436
437 #ifdef  MYDEBUG
438 if (_popt_debug)
439     {   const char ** avp;
440         fprintf(stderr, "==> execvp(%s) argv[%d]:", argv[0], argc);
441         for (avp = argv; *avp; avp++)
442             fprintf(stderr, " '%s'", *avp);
443         fprintf(stderr, "\n");
444     }
445 #endif
446
447     rc = execvp(argv[0], (char *const *)argv);
448
449     return POPT_ERROR_ERRNO;
450 }
451 /*@=bounds =boundswrite @*/
452
453 /*@-boundswrite@*/
454 /*@observer@*/ /*@null@*/ static const struct poptOption *
455 findOption(const struct poptOption * opt, /*@null@*/ const char * longName,
456                 char shortName,
457                 /*@null@*/ /*@out@*/ poptCallbackType * callback,
458                 /*@null@*/ /*@out@*/ const void ** callbackData,
459                 int singleDash)
460         /*@modifies *callback, *callbackData */
461 {
462     const struct poptOption * cb = NULL;
463
464     /* This happens when a single - is given */
465     if (singleDash && !shortName && (longName && *longName == '\0'))
466         shortName = '-';
467
468     for (; opt->longName || opt->shortName || opt->arg; opt++) {
469
470         if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
471             const struct poptOption * opt2;
472
473             /* Recurse on included sub-tables. */
474             if (opt->arg == NULL) continue;     /* XXX program error */
475             opt2 = findOption(opt->arg, longName, shortName, callback,
476                               callbackData, singleDash);
477             if (opt2 == NULL) continue;
478             /* Sub-table data will be inheirited if no data yet. */
479             if (!(callback && *callback)) return opt2;
480             if (!(callbackData && *callbackData == NULL)) return opt2;
481             /*@-observertrans -dependenttrans @*/
482             *callbackData = opt->descrip;
483             /*@=observertrans =dependenttrans @*/
484             return opt2;
485         } else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_CALLBACK) {
486             cb = opt;
487         } else if (longName && opt->longName &&
488                    (!singleDash || (opt->argInfo & POPT_ARGFLAG_ONEDASH)) &&
489                 /*@-nullpass@*/         /* LCL: opt->longName != NULL */
490                    !strcmp(longName, opt->longName))
491                 /*@=nullpass@*/
492         {
493             break;
494         } else if (shortName && shortName == opt->shortName) {
495             break;
496         }
497     }
498
499     if (!opt->longName && !opt->shortName)
500         return NULL;
501     /*@-modobserver -mods @*/
502     if (callback) *callback = NULL;
503     if (callbackData) *callbackData = NULL;
504     if (cb) {
505         if (callback)
506         /*@-castfcnptr@*/
507             *callback = (poptCallbackType)cb->arg;
508         /*@=castfcnptr@*/
509         if (!(cb->argInfo & POPT_CBFLAG_INC_DATA)) {
510             if (callbackData)
511                 /*@-observertrans@*/    /* FIX: typedef double indirection. */
512                 *callbackData = cb->descrip;
513                 /*@=observertrans@*/
514         }
515     }
516     /*@=modobserver =mods @*/
517
518     return opt;
519 }
520 /*@=boundswrite@*/
521
522 static const char * findNextArg(/*@special@*/ poptContext con,
523                 unsigned argx, int delete_arg)
524         /*@uses con->optionStack, con->os,
525                 con->os->next, con->os->argb, con->os->argc, con->os->argv @*/
526         /*@modifies con @*/
527 {
528     struct optionStackEntry * os = con->os;
529     const char * arg;
530
531     do {
532         int i;
533         arg = NULL;
534         while (os->next == os->argc && os > con->optionStack) os--;
535         if (os->next == os->argc && os == con->optionStack) break;
536         if (os->argv != NULL)
537         for (i = os->next; i < os->argc; i++) {
538             /*@-sizeoftype@*/
539             if (os->argb && PBM_ISSET(i, os->argb))
540                 /*@innercontinue@*/ continue;
541             if (*os->argv[i] == '-')
542                 /*@innercontinue@*/ continue;
543             if (--argx > 0)
544                 /*@innercontinue@*/ continue;
545             arg = os->argv[i];
546             if (delete_arg) {
547                 if (os->argb == NULL) os->argb = PBM_ALLOC(os->argc);
548                 if (os->argb != NULL)   /* XXX can't happen */
549                 PBM_SET(i, os->argb);
550             }
551             /*@innerbreak@*/ break;
552             /*@=sizeoftype@*/
553         }
554         if (os > con->optionStack) os--;
555     } while (arg == NULL);
556     return arg;
557 }
558
559 /*@-boundswrite@*/
560 static /*@only@*/ /*@null@*/ const char *
561 expandNextArg(/*@special@*/ poptContext con, const char * s)
562         /*@uses con->optionStack, con->os,
563                 con->os->next, con->os->argb, con->os->argc, con->os->argv @*/
564         /*@modifies con @*/
565 {
566     const char * a = NULL;
567     size_t alen;
568     char *t, *te;
569     size_t tn = strlen(s) + 1;
570     char c;
571
572     te = t = malloc(tn);;
573     if (t == NULL) return NULL;         /* XXX can't happen */
574     while ((c = *s++) != '\0') {
575         switch (c) {
576 #if 0   /* XXX can't do this */
577         case '\\':      /* escape */
578             c = *s++;
579             /*@switchbreak@*/ break;
580 #endif
581         case '!':
582             if (!(s[0] == '#' && s[1] == ':' && s[2] == '+'))
583                 /*@switchbreak@*/ break;
584             /* XXX Make sure that findNextArg deletes only next arg. */
585             if (a == NULL) {
586                 if ((a = findNextArg(con, 1, 1)) == NULL)
587                     /*@switchbreak@*/ break;
588             }
589             s += 3;
590
591             alen = strlen(a);
592             tn += alen;
593             *te = '\0';
594             t = realloc(t, tn);
595             te = t + strlen(t);
596             strncpy(te, a, alen); te += alen;
597             continue;
598             /*@notreached@*/ /*@switchbreak@*/ break;
599         default:
600             /*@switchbreak@*/ break;
601         }
602         *te++ = c;
603     }
604     *te = '\0';
605     t = realloc(t, strlen(t) + 1);      /* XXX memory leak, hard to plug */
606     return t;
607 }
608 /*@=boundswrite@*/
609
610 static void poptStripArg(/*@special@*/ poptContext con, int which)
611         /*@uses con->arg_strip, con->optionStack @*/
612         /*@defines con->arg_strip @*/
613         /*@modifies con @*/
614 {
615     /*@-sizeoftype@*/
616     if (con->arg_strip == NULL)
617         con->arg_strip = PBM_ALLOC(con->optionStack[0].argc);
618     if (con->arg_strip != NULL)         /* XXX can't happen */
619     PBM_SET(which, con->arg_strip);
620     /*@=sizeoftype@*/
621     /*@-compdef@*/ /* LCL: con->arg_strip udefined? */
622     return;
623     /*@=compdef@*/
624 }
625
626 int poptSaveLong(long * arg, int argInfo, long aLong)
627 {
628     /* XXX Check alignment, may fail on funky platforms. */
629     if (arg == NULL || (((unsigned long)arg) & (sizeof(*arg)-1)))
630         return POPT_ERROR_NULLARG;
631
632     if (argInfo & POPT_ARGFLAG_NOT)
633         aLong = ~aLong;
634     switch (argInfo & POPT_ARGFLAG_LOGICALOPS) {
635     case 0:
636         *arg = aLong;
637         break;
638     case POPT_ARGFLAG_OR:
639         *arg |= aLong;
640         break;
641     case POPT_ARGFLAG_AND:
642         *arg &= aLong;
643         break;
644     case POPT_ARGFLAG_XOR:
645         *arg ^= aLong;
646         break;
647     default:
648         return POPT_ERROR_BADOPERATION;
649         /*@notreached@*/ break;
650     }
651     return 0;
652 }
653
654 int poptSaveInt(/*@null@*/ int * arg, int argInfo, long aLong)
655 {
656     /* XXX Check alignment, may fail on funky platforms. */
657     if (arg == NULL || (((unsigned long)arg) & (sizeof(*arg)-1)))
658         return POPT_ERROR_NULLARG;
659
660     if (argInfo & POPT_ARGFLAG_NOT)
661         aLong = ~aLong;
662     switch (argInfo & POPT_ARGFLAG_LOGICALOPS) {
663     case 0:
664         *arg = aLong;
665         break;
666     case POPT_ARGFLAG_OR:
667         *arg |= aLong;
668         break;
669     case POPT_ARGFLAG_AND:
670         *arg &= aLong;
671         break;
672     case POPT_ARGFLAG_XOR:
673         *arg ^= aLong;
674         break;
675     default:
676         return POPT_ERROR_BADOPERATION;
677         /*@notreached@*/ break;
678     }
679     return 0;
680 }
681
682 /*@-boundswrite@*/
683 /* returns 'val' element, -1 on last item, POPT_ERROR_* on error */
684 int poptGetNextOpt(poptContext con)
685 {
686     const struct poptOption * opt = NULL;
687     int done = 0;
688
689     if (con == NULL)
690         return -1;
691     while (!done) {
692         const char * origOptString = NULL;
693         poptCallbackType cb = NULL;
694         const void * cbData = NULL;
695         const char * longArg = NULL;
696         int canstrip = 0;
697         int shorty = 0;
698
699         while (!con->os->nextCharArg && con->os->next == con->os->argc
700                 && con->os > con->optionStack) {
701             cleanOSE(con->os--);
702         }
703         if (!con->os->nextCharArg && con->os->next == con->os->argc) {
704             /*@-internalglobs@*/
705             invokeCallbacksPOST(con, con->options);
706             /*@=internalglobs@*/
707             if (con->doExec) return execCommand(con);
708             return -1;
709         }
710
711         /* Process next long option */
712         if (!con->os->nextCharArg) {
713             char * localOptString, * optString;
714             int thisopt;
715
716             /*@-sizeoftype@*/
717             if (con->os->argb && PBM_ISSET(con->os->next, con->os->argb)) {
718                 con->os->next++;
719                 continue;
720             }
721             /*@=sizeoftype@*/
722             thisopt = con->os->next;
723             if (con->os->argv != NULL)  /* XXX can't happen */
724             origOptString = con->os->argv[con->os->next++];
725
726             if (origOptString == NULL)  /* XXX can't happen */
727                 return POPT_ERROR_BADOPT;
728
729             if (con->restLeftover || *origOptString != '-') {
730                 if (con->flags & POPT_CONTEXT_POSIXMEHARDER)
731                     con->restLeftover = 1;
732                 if (con->flags & POPT_CONTEXT_ARG_OPTS) {
733                     con->os->nextArg = xstrdup(origOptString);
734                     return 0;
735                 }
736                 if (con->leftovers != NULL)     /* XXX can't happen */
737                     con->leftovers[con->numLeftovers++] = origOptString;
738                 continue;
739             }
740
741             /* Make a copy we can hack at */
742             localOptString = optString =
743                 strcpy(alloca(strlen(origOptString) + 1), origOptString);
744
745             if (optString[0] == '\0')
746                 return POPT_ERROR_BADOPT;
747
748             if (optString[1] == '-' && !optString[2]) {
749                 con->restLeftover = 1;
750                 continue;
751             } else {
752                 char *oe;
753                 int singleDash;
754
755                 optString++;
756                 if (*optString == '-')
757                     singleDash = 0, optString++;
758                 else
759                     singleDash = 1;
760
761                 /* XXX aliases with arg substitution need "--alias=arg" */
762                 if (handleAlias(con, optString, '\0', NULL))
763                     continue;
764
765                 if (handleExec(con, optString, '\0'))
766                     continue;
767
768                 /* Check for "--long=arg" option. */
769                 for (oe = optString; *oe && *oe != '='; oe++)
770                     {};
771                 if (*oe == '=') {
772                     *oe++ = '\0';
773                     /* XXX longArg is mapped back to persistent storage. */
774                     longArg = origOptString + (oe - localOptString);
775                 }
776
777                 opt = findOption(con->options, optString, '\0', &cb, &cbData,
778                                  singleDash);
779                 if (!opt && !singleDash)
780                     return POPT_ERROR_BADOPT;
781             }
782
783             if (!opt) {
784                 con->os->nextCharArg = origOptString + 1;
785             } else {
786                 if (con->os == con->optionStack &&
787                    opt->argInfo & POPT_ARGFLAG_STRIP)
788                 {
789                     canstrip = 1;
790                     poptStripArg(con, thisopt);
791                 }
792                 shorty = 0;
793             }
794         }
795
796         /* Process next short option */
797         /*@-branchstate@*/              /* FIX: W2DO? */
798         if (con->os->nextCharArg) {
799             origOptString = con->os->nextCharArg;
800
801             con->os->nextCharArg = NULL;
802
803             if (handleAlias(con, NULL, *origOptString, origOptString + 1))
804                 continue;
805
806             if (handleExec(con, NULL, *origOptString)) {
807                 /* Restore rest of short options for further processing */
808                 origOptString++;
809                 if (*origOptString != '\0')
810                     con->os->nextCharArg = origOptString;
811                 continue;
812             }
813
814             opt = findOption(con->options, NULL, *origOptString, &cb,
815                              &cbData, 0);
816             if (!opt)
817                 return POPT_ERROR_BADOPT;
818             shorty = 1;
819
820             origOptString++;
821             if (*origOptString != '\0')
822                 con->os->nextCharArg = origOptString;
823         }
824         /*@=branchstate@*/
825
826         if (opt == NULL) return POPT_ERROR_BADOPT;      /* XXX can't happen */
827         if (opt->arg && (opt->argInfo & POPT_ARG_MASK) == POPT_ARG_NONE) {
828             if (poptSaveInt((int *)opt->arg, opt->argInfo, 1L))
829                 return POPT_ERROR_BADOPERATION;
830         } else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_VAL) {
831             if (opt->arg) {
832                 if (poptSaveInt((int *)opt->arg, opt->argInfo, (long)opt->val))
833                     return POPT_ERROR_BADOPERATION;
834             }
835         } else if ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_NONE) {
836             con->os->nextArg = _free(con->os->nextArg);
837             /*@-usedef@*/       /* FIX: W2DO? */
838             if (longArg) {
839             /*@=usedef@*/
840                 longArg = expandNextArg(con, longArg);
841                 con->os->nextArg = longArg;
842             } else if (con->os->nextCharArg) {
843                 longArg = expandNextArg(con, con->os->nextCharArg);
844                 con->os->nextArg = longArg;
845                 con->os->nextCharArg = NULL;
846             } else {
847                 while (con->os->next == con->os->argc &&
848                        con->os > con->optionStack) {
849                     cleanOSE(con->os--);
850                 }
851                 if (con->os->next == con->os->argc) {
852                     if (!(opt->argInfo & POPT_ARGFLAG_OPTIONAL))
853                         /*@-compdef@*/  /* FIX: con->os->argv not defined */
854                         return POPT_ERROR_NOARG;
855                         /*@=compdef@*/
856                     con->os->nextArg = NULL;
857                 } else {
858
859                     /*
860                      * Make sure this isn't part of a short arg or the
861                      * result of an alias expansion.
862                      */
863                     if (con->os == con->optionStack &&
864                         (opt->argInfo & POPT_ARGFLAG_STRIP) &&
865                         canstrip) {
866                         poptStripArg(con, con->os->next);
867                     }
868                 
869                     if (con->os->argv != NULL) {        /* XXX can't happen */
870                         /* XXX watchout: subtle side-effects live here. */
871                         longArg = con->os->argv[con->os->next++];
872                         longArg = expandNextArg(con, longArg);
873                         con->os->nextArg = longArg;
874                     }
875                 }
876             }
877             longArg = NULL;
878
879             if (opt->arg) {
880                 switch (opt->argInfo & POPT_ARG_MASK) {
881                 case POPT_ARG_STRING:
882                     /* XXX memory leak, hard to plug */
883                     *((const char **) opt->arg) = (con->os->nextArg)
884                         ? xstrdup(con->os->nextArg) : NULL;
885                     /*@switchbreak@*/ break;
886
887                 case POPT_ARG_INT:
888                 case POPT_ARG_LONG:
889                 {   long aLong = 0;
890                     char *end;
891
892                     if (con->os->nextArg) {
893                         aLong = strtol(con->os->nextArg, &end, 0);
894                         if (!(end && *end == '\0'))
895                             return POPT_ERROR_BADNUMBER;
896                     }
897
898                     if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_LONG) {
899                         if (aLong == LONG_MIN || aLong == LONG_MAX)
900                             return POPT_ERROR_OVERFLOW;
901                         if (poptSaveLong((long *)opt->arg, opt->argInfo, aLong))
902                             return POPT_ERROR_BADOPERATION;
903                     } else {
904                         if (aLong > INT_MAX || aLong < INT_MIN)
905                             return POPT_ERROR_OVERFLOW;
906                         if (poptSaveInt((int *)opt->arg, opt->argInfo, aLong))
907                             return POPT_ERROR_BADOPERATION;
908                     }
909                 }   /*@switchbreak@*/ break;
910
911                 case POPT_ARG_FLOAT:
912                 case POPT_ARG_DOUBLE:
913                 {   double aDouble = 0.0;
914                     char *end;
915
916                     if (con->os->nextArg) {
917                         /*@-mods@*/
918                         int saveerrno = errno;
919                         errno = 0;
920                         aDouble = strtod(con->os->nextArg, &end);
921                         if (errno == ERANGE)
922                             return POPT_ERROR_OVERFLOW;
923                         errno = saveerrno;
924                         /*@=mods@*/
925                         if (*end != '\0')
926                             return POPT_ERROR_BADNUMBER;
927                     }
928
929                     if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_DOUBLE) {
930                         *((double *) opt->arg) = aDouble;
931                     } else {
932 #define _ABS(a) ((((a) - 0.0) < DBL_EPSILON) ? -(a) : (a))
933                         if ((_ABS(aDouble) - FLT_MAX) > DBL_EPSILON)
934                             return POPT_ERROR_OVERFLOW;
935                         if ((FLT_MIN - _ABS(aDouble)) > DBL_EPSILON)
936                             return POPT_ERROR_OVERFLOW;
937                         *((float *) opt->arg) = aDouble;
938                     }
939                 }   /*@switchbreak@*/ break;
940                 default:
941                     fprintf(stdout,
942                         POPT_("option type (%d) not implemented in popt\n"),
943                         (opt->argInfo & POPT_ARG_MASK));
944                     exit(EXIT_FAILURE);
945                     /*@notreached@*/ /*@switchbreak@*/ break;
946                 }
947             }
948         }
949
950         if (cb) {
951             /*@-internalglobs@*/
952             invokeCallbacksOPTION(con, con->options, opt, cbData, shorty);
953             /*@=internalglobs@*/
954         } else if (opt->val && ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_VAL))
955             done = 1;
956
957         if ((con->finalArgvCount + 2) >= (con->finalArgvAlloced)) {
958             con->finalArgvAlloced += 10;
959             con->finalArgv = realloc(con->finalArgv,
960                             sizeof(*con->finalArgv) * con->finalArgvAlloced);
961         }
962
963         if (con->finalArgv != NULL)
964         {   char *s = malloc((opt->longName ? strlen(opt->longName) : 0) + 3);
965             if (s != NULL) {    /* XXX can't happen */
966                 if (opt->longName)
967                     sprintf(s, "%s%s",
968                         ((opt->argInfo & POPT_ARGFLAG_ONEDASH) ? "-" : "--"),
969                         opt->longName);
970                 else
971                     sprintf(s, "-%c", opt->shortName);
972                 con->finalArgv[con->finalArgvCount++] = s;
973             } else
974                 con->finalArgv[con->finalArgvCount++] = NULL;
975         }
976
977         if (opt->arg && (opt->argInfo & POPT_ARG_MASK) == POPT_ARG_NONE)
978             /*@-ifempty@*/ ; /*@=ifempty@*/
979         else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_VAL)
980             /*@-ifempty@*/ ; /*@=ifempty@*/
981         else if ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_NONE) {
982             if (con->finalArgv != NULL && con->os->nextArg)
983                 con->finalArgv[con->finalArgvCount++] =
984                         /*@-nullpass@*/ /* LCL: con->os->nextArg != NULL */
985                         xstrdup(con->os->nextArg);
986                         /*@=nullpass@*/
987         }
988     }
989
990     return (opt ? opt->val : -1);       /* XXX can't happen */
991 }
992 /*@=boundswrite@*/
993
994 const char * poptGetOptArg(poptContext con)
995 {
996     const char * ret = NULL;
997     /*@-branchstate@*/
998     if (con) {
999         ret = con->os->nextArg;
1000         con->os->nextArg = NULL;
1001     }
1002     /*@=branchstate@*/
1003     return ret;
1004 }
1005
1006 const char * poptGetArg(poptContext con)
1007 {
1008     const char * ret = NULL;
1009     if (con && con->leftovers != NULL && con->nextLeftover < con->numLeftovers)
1010         ret = con->leftovers[con->nextLeftover++];
1011     return ret;
1012 }
1013
1014 const char * poptPeekArg(poptContext con)
1015 {
1016     const char * ret = NULL;
1017     if (con && con->leftovers != NULL && con->nextLeftover < con->numLeftovers)
1018         ret = con->leftovers[con->nextLeftover];
1019     return ret;
1020 }
1021
1022 /*@-boundswrite@*/
1023 const char ** poptGetArgs(poptContext con)
1024 {
1025     if (con == NULL ||
1026         con->leftovers == NULL || con->numLeftovers == con->nextLeftover)
1027         return NULL;
1028
1029     /* some apps like [like RPM ;-) ] need this NULL terminated */
1030     con->leftovers[con->numLeftovers] = NULL;
1031
1032     /*@-nullret -nullstate @*/  /* FIX: typedef double indirection. */
1033     return (con->leftovers + con->nextLeftover);
1034     /*@=nullret =nullstate @*/
1035 }
1036 /*@=boundswrite@*/
1037
1038 poptContext poptFreeContext(poptContext con)
1039 {
1040     poptItem item;
1041     int i;
1042
1043     if (con == NULL) return con;
1044     poptResetContext(con);
1045     con->os->argb = _free(con->os->argb);
1046
1047     if (con->aliases != NULL)
1048     for (i = 0; i < con->numAliases; i++) {
1049         item = con->aliases + i;
1050         /*@-modobserver -observertrans -dependenttrans@*/
1051         item->option.longName = _free(item->option.longName);
1052         item->option.descrip = _free(item->option.descrip);
1053         item->option.argDescrip = _free(item->option.argDescrip);
1054         /*@=modobserver =observertrans =dependenttrans@*/
1055         item->argv = _free(item->argv);
1056     }
1057     con->aliases = _free(con->aliases);
1058
1059     if (con->execs != NULL)
1060     for (i = 0; i < con->numExecs; i++) {
1061         item = con->execs + i;
1062         /*@-modobserver -observertrans -dependenttrans@*/
1063         item->option.longName = _free(item->option.longName);
1064         item->option.descrip = _free(item->option.descrip);
1065         item->option.argDescrip = _free(item->option.argDescrip);
1066         /*@=modobserver =observertrans =dependenttrans@*/
1067         item->argv = _free(item->argv);
1068     }
1069     con->execs = _free(con->execs);
1070
1071     con->leftovers = _free(con->leftovers);
1072     con->finalArgv = _free(con->finalArgv);
1073     con->appName = _free(con->appName);
1074     con->otherHelp = _free(con->otherHelp);
1075     con->execPath = _free(con->execPath);
1076     con->arg_strip = PBM_FREE(con->arg_strip);
1077     
1078     con = _free(con);
1079     return con;
1080 }
1081
1082 int poptAddAlias(poptContext con, struct poptAlias alias,
1083                 /*@unused@*/ int flags)
1084 {
1085     poptItem item = alloca(sizeof(*item));
1086     memset(item, 0, sizeof(*item));
1087     item->option.longName = alias.longName;
1088     item->option.shortName = alias.shortName;
1089     item->option.argInfo = POPT_ARGFLAG_DOC_HIDDEN;
1090     item->option.arg = 0;
1091     item->option.val = 0;
1092     item->option.descrip = NULL;
1093     item->option.argDescrip = NULL;
1094     item->argc = alias.argc;
1095     item->argv = alias.argv;
1096     return poptAddItem(con, item, 0);
1097 }
1098
1099 /*@-boundswrite@*/
1100 /*@-mustmod@*/ /* LCL: con not modified? */
1101 int poptAddItem(poptContext con, poptItem newItem, int flags)
1102 {
1103     poptItem * items, item;
1104     int * nitems;
1105
1106     switch (flags) {
1107     case 1:
1108         items = &con->execs;
1109         nitems = &con->numExecs;
1110         break;
1111     case 0:
1112         items = &con->aliases;
1113         nitems = &con->numAliases;
1114         break;
1115     default:
1116         return 1;
1117         /*@notreached@*/ break;
1118     }
1119
1120     *items = realloc((*items), ((*nitems) + 1) * sizeof(**items));
1121     if ((*items) == NULL)
1122         return 1;
1123
1124     item = (*items) + (*nitems);
1125
1126     item->option.longName =
1127         (newItem->option.longName ? xstrdup(newItem->option.longName) : NULL);
1128     item->option.shortName = newItem->option.shortName;
1129     item->option.argInfo = newItem->option.argInfo;
1130     item->option.arg = newItem->option.arg;
1131     item->option.val = newItem->option.val;
1132     item->option.descrip =
1133         (newItem->option.descrip ? xstrdup(newItem->option.descrip) : NULL);
1134     item->option.argDescrip =
1135        (newItem->option.argDescrip ? xstrdup(newItem->option.argDescrip) : NULL);
1136     item->argc = newItem->argc;
1137     item->argv = newItem->argv;
1138
1139     (*nitems)++;
1140
1141     return 0;
1142 }
1143 /*@=mustmod@*/
1144 /*@=boundswrite@*/
1145
1146 const char * poptBadOption(poptContext con, int flags)
1147 {
1148     struct optionStackEntry * os = NULL;
1149
1150     if (con != NULL)
1151         os = (flags & POPT_BADOPTION_NOALIAS) ? con->optionStack : con->os;
1152
1153     /*@-nullderef@*/    /* LCL: os->argv != NULL */
1154     return (os && os->argv ? os->argv[os->next - 1] : NULL);
1155     /*@=nullderef@*/
1156 }
1157
1158 const char *poptStrerror(const int error)
1159 {
1160     switch (error) {
1161       case POPT_ERROR_NOARG:
1162         return POPT_("missing argument");
1163       case POPT_ERROR_BADOPT:
1164         return POPT_("unknown option");
1165       case POPT_ERROR_BADOPERATION:
1166         return POPT_("mutually exclusive logical operations requested");
1167       case POPT_ERROR_NULLARG:
1168         return POPT_("opt->arg should not be NULL");
1169       case POPT_ERROR_OPTSTOODEEP:
1170         return POPT_("aliases nested too deeply");
1171       case POPT_ERROR_BADQUOTE:
1172         return POPT_("error in parameter quoting");
1173       case POPT_ERROR_BADNUMBER:
1174         return POPT_("invalid numeric value");
1175       case POPT_ERROR_OVERFLOW:
1176         return POPT_("number too large or too small");
1177       case POPT_ERROR_MALLOC:
1178         return POPT_("memory allocation failed");
1179       case POPT_ERROR_ERRNO:
1180         return strerror(errno);
1181       default:
1182         return POPT_("unknown error");
1183     }
1184 }
1185
1186 int poptStuffArgs(poptContext con, const char ** argv)
1187 {
1188     int argc;
1189     int rc;
1190
1191     if ((con->os - con->optionStack) == POPT_OPTION_DEPTH)
1192         return POPT_ERROR_OPTSTOODEEP;
1193
1194     for (argc = 0; argv[argc]; argc++)
1195         {};
1196
1197     con->os++;
1198     con->os->next = 0;
1199     con->os->nextArg = NULL;
1200     con->os->nextCharArg = NULL;
1201     con->os->currAlias = NULL;
1202     rc = poptDupArgv(argc, argv, &con->os->argc, &con->os->argv);
1203     con->os->argb = NULL;
1204     con->os->stuffed = 1;
1205
1206     return rc;
1207 }
1208
1209 const char * poptGetInvocationName(poptContext con)
1210 {
1211     return (con->os->argv ? con->os->argv[0] : "");
1212 }
1213
1214 /*@-boundswrite@*/
1215 int poptStrippedArgv(poptContext con, int argc, char ** argv)
1216 {
1217     int numargs = argc;
1218     int j = 1;
1219     int i;
1220     
1221     /*@-sizeoftype@*/
1222     if (con->arg_strip)
1223     for (i = 1; i < argc; i++) {
1224         if (PBM_ISSET(i, con->arg_strip))
1225             numargs--;
1226     }
1227     
1228     for (i = 1; i < argc; i++) {
1229         if (con->arg_strip && PBM_ISSET(i, con->arg_strip))
1230             continue;
1231         argv[j] = (j < numargs) ? argv[i] : NULL;
1232         j++;
1233     }
1234     /*@=sizeoftype@*/
1235     
1236     return numargs;
1237 }
1238 /*@=boundswrite@*/