Change the way apps open their input and output files
[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 #include <openssl/err.h>
126 #ifdef OPENSSL_FIPS
127 # include <openssl/fips.h>
128 #endif
129 #define USE_SOCKETS /* needed for the _O_BINARY defs in the MS world */
130 #include "s_apps.h"
131 /* Needed to get the other O_xxx flags. */
132 #ifdef OPENSSL_SYS_VMS
133 # include <unixio.h>
134 #endif
135 #ifndef NO_SYS_TYPES_H
136 # include <sys/types.h>
137 #endif
138 #ifndef OPENSSL_NO_POSIX_IO
139 # include <sys/stat.h>
140 # include <fcntl.h>
141 #endif
142 #define INCLUDE_FUNCTION_TABLE
143 #include "apps.h"
144
145
146 #ifdef OPENSSL_NO_CAMELLIA
147 # define FORMAT "%-15s"
148 # define COLUMNS 5
149 #else
150 # define FORMAT "%-18s"
151 # define COLUMNS 4
152 #endif
153
154 /* Special sentinel to exit the program. */
155 #define EXIT_THE_PROGRAM (-1)
156
157 /*
158  * The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
159  * the base prototypes (we cast each variable inside the function to the
160  * required type of "FUNCTION*"). This removes the necessity for
161  * macro-generated wrapper functions.
162  */
163 DECLARE_LHASH_OF(FUNCTION);
164 static LHASH_OF(FUNCTION) *prog_init(void);
165 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
166 static void list_pkey(void);
167 static void list_type(FUNC_TYPE ft);
168 char *default_config_file = NULL;
169
170 CONF *config = NULL;
171 BIO *bio_in = NULL;
172 BIO *bio_out = NULL;
173 BIO *bio_err = NULL;
174
175 static void apps_startup()
176 {
177 #ifdef SIGPIPE
178     signal(SIGPIPE, SIG_IGN);
179 #endif
180     CRYPTO_malloc_init();
181     ERR_load_crypto_strings();
182     ERR_load_SSL_strings();
183     OpenSSL_add_all_algorithms();
184     OpenSSL_add_ssl_algorithms();
185     OPENSSL_load_builtin_modules();
186     setup_ui_method();
187     /*SSL_library_init();*/
188 #ifndef OPENSSL_NO_ENGINE
189     ENGINE_load_builtin_engines();
190 #endif
191 }
192
193 static void apps_shutdown()
194 {
195 #ifndef OPENSSL_NO_ENGINE
196     ENGINE_cleanup();
197 #endif
198     destroy_ui_method();
199     CONF_modules_unload(1);
200 #ifndef OPENSSL_NO_COMP
201     COMP_zlib_cleanup();
202     SSL_COMP_free_compression_methods();
203 #endif
204     OBJ_cleanup();
205     EVP_cleanup();
206     CRYPTO_cleanup_all_ex_data();
207     ERR_remove_thread_state(NULL);
208     RAND_cleanup();
209     ERR_free_strings();
210 }
211
212 static char *make_config_name()
213 {
214     const char *t;
215     size_t len;
216     char *p;
217
218     if ((t = getenv("OPENSSL_CONF")) != NULL
219         || (t = getenv("SSLEAY_CONF")) != NULL)
220         return BUF_strdup(t);
221
222     t = X509_get_default_cert_area();
223     len = strlen(t) + 1 + strlen(OPENSSL_CONF) + 1;
224     p = app_malloc(len, "config filename buffer");
225     strcpy(p, t);
226 #ifndef OPENSSL_SYS_VMS
227     strcat(p, "/");
228 #endif
229     strcat(p, OPENSSL_CONF);
230
231     return p;
232 }
233
234 static void lock_dbg_cb(int mode, int type, const char *file, int line)
235 {
236     static int modes[CRYPTO_NUM_LOCKS];
237     const char *errstr = NULL;
238     int rw = mode & (CRYPTO_READ | CRYPTO_WRITE);
239
240     if (rw != CRYPTO_READ && rw != CRYPTO_WRITE) {
241         errstr = "invalid mode";
242         goto err;
243     }
244
245     if (type < 0 || type >= CRYPTO_NUM_LOCKS) {
246         errstr = "type out of bounds";
247         goto err;
248     }
249
250     if (mode & CRYPTO_LOCK) {
251         if (modes[type]) {
252             errstr = "already locked";
253             /* must not happen in a single-threaded program --> deadlock! */
254             goto err;
255         }
256         modes[type] = rw;
257     } else if (mode & CRYPTO_UNLOCK) {
258         if (!modes[type]) {
259             errstr = "not locked";
260             goto err;
261         }
262
263         if (modes[type] != rw) {
264             errstr = (rw == CRYPTO_READ) ?
265                 "CRYPTO_r_unlock on write lock" :
266                 "CRYPTO_w_unlock on read lock";
267         }
268
269         modes[type] = 0;
270     } else {
271         errstr = "invalid mode";
272         goto err;
273     }
274
275  err:
276     if (errstr) {
277         BIO_printf(bio_err,
278                    "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
279                    errstr, mode, type, file, line);
280     }
281 }
282
283 BIO *dup_bio_in(void)
284 {
285     return BIO_new_fp(stdin, BIO_NOCLOSE | BIO_FP_TEXT);
286 }
287
288 BIO *dup_bio_out(void)
289 {
290     BIO *b = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
291 #ifdef OPENSSL_SYS_VMS
292     b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
293 #endif
294     return b;
295 }
296
297 void unbuffer(FILE *fp)
298 {
299     setbuf(fp, NULL);
300 }
301
302 static const char *modestr(char mode, int format)
303 {
304     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
305
306     switch (mode) {
307     case 'a':
308         return (format) & B_FORMAT_TEXT ? "ab" : "a";
309     case 'r':
310         return (format) & B_FORMAT_TEXT ? "rb" : "r";
311     case 'w':
312         return (format) & B_FORMAT_TEXT ? "wb" : "w";
313     }
314     /* The assert above should make sure we never reach this point */
315     return NULL;
316 }
317
318 static const char *modeverb(char mode)
319 {
320     switch (mode) {
321     case 'a':
322         return "appending";
323     case 'r':
324         return "reading";
325     case 'w':
326         return "writing";
327     }
328     return "(doing something)";
329 }
330
331 /*
332  * Open a file for writing, owner-read-only.
333  */
334 BIO *bio_open_owner(const char *filename, int format, int private)
335 {
336     FILE *fp = NULL;
337     BIO *b = NULL;
338     int fd = -1, bflags, mode, binmode;
339
340     if (!private || filename == NULL || strcmp(filename, "-") == 0)
341         return bio_open_default(filename, 'w', format);
342
343     mode = O_WRONLY;
344 #ifdef O_CREAT
345     mode |= O_CREAT;
346 #endif
347 #ifdef O_TRUNC
348     mode |= O_TRUNC;
349 #endif
350     binmode = !(format & B_FORMAT_TEXT);
351     if (binmode) {
352 #ifdef O_BINARY
353         mode |= O_BINARY;
354 #elif defined(_O_BINARY)
355         mode |= _O_BINARY;
356 #endif
357     }
358
359     fd = open(filename, mode, 0600);
360     if (fd < 0)
361         goto err;
362     fp = fdopen(fd, modestr('w', format));
363     if (fp == NULL)
364         goto err;
365     bflags = BIO_CLOSE;
366     if (!binmode)
367         bflags |= BIO_FP_TEXT;
368     b = BIO_new_fp(fp, bflags);
369     if (b)
370         return b;
371
372  err:
373     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
374                opt_getprog(), filename, strerror(errno));
375     ERR_print_errors(bio_err);
376     /* If we have fp, then fdopen took over fd, so don't close both. */
377     if (fp)
378         fclose(fp);
379     else if (fd >= 0)
380         close(fd);
381     return NULL;
382 }
383
384 static BIO *bio_open_default_(const char *filename, char mode, int format,
385                               int quiet)
386 {
387     BIO *ret;
388
389     if (filename == NULL || strcmp(filename, "-") == 0) {
390         ret = mode == 'r' ? dup_bio_in() : dup_bio_out();
391         if (quiet) {
392             ERR_clear_error();
393             return ret;
394         }
395         if (ret != NULL)
396             return ret;
397         BIO_printf(bio_err,
398                    "Can't open %s, %s\n",
399                    mode == 'r' ? "stdin" : "stdout", strerror(errno));
400     } else {
401         ret = BIO_new_file(filename, modestr(mode, format));
402         if (quiet) {
403             ERR_clear_error();
404             return ret;
405         }
406         if (ret != NULL)
407             return ret;
408         BIO_printf(bio_err,
409                    "Can't open %s for %s, %s\n",
410                    filename, modeverb(mode), strerror(errno));
411     }
412     ERR_print_errors(bio_err);
413     return NULL;
414 }
415
416 BIO *bio_open_default(const char *filename, char mode, int format)
417 {
418     return bio_open_default_(filename, mode, format, 0);
419 }
420
421 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
422 {
423     return bio_open_default_(filename, mode, format, 1);
424 }
425
426 #if defined( OPENSSL_SYS_VMS)
427 extern char **copy_argv(int *argc, char **argv);
428 #endif
429
430 int main(int argc, char *argv[])
431 {
432     FUNCTION f, *fp;
433     LHASH_OF(FUNCTION) *prog = NULL;
434     char **copied_argv = NULL;
435     char *p, *pname;
436     char buf[1024];
437     const char *prompt;
438     ARGS arg;
439     int first, n, i, ret = 0;
440
441     arg.argv = NULL;
442     arg.size = 0;
443
444     /* Set up some of the environment. */
445     default_config_file = make_config_name();
446     bio_in = dup_bio_in();
447     bio_out = dup_bio_out();
448     bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
449
450 #if defined( OPENSSL_SYS_VMS)
451     copied_argv = argv = copy_argv(&argc, argv);
452 #endif
453
454     p = getenv("OPENSSL_DEBUG_MEMORY");
455     if (p == NULL)
456         /* if not set, use compiled-in default */
457         ;
458     else if (strcmp(p, "off") != 0) {
459         CRYPTO_malloc_debug_init();
460         CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
461     } else {
462         CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
463     }
464     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
465     CRYPTO_set_locking_callback(lock_dbg_cb);
466
467     if (getenv("OPENSSL_FIPS")) {
468 #ifdef OPENSSL_FIPS
469         if (!FIPS_mode_set(1)) {
470             ERR_load_crypto_strings();
471             ERR_print_errors(bio_err);
472             return 1;
473         }
474 #else
475         BIO_printf(bio_err, "FIPS mode not supported.\n");
476         return 1;
477 #endif
478     }
479
480     apps_startup();
481
482     /*
483      * If first argument is a colon, skip it.  Because in "interactive"
484      * mode our prompt is a colon and we can cut/paste whole lines
485      * by doing this hack.
486      */
487     if (argv[1] && strcmp(argv[1], ":") == 0) {
488         argv[1] = argv[0];
489         argc--;
490         argv++;
491     }
492     prog = prog_init();
493     pname = opt_progname(argv[0]);
494
495     /* first check the program name */
496     f.name = pname;
497     fp = lh_FUNCTION_retrieve(prog, &f);
498     if (fp != NULL) {
499         argv[0] = pname;
500         ret = fp->func(argc, argv);
501         goto end;
502     }
503
504     /* If there is stuff on the command line, run with that. */
505     if (argc != 1) {
506         argc--;
507         argv++;
508         ret = do_cmd(prog, argc, argv);
509         if (ret < 0)
510             ret = 0;
511         goto end;
512     }
513
514     /* ok, lets enter interactive mode */
515     for (;;) {
516         ret = 0;
517         /* Read a line, continue reading if line ends with \ */
518         for (p = buf, n = sizeof buf, i = 0, first = 1; n > 0; first = 0) {
519             prompt = first ? "openssl : " : "> ";
520             p[0] = '\0';
521 #ifndef READLINE
522             fputs(prompt, stdout);
523             fflush(stdout);
524             if (!fgets(p, n, stdin))
525                 goto end;
526             if (p[0] == '\0')
527                 goto end;
528             i = strlen(p);
529             if (i <= 1)
530                 break;
531             if (p[i - 2] != '\\')
532                 break;
533             i -= 2;
534             p += i;
535             n -= i;
536 #else
537             {
538                 extern char *readline(const char *);
539                 extern void add_history(const char *cp);
540                 char *text;
541
542                 char *text = readline(prompt);
543                 if (text == NULL)
544                     goto end;
545                 i = strlen(text);
546                 if (i == 0 || i > n)
547                     break;
548                 if (text[i - 1] != '\\') {
549                     p += strlen(strcpy(p, text));
550                     free(text);
551                     add_history(buf);
552                     break;
553                 }
554
555                 text[i - 1] = '\0';
556                 p += strlen(strcpy(p, text));
557                 free(text);
558                 n -= i;
559             }
560 #endif
561         }
562
563         if (!chopup_args(&arg, buf)) {
564             BIO_printf(bio_err, "Can't parse (no memory?)\n");
565             break;
566         }
567
568         ret = do_cmd(prog, arg.argc, arg.argv);
569         if (ret == EXIT_THE_PROGRAM) {
570             ret = 0;
571             goto end;
572         }
573         if (ret != 0)
574             BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
575         (void)BIO_flush(bio_out);
576         (void)BIO_flush(bio_err);
577     }
578     ret = 1;
579  end:
580     OPENSSL_free(copied_argv);
581     OPENSSL_free(default_config_file);
582     NCONF_free(config);
583     config = NULL;
584     lh_FUNCTION_free(prog);
585     OPENSSL_free(arg.argv);
586
587     BIO_free(bio_in);
588     BIO_free_all(bio_out);
589     apps_shutdown();
590     CRYPTO_mem_leaks(bio_err);
591     BIO_free(bio_err);
592     return (ret);
593 }
594
595 OPTIONS exit_options[] = {
596     {NULL}
597 };
598
599 static void list_cipher_fn(const EVP_CIPHER *c,
600                            const char *from, const char *to, void *arg)
601 {
602     if (c)
603         BIO_printf(arg, "%s\n", EVP_CIPHER_name(c));
604     else {
605         if (!from)
606             from = "<undefined>";
607         if (!to)
608             to = "<undefined>";
609         BIO_printf(arg, "%s => %s\n", from, to);
610     }
611 }
612
613 static void list_md_fn(const EVP_MD *m,
614                        const char *from, const char *to, void *arg)
615 {
616     if (m)
617         BIO_printf(arg, "%s\n", EVP_MD_name(m));
618     else {
619         if (!from)
620             from = "<undefined>";
621         if (!to)
622             to = "<undefined>";
623         BIO_printf((BIO *)arg, "%s => %s\n", from, to);
624     }
625 }
626
627 /* Unified enum for help and list commands. */
628 typedef enum HELPLIST_CHOICE {
629     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
630     OPT_COMMANDS, OPT_DIGEST_COMMANDS,
631     OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS,
632     OPT_PK_ALGORITHMS
633 } HELPLIST_CHOICE;
634
635 OPTIONS list_options[] = {
636     {"help", OPT_HELP, '-', "Display this summary"},
637     {"commands", OPT_COMMANDS, '-', "List of standard commands"},
638     {"digest-commands", OPT_DIGEST_COMMANDS, '-',
639      "List of message digest commands"},
640     {"digest-algorithms", OPT_DIGEST_ALGORITHMS, '-',
641      "List of message digest algorithms"},
642     {"cipher-commands", OPT_CIPHER_COMMANDS, '-', "List of cipher commands"},
643     {"cipher-algorithms", OPT_CIPHER_ALGORITHMS, '-',
644      "List of cipher algorithms"},
645     {"public-key-algorithms", OPT_PK_ALGORITHMS, '-',
646      "List of public key algorithms"},
647     {NULL}
648 };
649
650 int list_main(int argc, char **argv)
651 {
652     char *prog;
653     HELPLIST_CHOICE o;
654
655     prog = opt_init(argc, argv, list_options);
656     while ((o = opt_next()) != OPT_EOF) {
657         switch (o) {
658         case OPT_EOF:
659         case OPT_ERR:
660             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
661             return 1;
662         case OPT_HELP:
663             opt_help(list_options);
664             break;
665         case OPT_COMMANDS:
666             list_type(FT_general);
667             break;
668         case OPT_DIGEST_COMMANDS:
669             list_type(FT_md);
670             break;
671         case OPT_DIGEST_ALGORITHMS:
672             EVP_MD_do_all_sorted(list_md_fn, bio_out);
673             break;
674         case OPT_CIPHER_COMMANDS:
675             list_type(FT_cipher);
676             break;
677         case OPT_CIPHER_ALGORITHMS:
678             EVP_CIPHER_do_all_sorted(list_cipher_fn, bio_out);
679             break;
680         case OPT_PK_ALGORITHMS:
681             list_pkey();
682             break;
683         }
684     }
685
686     return 0;
687 }
688
689 OPTIONS help_options[] = {
690     {"help", OPT_HELP, '-', "Display this summary"},
691     {NULL}
692 };
693
694 int help_main(int argc, char **argv)
695 {
696     FUNCTION *fp;
697     int i, nl;
698     FUNC_TYPE tp;
699     char *prog;
700     HELPLIST_CHOICE o;
701
702     prog = opt_init(argc, argv, help_options);
703     while ((o = opt_next()) != OPT_EOF) {
704         switch (o) {
705         default:
706             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
707             return 1;
708         case OPT_HELP:
709             opt_help(help_options);
710             return 0;
711         }
712     }
713     argc = opt_num_rest();
714     argv = opt_rest();
715
716     if (argc != 0) {
717         BIO_printf(bio_err, "Usage: %s\n", prog);
718         return 1;
719     }
720
721     BIO_printf(bio_err, "\nStandard commands");
722     i = 0;
723     tp = FT_none;
724     for (fp = functions; fp->name != NULL; fp++) {
725         nl = 0;
726         if (((i++) % COLUMNS) == 0) {
727             BIO_printf(bio_err, "\n");
728             nl = 1;
729         }
730         if (fp->type != tp) {
731             tp = fp->type;
732             if (!nl)
733                 BIO_printf(bio_err, "\n");
734             if (tp == FT_md) {
735                 i = 1;
736                 BIO_printf(bio_err,
737                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
738             } else if (tp == FT_cipher) {
739                 i = 1;
740                 BIO_printf(bio_err,
741                            "\nCipher commands (see the `enc' command for more details)\n");
742             }
743         }
744         BIO_printf(bio_err, FORMAT, fp->name);
745     }
746     BIO_printf(bio_err, "\n\n");
747     return 0;
748 }
749
750 int exit_main(int argc, char **argv)
751 {
752     return EXIT_THE_PROGRAM;
753 }
754
755 static void list_type(FUNC_TYPE ft)
756 {
757     FUNCTION *fp;
758     int i = 0;
759
760     for (fp = functions; fp->name != NULL; fp++)
761         if (fp->type == ft) {
762             if ((i++ % COLUMNS) == 0)
763                 BIO_printf(bio_out, "\n");
764             BIO_printf(bio_out, FORMAT, fp->name);
765         }
766     BIO_printf(bio_out, "\n");
767 }
768
769 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
770 {
771     FUNCTION f, *fp;
772
773     if (argc <= 0 || argv[0] == NULL)
774         return (0);
775     f.name = argv[0];
776     fp = lh_FUNCTION_retrieve(prog, &f);
777     if (fp == NULL) {
778         if (EVP_get_digestbyname(argv[0])) {
779             f.type = FT_md;
780             f.func = dgst_main;
781             fp = &f;
782         } else if (EVP_get_cipherbyname(argv[0])) {
783             f.type = FT_cipher;
784             f.func = enc_main;
785             fp = &f;
786         }
787     }
788     if (fp != NULL) {
789         return (fp->func(argc, argv));
790     }
791     if ((strncmp(argv[0], "no-", 3)) == 0) {
792         /*
793          * User is asking if foo is unsupported, by trying to "run" the
794          * no-foo command.  Strange.
795          */
796         f.name = argv[0] + 3;
797         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
798             BIO_printf(bio_out, "%s\n", argv[0]);
799             return (0);
800         }
801         BIO_printf(bio_out, "%s\n", argv[0] + 3);
802         return 1;
803     }
804     if (strcmp(argv[0], "quit") == 0 || strcmp(argv[0], "q") == 0 ||
805         strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "bye") == 0)
806         /* Special value to mean "exit the program. */
807         return EXIT_THE_PROGRAM;
808
809     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
810                argv[0]);
811     return (1);
812 }
813
814 static void list_pkey(void)
815 {
816     int i;
817
818     for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
819         const EVP_PKEY_ASN1_METHOD *ameth;
820         int pkey_id, pkey_base_id, pkey_flags;
821         const char *pinfo, *pem_str;
822         ameth = EVP_PKEY_asn1_get0(i);
823         EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags,
824                                 &pinfo, &pem_str, ameth);
825         if (pkey_flags & ASN1_PKEY_ALIAS) {
826             BIO_printf(bio_out, "Name: %s\n", OBJ_nid2ln(pkey_id));
827             BIO_printf(bio_out, "\tAlias for: %s\n",
828                        OBJ_nid2ln(pkey_base_id));
829         } else {
830             BIO_printf(bio_out, "Name: %s\n", pinfo);
831             BIO_printf(bio_out, "\tType: %s Algorithm\n",
832                        pkey_flags & ASN1_PKEY_DYNAMIC ?
833                        "External" : "Builtin");
834             BIO_printf(bio_out, "\tOID: %s\n", OBJ_nid2ln(pkey_id));
835             if (pem_str == NULL)
836                 pem_str = "(none)";
837             BIO_printf(bio_out, "\tPEM string: %s\n", pem_str);
838         }
839
840     }
841 }
842
843 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
844 {
845     return strncmp(a->name, b->name, 8);
846 }
847
848 static IMPLEMENT_LHASH_COMP_FN(function, FUNCTION)
849
850 static unsigned long function_hash(const FUNCTION * a)
851 {
852     return lh_strhash(a->name);
853 }
854
855 static IMPLEMENT_LHASH_HASH_FN(function, FUNCTION)
856
857 static int SortFnByName(const void *_f1, const void *_f2)
858 {
859     const FUNCTION *f1 = _f1;
860     const FUNCTION *f2 = _f2;
861
862     if (f1->type != f2->type)
863         return f1->type - f2->type;
864     return strcmp(f1->name, f2->name);
865 }
866
867 static LHASH_OF(FUNCTION) *prog_init(void)
868 {
869     LHASH_OF(FUNCTION) *ret;
870     FUNCTION *f;
871     size_t i;
872
873     /* Sort alphabetically within category. For nicer help displays. */
874     for (i = 0, f = functions; f->name != NULL; ++f, ++i) ;
875     qsort(functions, i, sizeof(*functions), SortFnByName);
876
877     if ((ret = lh_FUNCTION_new()) == NULL)
878         return (NULL);
879
880     for (f = functions; f->name != NULL; f++)
881         (void)lh_FUNCTION_insert(ret, f);
882     return (ret);
883 }