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