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