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