98979fc2a1362b68fb41c7ec1e5b2c7ba18531c4
[openssl.git] / apps / lib / opt.c
1 /*
2  * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /*
11  * This file is also used by the test suite. Do not #include "apps.h".
12  */
13 #include "opt.h"
14 #include "fmt.h"
15 #include "internal/nelem.h"
16 #include <string.h>
17 #if !defined(OPENSSL_SYS_MSDOS)
18 # include <unistd.h>
19 #endif
20
21 #include <stdlib.h>
22 #include <errno.h>
23 #include <ctype.h>
24 #include <limits.h>
25 #include <openssl/bio.h>
26 #include <openssl/x509v3.h>
27
28 #define MAX_OPT_HELP_WIDTH 30
29 const char OPT_HELP_STR[] = "--";
30 const char OPT_MORE_STR[] = "---";
31 const char OPT_SECTION_STR[] = "----";
32
33 /* Our state */
34 static char **argv;
35 static int argc;
36 static int opt_index;
37 static char *arg;
38 static char *flag;
39 static char *dunno;
40 static const OPTIONS *unknown;
41 static const OPTIONS *opts;
42 static char prog[40];
43
44 /*
45  * Return the simple name of the program; removing various platform gunk.
46  */
47 #if defined(OPENSSL_SYS_WIN32)
48 char *opt_progname(const char *argv0)
49 {
50     size_t i, n;
51     const char *p;
52     char *q;
53
54     /* find the last '/', '\' or ':' */
55     for (p = argv0 + strlen(argv0); --p > argv0;)
56         if (*p == '/' || *p == '\\' || *p == ':') {
57             p++;
58             break;
59         }
60
61     /* Strip off trailing nonsense. */
62     n = strlen(p);
63     if (n > 4 &&
64         (strcmp(&p[n - 4], ".exe") == 0 || strcmp(&p[n - 4], ".EXE") == 0))
65         n -= 4;
66
67     /* Copy over the name, in lowercase. */
68     if (n > sizeof(prog) - 1)
69         n = sizeof(prog) - 1;
70     for (q = prog, i = 0; i < n; i++, p++)
71         *q++ = tolower((unsigned char)*p);
72     *q = '\0';
73     return prog;
74 }
75
76 #elif defined(OPENSSL_SYS_VMS)
77
78 char *opt_progname(const char *argv0)
79 {
80     const char *p, *q;
81
82     /* Find last special character sys:[foo.bar]openssl */
83     for (p = argv0 + strlen(argv0); --p > argv0;)
84         if (*p == ':' || *p == ']' || *p == '>') {
85             p++;
86             break;
87         }
88
89     q = strrchr(p, '.');
90     strncpy(prog, p, sizeof(prog) - 1);
91     prog[sizeof(prog) - 1] = '\0';
92     if (q != NULL && q - p < sizeof(prog))
93         prog[q - p] = '\0';
94     return prog;
95 }
96
97 #else
98
99 char *opt_progname(const char *argv0)
100 {
101     const char *p;
102
103     /* Could use strchr, but this is like the ones above. */
104     for (p = argv0 + strlen(argv0); --p > argv0;)
105         if (*p == '/') {
106             p++;
107             break;
108         }
109     strncpy(prog, p, sizeof(prog) - 1);
110     prog[sizeof(prog) - 1] = '\0';
111     return prog;
112 }
113 #endif
114
115 char *opt_getprog(void)
116 {
117     return prog;
118 }
119
120 /* Set up the arg parsing. */
121 char *opt_init(int ac, char **av, const OPTIONS *o)
122 {
123     /* Store state. */
124     argc = ac;
125     argv = av;
126     opt_begin();
127     opts = o;
128     opt_progname(av[0]);
129     unknown = NULL;
130
131     for (; o->name; ++o) {
132 #ifndef NDEBUG
133         const OPTIONS *next;
134         int duplicated, i;
135 #endif
136
137         if (o->name == OPT_HELP_STR || o->name == OPT_MORE_STR ||
138             o->name == OPT_SECTION_STR)
139             continue;
140 #ifndef NDEBUG
141         i = o->valtype;
142
143         /* Make sure options are legit. */
144         OPENSSL_assert(o->name[0] != '-');
145         OPENSSL_assert(o->retval > 0);
146         switch (i) {
147         case   0: case '-': case '/': case '<': case '>': case 'E': case 'F':
148         case 'M': case 'U': case 'f': case 'l': case 'n': case 'p': case 's':
149         case 'u': case 'c': case ':':
150             break;
151         default:
152             OPENSSL_assert(0);
153         }
154
155         /* Make sure there are no duplicates. */
156         for (next = o + 1; next->name; ++next) {
157             /*
158              * Some compilers inline strcmp and the assert string is too long.
159              */
160             duplicated = strcmp(o->name, next->name) == 0;
161             OPENSSL_assert(!duplicated);
162         }
163 #endif
164         if (o->name[0] == '\0') {
165             OPENSSL_assert(unknown == NULL);
166             unknown = o;
167             OPENSSL_assert(unknown->valtype == 0 || unknown->valtype == '-');
168         }
169     }
170     return prog;
171 }
172
173 static OPT_PAIR formats[] = {
174     {"PEM/DER", OPT_FMT_PEMDER},
175     {"pkcs12", OPT_FMT_PKCS12},
176     {"smime", OPT_FMT_SMIME},
177     {"engine", OPT_FMT_ENGINE},
178     {"msblob", OPT_FMT_MSBLOB},
179     {"nss", OPT_FMT_NSS},
180     {"text", OPT_FMT_TEXT},
181     {"http", OPT_FMT_HTTP},
182     {"pvk", OPT_FMT_PVK},
183     {NULL}
184 };
185
186 /* Print an error message about a failed format parse. */
187 int opt_format_error(const char *s, unsigned long flags)
188 {
189     OPT_PAIR *ap;
190
191     if (flags == OPT_FMT_PEMDER) {
192         opt_printf_stderr("%s: Bad format \"%s\"; must be pem or der\n",
193                           prog, s);
194     } else {
195         opt_printf_stderr("%s: Bad format \"%s\"; must be one of:\n",
196                           prog, s);
197         for (ap = formats; ap->name; ap++)
198             if (flags & ap->retval)
199                 opt_printf_stderr("   %s\n", ap->name);
200     }
201     return 0;
202 }
203
204 /* Parse a format string, put it into *result; return 0 on failure, else 1. */
205 int opt_format(const char *s, unsigned long flags, int *result)
206 {
207     switch (*s) {
208     default:
209         return 0;
210     case 'D':
211     case 'd':
212         if ((flags & OPT_FMT_PEMDER) == 0)
213             return opt_format_error(s, flags);
214         *result = FORMAT_ASN1;
215         break;
216     case 'T':
217     case 't':
218         if ((flags & OPT_FMT_TEXT) == 0)
219             return opt_format_error(s, flags);
220         *result = FORMAT_TEXT;
221         break;
222     case 'N':
223     case 'n':
224         if ((flags & OPT_FMT_NSS) == 0)
225             return opt_format_error(s, flags);
226         if (strcmp(s, "NSS") != 0 && strcmp(s, "nss") != 0)
227             return opt_format_error(s, flags);
228         *result = FORMAT_NSS;
229         break;
230     case 'S':
231     case 's':
232         if ((flags & OPT_FMT_SMIME) == 0)
233             return opt_format_error(s, flags);
234         *result = FORMAT_SMIME;
235         break;
236     case 'M':
237     case 'm':
238         if ((flags & OPT_FMT_MSBLOB) == 0)
239             return opt_format_error(s, flags);
240         *result = FORMAT_MSBLOB;
241         break;
242     case 'E':
243     case 'e':
244         if ((flags & OPT_FMT_ENGINE) == 0)
245             return opt_format_error(s, flags);
246         *result = FORMAT_ENGINE;
247         break;
248     case 'H':
249     case 'h':
250         if ((flags & OPT_FMT_HTTP) == 0)
251             return opt_format_error(s, flags);
252         *result = FORMAT_HTTP;
253         break;
254     case '1':
255         if ((flags & OPT_FMT_PKCS12) == 0)
256             return opt_format_error(s, flags);
257         *result = FORMAT_PKCS12;
258         break;
259     case 'P':
260     case 'p':
261         if (s[1] == '\0' || strcmp(s, "PEM") == 0 || strcmp(s, "pem") == 0) {
262             if ((flags & OPT_FMT_PEMDER) == 0)
263                 return opt_format_error(s, flags);
264             *result = FORMAT_PEM;
265         } else if (strcmp(s, "PVK") == 0 || strcmp(s, "pvk") == 0) {
266             if ((flags & OPT_FMT_PVK) == 0)
267                 return opt_format_error(s, flags);
268             *result = FORMAT_PVK;
269         } else if (strcmp(s, "P12") == 0 || strcmp(s, "p12") == 0
270                    || strcmp(s, "PKCS12") == 0 || strcmp(s, "pkcs12") == 0) {
271             if ((flags & OPT_FMT_PKCS12) == 0)
272                 return opt_format_error(s, flags);
273             *result = FORMAT_PKCS12;
274         } else {
275             return 0;
276         }
277         break;
278     }
279     return 1;
280 }
281
282 /* Parse a cipher name, put it in *EVP_CIPHER; return 0 on failure, else 1. */
283 int opt_cipher(const char *name, const EVP_CIPHER **cipherp)
284 {
285     *cipherp = EVP_get_cipherbyname(name);
286     if (*cipherp != NULL)
287         return 1;
288     opt_printf_stderr("%s: Unrecognized flag %s\n", prog, name);
289     return 0;
290 }
291
292 /*
293  * Parse message digest name, put it in *EVP_MD; return 0 on failure, else 1.
294  */
295 int opt_md(const char *name, const EVP_MD **mdp)
296 {
297     *mdp = EVP_get_digestbyname(name);
298     if (*mdp != NULL)
299         return 1;
300     opt_printf_stderr("%s: Unrecognized flag %s\n", prog, name);
301     return 0;
302 }
303
304 /* Look through a list of name/value pairs. */
305 int opt_pair(const char *name, const OPT_PAIR* pairs, int *result)
306 {
307     const OPT_PAIR *pp;
308
309     for (pp = pairs; pp->name; pp++)
310         if (strcmp(pp->name, name) == 0) {
311             *result = pp->retval;
312             return 1;
313         }
314     opt_printf_stderr("%s: Value must be one of:\n", prog);
315     for (pp = pairs; pp->name; pp++)
316         opt_printf_stderr("\t%s\n", pp->name);
317     return 0;
318 }
319
320 /* Parse an int, put it into *result; return 0 on failure, else 1. */
321 int opt_int(const char *value, int *result)
322 {
323     long l;
324
325     if (!opt_long(value, &l))
326         return 0;
327     *result = (int)l;
328     if (*result != l) {
329         opt_printf_stderr("%s: Value \"%s\" outside integer range\n",
330                           prog, value);
331         return 0;
332     }
333     return 1;
334 }
335
336 static void opt_number_error(const char *v)
337 {
338     size_t i = 0;
339     struct strstr_pair_st {
340         char *prefix;
341         char *name;
342     } b[] = {
343         {"0x", "a hexadecimal"},
344         {"0X", "a hexadecimal"},
345         {"0", "an octal"}
346     };
347
348     for (i = 0; i < OSSL_NELEM(b); i++) {
349         if (strncmp(v, b[i].prefix, strlen(b[i].prefix)) == 0) {
350             opt_printf_stderr("%s: Can't parse \"%s\" as %s number\n",
351                               prog, v, b[i].name);
352             return;
353         }
354     }
355     opt_printf_stderr("%s: Can't parse \"%s\" as a number\n", prog, v);
356     return;
357 }
358
359 /* Parse a long, put it into *result; return 0 on failure, else 1. */
360 int opt_long(const char *value, long *result)
361 {
362     int oerrno = errno;
363     long l;
364     char *endp;
365
366     errno = 0;
367     l = strtol(value, &endp, 0);
368     if (*endp
369             || endp == value
370             || ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE)
371             || (l == 0 && errno != 0)) {
372         opt_number_error(value);
373         errno = oerrno;
374         return 0;
375     }
376     *result = l;
377     errno = oerrno;
378     return 1;
379 }
380
381 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L && \
382     defined(INTMAX_MAX) && defined(UINTMAX_MAX) && \
383     !defined(OPENSSL_NO_INTTYPES_H)
384
385 /* Parse an intmax_t, put it into *result; return 0 on failure, else 1. */
386 int opt_imax(const char *value, intmax_t *result)
387 {
388     int oerrno = errno;
389     intmax_t m;
390     char *endp;
391
392     errno = 0;
393     m = strtoimax(value, &endp, 0);
394     if (*endp
395             || endp == value
396             || ((m == INTMAX_MAX || m == INTMAX_MIN) && errno == ERANGE)
397             || (m == 0 && errno != 0)) {
398         opt_number_error(value);
399         errno = oerrno;
400         return 0;
401     }
402     *result = m;
403     errno = oerrno;
404     return 1;
405 }
406
407 /* Parse a uintmax_t, put it into *result; return 0 on failure, else 1. */
408 int opt_umax(const char *value, uintmax_t *result)
409 {
410     int oerrno = errno;
411     uintmax_t m;
412     char *endp;
413
414     errno = 0;
415     m = strtoumax(value, &endp, 0);
416     if (*endp
417             || endp == value
418             || (m == UINTMAX_MAX && errno == ERANGE)
419             || (m == 0 && errno != 0)) {
420         opt_number_error(value);
421         errno = oerrno;
422         return 0;
423     }
424     *result = m;
425     errno = oerrno;
426     return 1;
427 }
428 #endif
429
430 /*
431  * Parse an unsigned long, put it into *result; return 0 on failure, else 1.
432  */
433 int opt_ulong(const char *value, unsigned long *result)
434 {
435     int oerrno = errno;
436     char *endptr;
437     unsigned long l;
438
439     errno = 0;
440     l = strtoul(value, &endptr, 0);
441     if (*endptr
442             || endptr == value
443             || ((l == ULONG_MAX) && errno == ERANGE)
444             || (l == 0 && errno != 0)) {
445         opt_number_error(value);
446         errno = oerrno;
447         return 0;
448     }
449     *result = l;
450     errno = oerrno;
451     return 1;
452 }
453
454 /*
455  * We pass opt as an int but cast it to "enum range" so that all the
456  * items in the OPT_V_ENUM enumeration are caught; this makes -Wswitch
457  * in gcc do the right thing.
458  */
459 enum range { OPT_V_ENUM };
460
461 int opt_verify(int opt, X509_VERIFY_PARAM *vpm)
462 {
463     int i;
464     ossl_intmax_t t = 0;
465     ASN1_OBJECT *otmp;
466     X509_PURPOSE *xptmp;
467     const X509_VERIFY_PARAM *vtmp;
468
469     OPENSSL_assert(vpm != NULL);
470     OPENSSL_assert(opt > OPT_V__FIRST);
471     OPENSSL_assert(opt < OPT_V__LAST);
472
473     switch ((enum range)opt) {
474     case OPT_V__FIRST:
475     case OPT_V__LAST:
476         return 0;
477     case OPT_V_POLICY:
478         otmp = OBJ_txt2obj(opt_arg(), 0);
479         if (otmp == NULL) {
480             opt_printf_stderr("%s: Invalid Policy %s\n", prog, opt_arg());
481             return 0;
482         }
483         X509_VERIFY_PARAM_add0_policy(vpm, otmp);
484         break;
485     case OPT_V_PURPOSE:
486         /* purpose name -> purpose index */
487         i = X509_PURPOSE_get_by_sname(opt_arg());
488         if (i < 0) {
489             opt_printf_stderr("%s: Invalid purpose %s\n", prog, opt_arg());
490             return 0;
491         }
492
493         /* purpose index -> purpose object */
494         xptmp = X509_PURPOSE_get0(i);
495
496         /* purpose object -> purpose value */
497         i = X509_PURPOSE_get_id(xptmp);
498
499         if (!X509_VERIFY_PARAM_set_purpose(vpm, i)) {
500             opt_printf_stderr("%s: Internal error setting purpose %s\n",
501                               prog, opt_arg());
502             return 0;
503         }
504         break;
505     case OPT_V_VERIFY_NAME:
506         vtmp = X509_VERIFY_PARAM_lookup(opt_arg());
507         if (vtmp == NULL) {
508             opt_printf_stderr("%s: Invalid verify name %s\n",
509                               prog, opt_arg());
510             return 0;
511         }
512         X509_VERIFY_PARAM_set1(vpm, vtmp);
513         break;
514     case OPT_V_VERIFY_DEPTH:
515         i = atoi(opt_arg());
516         if (i >= 0)
517             X509_VERIFY_PARAM_set_depth(vpm, i);
518         break;
519     case OPT_V_VERIFY_AUTH_LEVEL:
520         i = atoi(opt_arg());
521         if (i >= 0)
522             X509_VERIFY_PARAM_set_auth_level(vpm, i);
523         break;
524     case OPT_V_ATTIME:
525         if (!opt_imax(opt_arg(), &t))
526             return 0;
527         if (t != (time_t)t) {
528             opt_printf_stderr("%s: epoch time out of range %s\n",
529                               prog, opt_arg());
530             return 0;
531         }
532         X509_VERIFY_PARAM_set_time(vpm, (time_t)t);
533         break;
534     case OPT_V_VERIFY_HOSTNAME:
535         if (!X509_VERIFY_PARAM_set1_host(vpm, opt_arg(), 0))
536             return 0;
537         break;
538     case OPT_V_VERIFY_EMAIL:
539         if (!X509_VERIFY_PARAM_set1_email(vpm, opt_arg(), 0))
540             return 0;
541         break;
542     case OPT_V_VERIFY_IP:
543         if (!X509_VERIFY_PARAM_set1_ip_asc(vpm, opt_arg()))
544             return 0;
545         break;
546     case OPT_V_IGNORE_CRITICAL:
547         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_IGNORE_CRITICAL);
548         break;
549     case OPT_V_ISSUER_CHECKS:
550         /* NOP, deprecated */
551         break;
552     case OPT_V_CRL_CHECK:
553         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CRL_CHECK);
554         break;
555     case OPT_V_CRL_CHECK_ALL:
556         X509_VERIFY_PARAM_set_flags(vpm,
557                                     X509_V_FLAG_CRL_CHECK |
558                                     X509_V_FLAG_CRL_CHECK_ALL);
559         break;
560     case OPT_V_POLICY_CHECK:
561         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_POLICY_CHECK);
562         break;
563     case OPT_V_EXPLICIT_POLICY:
564         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXPLICIT_POLICY);
565         break;
566     case OPT_V_INHIBIT_ANY:
567         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_ANY);
568         break;
569     case OPT_V_INHIBIT_MAP:
570         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_MAP);
571         break;
572     case OPT_V_X509_STRICT:
573         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_X509_STRICT);
574         break;
575     case OPT_V_EXTENDED_CRL:
576         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXTENDED_CRL_SUPPORT);
577         break;
578     case OPT_V_USE_DELTAS:
579         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_USE_DELTAS);
580         break;
581     case OPT_V_POLICY_PRINT:
582         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NOTIFY_POLICY);
583         break;
584     case OPT_V_CHECK_SS_SIG:
585         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CHECK_SS_SIGNATURE);
586         break;
587     case OPT_V_TRUSTED_FIRST:
588         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_TRUSTED_FIRST);
589         break;
590     case OPT_V_SUITEB_128_ONLY:
591         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS_ONLY);
592         break;
593     case OPT_V_SUITEB_128:
594         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS);
595         break;
596     case OPT_V_SUITEB_192:
597         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_192_LOS);
598         break;
599     case OPT_V_PARTIAL_CHAIN:
600         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_PARTIAL_CHAIN);
601         break;
602     case OPT_V_NO_ALT_CHAINS:
603         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_ALT_CHAINS);
604         break;
605     case OPT_V_NO_CHECK_TIME:
606         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_CHECK_TIME);
607         break;
608     case OPT_V_ALLOW_PROXY_CERTS:
609         X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_ALLOW_PROXY_CERTS);
610         break;
611     }
612     return 1;
613
614 }
615
616 void opt_begin(void)
617 {
618     opt_index = 1;
619     arg = NULL;
620     flag = NULL;
621 }
622
623 /*
624  * Parse the next flag (and value if specified), return 0 if done, -1 on
625  * error, otherwise the flag's retval.
626  */
627 int opt_next(void)
628 {
629     char *p;
630     const OPTIONS *o;
631     int ival;
632     long lval;
633     unsigned long ulval;
634     ossl_intmax_t imval;
635     ossl_uintmax_t umval;
636
637     /* Look at current arg; at end of the list? */
638     arg = NULL;
639     p = argv[opt_index];
640     if (p == NULL)
641         return 0;
642
643     /* If word doesn't start with a -, we're done. */
644     if (*p != '-')
645         return 0;
646
647     /* Hit "--" ? We're done. */
648     opt_index++;
649     if (strcmp(p, "--") == 0)
650         return 0;
651
652     /* Allow -nnn and --nnn */
653     if (*++p == '-')
654         p++;
655     flag = p - 1;
656
657     /* If we have --flag=foo, snip it off */
658     if ((arg = strchr(p, '=')) != NULL)
659         *arg++ = '\0';
660     for (o = opts; o->name; ++o) {
661         /* If not this option, move on to the next one. */
662         if (strcmp(p, o->name) != 0)
663             continue;
664
665         /* If it doesn't take a value, make sure none was given. */
666         if (o->valtype == 0 || o->valtype == '-') {
667             if (arg) {
668                 opt_printf_stderr("%s: Option -%s does not take a value\n",
669                                   prog, p);
670                 return -1;
671             }
672             return o->retval;
673         }
674
675         /* Want a value; get the next param if =foo not used. */
676         if (arg == NULL) {
677             if (argv[opt_index] == NULL) {
678                 opt_printf_stderr("%s: Option -%s needs a value\n",
679                                   prog, o->name);
680                 return -1;
681             }
682             arg = argv[opt_index++];
683         }
684
685         /* Syntax-check value. */
686         switch (o->valtype) {
687         default:
688         case 's':
689         case ':':
690             /* Just a string. */
691             break;
692         case '/':
693             if (opt_isdir(arg) > 0)
694                 break;
695             opt_printf_stderr("%s: Not a directory: %s\n", prog, arg);
696             return -1;
697         case '<':
698             /* Input file. */
699             break;
700         case '>':
701             /* Output file. */
702             break;
703         case 'p':
704         case 'n':
705             if (!opt_int(arg, &ival)
706                     || (o->valtype == 'p' && ival <= 0)) {
707                 opt_printf_stderr("%s: Non-positive number \"%s\" for -%s\n",
708                                   prog, arg, o->name);
709                 return -1;
710             }
711             break;
712         case 'M':
713             if (!opt_imax(arg, &imval)) {
714                 opt_printf_stderr("%s: Invalid number \"%s\" for -%s\n",
715                                   prog, arg, o->name);
716                 return -1;
717             }
718             break;
719         case 'U':
720             if (!opt_umax(arg, &umval)) {
721                 opt_printf_stderr("%s: Invalid number \"%s\" for -%s\n",
722                                   prog, arg, o->name);
723                 return -1;
724             }
725             break;
726         case 'l':
727             if (!opt_long(arg, &lval)) {
728                 opt_printf_stderr("%s: Invalid number \"%s\" for -%s\n",
729                                   prog, arg, o->name);
730                 return -1;
731             }
732             break;
733         case 'u':
734             if (!opt_ulong(arg, &ulval)) {
735                 opt_printf_stderr("%s: Invalid number \"%s\" for -%s\n",
736                                   prog, arg, o->name);
737                 return -1;
738             }
739             break;
740         case 'c':
741         case 'E':
742         case 'F':
743         case 'f':
744             if (opt_format(arg,
745                            o->valtype == 'c' ? OPT_FMT_PDS :
746                            o->valtype == 'E' ? OPT_FMT_PDE :
747                            o->valtype == 'F' ? OPT_FMT_PEMDER
748                            : OPT_FMT_ANY, &ival))
749                 break;
750             opt_printf_stderr("%s: Invalid format \"%s\" for -%s\n",
751                               prog, arg, o->name);
752             return -1;
753         }
754
755         /* Return the flag value. */
756         return o->retval;
757     }
758     if (unknown != NULL) {
759         dunno = p;
760         return unknown->retval;
761     }
762     opt_printf_stderr("%s: Option unknown option -%s\n", prog, p);
763     return -1;
764 }
765
766 /* Return the most recent flag parameter. */
767 char *opt_arg(void)
768 {
769     return arg;
770 }
771
772 /* Return the most recent flag. */
773 char *opt_flag(void)
774 {
775     return flag;
776 }
777
778 /* Return the unknown option. */
779 char *opt_unknown(void)
780 {
781     return dunno;
782 }
783
784 /* Return the rest of the arguments after parsing flags. */
785 char **opt_rest(void)
786 {
787     return &argv[opt_index];
788 }
789
790 /* How many items in remaining args? */
791 int opt_num_rest(void)
792 {
793     int i = 0;
794     char **pp;
795
796     for (pp = opt_rest(); *pp; pp++, i++)
797         continue;
798     return i;
799 }
800
801 /* Return a string describing the parameter type. */
802 static const char *valtype2param(const OPTIONS *o)
803 {
804     switch (o->valtype) {
805     case 0:
806     case '-':
807         return "";
808     case ':':
809         return "uri";
810     case 's':
811         return "val";
812     case '/':
813         return "dir";
814     case '<':
815         return "infile";
816     case '>':
817         return "outfile";
818     case 'p':
819         return "+int";
820     case 'n':
821         return "int";
822     case 'l':
823         return "long";
824     case 'u':
825         return "ulong";
826     case 'E':
827         return "PEM|DER|ENGINE";
828     case 'F':
829         return "PEM|DER";
830     case 'f':
831         return "format";
832     case 'M':
833         return "intmax";
834     case 'U':
835         return "uintmax";
836     }
837     return "parm";
838 }
839
840 void opt_print(const OPTIONS *o, int width)
841 {
842     const char* help;
843     char start[80 + 1];
844     char *p;
845
846         help = o->helpstr ? o->helpstr : "(No additional info)";
847         if (o->name == OPT_HELP_STR || o->name == OPT_SECTION_STR) {
848             opt_printf_stderr(help, prog);
849             return;
850         }
851
852         /* Pad out prefix */
853         memset(start, ' ', sizeof(start) - 1);
854         start[sizeof(start) - 1] = '\0';
855
856         if (o->name == OPT_MORE_STR) {
857             /* Continuation of previous line; pad and print. */
858             start[width] = '\0';
859             opt_printf_stderr("%s  %s\n", start, help);
860             return;
861         }
862
863         /* Build up the "-flag [param]" part. */
864         p = start;
865         *p++ = ' ';
866         *p++ = '-';
867         if (o->name[0])
868             p += strlen(strcpy(p, o->name));
869         else
870             *p++ = '*';
871         if (o->valtype != '-') {
872             *p++ = ' ';
873             p += strlen(strcpy(p, valtype2param(o)));
874         }
875         *p = ' ';
876         if ((int)(p - start) >= MAX_OPT_HELP_WIDTH) {
877             *p = '\0';
878             opt_printf_stderr("%s\n", start);
879             memset(start, ' ', sizeof(start));
880         }
881         start[width] = '\0';
882         opt_printf_stderr("%s  %s\n", start, help);
883 }
884
885 void opt_help(const OPTIONS *list)
886 {
887     const OPTIONS *o;
888     int i;
889     int standard_prolog;
890     int width = 5;
891     char start[80 + 1];
892
893     /* Starts with its own help message? */
894     standard_prolog = list[0].name != OPT_HELP_STR;
895
896     /* Find the widest help. */
897     for (o = list; o->name; o++) {
898         if (o->name == OPT_MORE_STR)
899             continue;
900         i = 2 + (int)strlen(o->name);
901         if (o->valtype != '-')
902             i += 1 + strlen(valtype2param(o));
903         if (i < MAX_OPT_HELP_WIDTH && i > width)
904             width = i;
905         OPENSSL_assert(i < (int)sizeof(start));
906     }
907
908     if (standard_prolog) {
909         opt_printf_stderr("Usage: %s [options]\n", prog);
910         if (list[0].name != OPT_SECTION_STR)
911             opt_printf_stderr("Valid options are:\n", prog);
912     }
913
914     /* Now let's print. */
915     for (o = list; o->name; o++) {
916         opt_print(o, width);
917     }
918 }
919
920 /* opt_isdir section */
921 #ifdef _WIN32
922 # include <windows.h>
923 int opt_isdir(const char *name)
924 {
925     DWORD attr;
926 # if defined(UNICODE) || defined(_UNICODE)
927     size_t i, len_0 = strlen(name) + 1;
928     WCHAR tempname[MAX_PATH];
929
930     if (len_0 > MAX_PATH)
931         return -1;
932
933 #  if !defined(_WIN32_WCE) || _WIN32_WCE>=101
934     if (!MultiByteToWideChar(CP_ACP, 0, name, len_0, tempname, MAX_PATH))
935 #  endif
936         for (i = 0; i < len_0; i++)
937             tempname[i] = (WCHAR)name[i];
938
939     attr = GetFileAttributes(tempname);
940 # else
941     attr = GetFileAttributes(name);
942 # endif
943     if (attr == INVALID_FILE_ATTRIBUTES)
944         return -1;
945     return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
946 }
947 #else
948 # include <sys/stat.h>
949 # ifndef S_ISDIR
950 #  if defined(_S_IFMT) && defined(_S_IFDIR)
951 #   define S_ISDIR(a)   (((a) & _S_IFMT) == _S_IFDIR)
952 #  else
953 #   define S_ISDIR(a)   (((a) & S_IFMT) == S_IFDIR)
954 #  endif
955 # endif
956
957 int opt_isdir(const char *name)
958 {
959 # if defined(S_ISDIR)
960     struct stat st;
961
962     if (stat(name, &st) == 0)
963         return S_ISDIR(st.st_mode);
964     else
965         return -1;
966 # else
967     return -1;
968 # endif
969 }
970 #endif