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