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