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