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