HTTP client: make server/proxy and port params more consistent; minor other improvements
[openssl.git] / apps / openssl.c
1 /*
2  * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <internal/cryptlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <openssl/bio.h>
15 #include <openssl/crypto.h>
16 #include <openssl/trace.h>
17 #include <openssl/lhash.h>
18 #include <openssl/conf.h>
19 #include <openssl/x509.h>
20 #include <openssl/pem.h>
21 #include <openssl/ssl.h>
22 #ifndef OPENSSL_NO_ENGINE
23 # include <openssl/engine.h>
24 #endif
25 #include <openssl/err.h>
26 /* Needed to get the other O_xxx flags. */
27 #ifdef OPENSSL_SYS_VMS
28 # include <unixio.h>
29 #endif
30 #include "apps.h"
31 #include "progs.h"
32
33 /* Special sentinel to exit the program. */
34 #define EXIT_THE_PROGRAM (-1)
35
36 /*
37  * The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
38  * the base prototypes (we cast each variable inside the function to the
39  * required type of "FUNCTION*"). This removes the necessity for
40  * macro-generated wrapper functions.
41  */
42 static LHASH_OF(FUNCTION) *prog_init(void);
43 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
44 char *default_config_file = NULL;
45
46 BIO *bio_in = NULL;
47 BIO *bio_out = NULL;
48 BIO *bio_err = NULL;
49
50 static void warn_deprecated(const char *pname,
51                             const char *deprecated_alternative)
52 {
53     BIO_printf(bio_err, "The command %s is deprecated.", pname);
54     if (strcmp(deprecated_alternative, DEPRECATED_NO_ALTERNATIVE) != 0)
55         BIO_printf(bio_err, " Use '%s' instead.", deprecated_alternative);
56     BIO_printf(bio_err, "\n");
57 }
58
59 static int apps_startup(void)
60 {
61 #ifdef SIGPIPE
62     signal(SIGPIPE, SIG_IGN);
63 #endif
64
65     /* Set non-default library initialisation settings */
66     if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN
67                           | OPENSSL_INIT_LOAD_CONFIG, NULL))
68         return 0;
69
70     setup_ui_method();
71
72     return 1;
73 }
74
75 static void apps_shutdown(void)
76 {
77     destroy_ui_method();
78 }
79
80 static char *make_config_name(void)
81 {
82     const char *t;
83     size_t len;
84     char *p;
85
86     if ((t = getenv("OPENSSL_CONF")) != NULL)
87         return OPENSSL_strdup(t);
88
89     t = X509_get_default_cert_area();
90     len = strlen(t) + 1 + strlen(OPENSSL_CONF) + 1;
91     p = app_malloc(len, "config filename buffer");
92     strcpy(p, t);
93 #ifndef OPENSSL_SYS_VMS
94     strcat(p, "/");
95 #endif
96     strcat(p, OPENSSL_CONF);
97
98     return p;
99 }
100
101
102 #ifndef OPENSSL_NO_TRACE
103 typedef struct tracedata_st {
104     BIO *bio;
105     unsigned int ingroup:1;
106 } tracedata;
107
108 static size_t internal_trace_cb(const char *buf, size_t cnt,
109                                 int category, int cmd, void *vdata)
110 {
111     int ret = 0;
112     tracedata *trace_data = vdata;
113     char buffer[256], *hex;
114     CRYPTO_THREAD_ID tid;
115
116     switch (cmd) {
117     case OSSL_TRACE_CTRL_BEGIN:
118         if (!ossl_assert(!trace_data->ingroup))
119             return 0;
120         trace_data->ingroup = 1;
121
122         tid = CRYPTO_THREAD_get_current_id();
123         hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid));
124         BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ",
125                      hex == NULL ? "<null>" : hex,
126                      OSSL_trace_get_category_name(category));
127         OPENSSL_free(hex);
128         BIO_set_prefix(trace_data->bio, buffer);
129         break;
130     case OSSL_TRACE_CTRL_WRITE:
131         if (!ossl_assert(trace_data->ingroup))
132             return 0;
133
134         ret = BIO_write(trace_data->bio, buf, cnt);
135         break;
136     case OSSL_TRACE_CTRL_END:
137         if (!ossl_assert(trace_data->ingroup))
138             return 0;
139         trace_data->ingroup = 0;
140
141         BIO_set_prefix(trace_data->bio, NULL);
142
143         break;
144     }
145
146     return ret < 0 ? 0 : ret;
147 }
148
149 DEFINE_STACK_OF(tracedata)
150 static STACK_OF(tracedata) *trace_data_stack;
151
152 static void tracedata_free(tracedata *data)
153 {
154     BIO_free_all(data->bio);
155     OPENSSL_free(data);
156 }
157
158 static STACK_OF(tracedata) *trace_data_stack;
159
160 static void cleanup_trace(void)
161 {
162     sk_tracedata_pop_free(trace_data_stack, tracedata_free);
163 }
164
165 static void setup_trace_category(int category)
166 {
167     BIO *channel;
168     tracedata *trace_data;
169
170     if (OSSL_trace_enabled(category))
171         return;
172
173     channel = BIO_push(BIO_new(BIO_f_prefix()), dup_bio_err(FORMAT_TEXT));
174     trace_data = OPENSSL_zalloc(sizeof(*trace_data));
175
176     if (trace_data == NULL
177         || (trace_data->bio = channel) == NULL
178         || OSSL_trace_set_callback(category, internal_trace_cb,
179                                    trace_data) == 0
180         || sk_tracedata_push(trace_data_stack, trace_data) == 0) {
181
182         fprintf(stderr,
183                 "warning: unable to setup trace callback for category '%s'.\n",
184                 OSSL_trace_get_category_name(category));
185
186         OSSL_trace_set_callback(category, NULL, NULL);
187         BIO_free_all(channel);
188     }
189 }
190
191 static void setup_trace(const char *str)
192 {
193     char *val;
194
195     /*
196      * We add this handler as early as possible to ensure it's executed
197      * as late as possible, i.e. after the TRACE code has done its cleanup
198      * (which happens last in OPENSSL_cleanup).
199      */
200     atexit(cleanup_trace);
201
202     trace_data_stack = sk_tracedata_new_null();
203     val = OPENSSL_strdup(str);
204
205     if (val != NULL) {
206         char *valp = val;
207         char *item;
208
209         for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) {
210             int category = OSSL_trace_get_category_num(item);
211
212             if (category == OSSL_TRACE_CATEGORY_ALL) {
213                 while (++category < OSSL_TRACE_CATEGORY_NUM)
214                     setup_trace_category(category);
215                 break;
216             } else if (category > 0) {
217                 setup_trace_category(category);
218             } else {
219                 fprintf(stderr,
220                         "warning: unknown trace category: '%s'.\n", item);
221             }
222         }
223     }
224
225     OPENSSL_free(val);
226 }
227 #endif /* OPENSSL_NO_TRACE */
228
229 int main(int argc, char *argv[])
230 {
231     FUNCTION f, *fp;
232     LHASH_OF(FUNCTION) *prog = NULL;
233     char *p, *pname;
234     char buf[1024];
235     const char *prompt;
236     ARGS arg;
237     int first, n, i, ret = 0;
238
239     arg.argv = NULL;
240     arg.size = 0;
241
242     /* Set up some of the environment. */
243     default_config_file = make_config_name();
244     bio_in = dup_bio_in(FORMAT_TEXT);
245     bio_out = dup_bio_out(FORMAT_TEXT);
246     bio_err = dup_bio_err(FORMAT_TEXT);
247
248 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
249     argv = copy_argv(&argc, argv);
250 #elif defined(_WIN32)
251     /*
252      * Replace argv[] with UTF-8 encoded strings.
253      */
254     win32_utf8argv(&argc, &argv);
255 #endif
256
257 #ifndef OPENSSL_NO_TRACE
258     setup_trace(getenv("OPENSSL_TRACE"));
259 #endif
260
261     if (getenv("OPENSSL_FIPS")) {
262         BIO_printf(bio_err, "FIPS mode not supported.\n");
263         return 1;
264     }
265
266     if (!apps_startup()) {
267         BIO_printf(bio_err,
268                    "FATAL: Startup failure (dev note: apps_startup() failed)\n");
269         ERR_print_errors(bio_err);
270         ret = 1;
271         goto end;
272     }
273
274     prog = prog_init();
275     if (prog == NULL) {
276         BIO_printf(bio_err,
277                    "FATAL: Startup failure (dev note: prog_init() failed)\n");
278         ERR_print_errors(bio_err);
279         ret = 1;
280         goto end;
281     }
282     pname = opt_progname(argv[0]);
283
284     /* first check the program name */
285     f.name = pname;
286     fp = lh_FUNCTION_retrieve(prog, &f);
287     if (fp != NULL) {
288         argv[0] = pname;
289         if (fp->deprecated_alternative != NULL)
290             warn_deprecated(pname, fp->deprecated_alternative);
291         ret = fp->func(argc, argv);
292         goto end;
293     }
294
295     /* If there is stuff on the command line, run with that. */
296     if (argc != 1) {
297         argc--;
298         argv++;
299         ret = do_cmd(prog, argc, argv);
300         if (ret < 0)
301             ret = 0;
302         goto end;
303     }
304
305     /* ok, lets enter interactive mode */
306     for (;;) {
307         ret = 0;
308         /* Read a line, continue reading if line ends with \ */
309         for (p = buf, n = sizeof(buf), i = 0, first = 1; n > 0; first = 0) {
310             prompt = first ? "OpenSSL> " : "> ";
311             p[0] = '\0';
312 #ifndef READLINE
313             fputs(prompt, stdout);
314             fflush(stdout);
315             if (!fgets(p, n, stdin))
316                 goto end;
317             if (p[0] == '\0')
318                 goto end;
319             i = strlen(p);
320             if (i <= 1)
321                 break;
322             if (p[i - 2] != '\\')
323                 break;
324             i -= 2;
325             p += i;
326             n -= i;
327 #else
328             {
329                 extern char *readline(const char *);
330                 extern void add_history(const char *cp);
331                 char *text;
332
333                 text = readline(prompt);
334                 if (text == NULL)
335                     goto end;
336                 i = strlen(text);
337                 if (i == 0 || i > n)
338                     break;
339                 if (text[i - 1] != '\\') {
340                     p += strlen(strcpy(p, text));
341                     free(text);
342                     add_history(buf);
343                     break;
344                 }
345
346                 text[i - 1] = '\0';
347                 p += strlen(strcpy(p, text));
348                 free(text);
349                 n -= i;
350             }
351 #endif
352         }
353
354         if (!chopup_args(&arg, buf)) {
355             BIO_printf(bio_err, "Can't parse (no memory?)\n");
356             break;
357         }
358
359         ret = do_cmd(prog, arg.argc, arg.argv);
360         if (ret == EXIT_THE_PROGRAM) {
361             ret = 0;
362             goto end;
363         }
364         if (ret != 0)
365             BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
366         (void)BIO_flush(bio_out);
367         (void)BIO_flush(bio_err);
368     }
369     ret = 1;
370  end:
371     OPENSSL_free(default_config_file);
372     lh_FUNCTION_free(prog);
373     OPENSSL_free(arg.argv);
374     app_RAND_write();
375
376     BIO_free(bio_in);
377     BIO_free_all(bio_out);
378     apps_shutdown();
379     BIO_free(bio_err);
380     EXIT(ret);
381 }
382
383 typedef enum HELP_CHOICE {
384     OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP
385 } HELP_CHOICE;
386
387 const OPTIONS help_options[] = {
388     {OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"},
389
390     OPT_SECTION("General"),
391     {"help", OPT_hHELP, '-', "Display this summary"},
392
393     OPT_PARAMETERS(),
394     {"command", 0, 0, "Name of command to display help (optional)"},
395     {NULL}
396 };
397
398
399 int help_main(int argc, char **argv)
400 {
401     FUNCTION *fp;
402     int i, nl;
403     FUNC_TYPE tp;
404     char *prog;
405     HELP_CHOICE o;
406     DISPLAY_COLUMNS dc;
407
408     prog = opt_init(argc, argv, help_options);
409     while ((o = opt_next()) != OPT_hEOF) {
410         switch (o) {
411         case OPT_hERR:
412         case OPT_hEOF:
413             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
414             return 1;
415         case OPT_hHELP:
416             opt_help(help_options);
417             return 0;
418         }
419     }
420
421     if (opt_num_rest() == 1) {
422         char *new_argv[3];
423
424         new_argv[0] = opt_rest()[0];
425         new_argv[1] = "--help";
426         new_argv[2] = NULL;
427         return do_cmd(prog_init(), 2, new_argv);
428     }
429     if (opt_num_rest() != 0) {
430         BIO_printf(bio_err, "Usage: %s\n", prog);
431         return 1;
432     }
433
434     calculate_columns(functions, &dc);
435     BIO_printf(bio_err, "Standard commands");
436     i = 0;
437     tp = FT_none;
438     for (fp = functions; fp->name != NULL; fp++) {
439         nl = 0;
440         if (i++ % dc.columns == 0) {
441             BIO_printf(bio_err, "\n");
442             nl = 1;
443         }
444         if (fp->type != tp) {
445             tp = fp->type;
446             if (!nl)
447                 BIO_printf(bio_err, "\n");
448             if (tp == FT_md) {
449                 i = 1;
450                 BIO_printf(bio_err,
451                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
452             } else if (tp == FT_cipher) {
453                 i = 1;
454                 BIO_printf(bio_err,
455                            "\nCipher commands (see the `enc' command for more details)\n");
456             }
457         }
458         BIO_printf(bio_err, "%-*s", dc.width, fp->name);
459     }
460     BIO_printf(bio_err, "\n\n");
461     return 0;
462 }
463
464 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
465 {
466     FUNCTION f, *fp;
467
468     if (argc <= 0 || argv[0] == NULL)
469         return 0;
470     f.name = argv[0];
471     fp = lh_FUNCTION_retrieve(prog, &f);
472     if (fp == NULL) {
473         if (EVP_get_digestbyname(argv[0])) {
474             f.type = FT_md;
475             f.func = dgst_main;
476             fp = &f;
477         } else if (EVP_get_cipherbyname(argv[0])) {
478             f.type = FT_cipher;
479             f.func = enc_main;
480             fp = &f;
481         }
482     }
483     if (fp != NULL) {
484         if (fp->deprecated_alternative != NULL)
485             warn_deprecated(fp->name, fp->deprecated_alternative);
486         return fp->func(argc, argv);
487     }
488     if ((strncmp(argv[0], "no-", 3)) == 0) {
489         /*
490          * User is asking if foo is unsupported, by trying to "run" the
491          * no-foo command.  Strange.
492          */
493         f.name = argv[0] + 3;
494         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
495             BIO_printf(bio_out, "%s\n", argv[0]);
496             return 0;
497         }
498         BIO_printf(bio_out, "%s\n", argv[0] + 3);
499         return 1;
500     }
501     if (strcmp(argv[0], "quit") == 0 || strcmp(argv[0], "q") == 0 ||
502         strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "bye") == 0)
503         /* Special value to mean "exit the program. */
504         return EXIT_THE_PROGRAM;
505
506     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
507                argv[0]);
508     return 1;
509 }
510
511 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
512 {
513     return strncmp(a->name, b->name, 8);
514 }
515
516 static unsigned long function_hash(const FUNCTION * a)
517 {
518     return OPENSSL_LH_strhash(a->name);
519 }
520
521 static int SortFnByName(const void *_f1, const void *_f2)
522 {
523     const FUNCTION *f1 = _f1;
524     const FUNCTION *f2 = _f2;
525
526     if (f1->type != f2->type)
527         return f1->type - f2->type;
528     return strcmp(f1->name, f2->name);
529 }
530
531 static LHASH_OF(FUNCTION) *prog_init(void)
532 {
533     static LHASH_OF(FUNCTION) *ret = NULL;
534     static int prog_inited = 0;
535     FUNCTION *f;
536     size_t i;
537
538     if (prog_inited)
539         return ret;
540
541     prog_inited = 1;
542
543     /* Sort alphabetically within category. For nicer help displays. */
544     for (i = 0, f = functions; f->name != NULL; ++f, ++i)
545         ;
546     qsort(functions, i, sizeof(*functions), SortFnByName);
547
548     if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL)
549         return NULL;
550
551     for (f = functions; f->name != NULL; f++)
552         (void)lh_FUNCTION_insert(ret, f);
553     return ret;
554 }