Correctly initialise PACKET to zero in the tests to avoid possible problems
[openssl.git] / apps / apps.c
1 /*
2  * Copyright 1995-2018 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 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
11 /*
12  * On VMS, you need to define this to get the declaration of fileno().  The
13  * value 2 is to make sure no function defined in POSIX-2 is left undefined.
14  */
15 # define _POSIX_C_SOURCE 2
16 #endif
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/types.h>
22 #ifndef OPENSSL_NO_POSIX_IO
23 # include <sys/stat.h>
24 # include <fcntl.h>
25 #endif
26 #include <ctype.h>
27 #include <errno.h>
28 #include <openssl/err.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31 #include <openssl/pem.h>
32 #include <openssl/pkcs12.h>
33 #include <openssl/ui.h>
34 #include <openssl/safestack.h>
35 #ifndef OPENSSL_NO_ENGINE
36 # include <openssl/engine.h>
37 #endif
38 #ifndef OPENSSL_NO_RSA
39 # include <openssl/rsa.h>
40 #endif
41 #include <openssl/bn.h>
42 #include <openssl/ssl.h>
43 #include "s_apps.h"
44 #include "apps.h"
45
46 #ifdef _WIN32
47 static int WIN32_rename(const char *from, const char *to);
48 # define rename(from,to) WIN32_rename((from),(to))
49 #endif
50
51 #define PASS_SOURCE_SIZE_MAX 4
52
53 typedef struct {
54     const char *name;
55     unsigned long flag;
56     unsigned long mask;
57 } NAME_EX_TBL;
58
59 static int set_table_opts(unsigned long *flags, const char *arg,
60                           const NAME_EX_TBL * in_tbl);
61 static int set_multi_opts(unsigned long *flags, const char *arg,
62                           const NAME_EX_TBL * in_tbl);
63
64 int app_init(long mesgwin);
65
66 int chopup_args(ARGS *arg, char *buf)
67 {
68     int quoted;
69     char c = '\0', *p = NULL;
70
71     arg->argc = 0;
72     if (arg->size == 0) {
73         arg->size = 20;
74         arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
75     }
76
77     for (p = buf;;) {
78         /* Skip whitespace. */
79         while (*p && isspace(_UC(*p)))
80             p++;
81         if (!*p)
82             break;
83
84         /* The start of something good :-) */
85         if (arg->argc >= arg->size) {
86             char **tmp;
87             arg->size += 20;
88             tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
89             if (tmp == NULL)
90                 return 0;
91             arg->argv = tmp;
92         }
93         quoted = *p == '\'' || *p == '"';
94         if (quoted)
95             c = *p++;
96         arg->argv[arg->argc++] = p;
97
98         /* now look for the end of this */
99         if (quoted) {
100             while (*p && *p != c)
101                 p++;
102             *p++ = '\0';
103         } else {
104             while (*p && !isspace(_UC(*p)))
105                 p++;
106             if (*p)
107                 *p++ = '\0';
108         }
109     }
110     arg->argv[arg->argc] = NULL;
111     return 1;
112 }
113
114 #ifndef APP_INIT
115 int app_init(long mesgwin)
116 {
117     return 1;
118 }
119 #endif
120
121 int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile,
122                              const char *CApath, int noCAfile, int noCApath)
123 {
124     if (CAfile == NULL && CApath == NULL) {
125         if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
126             return 0;
127         if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
128             return 0;
129
130         return 1;
131     }
132     return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
133 }
134
135 #ifndef OPENSSL_NO_CT
136
137 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
138 {
139     if (path == NULL)
140         return SSL_CTX_set_default_ctlog_list_file(ctx);
141
142     return SSL_CTX_set_ctlog_list_file(ctx, path);
143 }
144
145 #endif
146
147 static unsigned long nmflag = 0;
148 static char nmflag_set = 0;
149
150 int set_nameopt(const char *arg)
151 {
152     int ret = set_name_ex(&nmflag, arg);
153
154     if (ret)
155         nmflag_set = 1;
156
157     return ret;
158 }
159
160 unsigned long get_nameopt(void)
161 {
162     return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
163 }
164
165 int dump_cert_text(BIO *out, X509 *x)
166 {
167     print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
168     BIO_puts(out, "\n");
169     print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
170     BIO_puts(out, "\n");
171
172     return 0;
173 }
174
175 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
176 {
177     return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
178 }
179
180
181 static char *app_get_pass(const char *arg, int keepbio);
182
183 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
184 {
185     int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
186
187     if (arg1 != NULL) {
188         *pass1 = app_get_pass(arg1, same);
189         if (*pass1 == NULL)
190             return 0;
191     } else if (pass1 != NULL) {
192         *pass1 = NULL;
193     }
194     if (arg2 != NULL) {
195         *pass2 = app_get_pass(arg2, same ? 2 : 0);
196         if (*pass2 == NULL)
197             return 0;
198     } else if (pass2 != NULL) {
199         *pass2 = NULL;
200     }
201     return 1;
202 }
203
204 static char *app_get_pass(const char *arg, int keepbio)
205 {
206     static BIO *pwdbio = NULL;
207     char *tmp, tpass[APP_PASS_LEN];
208     int i;
209
210     /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
211     if (strncmp(arg, "pass:", 5) == 0)
212         return OPENSSL_strdup(arg + 5);
213     if (strncmp(arg, "env:", 4) == 0) {
214         tmp = getenv(arg + 4);
215         if (tmp == NULL) {
216             BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
217             return NULL;
218         }
219         return OPENSSL_strdup(tmp);
220     }
221     if (!keepbio || pwdbio == NULL) {
222         if (strncmp(arg, "file:", 5) == 0) {
223             pwdbio = BIO_new_file(arg + 5, "r");
224             if (pwdbio == NULL) {
225                 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
226                 return NULL;
227             }
228 #if !defined(_WIN32)
229             /*
230              * Under _WIN32, which covers even Win64 and CE, file
231              * descriptors referenced by BIO_s_fd are not inherited
232              * by child process and therefore below is not an option.
233              * It could have been an option if bss_fd.c was operating
234              * on real Windows descriptors, such as those obtained
235              * with CreateFile.
236              */
237         } else if (strncmp(arg, "fd:", 3) == 0) {
238             BIO *btmp;
239             i = atoi(arg + 3);
240             if (i >= 0)
241                 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
242             if ((i < 0) || !pwdbio) {
243                 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
244                 return NULL;
245             }
246             /*
247              * Can't do BIO_gets on an fd BIO so add a buffering BIO
248              */
249             btmp = BIO_new(BIO_f_buffer());
250             pwdbio = BIO_push(btmp, pwdbio);
251 #endif
252         } else if (strcmp(arg, "stdin") == 0) {
253             pwdbio = dup_bio_in(FORMAT_TEXT);
254             if (!pwdbio) {
255                 BIO_printf(bio_err, "Can't open BIO for stdin\n");
256                 return NULL;
257             }
258         } else {
259             /* argument syntax error; do not reveal too much about arg */
260             tmp = strchr(arg, ':');
261             if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
262                 BIO_printf(bio_err,
263                            "Invalid password argument, missing ':' within the first %d chars\n",
264                            PASS_SOURCE_SIZE_MAX + 1);
265             else
266                 BIO_printf(bio_err,
267                            "Invalid password argument, starting with \"%.*s\"\n",
268                            (int)(tmp - arg + 1), arg);
269             return NULL;
270         }
271     }
272     i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
273     if (keepbio != 1) {
274         BIO_free_all(pwdbio);
275         pwdbio = NULL;
276     }
277     if (i <= 0) {
278         BIO_printf(bio_err, "Error reading password from BIO\n");
279         return NULL;
280     }
281     tmp = strchr(tpass, '\n');
282     if (tmp != NULL)
283         *tmp = 0;
284     return OPENSSL_strdup(tpass);
285 }
286
287 CONF *app_load_config_bio(BIO *in, const char *filename)
288 {
289     long errorline = -1;
290     CONF *conf;
291     int i;
292
293     conf = NCONF_new(NULL);
294     i = NCONF_load_bio(conf, in, &errorline);
295     if (i > 0)
296         return conf;
297
298     if (errorline <= 0) {
299         BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
300     } else {
301         BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
302                    errorline);
303     }
304     if (filename != NULL)
305         BIO_printf(bio_err, "config file \"%s\"\n", filename);
306     else
307         BIO_printf(bio_err, "config input");
308
309     NCONF_free(conf);
310     return NULL;
311 }
312
313 CONF *app_load_config(const char *filename)
314 {
315     BIO *in;
316     CONF *conf;
317
318     in = bio_open_default(filename, 'r', FORMAT_TEXT);
319     if (in == NULL)
320         return NULL;
321
322     conf = app_load_config_bio(in, filename);
323     BIO_free(in);
324     return conf;
325 }
326
327 CONF *app_load_config_quiet(const char *filename)
328 {
329     BIO *in;
330     CONF *conf;
331
332     in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
333     if (in == NULL)
334         return NULL;
335
336     conf = app_load_config_bio(in, filename);
337     BIO_free(in);
338     return conf;
339 }
340
341 int app_load_modules(const CONF *config)
342 {
343     CONF *to_free = NULL;
344
345     if (config == NULL)
346         config = to_free = app_load_config_quiet(default_config_file);
347     if (config == NULL)
348         return 1;
349
350     if (CONF_modules_load(config, NULL, 0) <= 0) {
351         BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
352         ERR_print_errors(bio_err);
353         NCONF_free(to_free);
354         return 0;
355     }
356     NCONF_free(to_free);
357     return 1;
358 }
359
360 int add_oid_section(CONF *conf)
361 {
362     char *p;
363     STACK_OF(CONF_VALUE) *sktmp;
364     CONF_VALUE *cnf;
365     int i;
366
367     if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
368         ERR_clear_error();
369         return 1;
370     }
371     if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
372         BIO_printf(bio_err, "problem loading oid section %s\n", p);
373         return 0;
374     }
375     for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
376         cnf = sk_CONF_VALUE_value(sktmp, i);
377         if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
378             BIO_printf(bio_err, "problem creating object %s=%s\n",
379                        cnf->name, cnf->value);
380             return 0;
381         }
382     }
383     return 1;
384 }
385
386 static int load_pkcs12(BIO *in, const char *desc,
387                        pem_password_cb *pem_cb, PW_CB_DATA *cb_data,
388                        EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
389 {
390     const char *pass;
391     char tpass[PEM_BUFSIZE];
392     int len, ret = 0;
393     PKCS12 *p12;
394     p12 = d2i_PKCS12_bio(in, NULL);
395     if (p12 == NULL) {
396         BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
397         goto die;
398     }
399     /* See if an empty password will do */
400     if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
401         pass = "";
402     } else {
403         if (!pem_cb)
404             pem_cb = (pem_password_cb *)password_callback;
405         len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
406         if (len < 0) {
407             BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
408             goto die;
409         }
410         if (len < PEM_BUFSIZE)
411             tpass[len] = 0;
412         if (!PKCS12_verify_mac(p12, tpass, len)) {
413             BIO_printf(bio_err,
414                        "Mac verify error (wrong password?) in PKCS12 file for %s\n",
415                        desc);
416             goto die;
417         }
418         pass = tpass;
419     }
420     ret = PKCS12_parse(p12, pass, pkey, cert, ca);
421  die:
422     PKCS12_free(p12);
423     return ret;
424 }
425
426 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
427 static int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
428 {
429     char *host = NULL, *port = NULL, *path = NULL;
430     BIO *bio = NULL;
431     OCSP_REQ_CTX *rctx = NULL;
432     int use_ssl, rv = 0;
433     if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
434         goto err;
435     if (use_ssl) {
436         BIO_puts(bio_err, "https not supported\n");
437         goto err;
438     }
439     bio = BIO_new_connect(host);
440     if (!bio || !BIO_set_conn_port(bio, port))
441         goto err;
442     rctx = OCSP_REQ_CTX_new(bio, 1024);
443     if (rctx == NULL)
444         goto err;
445     if (!OCSP_REQ_CTX_http(rctx, "GET", path))
446         goto err;
447     if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
448         goto err;
449     if (pcert) {
450         do {
451             rv = X509_http_nbio(rctx, pcert);
452         } while (rv == -1);
453     } else {
454         do {
455             rv = X509_CRL_http_nbio(rctx, pcrl);
456         } while (rv == -1);
457     }
458
459  err:
460     OPENSSL_free(host);
461     OPENSSL_free(path);
462     OPENSSL_free(port);
463     BIO_free_all(bio);
464     OCSP_REQ_CTX_free(rctx);
465     if (rv != 1) {
466         BIO_printf(bio_err, "Error loading %s from %s\n",
467                    pcert ? "certificate" : "CRL", url);
468         ERR_print_errors(bio_err);
469     }
470     return rv;
471 }
472 #endif
473
474 X509 *load_cert(const char *file, int format, const char *cert_descrip)
475 {
476     X509 *x = NULL;
477     BIO *cert;
478
479     if (format == FORMAT_HTTP) {
480 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
481         load_cert_crl_http(file, &x, NULL);
482 #endif
483         return x;
484     }
485
486     if (file == NULL) {
487         unbuffer(stdin);
488         cert = dup_bio_in(format);
489     } else {
490         cert = bio_open_default(file, 'r', format);
491     }
492     if (cert == NULL)
493         goto end;
494
495     if (format == FORMAT_ASN1) {
496         x = d2i_X509_bio(cert, NULL);
497     } else if (format == FORMAT_PEM) {
498         x = PEM_read_bio_X509_AUX(cert, NULL,
499                                   (pem_password_cb *)password_callback, NULL);
500     } else if (format == FORMAT_PKCS12) {
501         if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
502             goto end;
503     } else {
504         BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
505         goto end;
506     }
507  end:
508     if (x == NULL) {
509         BIO_printf(bio_err, "unable to load certificate\n");
510         ERR_print_errors(bio_err);
511     }
512     BIO_free(cert);
513     return x;
514 }
515
516 X509_CRL *load_crl(const char *infile, int format)
517 {
518     X509_CRL *x = NULL;
519     BIO *in = NULL;
520
521     if (format == FORMAT_HTTP) {
522 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
523         load_cert_crl_http(infile, NULL, &x);
524 #endif
525         return x;
526     }
527
528     in = bio_open_default(infile, 'r', format);
529     if (in == NULL)
530         goto end;
531     if (format == FORMAT_ASN1) {
532         x = d2i_X509_CRL_bio(in, NULL);
533     } else if (format == FORMAT_PEM) {
534         x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
535     } else {
536         BIO_printf(bio_err, "bad input format specified for input crl\n");
537         goto end;
538     }
539     if (x == NULL) {
540         BIO_printf(bio_err, "unable to load CRL\n");
541         ERR_print_errors(bio_err);
542         goto end;
543     }
544
545  end:
546     BIO_free(in);
547     return x;
548 }
549
550 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
551                    const char *pass, ENGINE *e, const char *key_descrip)
552 {
553     BIO *key = NULL;
554     EVP_PKEY *pkey = NULL;
555     PW_CB_DATA cb_data;
556
557     cb_data.password = pass;
558     cb_data.prompt_info = file;
559
560     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
561         BIO_printf(bio_err, "no keyfile specified\n");
562         goto end;
563     }
564     if (format == FORMAT_ENGINE) {
565         if (e == NULL) {
566             BIO_printf(bio_err, "no engine specified\n");
567         } else {
568 #ifndef OPENSSL_NO_ENGINE
569             if (ENGINE_init(e)) {
570                 pkey = ENGINE_load_private_key(e, file,
571                                                (UI_METHOD *)get_ui_method(),
572                                                &cb_data);
573                 ENGINE_finish(e);
574             }
575             if (pkey == NULL) {
576                 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
577                 ERR_print_errors(bio_err);
578             }
579 #else
580             BIO_printf(bio_err, "engines not supported\n");
581 #endif
582         }
583         goto end;
584     }
585     if (file == NULL && maybe_stdin) {
586         unbuffer(stdin);
587         key = dup_bio_in(format);
588     } else {
589         key = bio_open_default(file, 'r', format);
590     }
591     if (key == NULL)
592         goto end;
593     if (format == FORMAT_ASN1) {
594         pkey = d2i_PrivateKey_bio(key, NULL);
595     } else if (format == FORMAT_PEM) {
596         pkey = PEM_read_bio_PrivateKey(key, NULL, wrap_password_callback, &cb_data);
597     } else if (format == FORMAT_PKCS12) {
598         if (!load_pkcs12(key, key_descrip, wrap_password_callback, &cb_data,
599                          &pkey, NULL, NULL))
600             goto end;
601 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
602     } else if (format == FORMAT_MSBLOB) {
603         pkey = b2i_PrivateKey_bio(key);
604     } else if (format == FORMAT_PVK) {
605         pkey = b2i_PVK_bio(key, wrap_password_callback, &cb_data);
606 #endif
607     } else {
608         BIO_printf(bio_err, "bad input format specified for key file\n");
609         goto end;
610     }
611  end:
612     BIO_free(key);
613     if (pkey == NULL) {
614         BIO_printf(bio_err, "unable to load %s\n", key_descrip);
615         ERR_print_errors(bio_err);
616     }
617     return pkey;
618 }
619
620 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
621                       const char *pass, ENGINE *e, const char *key_descrip)
622 {
623     BIO *key = NULL;
624     EVP_PKEY *pkey = NULL;
625     PW_CB_DATA cb_data;
626
627     cb_data.password = pass;
628     cb_data.prompt_info = file;
629
630     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
631         BIO_printf(bio_err, "no keyfile specified\n");
632         goto end;
633     }
634     if (format == FORMAT_ENGINE) {
635         if (e == NULL) {
636             BIO_printf(bio_err, "no engine specified\n");
637         } else {
638 #ifndef OPENSSL_NO_ENGINE
639             pkey = ENGINE_load_public_key(e, file, (UI_METHOD *)get_ui_method(),
640                                           &cb_data);
641             if (pkey == NULL) {
642                 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
643                 ERR_print_errors(bio_err);
644             }
645 #else
646             BIO_printf(bio_err, "engines not supported\n");
647 #endif
648         }
649         goto end;
650     }
651     if (file == NULL && maybe_stdin) {
652         unbuffer(stdin);
653         key = dup_bio_in(format);
654     } else {
655         key = bio_open_default(file, 'r', format);
656     }
657     if (key == NULL)
658         goto end;
659     if (format == FORMAT_ASN1) {
660         pkey = d2i_PUBKEY_bio(key, NULL);
661     } else if (format == FORMAT_ASN1RSA) {
662 #ifndef OPENSSL_NO_RSA
663         RSA *rsa;
664         rsa = d2i_RSAPublicKey_bio(key, NULL);
665         if (rsa) {
666             pkey = EVP_PKEY_new();
667             if (pkey != NULL)
668                 EVP_PKEY_set1_RSA(pkey, rsa);
669             RSA_free(rsa);
670         } else
671 #else
672         BIO_printf(bio_err, "RSA keys not supported\n");
673 #endif
674             pkey = NULL;
675     } else if (format == FORMAT_PEMRSA) {
676 #ifndef OPENSSL_NO_RSA
677         RSA *rsa;
678         rsa = PEM_read_bio_RSAPublicKey(key, NULL,
679                                         (pem_password_cb *)password_callback,
680                                         &cb_data);
681         if (rsa != NULL) {
682             pkey = EVP_PKEY_new();
683             if (pkey != NULL)
684                 EVP_PKEY_set1_RSA(pkey, rsa);
685             RSA_free(rsa);
686         } else
687 #else
688         BIO_printf(bio_err, "RSA keys not supported\n");
689 #endif
690             pkey = NULL;
691     } else if (format == FORMAT_PEM) {
692         pkey = PEM_read_bio_PUBKEY(key, NULL,
693                                    (pem_password_cb *)password_callback,
694                                    &cb_data);
695 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
696     } else if (format == FORMAT_MSBLOB) {
697         pkey = b2i_PublicKey_bio(key);
698 #endif
699     }
700  end:
701     BIO_free(key);
702     if (pkey == NULL)
703         BIO_printf(bio_err, "unable to load %s\n", key_descrip);
704     return pkey;
705 }
706
707 static int load_certs_crls(const char *file, int format,
708                            const char *pass, const char *desc,
709                            STACK_OF(X509) **pcerts,
710                            STACK_OF(X509_CRL) **pcrls)
711 {
712     int i;
713     BIO *bio;
714     STACK_OF(X509_INFO) *xis = NULL;
715     X509_INFO *xi;
716     PW_CB_DATA cb_data;
717     int rv = 0;
718
719     cb_data.password = pass;
720     cb_data.prompt_info = file;
721
722     if (format != FORMAT_PEM) {
723         BIO_printf(bio_err, "bad input format specified for %s\n", desc);
724         return 0;
725     }
726
727     bio = bio_open_default(file, 'r', FORMAT_PEM);
728     if (bio == NULL)
729         return 0;
730
731     xis = PEM_X509_INFO_read_bio(bio, NULL,
732                                  (pem_password_cb *)password_callback,
733                                  &cb_data);
734
735     BIO_free(bio);
736
737     if (pcerts != NULL && *pcerts == NULL) {
738         *pcerts = sk_X509_new_null();
739         if (*pcerts == NULL)
740             goto end;
741     }
742
743     if (pcrls != NULL && *pcrls == NULL) {
744         *pcrls = sk_X509_CRL_new_null();
745         if (*pcrls == NULL)
746             goto end;
747     }
748
749     for (i = 0; i < sk_X509_INFO_num(xis); i++) {
750         xi = sk_X509_INFO_value(xis, i);
751         if (xi->x509 != NULL && pcerts != NULL) {
752             if (!sk_X509_push(*pcerts, xi->x509))
753                 goto end;
754             xi->x509 = NULL;
755         }
756         if (xi->crl != NULL && pcrls != NULL) {
757             if (!sk_X509_CRL_push(*pcrls, xi->crl))
758                 goto end;
759             xi->crl = NULL;
760         }
761     }
762
763     if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
764         rv = 1;
765
766     if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
767         rv = 1;
768
769  end:
770
771     sk_X509_INFO_pop_free(xis, X509_INFO_free);
772
773     if (rv == 0) {
774         if (pcerts != NULL) {
775             sk_X509_pop_free(*pcerts, X509_free);
776             *pcerts = NULL;
777         }
778         if (pcrls != NULL) {
779             sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
780             *pcrls = NULL;
781         }
782         BIO_printf(bio_err, "unable to load %s\n",
783                    pcerts ? "certificates" : "CRLs");
784         ERR_print_errors(bio_err);
785     }
786     return rv;
787 }
788
789 void* app_malloc(int sz, const char *what)
790 {
791     void *vp = OPENSSL_malloc(sz);
792
793     if (vp == NULL) {
794         BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
795                 opt_getprog(), sz, what);
796         ERR_print_errors(bio_err);
797         exit(1);
798     }
799     return vp;
800 }
801
802 /*
803  * Initialize or extend, if *certs != NULL, a certificate stack.
804  */
805 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
806                const char *pass, const char *desc)
807 {
808     return load_certs_crls(file, format, pass, desc, certs, NULL);
809 }
810
811 /*
812  * Initialize or extend, if *crls != NULL, a certificate stack.
813  */
814 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
815               const char *pass, const char *desc)
816 {
817     return load_certs_crls(file, format, pass, desc, NULL, crls);
818 }
819
820 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
821 /* Return error for unknown extensions */
822 #define X509V3_EXT_DEFAULT              0
823 /* Print error for unknown extensions */
824 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
825 /* ASN1 parse unknown extensions */
826 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
827 /* BIO_dump unknown extensions */
828 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
829
830 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
831                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
832
833 int set_cert_ex(unsigned long *flags, const char *arg)
834 {
835     static const NAME_EX_TBL cert_tbl[] = {
836         {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
837         {"ca_default", X509_FLAG_CA, 0xffffffffl},
838         {"no_header", X509_FLAG_NO_HEADER, 0},
839         {"no_version", X509_FLAG_NO_VERSION, 0},
840         {"no_serial", X509_FLAG_NO_SERIAL, 0},
841         {"no_signame", X509_FLAG_NO_SIGNAME, 0},
842         {"no_validity", X509_FLAG_NO_VALIDITY, 0},
843         {"no_subject", X509_FLAG_NO_SUBJECT, 0},
844         {"no_issuer", X509_FLAG_NO_ISSUER, 0},
845         {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
846         {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
847         {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
848         {"no_aux", X509_FLAG_NO_AUX, 0},
849         {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
850         {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
851         {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
852         {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
853         {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
854         {NULL, 0, 0}
855     };
856     return set_multi_opts(flags, arg, cert_tbl);
857 }
858
859 int set_name_ex(unsigned long *flags, const char *arg)
860 {
861     static const NAME_EX_TBL ex_tbl[] = {
862         {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
863         {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
864         {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
865         {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
866         {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
867         {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
868         {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
869         {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
870         {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
871         {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
872         {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
873         {"compat", XN_FLAG_COMPAT, 0xffffffffL},
874         {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
875         {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
876         {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
877         {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
878         {"dn_rev", XN_FLAG_DN_REV, 0},
879         {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
880         {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
881         {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
882         {"align", XN_FLAG_FN_ALIGN, 0},
883         {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
884         {"space_eq", XN_FLAG_SPC_EQ, 0},
885         {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
886         {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
887         {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
888         {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
889         {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
890         {NULL, 0, 0}
891     };
892     if (set_multi_opts(flags, arg, ex_tbl) == 0)
893         return 0;
894     if (*flags != XN_FLAG_COMPAT
895         && (*flags & XN_FLAG_SEP_MASK) == 0)
896         *flags |= XN_FLAG_SEP_CPLUS_SPC;
897     return 1;
898 }
899
900 int set_ext_copy(int *copy_type, const char *arg)
901 {
902     if (strcasecmp(arg, "none") == 0)
903         *copy_type = EXT_COPY_NONE;
904     else if (strcasecmp(arg, "copy") == 0)
905         *copy_type = EXT_COPY_ADD;
906     else if (strcasecmp(arg, "copyall") == 0)
907         *copy_type = EXT_COPY_ALL;
908     else
909         return 0;
910     return 1;
911 }
912
913 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
914 {
915     STACK_OF(X509_EXTENSION) *exts = NULL;
916     X509_EXTENSION *ext, *tmpext;
917     ASN1_OBJECT *obj;
918     int i, idx, ret = 0;
919     if (!x || !req || (copy_type == EXT_COPY_NONE))
920         return 1;
921     exts = X509_REQ_get_extensions(req);
922
923     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
924         ext = sk_X509_EXTENSION_value(exts, i);
925         obj = X509_EXTENSION_get_object(ext);
926         idx = X509_get_ext_by_OBJ(x, obj, -1);
927         /* Does extension exist? */
928         if (idx != -1) {
929             /* If normal copy don't override existing extension */
930             if (copy_type == EXT_COPY_ADD)
931                 continue;
932             /* Delete all extensions of same type */
933             do {
934                 tmpext = X509_get_ext(x, idx);
935                 X509_delete_ext(x, idx);
936                 X509_EXTENSION_free(tmpext);
937                 idx = X509_get_ext_by_OBJ(x, obj, -1);
938             } while (idx != -1);
939         }
940         if (!X509_add_ext(x, ext, -1))
941             goto end;
942     }
943
944     ret = 1;
945
946  end:
947
948     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
949
950     return ret;
951 }
952
953 static int set_multi_opts(unsigned long *flags, const char *arg,
954                           const NAME_EX_TBL * in_tbl)
955 {
956     STACK_OF(CONF_VALUE) *vals;
957     CONF_VALUE *val;
958     int i, ret = 1;
959     if (!arg)
960         return 0;
961     vals = X509V3_parse_list(arg);
962     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
963         val = sk_CONF_VALUE_value(vals, i);
964         if (!set_table_opts(flags, val->name, in_tbl))
965             ret = 0;
966     }
967     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
968     return ret;
969 }
970
971 static int set_table_opts(unsigned long *flags, const char *arg,
972                           const NAME_EX_TBL * in_tbl)
973 {
974     char c;
975     const NAME_EX_TBL *ptbl;
976     c = arg[0];
977
978     if (c == '-') {
979         c = 0;
980         arg++;
981     } else if (c == '+') {
982         c = 1;
983         arg++;
984     } else {
985         c = 1;
986     }
987
988     for (ptbl = in_tbl; ptbl->name; ptbl++) {
989         if (strcasecmp(arg, ptbl->name) == 0) {
990             *flags &= ~ptbl->mask;
991             if (c)
992                 *flags |= ptbl->flag;
993             else
994                 *flags &= ~ptbl->flag;
995             return 1;
996         }
997     }
998     return 0;
999 }
1000
1001 void print_name(BIO *out, const char *title, X509_NAME *nm,
1002                 unsigned long lflags)
1003 {
1004     char *buf;
1005     char mline = 0;
1006     int indent = 0;
1007
1008     if (title)
1009         BIO_puts(out, title);
1010     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1011         mline = 1;
1012         indent = 4;
1013     }
1014     if (lflags == XN_FLAG_COMPAT) {
1015         buf = X509_NAME_oneline(nm, 0, 0);
1016         BIO_puts(out, buf);
1017         BIO_puts(out, "\n");
1018         OPENSSL_free(buf);
1019     } else {
1020         if (mline)
1021             BIO_puts(out, "\n");
1022         X509_NAME_print_ex(out, nm, indent, lflags);
1023         BIO_puts(out, "\n");
1024     }
1025 }
1026
1027 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1028                       int len, unsigned char *buffer)
1029 {
1030     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
1031     if (BN_is_zero(in)) {
1032         BIO_printf(out, "\n        0x00");
1033     } else {
1034         int i, l;
1035
1036         l = BN_bn2bin(in, buffer);
1037         for (i = 0; i < l; i++) {
1038             BIO_printf(out, (i % 10) == 0 ? "\n        " : " ");
1039             if (i < l - 1)
1040                 BIO_printf(out, "0x%02X,", buffer[i]);
1041             else
1042                 BIO_printf(out, "0x%02X", buffer[i]);
1043         }
1044     }
1045     BIO_printf(out, "\n    };\n");
1046 }
1047
1048 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1049 {
1050     int i;
1051
1052     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1053     for (i = 0; i < len; i++) {
1054         if ((i % 10) == 0)
1055             BIO_printf(out, "\n    ");
1056         if (i < len - 1)
1057             BIO_printf(out, "0x%02X, ", d[i]);
1058         else
1059             BIO_printf(out, "0x%02X", d[i]);
1060     }
1061     BIO_printf(out, "\n};\n");
1062 }
1063
1064 X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, int noCApath)
1065 {
1066     X509_STORE *store = X509_STORE_new();
1067     X509_LOOKUP *lookup;
1068
1069     if (store == NULL)
1070         goto end;
1071
1072     if (CAfile != NULL || !noCAfile) {
1073         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1074         if (lookup == NULL)
1075             goto end;
1076         if (CAfile) {
1077             if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1078                 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1079                 goto end;
1080             }
1081         } else {
1082             X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1083         }
1084     }
1085
1086     if (CApath != NULL || !noCApath) {
1087         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1088         if (lookup == NULL)
1089             goto end;
1090         if (CApath) {
1091             if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1092                 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1093                 goto end;
1094             }
1095         } else {
1096             X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1097         }
1098     }
1099
1100     ERR_clear_error();
1101     return store;
1102  end:
1103     X509_STORE_free(store);
1104     return NULL;
1105 }
1106
1107 #ifndef OPENSSL_NO_ENGINE
1108 /* Try to load an engine in a shareable library */
1109 static ENGINE *try_load_engine(const char *engine)
1110 {
1111     ENGINE *e = ENGINE_by_id("dynamic");
1112     if (e) {
1113         if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1114             || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1115             ENGINE_free(e);
1116             e = NULL;
1117         }
1118     }
1119     return e;
1120 }
1121 #endif
1122
1123 ENGINE *setup_engine(const char *engine, int debug)
1124 {
1125     ENGINE *e = NULL;
1126
1127 #ifndef OPENSSL_NO_ENGINE
1128     if (engine != NULL) {
1129         if (strcmp(engine, "auto") == 0) {
1130             BIO_printf(bio_err, "enabling auto ENGINE support\n");
1131             ENGINE_register_all_complete();
1132             return NULL;
1133         }
1134         if ((e = ENGINE_by_id(engine)) == NULL
1135             && (e = try_load_engine(engine)) == NULL) {
1136             BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1137             ERR_print_errors(bio_err);
1138             return NULL;
1139         }
1140         if (debug) {
1141             ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1142         }
1143         ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, (void *)get_ui_method(),
1144                         0, 1);
1145         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1146             BIO_printf(bio_err, "can't use that engine\n");
1147             ERR_print_errors(bio_err);
1148             ENGINE_free(e);
1149             return NULL;
1150         }
1151
1152         BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1153     }
1154 #endif
1155     return e;
1156 }
1157
1158 void release_engine(ENGINE *e)
1159 {
1160 #ifndef OPENSSL_NO_ENGINE
1161     if (e != NULL)
1162         /* Free our "structural" reference. */
1163         ENGINE_free(e);
1164 #endif
1165 }
1166
1167 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1168 {
1169     const char *n;
1170
1171     n = a[DB_serial];
1172     while (*n == '0')
1173         n++;
1174     return OPENSSL_LH_strhash(n);
1175 }
1176
1177 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1178                             const OPENSSL_CSTRING *b)
1179 {
1180     const char *aa, *bb;
1181
1182     for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1183     for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1184     return strcmp(aa, bb);
1185 }
1186
1187 static int index_name_qual(char **a)
1188 {
1189     return (a[0][0] == 'V');
1190 }
1191
1192 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1193 {
1194     return OPENSSL_LH_strhash(a[DB_name]);
1195 }
1196
1197 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1198 {
1199     return strcmp(a[DB_name], b[DB_name]);
1200 }
1201
1202 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1203 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1204 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1205 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1206 #undef BSIZE
1207 #define BSIZE 256
1208 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1209 {
1210     BIO *in = NULL;
1211     BIGNUM *ret = NULL;
1212     char buf[1024];
1213     ASN1_INTEGER *ai = NULL;
1214
1215     ai = ASN1_INTEGER_new();
1216     if (ai == NULL)
1217         goto err;
1218
1219     in = BIO_new_file(serialfile, "r");
1220     if (in == NULL) {
1221         if (!create) {
1222             perror(serialfile);
1223             goto err;
1224         }
1225         ERR_clear_error();
1226         ret = BN_new();
1227         if (ret == NULL || !rand_serial(ret, ai))
1228             BIO_printf(bio_err, "Out of memory\n");
1229     } else {
1230         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1231             BIO_printf(bio_err, "unable to load number from %s\n",
1232                        serialfile);
1233             goto err;
1234         }
1235         ret = ASN1_INTEGER_to_BN(ai, NULL);
1236         if (ret == NULL) {
1237             BIO_printf(bio_err,
1238                        "error converting number from bin to BIGNUM\n");
1239             goto err;
1240         }
1241     }
1242
1243     if (ret && retai) {
1244         *retai = ai;
1245         ai = NULL;
1246     }
1247  err:
1248     BIO_free(in);
1249     ASN1_INTEGER_free(ai);
1250     return ret;
1251 }
1252
1253 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1254                 ASN1_INTEGER **retai)
1255 {
1256     char buf[1][BSIZE];
1257     BIO *out = NULL;
1258     int ret = 0;
1259     ASN1_INTEGER *ai = NULL;
1260     int j;
1261
1262     if (suffix == NULL)
1263         j = strlen(serialfile);
1264     else
1265         j = strlen(serialfile) + strlen(suffix) + 1;
1266     if (j >= BSIZE) {
1267         BIO_printf(bio_err, "file name too long\n");
1268         goto err;
1269     }
1270
1271     if (suffix == NULL)
1272         OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1273     else {
1274 #ifndef OPENSSL_SYS_VMS
1275         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1276 #else
1277         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1278 #endif
1279     }
1280     out = BIO_new_file(buf[0], "w");
1281     if (out == NULL) {
1282         ERR_print_errors(bio_err);
1283         goto err;
1284     }
1285
1286     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1287         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1288         goto err;
1289     }
1290     i2a_ASN1_INTEGER(out, ai);
1291     BIO_puts(out, "\n");
1292     ret = 1;
1293     if (retai) {
1294         *retai = ai;
1295         ai = NULL;
1296     }
1297  err:
1298     BIO_free_all(out);
1299     ASN1_INTEGER_free(ai);
1300     return ret;
1301 }
1302
1303 int rotate_serial(const char *serialfile, const char *new_suffix,
1304                   const char *old_suffix)
1305 {
1306     char buf[2][BSIZE];
1307     int i, j;
1308
1309     i = strlen(serialfile) + strlen(old_suffix);
1310     j = strlen(serialfile) + strlen(new_suffix);
1311     if (i > j)
1312         j = i;
1313     if (j + 1 >= BSIZE) {
1314         BIO_printf(bio_err, "file name too long\n");
1315         goto err;
1316     }
1317 #ifndef OPENSSL_SYS_VMS
1318     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1319     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1320 #else
1321     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1322     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1323 #endif
1324     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1325 #ifdef ENOTDIR
1326         && errno != ENOTDIR
1327 #endif
1328         ) {
1329         BIO_printf(bio_err,
1330                    "unable to rename %s to %s\n", serialfile, buf[1]);
1331         perror("reason");
1332         goto err;
1333     }
1334     if (rename(buf[0], serialfile) < 0) {
1335         BIO_printf(bio_err,
1336                    "unable to rename %s to %s\n", buf[0], serialfile);
1337         perror("reason");
1338         rename(buf[1], serialfile);
1339         goto err;
1340     }
1341     return 1;
1342  err:
1343     return 0;
1344 }
1345
1346 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1347 {
1348     BIGNUM *btmp;
1349     int ret = 0;
1350
1351     btmp = b == NULL ? BN_new() : b;
1352     if (btmp == NULL)
1353         return 0;
1354
1355     if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1356         goto error;
1357     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1358         goto error;
1359
1360     ret = 1;
1361
1362  error:
1363
1364     if (btmp != b)
1365         BN_free(btmp);
1366
1367     return ret;
1368 }
1369
1370 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1371 {
1372     CA_DB *retdb = NULL;
1373     TXT_DB *tmpdb = NULL;
1374     BIO *in;
1375     CONF *dbattr_conf = NULL;
1376     char buf[BSIZE];
1377 #ifndef OPENSSL_NO_POSIX_IO
1378     FILE *dbfp;
1379     struct stat dbst;
1380 #endif
1381
1382     in = BIO_new_file(dbfile, "r");
1383     if (in == NULL) {
1384         ERR_print_errors(bio_err);
1385         goto err;
1386     }
1387
1388 #ifndef OPENSSL_NO_POSIX_IO
1389     BIO_get_fp(in, &dbfp);
1390     if (fstat(fileno(dbfp), &dbst) == -1) {
1391         SYSerr(SYS_F_FSTAT, errno);
1392         ERR_add_error_data(3, "fstat('", dbfile, "')");
1393         ERR_print_errors(bio_err);
1394         goto err;
1395     }
1396 #endif
1397
1398     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1399         goto err;
1400
1401 #ifndef OPENSSL_SYS_VMS
1402     BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1403 #else
1404     BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1405 #endif
1406     dbattr_conf = app_load_config_quiet(buf);
1407
1408     retdb = app_malloc(sizeof(*retdb), "new DB");
1409     retdb->db = tmpdb;
1410     tmpdb = NULL;
1411     if (db_attr)
1412         retdb->attributes = *db_attr;
1413     else {
1414         retdb->attributes.unique_subject = 1;
1415     }
1416
1417     if (dbattr_conf) {
1418         char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1419         if (p) {
1420             retdb->attributes.unique_subject = parse_yesno(p, 1);
1421         }
1422     }
1423
1424     retdb->dbfname = OPENSSL_strdup(dbfile);
1425 #ifndef OPENSSL_NO_POSIX_IO
1426     retdb->dbst = dbst;
1427 #endif
1428
1429  err:
1430     NCONF_free(dbattr_conf);
1431     TXT_DB_free(tmpdb);
1432     BIO_free_all(in);
1433     return retdb;
1434 }
1435
1436 /*
1437  * Returns > 0 on success, <= 0 on error
1438  */
1439 int index_index(CA_DB *db)
1440 {
1441     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1442                              LHASH_HASH_FN(index_serial),
1443                              LHASH_COMP_FN(index_serial))) {
1444         BIO_printf(bio_err,
1445                    "error creating serial number index:(%ld,%ld,%ld)\n",
1446                    db->db->error, db->db->arg1, db->db->arg2);
1447         return 0;
1448     }
1449
1450     if (db->attributes.unique_subject
1451         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1452                                 LHASH_HASH_FN(index_name),
1453                                 LHASH_COMP_FN(index_name))) {
1454         BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1455                    db->db->error, db->db->arg1, db->db->arg2);
1456         return 0;
1457     }
1458     return 1;
1459 }
1460
1461 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1462 {
1463     char buf[3][BSIZE];
1464     BIO *out;
1465     int j;
1466
1467     j = strlen(dbfile) + strlen(suffix);
1468     if (j + 6 >= BSIZE) {
1469         BIO_printf(bio_err, "file name too long\n");
1470         goto err;
1471     }
1472 #ifndef OPENSSL_SYS_VMS
1473     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1474     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1475     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1476 #else
1477     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1478     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1479     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1480 #endif
1481     out = BIO_new_file(buf[0], "w");
1482     if (out == NULL) {
1483         perror(dbfile);
1484         BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1485         goto err;
1486     }
1487     j = TXT_DB_write(out, db->db);
1488     BIO_free(out);
1489     if (j <= 0)
1490         goto err;
1491
1492     out = BIO_new_file(buf[1], "w");
1493     if (out == NULL) {
1494         perror(buf[2]);
1495         BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1496         goto err;
1497     }
1498     BIO_printf(out, "unique_subject = %s\n",
1499                db->attributes.unique_subject ? "yes" : "no");
1500     BIO_free(out);
1501
1502     return 1;
1503  err:
1504     return 0;
1505 }
1506
1507 int rotate_index(const char *dbfile, const char *new_suffix,
1508                  const char *old_suffix)
1509 {
1510     char buf[5][BSIZE];
1511     int i, j;
1512
1513     i = strlen(dbfile) + strlen(old_suffix);
1514     j = strlen(dbfile) + strlen(new_suffix);
1515     if (i > j)
1516         j = i;
1517     if (j + 6 >= BSIZE) {
1518         BIO_printf(bio_err, "file name too long\n");
1519         goto err;
1520     }
1521 #ifndef OPENSSL_SYS_VMS
1522     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1523     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1524     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1525     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1526     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1527 #else
1528     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1529     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1530     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1531     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1532     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1533 #endif
1534     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1535 #ifdef ENOTDIR
1536         && errno != ENOTDIR
1537 #endif
1538         ) {
1539         BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1540         perror("reason");
1541         goto err;
1542     }
1543     if (rename(buf[0], dbfile) < 0) {
1544         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1545         perror("reason");
1546         rename(buf[1], dbfile);
1547         goto err;
1548     }
1549     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1550 #ifdef ENOTDIR
1551         && errno != ENOTDIR
1552 #endif
1553         ) {
1554         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1555         perror("reason");
1556         rename(dbfile, buf[0]);
1557         rename(buf[1], dbfile);
1558         goto err;
1559     }
1560     if (rename(buf[2], buf[4]) < 0) {
1561         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1562         perror("reason");
1563         rename(buf[3], buf[4]);
1564         rename(dbfile, buf[0]);
1565         rename(buf[1], dbfile);
1566         goto err;
1567     }
1568     return 1;
1569  err:
1570     return 0;
1571 }
1572
1573 void free_index(CA_DB *db)
1574 {
1575     if (db) {
1576         TXT_DB_free(db->db);
1577         OPENSSL_free(db->dbfname);
1578         OPENSSL_free(db);
1579     }
1580 }
1581
1582 int parse_yesno(const char *str, int def)
1583 {
1584     if (str) {
1585         switch (*str) {
1586         case 'f':              /* false */
1587         case 'F':              /* FALSE */
1588         case 'n':              /* no */
1589         case 'N':              /* NO */
1590         case '0':              /* 0 */
1591             return 0;
1592         case 't':              /* true */
1593         case 'T':              /* TRUE */
1594         case 'y':              /* yes */
1595         case 'Y':              /* YES */
1596         case '1':              /* 1 */
1597             return 1;
1598         }
1599     }
1600     return def;
1601 }
1602
1603 /*
1604  * name is expected to be in the format /type0=value0/type1=value1/type2=...
1605  * where characters may be escaped by \
1606  */
1607 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1608 {
1609     int nextismulti = 0;
1610     char *work;
1611     X509_NAME *n;
1612
1613     if (*cp++ != '/') {
1614         BIO_printf(bio_err,
1615                    "name is expected to be in the format "
1616                    "/type0=value0/type1=value1/type2=... where characters may "
1617                    "be escaped by \\. This name is not in that format: '%s'\n",
1618                    --cp);
1619         return NULL;
1620     }
1621
1622     n = X509_NAME_new();
1623     if (n == NULL)
1624         return NULL;
1625     work = OPENSSL_strdup(cp);
1626     if (work == NULL) {
1627         BIO_printf(bio_err, "%s: Error copying name input\n", opt_getprog());
1628         goto err;
1629     }
1630
1631     while (*cp) {
1632         char *bp = work;
1633         char *typestr = bp;
1634         unsigned char *valstr;
1635         int nid;
1636         int ismulti = nextismulti;
1637         nextismulti = 0;
1638
1639         /* Collect the type */
1640         while (*cp && *cp != '=')
1641             *bp++ = *cp++;
1642         if (*cp == '\0') {
1643             BIO_printf(bio_err,
1644                     "%s: Hit end of string before finding the '='\n",
1645                     opt_getprog());
1646             goto err;
1647         }
1648         *bp++ = '\0';
1649         ++cp;
1650
1651         /* Collect the value. */
1652         valstr = (unsigned char *)bp;
1653         for (; *cp && *cp != '/'; *bp++ = *cp++) {
1654             if (canmulti && *cp == '+') {
1655                 nextismulti = 1;
1656                 break;
1657             }
1658             if (*cp == '\\' && *++cp == '\0') {
1659                 BIO_printf(bio_err,
1660                            "%s: escape character at end of string\n",
1661                            opt_getprog());
1662                 goto err;
1663             }
1664         }
1665         *bp++ = '\0';
1666
1667         /* If not at EOS (must be + or /), move forward. */
1668         if (*cp)
1669             ++cp;
1670
1671         /* Parse */
1672         nid = OBJ_txt2nid(typestr);
1673         if (nid == NID_undef) {
1674             BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1675                        opt_getprog(), typestr);
1676             continue;
1677         }
1678         if (*valstr == '\0') {
1679             BIO_printf(bio_err,
1680                        "%s: No value provided for Subject Attribute %s, skipped\n",
1681                        opt_getprog(), typestr);
1682             continue;
1683         }
1684         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1685                                         valstr, strlen((char *)valstr),
1686                                         -1, ismulti ? -1 : 0)) {
1687             BIO_printf(bio_err, "%s: Error adding name attribute \"/%s=%s\"\n",
1688                        opt_getprog(), typestr ,valstr);
1689             goto err;
1690         }
1691     }
1692
1693     OPENSSL_free(work);
1694     return n;
1695
1696  err:
1697     X509_NAME_free(n);
1698     OPENSSL_free(work);
1699     return NULL;
1700 }
1701
1702 /*
1703  * Read whole contents of a BIO into an allocated memory buffer and return
1704  * it.
1705  */
1706
1707 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1708 {
1709     BIO *mem;
1710     int len, ret;
1711     unsigned char tbuf[1024];
1712
1713     mem = BIO_new(BIO_s_mem());
1714     if (mem == NULL)
1715         return -1;
1716     for (;;) {
1717         if ((maxlen != -1) && maxlen < 1024)
1718             len = maxlen;
1719         else
1720             len = 1024;
1721         len = BIO_read(in, tbuf, len);
1722         if (len < 0) {
1723             BIO_free(mem);
1724             return -1;
1725         }
1726         if (len == 0)
1727             break;
1728         if (BIO_write(mem, tbuf, len) != len) {
1729             BIO_free(mem);
1730             return -1;
1731         }
1732         maxlen -= len;
1733
1734         if (maxlen == 0)
1735             break;
1736     }
1737     ret = BIO_get_mem_data(mem, (char **)out);
1738     BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1739     BIO_free(mem);
1740     return ret;
1741 }
1742
1743 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1744 {
1745     int rv;
1746     char *stmp, *vtmp = NULL;
1747     stmp = OPENSSL_strdup(value);
1748     if (!stmp)
1749         return -1;
1750     vtmp = strchr(stmp, ':');
1751     if (vtmp) {
1752         *vtmp = 0;
1753         vtmp++;
1754     }
1755     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1756     OPENSSL_free(stmp);
1757     return rv;
1758 }
1759
1760 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1761 {
1762     X509_POLICY_NODE *node;
1763     int i;
1764
1765     BIO_printf(bio_err, "%s Policies:", name);
1766     if (nodes) {
1767         BIO_puts(bio_err, "\n");
1768         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1769             node = sk_X509_POLICY_NODE_value(nodes, i);
1770             X509_POLICY_NODE_print(bio_err, node, 2);
1771         }
1772     } else {
1773         BIO_puts(bio_err, " <empty>\n");
1774     }
1775 }
1776
1777 void policies_print(X509_STORE_CTX *ctx)
1778 {
1779     X509_POLICY_TREE *tree;
1780     int explicit_policy;
1781     tree = X509_STORE_CTX_get0_policy_tree(ctx);
1782     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1783
1784     BIO_printf(bio_err, "Require explicit Policy: %s\n",
1785                explicit_policy ? "True" : "False");
1786
1787     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1788     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1789 }
1790
1791 /*-
1792  * next_protos_parse parses a comma separated list of strings into a string
1793  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1794  *   outlen: (output) set to the length of the resulting buffer on success.
1795  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
1796  *   in: a NUL terminated string like "abc,def,ghi"
1797  *
1798  *   returns: a malloc'd buffer or NULL on failure.
1799  */
1800 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1801 {
1802     size_t len;
1803     unsigned char *out;
1804     size_t i, start = 0;
1805
1806     len = strlen(in);
1807     if (len >= 65535)
1808         return NULL;
1809
1810     out = app_malloc(strlen(in) + 1, "NPN buffer");
1811     for (i = 0; i <= len; ++i) {
1812         if (i == len || in[i] == ',') {
1813             if (i - start > 255) {
1814                 OPENSSL_free(out);
1815                 return NULL;
1816             }
1817             out[start] = (unsigned char)(i - start);
1818             start = i + 1;
1819         } else {
1820             out[i + 1] = in[i];
1821         }
1822     }
1823
1824     *outlen = len + 1;
1825     return out;
1826 }
1827
1828 void print_cert_checks(BIO *bio, X509 *x,
1829                        const char *checkhost,
1830                        const char *checkemail, const char *checkip)
1831 {
1832     if (x == NULL)
1833         return;
1834     if (checkhost) {
1835         BIO_printf(bio, "Hostname %s does%s match certificate\n",
1836                    checkhost,
1837                    X509_check_host(x, checkhost, 0, 0, NULL) == 1
1838                        ? "" : " NOT");
1839     }
1840
1841     if (checkemail) {
1842         BIO_printf(bio, "Email %s does%s match certificate\n",
1843                    checkemail, X509_check_email(x, checkemail, 0, 0)
1844                    ? "" : " NOT");
1845     }
1846
1847     if (checkip) {
1848         BIO_printf(bio, "IP %s does%s match certificate\n",
1849                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1850     }
1851 }
1852
1853 /* Get first http URL from a DIST_POINT structure */
1854
1855 static const char *get_dp_url(DIST_POINT *dp)
1856 {
1857     GENERAL_NAMES *gens;
1858     GENERAL_NAME *gen;
1859     int i, gtype;
1860     ASN1_STRING *uri;
1861     if (!dp->distpoint || dp->distpoint->type != 0)
1862         return NULL;
1863     gens = dp->distpoint->name.fullname;
1864     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1865         gen = sk_GENERAL_NAME_value(gens, i);
1866         uri = GENERAL_NAME_get0_value(gen, &gtype);
1867         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1868             const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1869             if (strncmp(uptr, "http://", 7) == 0)
1870                 return uptr;
1871         }
1872     }
1873     return NULL;
1874 }
1875
1876 /*
1877  * Look through a CRLDP structure and attempt to find an http URL to
1878  * downloads a CRL from.
1879  */
1880
1881 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1882 {
1883     int i;
1884     const char *urlptr = NULL;
1885     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1886         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1887         urlptr = get_dp_url(dp);
1888         if (urlptr)
1889             return load_crl(urlptr, FORMAT_HTTP);
1890     }
1891     return NULL;
1892 }
1893
1894 /*
1895  * Example of downloading CRLs from CRLDP: not usable for real world as it
1896  * always downloads, doesn't support non-blocking I/O and doesn't cache
1897  * anything.
1898  */
1899
1900 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
1901 {
1902     X509 *x;
1903     STACK_OF(X509_CRL) *crls = NULL;
1904     X509_CRL *crl;
1905     STACK_OF(DIST_POINT) *crldp;
1906
1907     crls = sk_X509_CRL_new_null();
1908     if (!crls)
1909         return NULL;
1910     x = X509_STORE_CTX_get_current_cert(ctx);
1911     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1912     crl = load_crl_crldp(crldp);
1913     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1914     if (!crl) {
1915         sk_X509_CRL_free(crls);
1916         return NULL;
1917     }
1918     sk_X509_CRL_push(crls, crl);
1919     /* Try to download delta CRL */
1920     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1921     crl = load_crl_crldp(crldp);
1922     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1923     if (crl)
1924         sk_X509_CRL_push(crls, crl);
1925     return crls;
1926 }
1927
1928 void store_setup_crl_download(X509_STORE *st)
1929 {
1930     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1931 }
1932
1933 /*
1934  * Platform-specific sections
1935  */
1936 #if defined(_WIN32)
1937 # ifdef fileno
1938 #  undef fileno
1939 #  define fileno(a) (int)_fileno(a)
1940 # endif
1941
1942 # include <windows.h>
1943 # include <tchar.h>
1944
1945 static int WIN32_rename(const char *from, const char *to)
1946 {
1947     TCHAR *tfrom = NULL, *tto;
1948     DWORD err;
1949     int ret = 0;
1950
1951     if (sizeof(TCHAR) == 1) {
1952         tfrom = (TCHAR *)from;
1953         tto = (TCHAR *)to;
1954     } else {                    /* UNICODE path */
1955
1956         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
1957         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
1958         if (tfrom == NULL)
1959             goto err;
1960         tto = tfrom + flen;
1961 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1962         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
1963 # endif
1964             for (i = 0; i < flen; i++)
1965                 tfrom[i] = (TCHAR)from[i];
1966 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1967         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
1968 # endif
1969             for (i = 0; i < tlen; i++)
1970                 tto[i] = (TCHAR)to[i];
1971     }
1972
1973     if (MoveFile(tfrom, tto))
1974         goto ok;
1975     err = GetLastError();
1976     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
1977         if (DeleteFile(tto) && MoveFile(tfrom, tto))
1978             goto ok;
1979         err = GetLastError();
1980     }
1981     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
1982         errno = ENOENT;
1983     else if (err == ERROR_ACCESS_DENIED)
1984         errno = EACCES;
1985     else
1986         errno = EINVAL;         /* we could map more codes... */
1987  err:
1988     ret = -1;
1989  ok:
1990     if (tfrom != NULL && tfrom != (TCHAR *)from)
1991         free(tfrom);
1992     return ret;
1993 }
1994 #endif
1995
1996 /* app_tminterval section */
1997 #if defined(_WIN32)
1998 double app_tminterval(int stop, int usertime)
1999 {
2000     FILETIME now;
2001     double ret = 0;
2002     static ULARGE_INTEGER tmstart;
2003     static int warning = 1;
2004 # ifdef _WIN32_WINNT
2005     static HANDLE proc = NULL;
2006
2007     if (proc == NULL) {
2008         if (check_winnt())
2009             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2010                                GetCurrentProcessId());
2011         if (proc == NULL)
2012             proc = (HANDLE) - 1;
2013     }
2014
2015     if (usertime && proc != (HANDLE) - 1) {
2016         FILETIME junk;
2017         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2018     } else
2019 # endif
2020     {
2021         SYSTEMTIME systime;
2022
2023         if (usertime && warning) {
2024             BIO_printf(bio_err, "To get meaningful results, run "
2025                        "this program on idle system.\n");
2026             warning = 0;
2027         }
2028         GetSystemTime(&systime);
2029         SystemTimeToFileTime(&systime, &now);
2030     }
2031
2032     if (stop == TM_START) {
2033         tmstart.u.LowPart = now.dwLowDateTime;
2034         tmstart.u.HighPart = now.dwHighDateTime;
2035     } else {
2036         ULARGE_INTEGER tmstop;
2037
2038         tmstop.u.LowPart = now.dwLowDateTime;
2039         tmstop.u.HighPart = now.dwHighDateTime;
2040
2041         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2042     }
2043
2044     return ret;
2045 }
2046 #elif defined(OPENSSL_SYS_VXWORKS)
2047 # include <time.h>
2048
2049 double app_tminterval(int stop, int usertime)
2050 {
2051     double ret = 0;
2052 # ifdef CLOCK_REALTIME
2053     static struct timespec tmstart;
2054     struct timespec now;
2055 # else
2056     static unsigned long tmstart;
2057     unsigned long now;
2058 # endif
2059     static int warning = 1;
2060
2061     if (usertime && warning) {
2062         BIO_printf(bio_err, "To get meaningful results, run "
2063                    "this program on idle system.\n");
2064         warning = 0;
2065     }
2066 # ifdef CLOCK_REALTIME
2067     clock_gettime(CLOCK_REALTIME, &now);
2068     if (stop == TM_START)
2069         tmstart = now;
2070     else
2071         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2072                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2073 # else
2074     now = tickGet();
2075     if (stop == TM_START)
2076         tmstart = now;
2077     else
2078         ret = (now - tmstart) / (double)sysClkRateGet();
2079 # endif
2080     return ret;
2081 }
2082
2083 #elif defined(OPENSSL_SYSTEM_VMS)
2084 # include <time.h>
2085 # include <times.h>
2086
2087 double app_tminterval(int stop, int usertime)
2088 {
2089     static clock_t tmstart;
2090     double ret = 0;
2091     clock_t now;
2092 # ifdef __TMS
2093     struct tms rus;
2094
2095     now = times(&rus);
2096     if (usertime)
2097         now = rus.tms_utime;
2098 # else
2099     if (usertime)
2100         now = clock();          /* sum of user and kernel times */
2101     else {
2102         struct timeval tv;
2103         gettimeofday(&tv, NULL);
2104         now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2105                         (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2106             );
2107     }
2108 # endif
2109     if (stop == TM_START)
2110         tmstart = now;
2111     else
2112         ret = (now - tmstart) / (double)(CLK_TCK);
2113
2114     return ret;
2115 }
2116
2117 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2118 # include <sys/times.h>
2119
2120 double app_tminterval(int stop, int usertime)
2121 {
2122     double ret = 0;
2123     struct tms rus;
2124     clock_t now = times(&rus);
2125     static clock_t tmstart;
2126
2127     if (usertime)
2128         now = rus.tms_utime;
2129
2130     if (stop == TM_START) {
2131         tmstart = now;
2132     } else {
2133         long int tck = sysconf(_SC_CLK_TCK);
2134         ret = (now - tmstart) / (double)tck;
2135     }
2136
2137     return ret;
2138 }
2139
2140 #else
2141 # include <sys/time.h>
2142 # include <sys/resource.h>
2143
2144 double app_tminterval(int stop, int usertime)
2145 {
2146     double ret = 0;
2147     struct rusage rus;
2148     struct timeval now;
2149     static struct timeval tmstart;
2150
2151     if (usertime)
2152         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2153     else
2154         gettimeofday(&now, NULL);
2155
2156     if (stop == TM_START)
2157         tmstart = now;
2158     else
2159         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2160                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2161
2162     return ret;
2163 }
2164 #endif
2165
2166 int app_access(const char* name, int flag)
2167 {
2168 #ifdef _WIN32
2169     return _access(name, flag);
2170 #else
2171     return access(name, flag);
2172 #endif
2173 }
2174
2175 int app_isdir(const char *name)
2176 {
2177     return opt_isdir(name);
2178 }
2179
2180 /* raw_read|write section */
2181 #if defined(__VMS)
2182 # include "vms_term_sock.h"
2183 static int stdin_sock = -1;
2184
2185 static void close_stdin_sock(void)
2186 {
2187     TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2188 }
2189
2190 int fileno_stdin(void)
2191 {
2192     if (stdin_sock == -1) {
2193         TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2194         atexit(close_stdin_sock);
2195     }
2196
2197     return stdin_sock;
2198 }
2199 #else
2200 int fileno_stdin(void)
2201 {
2202     return fileno(stdin);
2203 }
2204 #endif
2205
2206 int fileno_stdout(void)
2207 {
2208     return fileno(stdout);
2209 }
2210
2211 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2212 int raw_read_stdin(void *buf, int siz)
2213 {
2214     DWORD n;
2215     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2216         return n;
2217     else
2218         return -1;
2219 }
2220 #elif defined(__VMS)
2221 # include <sys/socket.h>
2222
2223 int raw_read_stdin(void *buf, int siz)
2224 {
2225     return recv(fileno_stdin(), buf, siz, 0);
2226 }
2227 #else
2228 int raw_read_stdin(void *buf, int siz)
2229 {
2230     return read(fileno_stdin(), buf, siz);
2231 }
2232 #endif
2233
2234 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2235 int raw_write_stdout(const void *buf, int siz)
2236 {
2237     DWORD n;
2238     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2239         return n;
2240     else
2241         return -1;
2242 }
2243 #else
2244 int raw_write_stdout(const void *buf, int siz)
2245 {
2246     return write(fileno_stdout(), buf, siz);
2247 }
2248 #endif
2249
2250 /*
2251  * Centralized handling of input and output files with format specification
2252  * The format is meant to show what the input and output is supposed to be,
2253  * and is therefore a show of intent more than anything else.  However, it
2254  * does impact behavior on some platforms, such as differentiating between
2255  * text and binary input/output on non-Unix platforms
2256  */
2257 BIO *dup_bio_in(int format)
2258 {
2259     return BIO_new_fp(stdin,
2260                       BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2261 }
2262
2263 BIO *dup_bio_out(int format)
2264 {
2265     BIO *b = BIO_new_fp(stdout,
2266                         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2267     void *prefix = NULL;
2268
2269 #ifdef OPENSSL_SYS_VMS
2270     if (FMT_istext(format))
2271         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2272 #endif
2273
2274     if (FMT_istext(format)
2275         && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2276         b = BIO_push(BIO_new(apps_bf_prefix()), b);
2277         BIO_ctrl(b, PREFIX_CTRL_SET_PREFIX, 0, prefix);
2278     }
2279
2280     return b;
2281 }
2282
2283 BIO *dup_bio_err(int format)
2284 {
2285     BIO *b = BIO_new_fp(stderr,
2286                         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2287 #ifdef OPENSSL_SYS_VMS
2288     if (FMT_istext(format))
2289         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2290 #endif
2291     return b;
2292 }
2293
2294 /*
2295  * Because the prefix method is created dynamically, we must also be able
2296  * to destroy it.
2297  */
2298 void destroy_prefix_method(void)
2299 {
2300     BIO_METHOD *prefix_method = apps_bf_prefix();
2301     BIO_meth_free(prefix_method);
2302     prefix_method = NULL;
2303 }
2304
2305 void unbuffer(FILE *fp)
2306 {
2307 /*
2308  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2309  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2310  * However, we trust that the C RTL will never give us a FILE pointer
2311  * above the first 4 GB of memory, so we simply turn off the warning
2312  * temporarily.
2313  */
2314 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2315 # pragma environment save
2316 # pragma message disable maylosedata2
2317 #endif
2318     setbuf(fp, NULL);
2319 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2320 # pragma environment restore
2321 #endif
2322 }
2323
2324 static const char *modestr(char mode, int format)
2325 {
2326     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2327
2328     switch (mode) {
2329     case 'a':
2330         return FMT_istext(format) ? "a" : "ab";
2331     case 'r':
2332         return FMT_istext(format) ? "r" : "rb";
2333     case 'w':
2334         return FMT_istext(format) ? "w" : "wb";
2335     }
2336     /* The assert above should make sure we never reach this point */
2337     return NULL;
2338 }
2339
2340 static const char *modeverb(char mode)
2341 {
2342     switch (mode) {
2343     case 'a':
2344         return "appending";
2345     case 'r':
2346         return "reading";
2347     case 'w':
2348         return "writing";
2349     }
2350     return "(doing something)";
2351 }
2352
2353 /*
2354  * Open a file for writing, owner-read-only.
2355  */
2356 BIO *bio_open_owner(const char *filename, int format, int private)
2357 {
2358     FILE *fp = NULL;
2359     BIO *b = NULL;
2360     int fd = -1, bflags, mode, textmode;
2361
2362     if (!private || filename == NULL || strcmp(filename, "-") == 0)
2363         return bio_open_default(filename, 'w', format);
2364
2365     mode = O_WRONLY;
2366 #ifdef O_CREAT
2367     mode |= O_CREAT;
2368 #endif
2369 #ifdef O_TRUNC
2370     mode |= O_TRUNC;
2371 #endif
2372     textmode = FMT_istext(format);
2373     if (!textmode) {
2374 #ifdef O_BINARY
2375         mode |= O_BINARY;
2376 #elif defined(_O_BINARY)
2377         mode |= _O_BINARY;
2378 #endif
2379     }
2380
2381 #ifdef OPENSSL_SYS_VMS
2382     /* VMS doesn't have O_BINARY, it just doesn't make sense.  But,
2383      * it still needs to know that we're going binary, or fdopen()
2384      * will fail with "invalid argument"...  so we tell VMS what the
2385      * context is.
2386      */
2387     if (!textmode)
2388         fd = open(filename, mode, 0600, "ctx=bin");
2389     else
2390 #endif
2391         fd = open(filename, mode, 0600);
2392     if (fd < 0)
2393         goto err;
2394     fp = fdopen(fd, modestr('w', format));
2395     if (fp == NULL)
2396         goto err;
2397     bflags = BIO_CLOSE;
2398     if (textmode)
2399         bflags |= BIO_FP_TEXT;
2400     b = BIO_new_fp(fp, bflags);
2401     if (b)
2402         return b;
2403
2404  err:
2405     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2406                opt_getprog(), filename, strerror(errno));
2407     ERR_print_errors(bio_err);
2408     /* If we have fp, then fdopen took over fd, so don't close both. */
2409     if (fp)
2410         fclose(fp);
2411     else if (fd >= 0)
2412         close(fd);
2413     return NULL;
2414 }
2415
2416 static BIO *bio_open_default_(const char *filename, char mode, int format,
2417                               int quiet)
2418 {
2419     BIO *ret;
2420
2421     if (filename == NULL || strcmp(filename, "-") == 0) {
2422         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2423         if (quiet) {
2424             ERR_clear_error();
2425             return ret;
2426         }
2427         if (ret != NULL)
2428             return ret;
2429         BIO_printf(bio_err,
2430                    "Can't open %s, %s\n",
2431                    mode == 'r' ? "stdin" : "stdout", strerror(errno));
2432     } else {
2433         ret = BIO_new_file(filename, modestr(mode, format));
2434         if (quiet) {
2435             ERR_clear_error();
2436             return ret;
2437         }
2438         if (ret != NULL)
2439             return ret;
2440         BIO_printf(bio_err,
2441                    "Can't open %s for %s, %s\n",
2442                    filename, modeverb(mode), strerror(errno));
2443     }
2444     ERR_print_errors(bio_err);
2445     return NULL;
2446 }
2447
2448 BIO *bio_open_default(const char *filename, char mode, int format)
2449 {
2450     return bio_open_default_(filename, mode, format, 0);
2451 }
2452
2453 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2454 {
2455     return bio_open_default_(filename, mode, format, 1);
2456 }
2457
2458 void wait_for_async(SSL *s)
2459 {
2460     /* On Windows select only works for sockets, so we simply don't wait  */
2461 #ifndef OPENSSL_SYS_WINDOWS
2462     int width = 0;
2463     fd_set asyncfds;
2464     OSSL_ASYNC_FD *fds;
2465     size_t numfds;
2466     size_t i;
2467
2468     if (!SSL_get_all_async_fds(s, NULL, &numfds))
2469         return;
2470     if (numfds == 0)
2471         return;
2472     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2473     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2474         OPENSSL_free(fds);
2475         return;
2476     }
2477
2478     FD_ZERO(&asyncfds);
2479     for (i = 0; i < numfds; i++) {
2480         if (width <= (int)fds[i])
2481             width = (int)fds[i] + 1;
2482         openssl_fdset((int)fds[i], &asyncfds);
2483     }
2484     select(width, (void *)&asyncfds, NULL, NULL, NULL);
2485     OPENSSL_free(fds);
2486 #endif
2487 }
2488
2489 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2490 #if defined(OPENSSL_SYS_MSDOS)
2491 int has_stdin_waiting(void)
2492 {
2493 # if defined(OPENSSL_SYS_WINDOWS)
2494     HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2495     DWORD events = 0;
2496     INPUT_RECORD inputrec;
2497     DWORD insize = 1;
2498     BOOL peeked;
2499
2500     if (inhand == INVALID_HANDLE_VALUE) {
2501         return 0;
2502     }
2503
2504     peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2505     if (!peeked) {
2506         /* Probably redirected input? _kbhit() does not work in this case */
2507         if (!feof(stdin)) {
2508             return 1;
2509         }
2510         return 0;
2511     }
2512 # endif
2513     return _kbhit();
2514 }
2515 #endif
2516
2517 /* Corrupt a signature by modifying final byte */
2518 void corrupt_signature(const ASN1_STRING *signature)
2519 {
2520         unsigned char *s = signature->data;
2521         s[signature->length - 1] ^= 0x1;
2522 }
2523
2524 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2525                    int days)
2526 {
2527     if (startdate == NULL || strcmp(startdate, "today") == 0) {
2528         if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2529             return 0;
2530     } else {
2531         if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2532             return 0;
2533     }
2534     if (enddate == NULL) {
2535         if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2536             == NULL)
2537             return 0;
2538     } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2539         return 0;
2540     }
2541     return 1;
2542 }
2543
2544 void make_uppercase(char *string)
2545 {
2546     int i;
2547
2548     for (i = 0; string[i] != '\0'; i++)
2549         string[i] = toupper((unsigned char)string[i]);
2550 }
2551
2552 int opt_printf_stderr(const char *fmt, ...)
2553 {
2554     va_list ap;
2555     int ret;
2556
2557     va_start(ap, fmt);
2558     ret = BIO_vprintf(bio_err, fmt, ap);
2559     va_end(ap);
2560     return ret;
2561 }