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