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