test/testutil/init.c, apps/openssl.c: add trace cleanup handle earlier
[oweals/openssl.git] / apps / openssl.c
1 /*
2  * Copyright 1995-2018 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 #include <internal/cryptlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <openssl/bio.h>
15 #include <openssl/crypto.h>
16 #include <openssl/trace.h>
17 #include <openssl/lhash.h>
18 #include <openssl/conf.h>
19 #include <openssl/x509.h>
20 #include <openssl/pem.h>
21 #include <openssl/ssl.h>
22 #ifndef OPENSSL_NO_ENGINE
23 # include <openssl/engine.h>
24 #endif
25 #include <openssl/err.h>
26 #include "s_apps.h"
27 /* Needed to get the other O_xxx flags. */
28 #ifdef OPENSSL_SYS_VMS
29 # include <unixio.h>
30 #endif
31 #include "apps.h"
32 #define INCLUDE_FUNCTION_TABLE
33 #include "progs.h"
34
35 /* Structure to hold the number of columns to be displayed and the
36  * field width used to display them.
37  */
38 typedef struct {
39     int columns;
40     int width;
41 } DISPLAY_COLUMNS;
42
43 /* Special sentinel to exit the program. */
44 #define EXIT_THE_PROGRAM (-1)
45
46 /*
47  * The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
48  * the base prototypes (we cast each variable inside the function to the
49  * required type of "FUNCTION*"). This removes the necessity for
50  * macro-generated wrapper functions.
51  */
52 static LHASH_OF(FUNCTION) *prog_init(void);
53 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
54 static void list_pkey(void);
55 static void list_pkey_meth(void);
56 static void list_type(FUNC_TYPE ft, int one);
57 static void list_engines(void);
58 static void list_disabled(void);
59 char *default_config_file = NULL;
60
61 BIO *bio_in = NULL;
62 BIO *bio_out = NULL;
63 BIO *bio_err = NULL;
64
65 static void calculate_columns(DISPLAY_COLUMNS *dc)
66 {
67     FUNCTION *f;
68     int len, maxlen = 0;
69
70     for (f = functions; f->name != NULL; ++f)
71         if (f->type == FT_general || f->type == FT_md || f->type == FT_cipher)
72             if ((len = strlen(f->name)) > maxlen)
73                 maxlen = len;
74
75     dc->width = maxlen + 2;
76     dc->columns = (80 - 1) / dc->width;
77 }
78
79 static int apps_startup(void)
80 {
81 #ifdef SIGPIPE
82     signal(SIGPIPE, SIG_IGN);
83 #endif
84
85     /* Set non-default library initialisation settings */
86     if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN
87                           | OPENSSL_INIT_LOAD_CONFIG, NULL))
88         return 0;
89
90     setup_ui_method();
91
92     return 1;
93 }
94
95 static void apps_shutdown(void)
96 {
97     destroy_ui_method();
98 }
99
100 static char *make_config_name(void)
101 {
102     const char *t;
103     size_t len;
104     char *p;
105
106     if ((t = getenv("OPENSSL_CONF")) != NULL)
107         return OPENSSL_strdup(t);
108
109     t = X509_get_default_cert_area();
110     len = strlen(t) + 1 + strlen(OPENSSL_CONF) + 1;
111     p = app_malloc(len, "config filename buffer");
112     strcpy(p, t);
113 #ifndef OPENSSL_SYS_VMS
114     strcat(p, "/");
115 #endif
116     strcat(p, OPENSSL_CONF);
117
118     return p;
119 }
120
121
122 #ifndef OPENSSL_NO_TRACE
123 typedef struct tracedata_st {
124     BIO *bio;
125     unsigned int ingroup:1;
126 } tracedata;
127
128 static size_t internal_trace_cb(const char *buf, size_t cnt,
129                                 int category, int cmd, void *vdata)
130 {
131     int ret = 0;
132     tracedata *trace_data = vdata;
133     union {
134         CRYPTO_THREAD_ID tid;
135         unsigned long ltid;
136     } tid;
137     char buffer[256];
138
139     switch (cmd) {
140     case OSSL_TRACE_CTRL_BEGIN:
141         if (!ossl_assert(!trace_data->ingroup))
142             return 0;
143         trace_data->ingroup = 1;
144
145         tid.ltid = 0;
146         tid.tid = CRYPTO_THREAD_get_current_id();
147
148         BIO_snprintf(buffer, sizeof(buffer), "TRACE[%lx]:%s: ", tid.ltid,
149                      OSSL_trace_get_category_name(category));
150         BIO_ctrl(trace_data->bio, PREFIX_CTRL_SET_PREFIX,
151                  strlen(buffer), buffer);
152         break;
153     case OSSL_TRACE_CTRL_WRITE:
154         if (!ossl_assert(trace_data->ingroup))
155             return 0;
156
157         ret = BIO_write(trace_data->bio, buf, cnt);
158         break;
159     case OSSL_TRACE_CTRL_END:
160         if (!ossl_assert(trace_data->ingroup))
161             return 0;
162         trace_data->ingroup = 0;
163
164         BIO_ctrl(trace_data->bio, PREFIX_CTRL_SET_PREFIX, 0, NULL);
165
166         break;
167     }
168
169     return ret < 0 ? 0 : ret;
170 }
171
172 DEFINE_STACK_OF(tracedata)
173 static STACK_OF(tracedata) *trace_data_stack;
174
175 static void tracedata_free(tracedata *data)
176 {
177     BIO_free_all(data->bio);
178     OPENSSL_free(data);
179 }
180
181 static STACK_OF(tracedata) *trace_data_stack;
182
183 static void cleanup_trace(void)
184 {
185     sk_tracedata_pop_free(trace_data_stack, tracedata_free);
186 }
187
188 static void setup_trace_category(int category)
189 {
190     BIO *channel;
191     tracedata *trace_data;
192
193     if (OSSL_trace_enabled(category))
194         return;
195
196     channel = BIO_push(BIO_new(apps_bf_prefix()),
197                        dup_bio_err(FORMAT_TEXT));
198     trace_data = OPENSSL_zalloc(sizeof(*trace_data));
199
200     if (trace_data == NULL
201         || (trace_data->bio = channel) == NULL
202         || OSSL_trace_set_callback(category, internal_trace_cb,
203                                    trace_data) == 0
204         || sk_tracedata_push(trace_data_stack, trace_data) == 0) {
205
206         fprintf(stderr,
207                 "warning: unable to setup trace callback for category '%s'.\n",
208                 OSSL_trace_get_category_name(category));
209
210         OSSL_trace_set_callback(category, NULL, NULL);
211         BIO_free_all(channel);
212     }
213 }
214
215 static void setup_trace(const char *str)
216 {
217     char *val;
218
219     /*
220      * We add this handler as early as possible to ensure it's executed
221      * as late as possible, i.e. after the TRACE code has done its cleanup
222      * (which happens last in OPENSSL_cleanup).
223      */
224     atexit(cleanup_trace);
225
226     trace_data_stack = sk_tracedata_new_null();
227     val = OPENSSL_strdup(str);
228
229     if (val != NULL) {
230         char *valp = val;
231         char *item;
232
233         for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) {
234             int category = OSSL_trace_get_category_num(item);
235
236             if (category == OSSL_TRACE_CATEGORY_ALL) {
237                 while (++category < OSSL_TRACE_CATEGORY_NUM)
238                     setup_trace_category(category);
239                 break;
240             } else if (category > 0) {
241                 setup_trace_category(category);
242             } else {
243                 fprintf(stderr,
244                         "warning: unknown trace category: '%s'.\n", item);
245             }
246         }
247     }
248
249     OPENSSL_free(val);
250 }
251 #endif /* OPENSSL_NO_TRACE */
252
253 int main(int argc, char *argv[])
254 {
255     FUNCTION f, *fp;
256     LHASH_OF(FUNCTION) *prog = NULL;
257     char *p, *pname;
258     char buf[1024];
259     const char *prompt;
260     ARGS arg;
261     int first, n, i, ret = 0;
262
263     arg.argv = NULL;
264     arg.size = 0;
265
266     /* Set up some of the environment. */
267     default_config_file = make_config_name();
268     bio_in = dup_bio_in(FORMAT_TEXT);
269     bio_out = dup_bio_out(FORMAT_TEXT);
270     bio_err = dup_bio_err(FORMAT_TEXT);
271
272 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
273     argv = copy_argv(&argc, argv);
274 #elif defined(_WIN32)
275     /*
276      * Replace argv[] with UTF-8 encoded strings.
277      */
278     win32_utf8argv(&argc, &argv);
279 #endif
280
281     /*
282      * We use the prefix method to get the trace output we want.  Since some
283      * trace outputs happen with OPENSSL_cleanup(), which is run automatically
284      * after exit(), we need to destroy the prefix method as late as possible.
285      */
286     atexit(destroy_prefix_method);
287
288 #ifndef OPENSSL_NO_TRACE
289     setup_trace(getenv("OPENSSL_TRACE"));
290 #endif
291
292     p = getenv("OPENSSL_DEBUG_MEMORY");
293     if (p != NULL && strcmp(p, "on") == 0)
294         CRYPTO_set_mem_debug(1);
295     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
296
297     if (getenv("OPENSSL_FIPS")) {
298         BIO_printf(bio_err, "FIPS mode not supported.\n");
299         return 1;
300     }
301
302     if (!apps_startup()) {
303         BIO_printf(bio_err,
304                    "FATAL: Startup failure (dev note: apps_startup() failed)\n");
305         ERR_print_errors(bio_err);
306         ret = 1;
307         goto end;
308     }
309
310     prog = prog_init();
311     pname = opt_progname(argv[0]);
312
313     /* first check the program name */
314     f.name = pname;
315     fp = lh_FUNCTION_retrieve(prog, &f);
316     if (fp != NULL) {
317         argv[0] = pname;
318         ret = fp->func(argc, argv);
319         goto end;
320     }
321
322     /* If there is stuff on the command line, run with that. */
323     if (argc != 1) {
324         argc--;
325         argv++;
326         ret = do_cmd(prog, argc, argv);
327         if (ret < 0)
328             ret = 0;
329         goto end;
330     }
331
332     /* ok, lets enter interactive mode */
333     for (;;) {
334         ret = 0;
335         /* Read a line, continue reading if line ends with \ */
336         for (p = buf, n = sizeof(buf), i = 0, first = 1; n > 0; first = 0) {
337             prompt = first ? "OpenSSL> " : "> ";
338             p[0] = '\0';
339 #ifndef READLINE
340             fputs(prompt, stdout);
341             fflush(stdout);
342             if (!fgets(p, n, stdin))
343                 goto end;
344             if (p[0] == '\0')
345                 goto end;
346             i = strlen(p);
347             if (i <= 1)
348                 break;
349             if (p[i - 2] != '\\')
350                 break;
351             i -= 2;
352             p += i;
353             n -= i;
354 #else
355             {
356                 extern char *readline(const char *);
357                 extern void add_history(const char *cp);
358                 char *text;
359
360                 text = readline(prompt);
361                 if (text == NULL)
362                     goto end;
363                 i = strlen(text);
364                 if (i == 0 || i > n)
365                     break;
366                 if (text[i - 1] != '\\') {
367                     p += strlen(strcpy(p, text));
368                     free(text);
369                     add_history(buf);
370                     break;
371                 }
372
373                 text[i - 1] = '\0';
374                 p += strlen(strcpy(p, text));
375                 free(text);
376                 n -= i;
377             }
378 #endif
379         }
380
381         if (!chopup_args(&arg, buf)) {
382             BIO_printf(bio_err, "Can't parse (no memory?)\n");
383             break;
384         }
385
386         ret = do_cmd(prog, arg.argc, arg.argv);
387         if (ret == EXIT_THE_PROGRAM) {
388             ret = 0;
389             goto end;
390         }
391         if (ret != 0)
392             BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
393         (void)BIO_flush(bio_out);
394         (void)BIO_flush(bio_err);
395     }
396     ret = 1;
397  end:
398     OPENSSL_free(default_config_file);
399     lh_FUNCTION_free(prog);
400     OPENSSL_free(arg.argv);
401     app_RAND_write();
402
403     BIO_free(bio_in);
404     BIO_free_all(bio_out);
405     apps_shutdown();
406 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
407     if (CRYPTO_mem_leaks(bio_err) <= 0)
408         ret = 1;
409 #endif
410     BIO_free(bio_err);
411     EXIT(ret);
412 }
413
414 static void list_cipher_fn(const EVP_CIPHER *c,
415                            const char *from, const char *to, void *arg)
416 {
417     if (c != NULL) {
418         BIO_printf(arg, "%s\n", EVP_CIPHER_name(c));
419     } else {
420         if (from == NULL)
421             from = "<undefined>";
422         if (to == NULL)
423             to = "<undefined>";
424         BIO_printf(arg, "%s => %s\n", from, to);
425     }
426 }
427
428 static void list_md_fn(const EVP_MD *m,
429                        const char *from, const char *to, void *arg)
430 {
431     if (m != NULL) {
432         BIO_printf(arg, "%s\n", EVP_MD_name(m));
433     } else {
434         if (from == NULL)
435             from = "<undefined>";
436         if (to == NULL)
437             to = "<undefined>";
438         BIO_printf((BIO *)arg, "%s => %s\n", from, to);
439     }
440 }
441
442 static void list_mac_fn(const EVP_MAC *m,
443                         const char *from, const char *to, void *arg)
444 {
445     if (m != NULL) {
446         BIO_printf(arg, "%s\n", EVP_MAC_name(m));
447     } else {
448         if (from == NULL)
449             from = "<undefined>";
450         if (to == NULL)
451             to = "<undefined>";
452         BIO_printf(arg, "%s => %s\n", from, to);
453     }
454 }
455
456 static void list_missing_help(void)
457 {
458     const FUNCTION *fp;
459     const OPTIONS *o;
460
461     for (fp = functions; fp->name != NULL; fp++) {
462         if ((o = fp->help) != NULL) {
463             /* If there is help, list what flags are not documented. */
464             for ( ; o->name != NULL; o++) {
465                 if (o->helpstr == NULL)
466                     BIO_printf(bio_out, "%s %s\n", fp->name, o->name);
467             }
468         } else if (fp->func != dgst_main) {
469             /* If not aliased to the dgst command, */
470             BIO_printf(bio_out, "%s *\n", fp->name);
471         }
472     }
473 }
474
475 static void list_objects(void)
476 {
477     int max_nid = OBJ_new_nid(0);
478     int i;
479     char *oid_buf = NULL;
480     int oid_size = 0;
481
482     /* Skip 0, since that's NID_undef */
483     for (i = 1; i < max_nid; i++) {
484         const ASN1_OBJECT *obj = OBJ_nid2obj(i);
485         const char *sn = OBJ_nid2sn(i);
486         const char *ln = OBJ_nid2ln(i);
487         int n = 0;
488
489         /*
490          * If one of the retrieved objects somehow generated an error,
491          * we ignore it.  The check for NID_undef below will detect the
492          * error and simply skip to the next NID.
493          */
494         ERR_clear_error();
495
496         if (OBJ_obj2nid(obj) == NID_undef)
497             continue;
498
499         if ((n = OBJ_obj2txt(NULL, 0, obj, 1)) == 0) {
500             BIO_printf(bio_out, "# None-OID object: %s, %s\n", sn, ln);
501             continue;
502         }
503         if (n < 0)
504             break;               /* Error */
505
506         if (n > oid_size) {
507             oid_buf = OPENSSL_realloc(oid_buf, n + 1);
508             if (oid_buf == NULL) {
509                 BIO_printf(bio_err, "ERROR: Memory allocation\n");
510                 break;           /* Error */
511             }
512             oid_size = n + 1;
513         }
514         if (OBJ_obj2txt(oid_buf, oid_size, obj, 1) < 0)
515             break;               /* Error */
516         if (ln == NULL || strcmp(sn, ln) == 0)
517             BIO_printf(bio_out, "%s = %s\n", sn, oid_buf);
518         else
519             BIO_printf(bio_out, "%s = %s, %s\n", sn, ln, oid_buf);
520     }
521
522     OPENSSL_free(oid_buf);
523 }
524
525 static void list_options_for_command(const char *command)
526 {
527     const FUNCTION *fp;
528     const OPTIONS *o;
529
530     for (fp = functions; fp->name != NULL; fp++)
531         if (strcmp(fp->name, command) == 0)
532             break;
533     if (fp->name == NULL) {
534         BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
535                 command);
536         return;
537     }
538
539     if ((o = fp->help) == NULL)
540         return;
541
542     for ( ; o->name != NULL; o++) {
543         if (o->name == OPT_HELP_STR
544                 || o->name == OPT_MORE_STR
545                 || o->name[0] == '\0')
546             continue;
547         BIO_printf(bio_out, "%s %c\n", o->name, o->valtype);
548     }
549 }
550
551
552 /* Unified enum for help and list commands. */
553 typedef enum HELPLIST_CHOICE {
554     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ONE,
555     OPT_COMMANDS, OPT_DIGEST_COMMANDS, OPT_MAC_ALGORITHMS, OPT_OPTIONS,
556     OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS,
557     OPT_PK_ALGORITHMS, OPT_PK_METHOD, OPT_ENGINES, OPT_DISABLED,
558     OPT_MISSING_HELP, OPT_OBJECTS
559 } HELPLIST_CHOICE;
560
561 const OPTIONS list_options[] = {
562     {"help", OPT_HELP, '-', "Display this summary"},
563     {"1", OPT_ONE, '-', "List in one column"},
564     {"commands", OPT_COMMANDS, '-', "List of standard commands"},
565     {"digest-commands", OPT_DIGEST_COMMANDS, '-',
566      "List of message digest commands"},
567     {"digest-algorithms", OPT_DIGEST_ALGORITHMS, '-',
568      "List of message digest algorithms"},
569     {"mac-algorithms", OPT_MAC_ALGORITHMS, '-',
570      "List of message authentication code algorithms"},
571     {"cipher-commands", OPT_CIPHER_COMMANDS, '-', "List of cipher commands"},
572     {"cipher-algorithms", OPT_CIPHER_ALGORITHMS, '-',
573      "List of cipher algorithms"},
574     {"public-key-algorithms", OPT_PK_ALGORITHMS, '-',
575      "List of public key algorithms"},
576     {"public-key-methods", OPT_PK_METHOD, '-',
577      "List of public key methods"},
578     {"engines", OPT_ENGINES, '-',
579      "List of loaded engines"},
580     {"disabled", OPT_DISABLED, '-',
581      "List of disabled features"},
582     {"missing-help", OPT_MISSING_HELP, '-',
583      "List missing detailed help strings"},
584     {"options", OPT_OPTIONS, 's',
585      "List options for specified command"},
586     {"objects", OPT_OBJECTS, '-',
587      "List built in objects (OID<->name mappings)"},
588     {NULL}
589 };
590
591 int list_main(int argc, char **argv)
592 {
593     char *prog;
594     HELPLIST_CHOICE o;
595     int one = 0, done = 0;
596
597     prog = opt_init(argc, argv, list_options);
598     while ((o = opt_next()) != OPT_EOF) {
599         switch (o) {
600         case OPT_EOF:  /* Never hit, but suppresses warning */
601         case OPT_ERR:
602 opthelp:
603             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
604             return 1;
605         case OPT_HELP:
606             opt_help(list_options);
607             break;
608         case OPT_ONE:
609             one = 1;
610             break;
611         case OPT_COMMANDS:
612             list_type(FT_general, one);
613             break;
614         case OPT_DIGEST_COMMANDS:
615             list_type(FT_md, one);
616             break;
617         case OPT_DIGEST_ALGORITHMS:
618             EVP_MD_do_all_sorted(list_md_fn, bio_out);
619             break;
620         case OPT_MAC_ALGORITHMS:
621             EVP_MAC_do_all_sorted(list_mac_fn, bio_out);
622             break;
623         case OPT_CIPHER_COMMANDS:
624             list_type(FT_cipher, one);
625             break;
626         case OPT_CIPHER_ALGORITHMS:
627             EVP_CIPHER_do_all_sorted(list_cipher_fn, bio_out);
628             break;
629         case OPT_PK_ALGORITHMS:
630             list_pkey();
631             break;
632         case OPT_PK_METHOD:
633             list_pkey_meth();
634             break;
635         case OPT_ENGINES:
636             list_engines();
637             break;
638         case OPT_DISABLED:
639             list_disabled();
640             break;
641         case OPT_MISSING_HELP:
642             list_missing_help();
643             break;
644         case OPT_OBJECTS:
645             list_objects();
646             break;
647         case OPT_OPTIONS:
648             list_options_for_command(opt_arg());
649             break;
650         }
651         done = 1;
652     }
653     if (opt_num_rest() != 0) {
654         BIO_printf(bio_err, "Extra arguments given.\n");
655         goto opthelp;
656     }
657
658     if (!done)
659         goto opthelp;
660
661     return 0;
662 }
663
664 typedef enum HELP_CHOICE {
665     OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP
666 } HELP_CHOICE;
667
668 const OPTIONS help_options[] = {
669     {OPT_HELP_STR, 1, '-', "Usage: help [options]\n"},
670     {OPT_HELP_STR, 1, '-', "       help [command]\n"},
671     {"help", OPT_hHELP, '-', "Display this summary"},
672     {NULL}
673 };
674
675
676 int help_main(int argc, char **argv)
677 {
678     FUNCTION *fp;
679     int i, nl;
680     FUNC_TYPE tp;
681     char *prog;
682     HELP_CHOICE o;
683     DISPLAY_COLUMNS dc;
684
685     prog = opt_init(argc, argv, help_options);
686     while ((o = opt_next()) != OPT_hEOF) {
687         switch (o) {
688         case OPT_hERR:
689         case OPT_hEOF:
690             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
691             return 1;
692         case OPT_hHELP:
693             opt_help(help_options);
694             return 0;
695         }
696     }
697
698     if (opt_num_rest() == 1) {
699         char *new_argv[3];
700
701         new_argv[0] = opt_rest()[0];
702         new_argv[1] = "--help";
703         new_argv[2] = NULL;
704         return do_cmd(prog_init(), 2, new_argv);
705     }
706     if (opt_num_rest() != 0) {
707         BIO_printf(bio_err, "Usage: %s\n", prog);
708         return 1;
709     }
710
711     calculate_columns(&dc);
712     BIO_printf(bio_err, "Standard commands");
713     i = 0;
714     tp = FT_none;
715     for (fp = functions; fp->name != NULL; fp++) {
716         nl = 0;
717         if (i++ % dc.columns == 0) {
718             BIO_printf(bio_err, "\n");
719             nl = 1;
720         }
721         if (fp->type != tp) {
722             tp = fp->type;
723             if (!nl)
724                 BIO_printf(bio_err, "\n");
725             if (tp == FT_md) {
726                 i = 1;
727                 BIO_printf(bio_err,
728                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
729             } else if (tp == FT_cipher) {
730                 i = 1;
731                 BIO_printf(bio_err,
732                            "\nCipher commands (see the `enc' command for more details)\n");
733             }
734         }
735         BIO_printf(bio_err, "%-*s", dc.width, fp->name);
736     }
737     BIO_printf(bio_err, "\n\n");
738     return 0;
739 }
740
741 static void list_type(FUNC_TYPE ft, int one)
742 {
743     FUNCTION *fp;
744     int i = 0;
745     DISPLAY_COLUMNS dc;
746
747     memset(&dc, 0, sizeof(dc));
748     if (!one)
749         calculate_columns(&dc);
750
751     for (fp = functions; fp->name != NULL; fp++) {
752         if (fp->type != ft)
753             continue;
754         if (one) {
755             BIO_printf(bio_out, "%s\n", fp->name);
756         } else {
757             if (i % dc.columns == 0 && i > 0)
758                 BIO_printf(bio_out, "\n");
759             BIO_printf(bio_out, "%-*s", dc.width, fp->name);
760             i++;
761         }
762     }
763     if (!one)
764         BIO_printf(bio_out, "\n\n");
765 }
766
767 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
768 {
769     FUNCTION f, *fp;
770
771     if (argc <= 0 || argv[0] == NULL)
772         return 0;
773     f.name = argv[0];
774     fp = lh_FUNCTION_retrieve(prog, &f);
775     if (fp == NULL) {
776         if (EVP_get_digestbyname(argv[0])) {
777             f.type = FT_md;
778             f.func = dgst_main;
779             fp = &f;
780         } else if (EVP_get_cipherbyname(argv[0])) {
781             f.type = FT_cipher;
782             f.func = enc_main;
783             fp = &f;
784         }
785     }
786     if (fp != NULL) {
787         return fp->func(argc, argv);
788     }
789     if ((strncmp(argv[0], "no-", 3)) == 0) {
790         /*
791          * User is asking if foo is unsupported, by trying to "run" the
792          * no-foo command.  Strange.
793          */
794         f.name = argv[0] + 3;
795         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
796             BIO_printf(bio_out, "%s\n", argv[0]);
797             return 0;
798         }
799         BIO_printf(bio_out, "%s\n", argv[0] + 3);
800         return 1;
801     }
802     if (strcmp(argv[0], "quit") == 0 || strcmp(argv[0], "q") == 0 ||
803         strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "bye") == 0)
804         /* Special value to mean "exit the program. */
805         return EXIT_THE_PROGRAM;
806
807     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
808                argv[0]);
809     return 1;
810 }
811
812 static void list_pkey(void)
813 {
814     int i;
815
816     for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
817         const EVP_PKEY_ASN1_METHOD *ameth;
818         int pkey_id, pkey_base_id, pkey_flags;
819         const char *pinfo, *pem_str;
820         ameth = EVP_PKEY_asn1_get0(i);
821         EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags,
822                                 &pinfo, &pem_str, ameth);
823         if (pkey_flags & ASN1_PKEY_ALIAS) {
824             BIO_printf(bio_out, "Name: %s\n", OBJ_nid2ln(pkey_id));
825             BIO_printf(bio_out, "\tAlias for: %s\n",
826                        OBJ_nid2ln(pkey_base_id));
827         } else {
828             BIO_printf(bio_out, "Name: %s\n", pinfo);
829             BIO_printf(bio_out, "\tType: %s Algorithm\n",
830                        pkey_flags & ASN1_PKEY_DYNAMIC ?
831                        "External" : "Builtin");
832             BIO_printf(bio_out, "\tOID: %s\n", OBJ_nid2ln(pkey_id));
833             if (pem_str == NULL)
834                 pem_str = "(none)";
835             BIO_printf(bio_out, "\tPEM string: %s\n", pem_str);
836         }
837
838     }
839 }
840
841 static void list_pkey_meth(void)
842 {
843     size_t i;
844     size_t meth_count = EVP_PKEY_meth_get_count();
845
846     for (i = 0; i < meth_count; i++) {
847         const EVP_PKEY_METHOD *pmeth = EVP_PKEY_meth_get0(i);
848         int pkey_id, pkey_flags;
849
850         EVP_PKEY_meth_get0_info(&pkey_id, &pkey_flags, pmeth);
851         BIO_printf(bio_out, "%s\n", OBJ_nid2ln(pkey_id));
852         BIO_printf(bio_out, "\tType: %s Algorithm\n",
853                    pkey_flags & ASN1_PKEY_DYNAMIC ?  "External" : "Builtin");
854     }
855 }
856
857 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
858 {
859     return strncmp(a->name, b->name, 8);
860 }
861
862 static unsigned long function_hash(const FUNCTION * a)
863 {
864     return OPENSSL_LH_strhash(a->name);
865 }
866
867 static int SortFnByName(const void *_f1, const void *_f2)
868 {
869     const FUNCTION *f1 = _f1;
870     const FUNCTION *f2 = _f2;
871
872     if (f1->type != f2->type)
873         return f1->type - f2->type;
874     return strcmp(f1->name, f2->name);
875 }
876
877 static void list_engines(void)
878 {
879 #ifndef OPENSSL_NO_ENGINE
880     ENGINE *e;
881
882     BIO_puts(bio_out, "Engines:\n");
883     e = ENGINE_get_first();
884     while (e) {
885         BIO_printf(bio_out, "%s\n", ENGINE_get_id(e));
886         e = ENGINE_get_next(e);
887     }
888 #else
889     BIO_puts(bio_out, "Engine support is disabled.\n");
890 #endif
891 }
892
893 static void list_disabled(void)
894 {
895     BIO_puts(bio_out, "Disabled algorithms:\n");
896 #ifdef OPENSSL_NO_ARIA
897     BIO_puts(bio_out, "ARIA\n");
898 #endif
899 #ifdef OPENSSL_NO_BF
900     BIO_puts(bio_out, "BF\n");
901 #endif
902 #ifdef OPENSSL_NO_BLAKE2
903     BIO_puts(bio_out, "BLAKE2\n");
904 #endif
905 #ifdef OPENSSL_NO_CAMELLIA
906     BIO_puts(bio_out, "CAMELLIA\n");
907 #endif
908 #ifdef OPENSSL_NO_CAST
909     BIO_puts(bio_out, "CAST\n");
910 #endif
911 #ifdef OPENSSL_NO_CMAC
912     BIO_puts(bio_out, "CMAC\n");
913 #endif
914 #ifdef OPENSSL_NO_CMS
915     BIO_puts(bio_out, "CMS\n");
916 #endif
917 #ifdef OPENSSL_NO_COMP
918     BIO_puts(bio_out, "COMP\n");
919 #endif
920 #ifdef OPENSSL_NO_DES
921     BIO_puts(bio_out, "DES\n");
922 #endif
923 #ifdef OPENSSL_NO_DGRAM
924     BIO_puts(bio_out, "DGRAM\n");
925 #endif
926 #ifdef OPENSSL_NO_DH
927     BIO_puts(bio_out, "DH\n");
928 #endif
929 #ifdef OPENSSL_NO_DSA
930     BIO_puts(bio_out, "DSA\n");
931 #endif
932 #if defined(OPENSSL_NO_DTLS)
933     BIO_puts(bio_out, "DTLS\n");
934 #endif
935 #if defined(OPENSSL_NO_DTLS1)
936     BIO_puts(bio_out, "DTLS1\n");
937 #endif
938 #if defined(OPENSSL_NO_DTLS1_2)
939     BIO_puts(bio_out, "DTLS1_2\n");
940 #endif
941 #ifdef OPENSSL_NO_EC
942     BIO_puts(bio_out, "EC\n");
943 #endif
944 #ifdef OPENSSL_NO_EC2M
945     BIO_puts(bio_out, "EC2M\n");
946 #endif
947 #ifdef OPENSSL_NO_ENGINE
948     BIO_puts(bio_out, "ENGINE\n");
949 #endif
950 #ifdef OPENSSL_NO_GOST
951     BIO_puts(bio_out, "GOST\n");
952 #endif
953 #ifdef OPENSSL_NO_IDEA
954     BIO_puts(bio_out, "IDEA\n");
955 #endif
956 #ifdef OPENSSL_NO_MD2
957     BIO_puts(bio_out, "MD2\n");
958 #endif
959 #ifdef OPENSSL_NO_MD4
960     BIO_puts(bio_out, "MD4\n");
961 #endif
962 #ifdef OPENSSL_NO_MD5
963     BIO_puts(bio_out, "MD5\n");
964 #endif
965 #ifdef OPENSSL_NO_MDC2
966     BIO_puts(bio_out, "MDC2\n");
967 #endif
968 #ifdef OPENSSL_NO_OCB
969     BIO_puts(bio_out, "OCB\n");
970 #endif
971 #ifdef OPENSSL_NO_OCSP
972     BIO_puts(bio_out, "OCSP\n");
973 #endif
974 #ifdef OPENSSL_NO_PSK
975     BIO_puts(bio_out, "PSK\n");
976 #endif
977 #ifdef OPENSSL_NO_RC2
978     BIO_puts(bio_out, "RC2\n");
979 #endif
980 #ifdef OPENSSL_NO_RC4
981     BIO_puts(bio_out, "RC4\n");
982 #endif
983 #ifdef OPENSSL_NO_RC5
984     BIO_puts(bio_out, "RC5\n");
985 #endif
986 #ifdef OPENSSL_NO_RMD160
987     BIO_puts(bio_out, "RMD160\n");
988 #endif
989 #ifdef OPENSSL_NO_RSA
990     BIO_puts(bio_out, "RSA\n");
991 #endif
992 #ifdef OPENSSL_NO_SCRYPT
993     BIO_puts(bio_out, "SCRYPT\n");
994 #endif
995 #ifdef OPENSSL_NO_SCTP
996     BIO_puts(bio_out, "SCTP\n");
997 #endif
998 #ifdef OPENSSL_NO_SEED
999     BIO_puts(bio_out, "SEED\n");
1000 #endif
1001 #ifdef OPENSSL_NO_SM2
1002     BIO_puts(bio_out, "SM2\n");
1003 #endif
1004 #ifdef OPENSSL_NO_SM3
1005     BIO_puts(bio_out, "SM3\n");
1006 #endif
1007 #ifdef OPENSSL_NO_SM4
1008     BIO_puts(bio_out, "SM4\n");
1009 #endif
1010 #ifdef OPENSSL_NO_SOCK
1011     BIO_puts(bio_out, "SOCK\n");
1012 #endif
1013 #ifdef OPENSSL_NO_SRP
1014     BIO_puts(bio_out, "SRP\n");
1015 #endif
1016 #ifdef OPENSSL_NO_SRTP
1017     BIO_puts(bio_out, "SRTP\n");
1018 #endif
1019 #ifdef OPENSSL_NO_SSL3
1020     BIO_puts(bio_out, "SSL3\n");
1021 #endif
1022 #ifdef OPENSSL_NO_TLS1
1023     BIO_puts(bio_out, "TLS1\n");
1024 #endif
1025 #ifdef OPENSSL_NO_TLS1_1
1026     BIO_puts(bio_out, "TLS1_1\n");
1027 #endif
1028 #ifdef OPENSSL_NO_TLS1_2
1029     BIO_puts(bio_out, "TLS1_2\n");
1030 #endif
1031 #ifdef OPENSSL_NO_WHIRLPOOL
1032     BIO_puts(bio_out, "WHIRLPOOL\n");
1033 #endif
1034 #ifndef ZLIB
1035     BIO_puts(bio_out, "ZLIB\n");
1036 #endif
1037 }
1038
1039 static LHASH_OF(FUNCTION) *prog_init(void)
1040 {
1041     static LHASH_OF(FUNCTION) *ret = NULL;
1042     static int prog_inited = 0;
1043     FUNCTION *f;
1044     size_t i;
1045
1046     if (prog_inited)
1047         return ret;
1048
1049     prog_inited = 1;
1050
1051     /* Sort alphabetically within category. For nicer help displays. */
1052     for (i = 0, f = functions; f->name != NULL; ++f, ++i)
1053         ;
1054     qsort(functions, i, sizeof(*functions), SortFnByName);
1055
1056     if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL)
1057         return NULL;
1058
1059     for (f = functions; f->name != NULL; f++)
1060         (void)lh_FUNCTION_insert(ret, f);
1061     return ret;
1062 }