Fix the update target and remove duplicate file updates
[openssl.git] / apps / openssl.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #include <stdio.h>
112 #include <string.h>
113 #include <stdlib.h>
114 #include <openssl/bio.h>
115 #include <openssl/crypto.h>
116 #include <openssl/rand.h>
117 #include <openssl/lhash.h>
118 #include <openssl/conf.h>
119 #include <openssl/x509.h>
120 #include <openssl/pem.h>
121 #include <openssl/ssl.h>
122 #ifndef OPENSSL_NO_ENGINE
123 # include <openssl/engine.h>
124 #endif
125 /* needed for the _O_BINARY defs in the MS world */
126 #define USE_SOCKETS
127 #include "s_apps.h"
128 #include <openssl/err.h>
129 #ifdef OPENSSL_FIPS
130 # include <openssl/fips.h>
131 #endif
132 #define INCLUDE_FUNCTION_TABLE
133 #include "apps.h"
134
135
136 #ifdef OPENSSL_NO_CAMELLIA
137 # define FORMAT "%-15s"
138 # define COLUMNS 5
139 #else
140 # define FORMAT "%-18s"
141 # define COLUMNS 4
142 #endif
143
144 /* Special sentinel to exit the program. */
145 #define EXIT_THE_PROGRAM (-1)
146
147 /*
148  * The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
149  * the base prototypes (we cast each variable inside the function to the
150  * required type of "FUNCTION*"). This removes the necessity for
151  * macro-generated wrapper functions.
152  */
153 DECLARE_LHASH_OF(FUNCTION);
154 static LHASH_OF(FUNCTION) *prog_init(void);
155 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
156 static void list_pkey(void);
157 static void list_type(FUNC_TYPE ft);
158 char *default_config_file = NULL;
159
160 CONF *config = NULL;
161 BIO *bio_in = NULL;
162 BIO *bio_out = NULL;
163 BIO *bio_err = NULL;
164
165 static void apps_startup()
166 {
167 #ifdef SIGPIPE
168     signal(SIGPIPE, SIG_IGN);
169 #endif
170     CRYPTO_malloc_init();
171     ERR_load_crypto_strings();
172     ERR_load_SSL_strings();
173     OpenSSL_add_all_algorithms();
174     OpenSSL_add_ssl_algorithms();
175     setup_ui_method();
176     /*SSL_library_init();*/
177 #ifndef OPENSSL_NO_ENGINE
178     ENGINE_load_builtin_engines();
179 #endif
180 }
181
182 static void apps_shutdown()
183 {
184 #ifndef OPENSSL_NO_ENGINE
185     ENGINE_cleanup();
186 #endif
187     destroy_ui_method();
188     CONF_modules_unload(1);
189 #ifndef OPENSSL_NO_COMP
190     COMP_zlib_cleanup();
191 #endif
192     OBJ_cleanup();
193     EVP_cleanup();
194     CRYPTO_cleanup_all_ex_data();
195     ERR_remove_thread_state(NULL);
196     RAND_cleanup();
197     ERR_free_strings();
198 }
199
200 static char *make_config_name()
201 {
202     const char *t = X509_get_default_cert_area();
203     size_t len;
204     char *p;
205
206     len = strlen(t) + strlen(OPENSSL_CONF) + 2;
207     p = app_malloc(len, "config filename buffer");
208     BUF_strlcpy(p, t, len);
209 #ifndef OPENSSL_SYS_VMS
210     BUF_strlcat(p, "/", len);
211 #endif
212     BUF_strlcat(p, OPENSSL_CONF, len);
213
214     return p;
215 }
216
217 static int load_config(CONF *cnf)
218 {
219     static int load_config_called = 0;
220
221     if (load_config_called)
222         return 1;
223     load_config_called = 1;
224     if (!cnf)
225         cnf = config;
226     if (!cnf)
227         return 1;
228
229     OPENSSL_load_builtin_modules();
230
231     if (CONF_modules_load(cnf, NULL, 0) <= 0) {
232         BIO_printf(bio_err, "Error configuring OpenSSL\n");
233         ERR_print_errors(bio_err);
234         return 0;
235     }
236     return 1;
237 }
238
239 static void lock_dbg_cb(int mode, int type, const char *file, int line)
240 {
241     static int modes[CRYPTO_NUM_LOCKS];
242     const char *errstr = NULL;
243     int rw = mode & (CRYPTO_READ | CRYPTO_WRITE);
244
245     if (rw != CRYPTO_READ && rw != CRYPTO_WRITE) {
246         errstr = "invalid mode";
247         goto err;
248     }
249
250     if (type < 0 || type >= CRYPTO_NUM_LOCKS) {
251         errstr = "type out of bounds";
252         goto err;
253     }
254
255     if (mode & CRYPTO_LOCK) {
256         if (modes[type]) {
257             errstr = "already locked";
258             /* must not happen in a single-threaded program --> deadlock! */
259             goto err;
260         }
261         modes[type] = rw;
262     } else if (mode & CRYPTO_UNLOCK) {
263         if (!modes[type]) {
264             errstr = "not locked";
265             goto err;
266         }
267
268         if (modes[type] != rw) {
269             errstr = (rw == CRYPTO_READ) ?
270                 "CRYPTO_r_unlock on write lock" :
271                 "CRYPTO_w_unlock on read lock";
272         }
273
274         modes[type] = 0;
275     } else {
276         errstr = "invalid mode";
277         goto err;
278     }
279
280  err:
281     if (errstr) {
282         /* we cannot use bio_err here */
283         fprintf(stderr,
284                 "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
285                 errstr, mode, type, file, line);
286     }
287 }
288
289 BIO *dup_bio_in(void)
290 {
291     return BIO_new_fp(stdin, BIO_NOCLOSE | BIO_FP_TEXT);
292 }
293
294 BIO *dup_bio_out(void)
295 {
296     BIO *b = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
297 #ifdef OPENSSL_SYS_VMS
298     b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
299 #endif
300     return b;
301 }
302
303 void unbuffer(FILE *fp)
304 {
305     setbuf(fp, NULL);
306 }
307
308 BIO *bio_open_default(const char *filename, const char *mode)
309 {
310     BIO *ret;
311
312     if (filename == NULL || strcmp(filename, "-") == 0) {
313         ret = *mode == 'r' ? dup_bio_in() : dup_bio_out();
314         if (ret != NULL)
315             return ret;
316         BIO_printf(bio_err,
317                    "Can't open %s, %s\n",
318                    *mode == 'r' ? "stdin" : "stdout", strerror(errno));
319     } else {
320         ret = BIO_new_file(filename, mode);
321         if (ret != NULL)
322             return ret;
323         BIO_printf(bio_err,
324                    "Can't open %s for %s, %s\n",
325                    filename,
326                    *mode == 'r' ? "reading" : "writing", strerror(errno));
327     }
328     ERR_print_errors(bio_err);
329     return NULL;
330 }
331
332 #if defined( OPENSSL_SYS_VMS)
333 extern char **copy_argv(int *argc, char **argv);
334 #endif
335
336 int main(int argc, char *argv[])
337 {
338     FUNCTION f, *fp;
339     LHASH_OF(FUNCTION) *prog = NULL;
340     char **copied_argv = NULL;
341     char *p, *pname, *to_free = NULL;
342     char buf[1024];
343     const char *prompt;
344     ARGS arg;
345     int first, n, i, ret = 0;
346     long errline;
347
348     arg.argv = NULL;
349     arg.size = 0;
350
351 #if defined( OPENSSL_SYS_VMS)
352     copied_argv = argv = copy_argv(&argc, argv);
353 #endif
354
355     p = getenv("OPENSSL_DEBUG_MEMORY");
356     if (p == NULL)
357         /* if not set, use compiled-in default */
358         ;
359     else if (strcmp(p, "off") != 0) {
360         CRYPTO_malloc_debug_init();
361         CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
362     } else {
363         CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
364     }
365     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
366     CRYPTO_set_locking_callback(lock_dbg_cb);
367
368     if (getenv("OPENSSL_FIPS")) {
369 #ifdef OPENSSL_FIPS
370         if (!FIPS_mode_set(1)) {
371             ERR_load_crypto_strings();
372             ERR_print_errors(BIO_new_fp(stderr, BIO_NOCLOSE));
373             EXIT(1);
374         }
375 #else
376         fprintf(stderr, "FIPS mode not supported.\n");
377         EXIT(1);
378 #endif
379     }
380
381     apps_startup();
382
383     /*
384      * If first argument is a colon, skip it.  Because in "interactive"
385      * mode our prompt is a colon and we can cut/paste whole lines
386      * by doing this hack.
387      */
388     if (argv[1] && strcmp(argv[1], ":") == 0) {
389         argv[1] = argv[0];
390         argc--;
391         argv++;
392     }
393     prog = prog_init();
394     pname = opt_progname(argv[0]);
395
396     /* Lets load up our environment a little */
397     bio_in = dup_bio_in();
398     bio_out = dup_bio_out();
399     bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
400
401     /* Determine and load the config file. */
402     default_config_file = getenv("OPENSSL_CONF");
403     if (default_config_file == NULL)
404         default_config_file = getenv("SSLEAY_CONF");
405     if (default_config_file == NULL)
406         default_config_file = to_free = make_config_name();
407     if (!load_config(NULL))
408         goto end;
409     config = NCONF_new(NULL);
410     i = NCONF_load(config, default_config_file, &errline);
411     if (i == 0) {
412         if (ERR_GET_REASON(ERR_peek_last_error())
413             == CONF_R_NO_SUCH_FILE) {
414             BIO_printf(bio_err,
415                        "%s: WARNING: can't open config file: %s\n",
416                        pname, default_config_file);
417             ERR_clear_error();
418             NCONF_free(config);
419             config = NULL;
420         } else {
421             ERR_print_errors(bio_err);
422             NCONF_free(config);
423             exit(1);
424         }
425     }
426
427     /* first check the program name */
428     f.name = pname;
429     fp = lh_FUNCTION_retrieve(prog, &f);
430     if (fp != NULL) {
431         argv[0] = pname;
432         ret = fp->func(argc, argv);
433         goto end;
434     }
435
436     /* If there is stuff on the command line, run with that. */
437     if (argc != 1) {
438         argc--;
439         argv++;
440         ret = do_cmd(prog, argc, argv);
441         if (ret < 0)
442             ret = 0;
443         goto end;
444     }
445
446     /* ok, lets enter interactive mode */
447     for (;;) {
448         ret = 0;
449         /* Read a line, continue reading if line ends with \ */
450         for (p = buf, n = sizeof buf, i = 0, first = 1; n > 0; first = 0) {
451             prompt = first ? "openssl : " : "> ";
452             p[0] = '\0';
453 #ifndef READLINE
454             fputs(prompt, stdout);
455             fflush(stdout);
456             if (!fgets(p, n, stdin))
457                 goto end;
458             if (p[0] == '\0')
459                 goto end;
460             i = strlen(p);
461             if (i <= 1)
462                 break;
463             if (p[i - 2] != '\\')
464                 break;
465             i -= 2;
466             p += i;
467             n -= i;
468 #else
469             {
470                 extern char *readline(const char *);
471                 extern void add_history(const char *cp);
472                 char *text;
473
474                 char *text = readline(prompt);
475                 if (text == NULL)
476                     goto end;
477                 i = strlen(text);
478                 if (i == 0 || i > n)
479                     break;
480                 if (text[i - 1] != '\\') {
481                     p += strlen(strcpy(p, text));
482                     free(text);
483                     add_history(buf);
484                     break;
485                 }
486
487                 text[i - 1] = '\0';
488                 p += strlen(strcpy(p, text));
489                 free(text);
490                 n -= i;
491             }
492 #endif
493         }
494
495         if (!chopup_args(&arg, buf)) {
496             BIO_printf(bio_err, "Can't parse (no memory?)\n");
497             break;
498         }
499
500         ret = do_cmd(prog, arg.argc, arg.argv);
501         if (ret == EXIT_THE_PROGRAM) {
502             ret = 0;
503             goto end;
504         }
505         if (ret != 0)
506             BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
507         (void)BIO_flush(bio_out);
508         (void)BIO_flush(bio_err);
509     }
510     ret = 1;
511  end:
512     OPENSSL_free(copied_argv);
513     OPENSSL_free(to_free);
514     NCONF_free(config);
515     config = NULL;
516     lh_FUNCTION_free(prog);
517     OPENSSL_free(arg.argv);
518
519     BIO_free(bio_in);
520     BIO_free_all(bio_out);
521     apps_shutdown();
522     CRYPTO_mem_leaks(bio_err);
523     BIO_free(bio_err);
524     return (ret);
525 }
526
527 OPTIONS exit_options[] = {
528     {NULL}
529 };
530
531 static void list_cipher_fn(const EVP_CIPHER *c,
532                            const char *from, const char *to, void *arg)
533 {
534     if (c)
535         BIO_printf(arg, "%s\n", EVP_CIPHER_name(c));
536     else {
537         if (!from)
538             from = "<undefined>";
539         if (!to)
540             to = "<undefined>";
541         BIO_printf(arg, "%s => %s\n", from, to);
542     }
543 }
544
545 static void list_md_fn(const EVP_MD *m,
546                        const char *from, const char *to, void *arg)
547 {
548     if (m)
549         BIO_printf(arg, "%s\n", EVP_MD_name(m));
550     else {
551         if (!from)
552             from = "<undefined>";
553         if (!to)
554             to = "<undefined>";
555         BIO_printf((BIO *)arg, "%s => %s\n", from, to);
556     }
557 }
558
559 /* Unified enum for help and list commands. */
560 typedef enum HELPLIST_CHOICE {
561     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
562     OPT_COMMANDS, OPT_DIGEST_COMMANDS,
563     OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS,
564     OPT_PK_ALGORITHMS
565 } HELPLIST_CHOICE;
566
567 OPTIONS list_options[] = {
568     {"help", OPT_HELP, '-', "Display this summary"},
569     {"commands", OPT_COMMANDS, '-', "List of standard commands"},
570     {"digest-commands", OPT_DIGEST_COMMANDS, '-',
571      "List of message digest commands"},
572     {"digest-algorithms", OPT_DIGEST_ALGORITHMS, '-',
573      "List of message digest algorithms"},
574     {"cipher-commands", OPT_CIPHER_COMMANDS, '-', "List of cipher commands"},
575     {"cipher-algorithms", OPT_CIPHER_ALGORITHMS, '-',
576      "List of cipher algorithms"},
577     {"public-key-algorithms", OPT_PK_ALGORITHMS, '-',
578      "List of public key algorithms"},
579     {NULL}
580 };
581
582 int list_main(int argc, char **argv)
583 {
584     char *prog;
585     HELPLIST_CHOICE o;
586
587     prog = opt_init(argc, argv, list_options);
588     while ((o = opt_next()) != OPT_EOF) {
589         switch (o) {
590         case OPT_EOF:
591         case OPT_ERR:
592             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
593             return 1;
594         case OPT_HELP:
595             opt_help(list_options);
596             break;
597         case OPT_COMMANDS:
598             list_type(FT_general);
599             break;
600         case OPT_DIGEST_COMMANDS:
601             list_type(FT_md);
602             break;
603         case OPT_DIGEST_ALGORITHMS:
604             EVP_MD_do_all_sorted(list_md_fn, bio_out);
605             break;
606         case OPT_CIPHER_COMMANDS:
607             list_type(FT_cipher);
608             break;
609         case OPT_CIPHER_ALGORITHMS:
610             EVP_CIPHER_do_all_sorted(list_cipher_fn, bio_out);
611             break;
612         case OPT_PK_ALGORITHMS:
613             list_pkey();
614             break;
615         }
616     }
617
618     return 0;
619 }
620
621 OPTIONS help_options[] = {
622     {"help", OPT_HELP, '-', "Display this summary"},
623     {NULL}
624 };
625
626 int help_main(int argc, char **argv)
627 {
628     FUNCTION *fp;
629     int i, nl;
630     FUNC_TYPE tp;
631     char *prog;
632     HELPLIST_CHOICE o;
633
634     prog = opt_init(argc, argv, help_options);
635     while ((o = opt_next()) != OPT_EOF) {
636         switch (o) {
637         default:
638             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
639             return 1;
640         case OPT_HELP:
641             opt_help(help_options);
642             return 0;
643         }
644     }
645     argc = opt_num_rest();
646     argv = opt_rest();
647
648     if (argc != 0) {
649         BIO_printf(bio_err, "Usage: %s\n", prog);
650         return 1;
651     }
652
653     BIO_printf(bio_err, "\nStandard commands");
654     i = 0;
655     tp = FT_none;
656     for (fp = functions; fp->name != NULL; fp++) {
657         nl = 0;
658         if (((i++) % COLUMNS) == 0) {
659             BIO_printf(bio_err, "\n");
660             nl = 1;
661         }
662         if (fp->type != tp) {
663             tp = fp->type;
664             if (!nl)
665                 BIO_printf(bio_err, "\n");
666             if (tp == FT_md) {
667                 i = 1;
668                 BIO_printf(bio_err,
669                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
670             } else if (tp == FT_cipher) {
671                 i = 1;
672                 BIO_printf(bio_err,
673                            "\nCipher commands (see the `enc' command for more details)\n");
674             }
675         }
676         BIO_printf(bio_err, FORMAT, fp->name);
677     }
678     BIO_printf(bio_err, "\n\n");
679     return 0;
680 }
681
682 int exit_main(int argc, char **argv)
683 {
684     return EXIT_THE_PROGRAM;
685 }
686
687 static void list_type(FUNC_TYPE ft)
688 {
689     FUNCTION *fp;
690     int i = 0;
691
692     for (fp = functions; fp->name != NULL; fp++)
693         if (fp->type == ft) {
694             if ((i++ % COLUMNS) == 0)
695                 BIO_printf(bio_out, "\n");
696             BIO_printf(bio_out, FORMAT, fp->name);
697         }
698     BIO_printf(bio_out, "\n");
699 }
700
701 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
702 {
703     FUNCTION f, *fp;
704
705     if (argc <= 0 || argv[0] == NULL)
706         return (0);
707     f.name = argv[0];
708     fp = lh_FUNCTION_retrieve(prog, &f);
709     if (fp == NULL) {
710         if (EVP_get_digestbyname(argv[0])) {
711             f.type = FT_md;
712             f.func = dgst_main;
713             fp = &f;
714         } else if (EVP_get_cipherbyname(argv[0])) {
715             f.type = FT_cipher;
716             f.func = enc_main;
717             fp = &f;
718         }
719     }
720     if (fp != NULL) {
721         return (fp->func(argc, argv));
722     }
723     if ((strncmp(argv[0], "no-", 3)) == 0) {
724         /*
725          * User is asking if foo is unsupported, by trying to "run" the
726          * no-foo command.  Strange.
727          */
728         f.name = argv[0] + 3;
729         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
730             BIO_printf(bio_out, "%s\n", argv[0]);
731             return (0);
732         }
733         BIO_printf(bio_out, "%s\n", argv[0] + 3);
734         return 1;
735     }
736     if (strcmp(argv[0], "quit") == 0 || strcmp(argv[0], "q") == 0 ||
737         strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "bye") == 0)
738         /* Special value to mean "exit the program. */
739         return EXIT_THE_PROGRAM;
740
741     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
742                argv[0]);
743     return (1);
744 }
745
746 static void list_pkey(void)
747 {
748     int i;
749
750     for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
751         const EVP_PKEY_ASN1_METHOD *ameth;
752         int pkey_id, pkey_base_id, pkey_flags;
753         const char *pinfo, *pem_str;
754         ameth = EVP_PKEY_asn1_get0(i);
755         EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags,
756                                 &pinfo, &pem_str, ameth);
757         if (pkey_flags & ASN1_PKEY_ALIAS) {
758             BIO_printf(bio_out, "Name: %s\n", OBJ_nid2ln(pkey_id));
759             BIO_printf(bio_out, "\tAlias for: %s\n",
760                        OBJ_nid2ln(pkey_base_id));
761         } else {
762             BIO_printf(bio_out, "Name: %s\n", pinfo);
763             BIO_printf(bio_out, "\tType: %s Algorithm\n",
764                        pkey_flags & ASN1_PKEY_DYNAMIC ?
765                        "External" : "Builtin");
766             BIO_printf(bio_out, "\tOID: %s\n", OBJ_nid2ln(pkey_id));
767             if (pem_str == NULL)
768                 pem_str = "(none)";
769             BIO_printf(bio_out, "\tPEM string: %s\n", pem_str);
770         }
771
772     }
773 }
774
775 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
776 {
777     return strncmp(a->name, b->name, 8);
778 }
779
780 static IMPLEMENT_LHASH_COMP_FN(function, FUNCTION)
781
782 static unsigned long function_hash(const FUNCTION * a)
783 {
784     return lh_strhash(a->name);
785 }
786
787 static IMPLEMENT_LHASH_HASH_FN(function, FUNCTION)
788
789 static int SortFnByName(const void *_f1, const void *_f2)
790 {
791     const FUNCTION *f1 = _f1;
792     const FUNCTION *f2 = _f2;
793
794     if (f1->type != f2->type)
795         return f1->type - f2->type;
796     return strcmp(f1->name, f2->name);
797 }
798
799 static LHASH_OF(FUNCTION) *prog_init(void)
800 {
801     LHASH_OF(FUNCTION) *ret;
802     FUNCTION *f;
803     size_t i;
804
805     /* Sort alphabetically within category. For nicer help displays. */
806     for (i = 0, f = functions; f->name != NULL; ++f, ++i) ;
807     qsort(functions, i, sizeof(*functions), SortFnByName);
808
809     if ((ret = lh_FUNCTION_new()) == NULL)
810         return (NULL);
811
812     for (f = functions; f->name != NULL; f++)
813         (void)lh_FUNCTION_insert(ret, f);
814     return (ret);
815 }