Small fixes after the Big apps cleanup
[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 = OPENSSL_malloc(len);
208     if (p == NULL)
209         return NULL;
210     BUF_strlcpy(p, t, len);
211 #ifndef OPENSSL_SYS_VMS
212     BUF_strlcat(p, "/", len);
213 #endif
214     BUF_strlcat(p, OPENSSL_CONF, len);
215
216     return p;
217 }
218
219 static int load_config(CONF *cnf)
220 {
221     static int load_config_called = 0;
222
223     if (load_config_called)
224         return 1;
225     load_config_called = 1;
226     if (!cnf)
227         cnf = config;
228     if (!cnf)
229         return 1;
230
231     OPENSSL_load_builtin_modules();
232
233     if (CONF_modules_load(cnf, NULL, 0) <= 0) {
234         BIO_printf(bio_err, "Error configuring OpenSSL\n");
235         ERR_print_errors(bio_err);
236         return 0;
237     }
238     return 1;
239 }
240
241 static void lock_dbg_cb(int mode, int type, const char *file, int line)
242 {
243     static int modes[CRYPTO_NUM_LOCKS];
244     const char *errstr = NULL;
245     int rw = mode & (CRYPTO_READ | CRYPTO_WRITE);
246
247     if (rw != CRYPTO_READ && rw != CRYPTO_WRITE) {
248         errstr = "invalid mode";
249         goto err;
250     }
251
252     if (type < 0 || type >= CRYPTO_NUM_LOCKS) {
253         errstr = "type out of bounds";
254         goto err;
255     }
256
257     if (mode & CRYPTO_LOCK) {
258         if (modes[type]) {
259             errstr = "already locked";
260             /* must not happen in a single-threaded program --> deadlock! */
261             goto err;
262         }
263         modes[type] = rw;
264     } else if (mode & CRYPTO_UNLOCK) {
265         if (!modes[type]) {
266             errstr = "not locked";
267             goto err;
268         }
269
270         if (modes[type] != rw) {
271             errstr = (rw == CRYPTO_READ) ?
272                 "CRYPTO_r_unlock on write lock" :
273                 "CRYPTO_w_unlock on read lock";
274         }
275
276         modes[type] = 0;
277     } else {
278         errstr = "invalid mode";
279         goto err;
280     }
281
282  err:
283     if (errstr) {
284         /* we cannot use bio_err here */
285         fprintf(stderr,
286                 "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
287                 errstr, mode, type, file, line);
288     }
289 }
290
291 BIO *dup_bio_in(void)
292 {
293     return BIO_new_fp(stdin, BIO_NOCLOSE | BIO_FP_TEXT);
294 }
295
296 BIO *dup_bio_out(void)
297 {
298     BIO *b = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
299 #ifdef OPENSSL_SYS_VMS
300     b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
301 #endif
302     return b;
303 }
304
305 void unbuffer(FILE *fp)
306 {
307     setbuf(fp, NULL);
308 }
309
310 BIO *bio_open_default(const char *filename, const char *mode)
311 {
312     BIO *ret;
313
314     if (filename == NULL || strcmp(filename, "-") == 0) {
315         ret = *mode == 'r' ? dup_bio_in() : dup_bio_out();
316         if (ret != NULL)
317             return ret;
318         BIO_printf(bio_err,
319                    "Can't open %s, %s\n",
320                    *mode == 'r' ? "stdin" : "stdout", strerror(errno));
321     } else {
322         ret = BIO_new_file(filename, mode);
323         if (ret != NULL)
324             return ret;
325         BIO_printf(bio_err,
326                    "Can't open %s for %s, %s\n",
327                    filename,
328                    *mode == 'r' ? "reading" : "writing", strerror(errno));
329     }
330     ERR_print_errors(bio_err);
331     return NULL;
332 }
333
334 #if defined( OPENSSL_SYS_VMS)
335 extern char **copy_argv(int *argc, char **argv);
336 #endif
337
338 int main(int argc, char *argv[])
339 {
340     FUNCTION f, *fp;
341     LHASH_OF(FUNCTION) *prog = NULL;
342     char **copied_argv = NULL;
343     char *p, *pname, *to_free = NULL;
344     char buf[1024];
345     const char *prompt;
346     ARGS arg;
347     int first, n, i, ret = 0;
348     long errline;
349
350     arg.argv = NULL;
351     arg.size = 0;
352
353 #if defined( OPENSSL_SYS_VMS)
354     copied_argv = argv = copy_argv(&argc, argv);
355 #endif
356
357     p = getenv("OPENSSL_DEBUG_MEMORY");
358     if (p == NULL)
359         /* if not set, use compiled-in default */
360         ;
361     else if (strcmp(p, "off") != 0) {
362         CRYPTO_malloc_debug_init();
363         CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
364     } else {
365         CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
366     }
367     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
368     CRYPTO_set_locking_callback(lock_dbg_cb);
369
370     if (getenv("OPENSSL_FIPS")) {
371 #ifdef OPENSSL_FIPS
372         if (!FIPS_mode_set(1)) {
373             ERR_load_crypto_strings();
374             ERR_print_errors(BIO_new_fp(stderr, BIO_NOCLOSE));
375             EXIT(1);
376         }
377 #else
378         fprintf(stderr, "FIPS mode not supported.\n");
379         EXIT(1);
380 #endif
381     }
382
383     apps_startup();
384
385     /*
386      * If first argument is a colon, skip it.  Because in "interactive"
387      * mode our prompt is a colon and we can cut/paste whole lines
388      * by doing this hack.
389      */
390     if (argv[1] && strcmp(argv[1], ":") == 0) {
391         argv[1] = argv[0];
392         argc--;
393         argv++;
394     }
395     prog = prog_init();
396     pname = opt_progname(argv[0]);
397
398     /* Lets load up our environment a little */
399     bio_in = dup_bio_in();
400     bio_out = dup_bio_out();
401     bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
402
403     /* Determine and load the config file. */
404     default_config_file = getenv("OPENSSL_CONF");
405     if (default_config_file == NULL)
406         default_config_file = getenv("SSLEAY_CONF");
407     if (default_config_file == NULL)
408         default_config_file = to_free = make_config_name();
409     if (!load_config(NULL))
410         goto end;
411     config = NCONF_new(NULL);
412     i = NCONF_load(config, default_config_file, &errline);
413     if (i == 0) {
414         if (ERR_GET_REASON(ERR_peek_last_error())
415             == CONF_R_NO_SUCH_FILE) {
416             BIO_printf(bio_err,
417                        "%s: WARNING: can't open config file: %s\n",
418                        pname, default_config_file);
419             ERR_clear_error();
420             NCONF_free(config);
421             config = NULL;
422         } else {
423             ERR_print_errors(bio_err);
424             NCONF_free(config);
425             exit(1);
426         }
427     }
428
429     /* first check the program name */
430     f.name = pname;
431     fp = lh_FUNCTION_retrieve(prog, &f);
432     if (fp != NULL) {
433         argv[0] = pname;
434         ret = fp->func(argc, argv);
435         goto end;
436     }
437
438     /* If there is stuff on the command line, run with that. */
439     if (argc != 1) {
440         argc--;
441         argv++;
442         ret = do_cmd(prog, argc, argv);
443         if (ret < 0)
444             ret = 0;
445         goto end;
446     }
447
448     /* ok, lets enter interactive mode */
449     for (;;) {
450         ret = 0;
451         /* Read a line, continue reading if line ends with \ */
452         for (p = buf, n = sizeof buf, i = 0, first = 1; n > 0; first = 0) {
453             prompt = first ? "openssl : " : "> ";
454             p[0] = '\0';
455 #ifndef READLINE
456             fputs(prompt, stdout);
457             fflush(stdout);
458             if (!fgets(p, n, stdin))
459                 goto end;
460             if (p[0] == '\0')
461                 goto end;
462             i = strlen(p);
463             if (i <= 1)
464                 break;
465             if (p[i - 2] != '\\')
466                 break;
467             i -= 2;
468             p += i;
469             n -= i;
470 #else
471             {
472                 extern char *readline(const char *);
473                 extern void add_history(const char *cp);
474                 char *text;
475
476                 char *text = readline(prompt);
477                 if (text == NULL)
478                     goto end;
479                 i = strlen(text);
480                 if (i == 0 || i > n)
481                     break;
482                 if (text[i - 1] != '\\') {
483                     p += strlen(strcpy(p, text));
484                     free(text);
485                     add_history(buf);
486                     break;
487                 }
488
489                 text[i - 1] = '\0';
490                 p += strlen(strcpy(p, text));
491                 free(text);
492                 n -= i;
493             }
494 #endif
495         }
496
497         if (!chopup_args(&arg, buf)) {
498             BIO_printf(bio_err, "Can't parse (no memory?)\n");
499             break;
500         }
501
502         ret = do_cmd(prog, arg.argc, arg.argv);
503         if (ret == EXIT_THE_PROGRAM) {
504             ret = 0;
505             goto end;
506         }
507         if (ret != 0)
508             BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
509         (void)BIO_flush(bio_out);
510         (void)BIO_flush(bio_err);
511     }
512     ret = 1;
513  end:
514     if (copied_argv)
515         OPENSSL_free(copied_argv);
516     if (to_free)
517         OPENSSL_free(to_free);
518     if (config != NULL) {
519         NCONF_free(config);
520         config = NULL;
521     }
522     if (prog != NULL)
523         lh_FUNCTION_free(prog);
524     if (arg.argv != NULL)
525         OPENSSL_free(arg.argv);
526
527     BIO_free(bio_in);
528     BIO_free_all(bio_out);
529     apps_shutdown();
530     /*CRYPTO_mem_leaks(bio_err);
531      */
532     BIO_free(bio_err);
533     return (ret);
534 }
535
536 OPTIONS exit_options[] = {
537     {NULL}
538 };
539
540 static void list_cipher_fn(const EVP_CIPHER *c,
541                            const char *from, const char *to, void *arg)
542 {
543     if (c)
544         BIO_printf(arg, "%s\n", EVP_CIPHER_name(c));
545     else {
546         if (!from)
547             from = "<undefined>";
548         if (!to)
549             to = "<undefined>";
550         BIO_printf(arg, "%s => %s\n", from, to);
551     }
552 }
553
554 static void list_md_fn(const EVP_MD *m,
555                        const char *from, const char *to, void *arg)
556 {
557     if (m)
558         BIO_printf(arg, "%s\n", EVP_MD_name(m));
559     else {
560         if (!from)
561             from = "<undefined>";
562         if (!to)
563             to = "<undefined>";
564         BIO_printf((BIO *)arg, "%s => %s\n", from, to);
565     }
566 }
567
568 /* Unified enum for help and list commands. */
569 typedef enum HELPLIST_CHOICE {
570     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
571     OPT_COMMANDS, OPT_DIGEST_COMMANDS,
572     OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS,
573     OPT_PK_ALGORITHMS
574 } HELPLIST_CHOICE;
575
576 OPTIONS list_options[] = {
577     {"help", OPT_HELP, '-', "Display this summary"},
578     {"commands", OPT_COMMANDS, '-', "List of standard commands"},
579     {"digest-commands", OPT_DIGEST_COMMANDS, '-',
580      "List of message digest commands"},
581     {"digest-algorithms", OPT_DIGEST_ALGORITHMS, '-',
582      "List of message digest algorithms"},
583     {"cipher-commands", OPT_CIPHER_COMMANDS, '-', "List of cipher commands"},
584     {"cipher-algorithms", OPT_CIPHER_ALGORITHMS, '-',
585      "List of cipher algorithms"},
586     {"public-key-algorithms", OPT_PK_ALGORITHMS, '-',
587      "List of public key algorithms"},
588     {NULL}
589 };
590
591 int list_main(int argc, char **argv)
592 {
593     char *prog;
594     HELPLIST_CHOICE o;
595
596     prog = opt_init(argc, argv, list_options);
597     while ((o = opt_next()) != OPT_EOF) {
598         switch (o) {
599         case OPT_EOF:
600         case OPT_ERR:
601             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
602             return 1;
603         case OPT_HELP:
604             opt_help(list_options);
605             break;
606         case OPT_COMMANDS:
607             list_type(FT_general);
608             break;
609         case OPT_DIGEST_COMMANDS:
610             list_type(FT_md);
611             break;
612         case OPT_DIGEST_ALGORITHMS:
613             EVP_MD_do_all_sorted(list_md_fn, bio_out);
614             break;
615         case OPT_CIPHER_COMMANDS:
616             list_type(FT_cipher);
617             break;
618         case OPT_CIPHER_ALGORITHMS:
619             EVP_CIPHER_do_all_sorted(list_cipher_fn, bio_out);
620             break;
621         case OPT_PK_ALGORITHMS:
622             list_pkey();
623             break;
624         }
625     }
626
627     return 0;
628 }
629
630 OPTIONS help_options[] = {
631     {"help", OPT_HELP, '-', "Display this summary"},
632     {NULL}
633 };
634
635 int help_main(int argc, char **argv)
636 {
637     FUNCTION *fp;
638     int i, nl;
639     FUNC_TYPE tp;
640     char *prog;
641     HELPLIST_CHOICE o;
642
643     prog = opt_init(argc, argv, help_options);
644     while ((o = opt_next()) != OPT_EOF) {
645         switch (o) {
646         default:
647             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
648             return 1;
649         case OPT_HELP:
650             opt_help(help_options);
651             return 0;
652         }
653     }
654     argc = opt_num_rest();
655     argv = opt_rest();
656
657     if (argc != 0) {
658         BIO_printf(bio_err, "Usage: %s\n", prog);
659         return 1;
660     }
661
662     BIO_printf(bio_err, "\nStandard commands");
663     i = 0;
664     tp = FT_none;
665     for (fp = functions; fp->name != NULL; fp++) {
666         nl = 0;
667         if (((i++) % COLUMNS) == 0) {
668             BIO_printf(bio_err, "\n");
669             nl = 1;
670         }
671         if (fp->type != tp) {
672             tp = fp->type;
673             if (!nl)
674                 BIO_printf(bio_err, "\n");
675             if (tp == FT_md) {
676                 i = 1;
677                 BIO_printf(bio_err,
678                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
679             } else if (tp == FT_cipher) {
680                 i = 1;
681                 BIO_printf(bio_err,
682                            "\nCipher commands (see the `enc' command for more details)\n");
683             }
684         }
685         BIO_printf(bio_err, FORMAT, fp->name);
686     }
687     BIO_printf(bio_err, "\n\n");
688     return 0;
689 }
690
691 int exit_main(int argc, char **argv)
692 {
693     return EXIT_THE_PROGRAM;
694 }
695
696 static void list_type(FUNC_TYPE ft)
697 {
698     FUNCTION *fp;
699     int i = 0;
700
701     for (fp = functions; fp->name != NULL; fp++)
702         if (fp->type == ft) {
703             if ((i++ % COLUMNS) == 0)
704                 BIO_printf(bio_out, "\n");
705             BIO_printf(bio_out, FORMAT, fp->name);
706         }
707     BIO_printf(bio_out, "\n");
708 }
709
710 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
711 {
712     FUNCTION f, *fp;
713
714     if (argc <= 0 || argv[0] == NULL)
715         return (0);
716     f.name = argv[0];
717     fp = lh_FUNCTION_retrieve(prog, &f);
718     if (fp == NULL) {
719         if (EVP_get_digestbyname(argv[0])) {
720             f.type = FT_md;
721             f.func = dgst_main;
722             fp = &f;
723         } else if (EVP_get_cipherbyname(argv[0])) {
724             f.type = FT_cipher;
725             f.func = enc_main;
726             fp = &f;
727         }
728     }
729     if (fp != NULL) {
730         return (fp->func(argc, argv));
731     }
732     if ((strncmp(argv[0], "no-", 3)) == 0) {
733         /*
734          * User is asking if foo is unsupported, by trying to "run" the
735          * no-foo command.  Strange.
736          */
737         f.name = argv[0] + 3;
738         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
739             BIO_printf(bio_out, "%s\n", argv[0]);
740             return (0);
741         }
742         BIO_printf(bio_out, "%s\n", argv[0] + 3);
743         return 1;
744     }
745     if (strcmp(argv[0], "quit") == 0 || strcmp(argv[0], "q") == 0 ||
746         strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "bye") == 0)
747         /* Special value to mean "exit the program. */
748         return EXIT_THE_PROGRAM;
749
750     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
751                argv[0]);
752     return (1);
753 }
754
755 static void list_pkey(void)
756 {
757     int i;
758
759     for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
760         const EVP_PKEY_ASN1_METHOD *ameth;
761         int pkey_id, pkey_base_id, pkey_flags;
762         const char *pinfo, *pem_str;
763         ameth = EVP_PKEY_asn1_get0(i);
764         EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags,
765                                 &pinfo, &pem_str, ameth);
766         if (pkey_flags & ASN1_PKEY_ALIAS) {
767             BIO_printf(bio_out, "Name: %s\n", OBJ_nid2ln(pkey_id));
768             BIO_printf(bio_out, "\tAlias for: %s\n",
769                        OBJ_nid2ln(pkey_base_id));
770         } else {
771             BIO_printf(bio_out, "Name: %s\n", pinfo);
772             BIO_printf(bio_out, "\tType: %s Algorithm\n",
773                        pkey_flags & ASN1_PKEY_DYNAMIC ?
774                        "External" : "Builtin");
775             BIO_printf(bio_out, "\tOID: %s\n", OBJ_nid2ln(pkey_id));
776             if (pem_str == NULL)
777                 pem_str = "(none)";
778             BIO_printf(bio_out, "\tPEM string: %s\n", pem_str);
779         }
780
781     }
782 }
783
784 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
785 {
786     return strncmp(a->name, b->name, 8);
787 }
788
789 static IMPLEMENT_LHASH_COMP_FN(function, FUNCTION)
790
791 static unsigned long function_hash(const FUNCTION * a)
792 {
793     return lh_strhash(a->name);
794 }
795
796 static IMPLEMENT_LHASH_HASH_FN(function, FUNCTION)
797
798 static int SortFnByName(const void *_f1, const void *_f2)
799 {
800     const FUNCTION *f1 = _f1;
801     const FUNCTION *f2 = _f2;
802
803     if (f1->type != f2->type)
804         return f1->type - f2->type;
805     return strcmp(f1->name, f2->name);
806 }
807
808 static LHASH_OF(FUNCTION) *prog_init(void)
809 {
810     LHASH_OF(FUNCTION) *ret;
811     FUNCTION *f;
812     size_t i;
813
814     /* Sort alphabetically within category. For nicer help displays. */
815     for (i = 0, f = functions; f->name != NULL; ++f, ++i) ;
816     qsort(functions, i, sizeof *functions, SortFnByName);
817
818     if ((ret = lh_FUNCTION_new()) == NULL)
819         return (NULL);
820
821     for (f = functions; f->name != NULL; f++)
822         (void)lh_FUNCTION_insert(ret, f);
823     return (ret);
824 }