Standardize apps use of -rand, etc.
[openssl.git] / apps / app_rand.c
1 /*
2  * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 "apps.h"
11 #include <openssl/bio.h>
12 #include <openssl/rand.h>
13 #include <openssl/conf.h>
14
15 static const char *save_rand_file;
16
17 void app_RAND_load_conf(CONF *c, const char *section)
18 {
19     const char *randfile = NCONF_get_string(c, section, "RANDFILE");
20
21     if (randfile == NULL) {
22         ERR_clear_error();
23         return;
24     }
25     if (RAND_load_file(randfile, -1) < 0) {
26         BIO_printf(bio_err, "Can't load %s into RNG\n", randfile);
27         ERR_print_errors(bio_err);
28         return;
29     }
30     if (save_rand_file == NULL)
31         save_rand_file = randfile;
32 }
33
34 static int loadfiles(char *name)
35 {
36     char *p, *n;
37     int last, ret = 1;
38
39     for ( ; ; ) {
40         last = 0;
41         for (p = name; *p != '\0' && *p != LIST_SEPARATOR_CHAR; p++)
42             continue;
43         if (*p == '\0')
44             last = 1;
45         *p = '\0';
46         if (RAND_load_file(name, -1) < 0) {
47             BIO_printf(bio_err, "Can't load %s into RNG\n", name);
48             ERR_print_errors(bio_err);
49             ret = 0;
50         }
51         n = name;
52         if (last)
53             break;
54         name = p + 1;
55         if (*name == '\0')
56             break;
57     }
58     return ret;
59 }
60
61 void app_RAND_write(void)
62 {
63     if (save_rand_file == NULL)
64         return;
65     if (RAND_write_file(save_rand_file) == -1) {
66         BIO_printf(bio_err, "Cannot write random bytes:\n");
67         ERR_print_errors(bio_err);
68     }
69 }
70
71
72 /*
73  * See comments in opt_verify for explanation of this.
74  */
75 enum r_range { OPT_R_ENUM };
76
77 int opt_rand(int opt)
78 {
79     switch ((enum r_range)opt) {
80     case OPT_R__FIRST:
81     case OPT_R__LAST:
82         break;
83     case OPT_R_RAND:
84         return loadfiles(opt_arg());
85         break;
86     case OPT_R_WRITERAND:
87         save_rand_file = opt_arg();
88         break;
89     }
90     return 1;
91 }