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