]> git.ipfire.org Git - thirdparty/openssl.git/blame - apps/opt.c
fix code indentation issue
[thirdparty/openssl.git] / apps / opt.c
CommitLineData
7e1b7485
RS
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"
7e1b7485
RS
52#include <string.h>
53#if !defined(OPENSSL_SYS_MSDOS)
54# include OPENSSL_UNISTD
55#endif
a3ed492f 56
7e1b7485
RS
57#include <stdlib.h>
58#include <errno.h>
59#include <ctype.h>
bd4850df 60#include <limits.h>
7e1b7485
RS
61#include <openssl/bio.h>
62
63#define MAX_OPT_HELP_WIDTH 30
64const char OPT_HELP_STR[] = "--";
65const char OPT_MORE_STR[] = "---";
66
67/* Our state */
68static char **argv;
69static int argc;
70static int opt_index;
71static char *arg;
72static char *flag;
73static char *dunno;
74static const OPTIONS *unknown;
75static const OPTIONS *opts;
76static char prog[40];
77
78/*
79 * Return the simple name of the program; removing various platform gunk.
80 */
81#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_NETWARE)
82char *opt_progname(const char *argv0)
83{
45f13518 84 size_t i, n;
7e1b7485
RS
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 &&
a3ed492f 98 (strcmp(&p[n - 4], ".exe") == 0 || strcmp(&p[n - 4], ".EXE") == 0))
7e1b7485
RS
99 n -= 4;
100#if defined(OPENSSL_SYS_NETWARE)
101 if (n > 4 &&
a3ed492f 102 (strcmp(&p[n - 4], ".nlm") == 0 || strcmp(&p[n - 4], ".NLM") == 0))
7e1b7485
RS
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++)
a3ed492f 110 *q++ = isupper(*p) ? tolower(*p) : *p;
7e1b7485
RS
111 *q = '\0';
112 return prog;
113}
114
115#elif defined(OPENSSL_SYS_VMS)
116
117char *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';
211a68b4 131 if (q != NULL && q - p < sizeof prog)
7e1b7485
RS
132 prog[q - p] = '\0';
133 return prog;
134}
135
136#else
137
138char *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
154char *opt_getprog(void)
155{
156 return prog;
157}
158
159/* Set up the arg parsing. */
160char *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
88806cfc 173 int duplicated, i;
7e1b7485
RS
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);
03f887ca
VD
184 switch (i) {
185 case 0: case '-': case '/': case '<': case '>': case 'F': case 'M':
186 case 'L': case 'U': case 'f': case 'n': case 'p': case 's': case 'u':
187 break;
188 default:
189 assert(0);
190 }
7e1b7485
RS
191
192 /* Make sure there are no duplicates. */
88806cfc 193 for (next = o + 1; next->name; ++next) {
7e1b7485 194 /*
88806cfc 195 * Some compilers inline strcmp and the assert string is too long.
7e1b7485 196 */
88806cfc
RS
197 duplicated = strcmp(o->name, next->name) == 0;
198 assert(!duplicated);
7e1b7485
RS
199 }
200#endif
201 if (o->name[0] == '\0') {
202 assert(unknown == NULL);
203 unknown = o;
204 assert(unknown->valtype == 0 || unknown->valtype == '-');
205 }
206 }
207 return prog;
208}
209
210static OPT_PAIR formats[] = {
211 {"PEM/DER", OPT_FMT_PEMDER},
212 {"pkcs12", OPT_FMT_PKCS12},
213 {"smime", OPT_FMT_SMIME},
214 {"engine", OPT_FMT_ENGINE},
215 {"msblob", OPT_FMT_MSBLOB},
216 {"netscape", OPT_FMT_NETSCAPE},
217 {"nss", OPT_FMT_NSS},
218 {"text", OPT_FMT_TEXT},
219 {"http", OPT_FMT_HTTP},
220 {"pvk", OPT_FMT_PVK},
221 {NULL}
222};
223
224/* Print an error message about a failed format parse. */
225int opt_format_error(const char *s, unsigned long flags)
226{
227 OPT_PAIR *ap;
228
229 if (flags == OPT_FMT_PEMDER)
230 BIO_printf(bio_err, "%s: Bad format \"%s\"; must be pem or der\n",
231 prog, s);
232 else {
233 BIO_printf(bio_err, "%s: Bad format \"%s\"; must be one of:\n",
234 prog, s);
235 for (ap = formats; ap->name; ap++)
236 if (flags & ap->retval)
237 BIO_printf(bio_err, " %s\n", ap->name);
238 }
239 return 0;
240}
241
242/* Parse a format string, put it into *result; return 0 on failure, else 1. */
243int opt_format(const char *s, unsigned long flags, int *result)
244{
245 switch (*s) {
246 default:
247 return 0;
248 case 'D':
249 case 'd':
250 if ((flags & OPT_FMT_PEMDER) == 0)
251 return opt_format_error(s, flags);
252 *result = FORMAT_ASN1;
253 break;
254 case 'T':
255 case 't':
256 if ((flags & OPT_FMT_TEXT) == 0)
257 return opt_format_error(s, flags);
258 *result = FORMAT_TEXT;
259 break;
260 case 'N':
261 case 'n':
0bc2f365
RS
262 if ((flags & OPT_FMT_NSS) == 0)
263 return opt_format_error(s, flags);
264 if (strcmp(s, "NSS") != 0 && strcmp(s, "nss") != 0)
265 return opt_format_error(s, flags);
266 *result = FORMAT_NSS;
7e1b7485
RS
267 break;
268 case 'S':
269 case 's':
270 if ((flags & OPT_FMT_SMIME) == 0)
271 return opt_format_error(s, flags);
272 *result = FORMAT_SMIME;
273 break;
274 case 'M':
275 case 'm':
276 if ((flags & OPT_FMT_MSBLOB) == 0)
277 return opt_format_error(s, flags);
278 *result = FORMAT_MSBLOB;
279 break;
280 case 'E':
281 case 'e':
282 if ((flags & OPT_FMT_ENGINE) == 0)
283 return opt_format_error(s, flags);
284 *result = FORMAT_ENGINE;
285 break;
286 case 'H':
287 case 'h':
288 if ((flags & OPT_FMT_HTTP) == 0)
289 return opt_format_error(s, flags);
290 *result = FORMAT_HTTP;
291 break;
292 case '1':
293 if ((flags & OPT_FMT_PKCS12) == 0)
294 return opt_format_error(s, flags);
295 *result = FORMAT_PKCS12;
296 break;
297 case 'P':
298 case 'p':
299 if (s[1] == '\0' || strcmp(s, "PEM") == 0 || strcmp(s, "pem") == 0) {
300 if ((flags & OPT_FMT_PEMDER) == 0)
301 return opt_format_error(s, flags);
302 *result = FORMAT_PEM;
303 } else if (strcmp(s, "PVK") == 0 || strcmp(s, "pvk") == 0) {
304 if ((flags & OPT_FMT_PVK) == 0)
305 return opt_format_error(s, flags);
306 *result = FORMAT_PVK;
307 } else if (strcmp(s, "P12") == 0 || strcmp(s, "p12") == 0
308 || strcmp(s, "PKCS12") == 0 || strcmp(s, "pkcs12") == 0) {
309 if ((flags & OPT_FMT_PKCS12) == 0)
310 return opt_format_error(s, flags);
311 *result = FORMAT_PKCS12;
312 } else
313 return 0;
314 break;
315 }
316 return 1;
317}
318
319/* Parse a cipher name, put it in *EVP_CIPHER; return 0 on failure, else 1. */
320int opt_cipher(const char *name, const EVP_CIPHER **cipherp)
321{
322 *cipherp = EVP_get_cipherbyname(name);
323 if (*cipherp)
324 return 1;
325 BIO_printf(bio_err, "%s: Unknown cipher %s\n", prog, name);
326 return 0;
327}
328
329/*
330 * Parse message digest name, put it in *EVP_MD; return 0 on failure, else 1.
331 */
332int opt_md(const char *name, const EVP_MD **mdp)
333{
334 *mdp = EVP_get_digestbyname(name);
335 if (*mdp)
336 return 1;
337 BIO_printf(bio_err, "%s: Unknown digest %s\n", prog, name);
338 return 0;
339}
340
341/* Look through a list of name/value pairs. */
342int opt_pair(const char *name, const OPT_PAIR* pairs, int *result)
343{
344 const OPT_PAIR *pp;
345
346 for (pp = pairs; pp->name; pp++)
347 if (strcmp(pp->name, name) == 0) {
348 *result = pp->retval;
349 return 1;
350 }
351 BIO_printf(bio_err, "%s: Value must be one of:\n", prog);
352 for (pp = pairs; pp->name; pp++)
353 BIO_printf(bio_err, "\t%s\n", pp->name);
354 return 0;
355}
356
7e1b7485
RS
357/* Parse an int, put it into *result; return 0 on failure, else 1. */
358int opt_int(const char *value, int *result)
359{
bd4850df
RS
360 long l;
361
362 if (!opt_long(value, &l))
363 return 0;
364 *result = (int)l;
365 if (*result != l) {
366 BIO_printf(bio_err, "%s: Value \"%s\" outside integer range\n",
7e1b7485
RS
367 prog, value);
368 return 0;
369 }
370 return 1;
371}
372
373/* Parse a long, put it into *result; return 0 on failure, else 1. */
374int opt_long(const char *value, long *result)
375{
bd4850df
RS
376 int oerrno = errno;
377 long l;
378 char *endp;
379
380 l = strtol(value, &endp, 0);
381 if (*endp
382 || endp == value
383 || ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE)
384 || (l == 0 && errno != 0)) {
385 BIO_printf(bio_err, "%s: Can't parse \"%s\" as a number\n",
386 prog, value);
387 errno = oerrno;
7e1b7485
RS
388 return 0;
389 }
bd4850df
RS
390 *result = l;
391 errno = oerrno;
7e1b7485
RS
392 return 1;
393}
394
d94a1a70
VD
395#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L && \
396 defined(INTMAX_MAX) && defined(UINTMAX_MAX)
03f887ca
VD
397
398/* Parse an intmax_t, put it into *result; return 0 on failure, else 1. */
399int opt_imax(const char *value, intmax_t *result)
400{
401 int oerrno = errno;
402 intmax_t m;
403 char *endp;
404
405 m = strtoimax(value, &endp, 0);
406 if (*endp
407 || endp == value
408 || ((m == INTMAX_MAX || m == INTMAX_MIN) && errno == ERANGE)
409 || (m == 0 && errno != 0)) {
410 BIO_printf(bio_err, "%s: Can't parse \"%s\" as a number\n",
411 prog, value);
412 errno = oerrno;
413 return 0;
414 }
415 *result = m;
416 errno = oerrno;
417 return 1;
418}
419
420/* Parse a uintmax_t, put it into *result; return 0 on failure, else 1. */
421int opt_umax(const char *value, uintmax_t *result)
422{
423 int oerrno = errno;
424 uintmax_t m;
425 char *endp;
426
427 m = strtoumax(value, &endp, 0);
428 if (*endp
429 || endp == value
430 || (m == UINTMAX_MAX && errno == ERANGE)
431 || (m == 0 && errno != 0)) {
432 BIO_printf(bio_err, "%s: Can't parse \"%s\" as a number\n",
433 prog, value);
434 errno = oerrno;
435 return 0;
436 }
437 *result = m;
438 errno = oerrno;
439 return 1;
440}
441#endif
442
7e1b7485
RS
443/*
444 * Parse an unsigned long, put it into *result; return 0 on failure, else 1.
445 */
446int opt_ulong(const char *value, unsigned long *result)
447{
bd4850df 448 int oerrno = errno;
7e1b7485 449 char *endptr;
bd4850df
RS
450 unsigned long l;
451
452 l = strtoul(value, &endptr, 0);
453 if (*endptr
454 || endptr == value
455 || ((l == ULONG_MAX) && errno == ERANGE)
456 || (l == 0 && errno != 0)) {
457 BIO_printf(bio_err, "%s: Can't parse \"%s\" as an unsigned number\n",
458 prog, value);
459 errno = oerrno;
7e1b7485
RS
460 return 0;
461 }
bd4850df
RS
462 *result = l;
463 errno = oerrno;
7e1b7485
RS
464 return 1;
465}
466
467/*
468 * We pass opt as an int but cast it to "enum range" so that all the
469 * items in the OPT_V_ENUM enumeration are caught; this makes -Wswitch
470 * in gcc do the right thing.
471 */
472enum range { OPT_V_ENUM };
473
474int opt_verify(int opt, X509_VERIFY_PARAM *vpm)
475{
7e1b7485 476 int i;
03f887ca 477 ossl_intmax_t t = 0;
7e1b7485
RS
478 ASN1_OBJECT *otmp;
479 X509_PURPOSE *xptmp;
480 const X509_VERIFY_PARAM *vtmp;
481
482 assert(vpm != NULL);
483 assert(opt > OPT_V__FIRST);
484 assert(opt < OPT_V__LAST);
485
486 switch ((enum range)opt) {
487 case OPT_V__FIRST:
488 case OPT_V__LAST:
489 return 0;
490 case OPT_V_POLICY:
491 otmp = OBJ_txt2obj(opt_arg(), 0);
492 if (otmp == NULL) {
493 BIO_printf(bio_err, "%s: Invalid Policy %s\n", prog, opt_arg());
494 return 0;
495 }
496 X509_VERIFY_PARAM_add0_policy(vpm, otmp);
497 break;
498 case OPT_V_PURPOSE:
0daccd4d 499 /* purpose name -> purpose index */
7e1b7485
RS
500 i = X509_PURPOSE_get_by_sname(opt_arg());
501 if (i < 0) {
502 BIO_printf(bio_err, "%s: Invalid purpose %s\n", prog, opt_arg());
503 return 0;
504 }
0daccd4d
VD
505
506 /* purpose index -> purpose object */
7e1b7485 507 xptmp = X509_PURPOSE_get0(i);
0daccd4d
VD
508
509 /* purpose object -> purpose value */
7e1b7485 510 i = X509_PURPOSE_get_id(xptmp);
0daccd4d
VD
511
512 if (!X509_VERIFY_PARAM_set_purpose(vpm, i)) {
513 BIO_printf(bio_err,
514 "%s: Internal error setting purpose %s\n",
515 prog, opt_arg());
516 return 0;
517 }
7e1b7485
RS
518 break;
519 case OPT_V_VERIFY_NAME:
520 vtmp = X509_VERIFY_PARAM_lookup(opt_arg());
521 if (vtmp == NULL) {
522 BIO_printf(bio_err, "%s: Invalid verify name %s\n",
523 prog, opt_arg());
524 return 0;
525 }
526 X509_VERIFY_PARAM_set1(vpm, vtmp);
527 break;
528 case OPT_V_VERIFY_DEPTH:
529 i = atoi(opt_arg());
530 if (i >= 0)
531 X509_VERIFY_PARAM_set_depth(vpm, i);
532 break;
533 case OPT_V_ATTIME:
03f887ca
VD
534 if (!opt_imax(opt_arg(), &t))
535 return 0;
536 if (t != (time_t)t) {
537 BIO_printf(bio_err, "%s: epoch time out of range %s\n",
538 prog, opt_arg());
539 return 0;
540 }
541 X509_VERIFY_PARAM_set_time(vpm, (time_t)t);
7e1b7485
RS
542 break;
543 case OPT_V_VERIFY_HOSTNAME:
544 if (!X509_VERIFY_PARAM_set1_host(vpm, opt_arg(), 0))
545 return 0;
546 break;
547 case OPT_V_VERIFY_EMAIL:
548 if (!X509_VERIFY_PARAM_set1_email(vpm, opt_arg(), 0))
549 return 0;
550 break;
551 case OPT_V_VERIFY_IP:
552 if (!X509_VERIFY_PARAM_set1_ip_asc(vpm, opt_arg()))
553 return 0;
554 break;
555 case OPT_V_IGNORE_CRITICAL:
556 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_IGNORE_CRITICAL);
557 break;
558 case OPT_V_ISSUER_CHECKS:
559 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CB_ISSUER_CHECK);
560 break;
561 case OPT_V_CRL_CHECK:
562 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CRL_CHECK);
563 break;
564 case OPT_V_CRL_CHECK_ALL:
565 X509_VERIFY_PARAM_set_flags(vpm,
566 X509_V_FLAG_CRL_CHECK |
567 X509_V_FLAG_CRL_CHECK_ALL);
568 break;
569 case OPT_V_POLICY_CHECK:
570 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_POLICY_CHECK);
571 break;
572 case OPT_V_EXPLICIT_POLICY:
573 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXPLICIT_POLICY);
574 break;
575 case OPT_V_INHIBIT_ANY:
576 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_ANY);
577 break;
578 case OPT_V_INHIBIT_MAP:
579 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_MAP);
580 break;
581 case OPT_V_X509_STRICT:
582 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_X509_STRICT);
583 break;
584 case OPT_V_EXTENDED_CRL:
585 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXTENDED_CRL_SUPPORT);
586 break;
587 case OPT_V_USE_DELTAS:
588 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_USE_DELTAS);
589 break;
590 case OPT_V_POLICY_PRINT:
591 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NOTIFY_POLICY);
592 break;
593 case OPT_V_CHECK_SS_SIG:
594 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CHECK_SS_SIGNATURE);
595 break;
596 case OPT_V_TRUSTED_FIRST:
597 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_TRUSTED_FIRST);
598 break;
599 case OPT_V_SUITEB_128_ONLY:
600 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS_ONLY);
601 break;
602 case OPT_V_SUITEB_128:
603 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS);
604 break;
605 case OPT_V_SUITEB_192:
606 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_192_LOS);
607 break;
608 case OPT_V_PARTIAL_CHAIN:
609 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_PARTIAL_CHAIN);
610 break;
611 case OPT_V_NO_ALT_CHAINS:
612 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_ALT_CHAINS);
d35ff2c0
DW
613 break;
614 case OPT_V_NO_CHECK_TIME:
615 X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_CHECK_TIME);
616 break;
7e1b7485
RS
617 }
618 return 1;
619
620}
621
622/*
623 * Parse the next flag (and value if specified), return 0 if done, -1 on
624 * error, otherwise the flag's retval.
625 */
626int opt_next(void)
627{
628 char *p;
7e1b7485 629 const OPTIONS *o;
bd4850df 630 int ival;
03f887ca
VD
631 long lval;
632 unsigned long ulval;
633 ossl_intmax_t imval;
634 ossl_uintmax_t umval;
7e1b7485
RS
635
636 /* Look at current arg; at end of the list? */
637 arg = NULL;
638 p = argv[opt_index];
639 if (p == NULL)
640 return 0;
641
642 /* If word doesn't start with a -, we're done. */
643 if (*p != '-')
644 return 0;
645
646 /* Hit "--" ? We're done. */
647 opt_index++;
648 if (strcmp(p, "--") == 0)
649 return 0;
650
651 /* Allow -nnn and --nnn */
652 if (*++p == '-')
653 p++;
654 flag = p - 1;
655
656 /* If we have --flag=foo, snip it off */
657 if ((arg = strchr(p, '=')) != NULL)
658 *arg++ = '\0';
659 for (o = opts; o->name; ++o) {
660 /* If not this option, move on to the next one. */
661 if (strcmp(p, o->name) != 0)
662 continue;
663
664 /* If it doesn't take a value, make sure none was given. */
665 if (o->valtype == 0 || o->valtype == '-') {
666 if (arg) {
667 BIO_printf(bio_err,
668 "%s: Option -%s does not take a value\n", prog, p);
669 return -1;
670 }
671 return o->retval;
672 }
673
674 /* Want a value; get the next param if =foo not used. */
675 if (arg == NULL) {
676 if (argv[opt_index] == NULL) {
677 BIO_printf(bio_err,
678 "%s: Option -%s needs a value\n", prog, o->name);
679 return -1;
680 }
681 arg = argv[opt_index++];
682 }
683
684 /* Syntax-check value. */
7e1b7485
RS
685 switch (o->valtype) {
686 default:
687 case 's':
688 /* Just a string. */
689 break;
690 case '/':
691 if (app_isdir(arg) >= 0)
692 break;
693 BIO_printf(bio_err, "%s: Not a directory: %s\n", prog, arg);
694 return -1;
695 case '<':
696 /* Input file. */
697 if (strcmp(arg, "-") == 0 || app_access(arg, R_OK) >= 0)
698 break;
699 BIO_printf(bio_err,
700 "%s: Cannot open input file %s, %s\n",
701 prog, arg, strerror(errno));
702 return -1;
703 case '>':
704 /* Output file. */
705 if (strcmp(arg, "-") == 0 || app_access(arg, W_OK) >= 0 || errno == ENOENT)
706 break;
707 BIO_printf(bio_err,
708 "%s: Cannot open output file %s, %s\n",
709 prog, arg, strerror(errno));
710 return -1;
711 case 'p':
712 case 'n':
bd4850df
RS
713 if (!opt_int(arg, &ival)
714 || (o->valtype == 'p' && ival <= 0)) {
715 BIO_printf(bio_err,
716 "%s: Non-positive number \"%s\" for -%s\n",
717 prog, arg, o->name);
718 return -1;
7e1b7485 719 }
bd4850df 720 break;
03f887ca
VD
721 case 'M':
722 if (!opt_imax(arg, &imval)) {
723 BIO_printf(bio_err,
724 "%s: Invalid number \"%s\" for -%s\n",
725 prog, arg, o->name);
726 return -1;
727 }
728 break;
729 case 'U':
730 if (!opt_umax(arg, &umval)) {
731 BIO_printf(bio_err,
732 "%s: Invalid number \"%s\" for -%s\n",
733 prog, arg, o->name);
734 return -1;
735 }
736 break;
737 case 'L':
738 if (!opt_long(arg, &lval)) {
739 BIO_printf(bio_err,
740 "%s: Invalid number \"%s\" for -%s\n",
741 prog, arg, o->name);
742 return -1;
743 }
744 break;
7e1b7485 745 case 'u':
03f887ca 746 if (!opt_ulong(arg, &ulval)) {
bd4850df
RS
747 BIO_printf(bio_err,
748 "%s: Invalid number \"%s\" for -%s\n",
749 prog, arg, o->name);
750 return -1;
751 }
752 break;
7e1b7485
RS
753 case 'f':
754 case 'F':
755 if (opt_format(arg,
756 o->valtype == 'F' ? OPT_FMT_PEMDER
bd4850df 757 : OPT_FMT_ANY, &ival))
7e1b7485
RS
758 break;
759 BIO_printf(bio_err,
760 "%s: Invalid format \"%s\" for -%s\n",
761 prog, arg, o->name);
762 return -1;
763 }
764
765 /* Return the flag value. */
766 return o->retval;
767 }
768 if (unknown != NULL) {
769 dunno = p;
770 return unknown->retval;
771 }
772 BIO_printf(bio_err, "%s: Option unknown option -%s\n", prog, p);
773 return -1;
774}
775
776/* Return the most recent flag parameter. */
777char *opt_arg(void)
778{
779 return arg;
780}
781
782/* Return the most recent flag. */
783char *opt_flag(void)
784{
785 return flag;
786}
787
788/* Return the unknown option. */
789char *opt_unknown(void)
790{
791 return dunno;
792}
793
794/* Return the rest of the arguments after parsing flags. */
795char **opt_rest(void)
796{
797 return &argv[opt_index];
798}
799
800/* How many items in remaining args? */
801int opt_num_rest(void)
802{
803 int i = 0;
804 char **pp;
805
806 for (pp = opt_rest(); *pp; pp++, i++)
807 continue;
808 return i;
809}
810
811/* Return a string describing the parameter type. */
812static const char *valtype2param(const OPTIONS *o)
813{
814 switch (o->valtype) {
815 case '-':
816 return "";
817 case 's':
818 return "val";
819 case '/':
820 return "dir";
821 case '<':
822 return "infile";
823 case '>':
824 return "outfile";
825 case 'p':
826 return "pnum";
827 case 'n':
828 return "num";
829 case 'u':
830 return "unum";
831 case 'F':
832 return "der/pem";
833 case 'f':
834 return "format";
835 }
836 return "parm";
837}
838
839void opt_help(const OPTIONS *list)
840{
841 const OPTIONS *o;
842 int i;
843 int standard_prolog;
844 int width = 5;
845 char start[80 + 1];
846 char *p;
847 const char *help;
848
849 /* Starts with its own help message? */
850 standard_prolog = list[0].name != OPT_HELP_STR;
851
852 /* Find the widest help. */
853 for (o = list; o->name; o++) {
854 if (o->name == OPT_MORE_STR)
855 continue;
856 i = 2 + (int)strlen(o->name);
857 if (o->valtype != '-')
858 i += 1 + strlen(valtype2param(o));
859 if (i < MAX_OPT_HELP_WIDTH && i > width)
860 width = i;
861 assert(i < (int)sizeof start);
862 }
863
864 if (standard_prolog)
865 BIO_printf(bio_err, "Usage: %s [options]\nValid options are:\n",
866 prog);
867
868 /* Now let's print. */
869 for (o = list; o->name; o++) {
870 help = o->helpstr ? o->helpstr : "(No additional info)";
871 if (o->name == OPT_HELP_STR) {
872 BIO_printf(bio_err, help, prog);
873 continue;
874 }
875
876 /* Pad out prefix */
16f8d4eb 877 memset(start, ' ', sizeof(start) - 1);
7e1b7485
RS
878 start[sizeof start - 1] = '\0';
879
880 if (o->name == OPT_MORE_STR) {
881 /* Continuation of previous line; padd and print. */
882 start[width] = '\0';
883 BIO_printf(bio_err, "%s %s\n", start, help);
884 continue;
885 }
886
887 /* Build up the "-flag [param]" part. */
888 p = start;
889 *p++ = ' ';
890 *p++ = '-';
891 if (o->name[0])
892 p += strlen(strcpy(p, o->name));
893 else
894 *p++ = '*';
895 if (o->valtype != '-') {
896 *p++ = ' ';
897 p += strlen(strcpy(p, valtype2param(o)));
898 }
899 *p = ' ';
900 if ((int)(p - start) >= MAX_OPT_HELP_WIDTH) {
901 *p = '\0';
902 BIO_printf(bio_err, "%s\n", start);
16f8d4eb 903 memset(start, ' ', sizeof(start));
7e1b7485
RS
904 }
905 start[width] = '\0';
906 BIO_printf(bio_err, "%s %s\n", start, help);
907 }
908}
909
910#ifdef COMPILE_STANDALONE_TEST_DRIVER
911# include <sys/stat.h>
912
913typedef enum OPTION_choice {
914 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
915 OPT_IN, OPT_INFORM, OPT_OUT, OPT_COUNT, OPT_U, OPT_FLAG,
916 OPT_STR, OPT_NOTUSED
917} OPTION_CHOICE;
918
919static OPTIONS options[] = {
920 {OPT_HELP_STR, 1, '-', "Usage: %s flags\n"},
921 {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
922 {"help", OPT_HELP, '-', "Display this summary"},
923 {"in", OPT_IN, '<', "input file"},
924 {OPT_MORE_STR, 1, '-', "more detail about input"},
925 {"inform", OPT_INFORM, 'f', "input file format; defaults to pem"},
926 {"out", OPT_OUT, '>', "output file"},
927 {"count", OPT_COUNT, 'p', "a counter greater than zero"},
928 {"u", OPT_U, 'u', "an unsigned number"},
929 {"flag", OPT_FLAG, 0, "just some flag"},
930 {"str", OPT_STR, 's', "the magic word"},
931 {"areallyverylongoption", OPT_HELP, '-', "long way for help"},
932 {NULL}
933};
934
935BIO *bio_err;
936
937int app_isdir(const char *name)
938{
939 struct stat sb;
940
941 return name != NULL && stat(name, &sb) >= 0 && S_ISDIR(sb.st_mode);
942}
943
944int main(int ac, char **av)
945{
946 OPTION_CHOICE o;
947 char **rest;
948 char *prog;
949
950 bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
951
952 prog = opt_init(ac, av, options);
953 while ((o = opt_next()) != OPT_EOF) {
954 switch (c) {
955 case OPT_NOTUSED:
956 case OPT_EOF:
957 case OPT_ERR:
958 printf("%s: Usage error; try -help.\n", prog);
959 return 1;
960 case OPT_HELP:
961 opt_help(options);
962 return 0;
963 case OPT_IN:
964 printf("in %s\n", opt_arg());
965 break;
966 case OPT_INFORM:
967 printf("inform %s\n", opt_arg());
968 break;
969 case OPT_OUT:
970 printf("out %s\n", opt_arg());
971 break;
972 case OPT_COUNT:
973 printf("count %s\n", opt_arg());
974 break;
975 case OPT_U:
976 printf("u %s\n", opt_arg());
977 break;
978 case OPT_FLAG:
979 printf("flag\n");
980 break;
981 case OPT_STR:
982 printf("str %s\n", opt_arg());
983 break;
984 }
985 }
986 argc = opt_num_rest();
987 argv = opt_rest();
988
989 printf("args = %d\n", argc);
990 if (argc)
991 while (*argv)
992 printf(" %s\n", *argv++);
993 return 0;
994}
995#endif