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