Copyright consolidation 01/10
[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_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
989         {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
990         {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
991         {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
992         {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
993         {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
994         {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
995         {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
996         {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
997         {"compat", XN_FLAG_COMPAT, 0xffffffffL},
998         {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
999         {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1000         {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1001         {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1002         {"dn_rev", XN_FLAG_DN_REV, 0},
1003         {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1004         {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1005         {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1006         {"align", XN_FLAG_FN_ALIGN, 0},
1007         {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1008         {"space_eq", XN_FLAG_SPC_EQ, 0},
1009         {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1010         {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1011         {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1012         {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1013         {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1014         {NULL, 0, 0}
1015     };
1016     if (set_multi_opts(flags, arg, ex_tbl) == 0)
1017         return 0;
1018     if ((*flags & XN_FLAG_SEP_MASK) == 0)
1019         *flags |= XN_FLAG_SEP_CPLUS_SPC;
1020     return 1;
1021 }
1022
1023 int set_ext_copy(int *copy_type, const char *arg)
1024 {
1025     if (strcasecmp(arg, "none") == 0)
1026         *copy_type = EXT_COPY_NONE;
1027     else if (strcasecmp(arg, "copy") == 0)
1028         *copy_type = EXT_COPY_ADD;
1029     else if (strcasecmp(arg, "copyall") == 0)
1030         *copy_type = EXT_COPY_ALL;
1031     else
1032         return 0;
1033     return 1;
1034 }
1035
1036 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1037 {
1038     STACK_OF(X509_EXTENSION) *exts = NULL;
1039     X509_EXTENSION *ext, *tmpext;
1040     ASN1_OBJECT *obj;
1041     int i, idx, ret = 0;
1042     if (!x || !req || (copy_type == EXT_COPY_NONE))
1043         return 1;
1044     exts = X509_REQ_get_extensions(req);
1045
1046     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1047         ext = sk_X509_EXTENSION_value(exts, i);
1048         obj = X509_EXTENSION_get_object(ext);
1049         idx = X509_get_ext_by_OBJ(x, obj, -1);
1050         /* Does extension exist? */
1051         if (idx != -1) {
1052             /* If normal copy don't override existing extension */
1053             if (copy_type == EXT_COPY_ADD)
1054                 continue;
1055             /* Delete all extensions of same type */
1056             do {
1057                 tmpext = X509_get_ext(x, idx);
1058                 X509_delete_ext(x, idx);
1059                 X509_EXTENSION_free(tmpext);
1060                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1061             } while (idx != -1);
1062         }
1063         if (!X509_add_ext(x, ext, -1))
1064             goto end;
1065     }
1066
1067     ret = 1;
1068
1069  end:
1070
1071     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1072
1073     return ret;
1074 }
1075
1076 static int set_multi_opts(unsigned long *flags, const char *arg,
1077                           const NAME_EX_TBL * in_tbl)
1078 {
1079     STACK_OF(CONF_VALUE) *vals;
1080     CONF_VALUE *val;
1081     int i, ret = 1;
1082     if (!arg)
1083         return 0;
1084     vals = X509V3_parse_list(arg);
1085     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1086         val = sk_CONF_VALUE_value(vals, i);
1087         if (!set_table_opts(flags, val->name, in_tbl))
1088             ret = 0;
1089     }
1090     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1091     return ret;
1092 }
1093
1094 static int set_table_opts(unsigned long *flags, const char *arg,
1095                           const NAME_EX_TBL * in_tbl)
1096 {
1097     char c;
1098     const NAME_EX_TBL *ptbl;
1099     c = arg[0];
1100
1101     if (c == '-') {
1102         c = 0;
1103         arg++;
1104     } else if (c == '+') {
1105         c = 1;
1106         arg++;
1107     } else
1108         c = 1;
1109
1110     for (ptbl = in_tbl; ptbl->name; ptbl++) {
1111         if (strcasecmp(arg, ptbl->name) == 0) {
1112             *flags &= ~ptbl->mask;
1113             if (c)
1114                 *flags |= ptbl->flag;
1115             else
1116                 *flags &= ~ptbl->flag;
1117             return 1;
1118         }
1119     }
1120     return 0;
1121 }
1122
1123 void print_name(BIO *out, const char *title, X509_NAME *nm,
1124                 unsigned long lflags)
1125 {
1126     char *buf;
1127     char mline = 0;
1128     int indent = 0;
1129
1130     if (title)
1131         BIO_puts(out, title);
1132     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1133         mline = 1;
1134         indent = 4;
1135     }
1136     if (lflags == XN_FLAG_COMPAT) {
1137         buf = X509_NAME_oneline(nm, 0, 0);
1138         BIO_puts(out, buf);
1139         BIO_puts(out, "\n");
1140         OPENSSL_free(buf);
1141     } else {
1142         if (mline)
1143             BIO_puts(out, "\n");
1144         X509_NAME_print_ex(out, nm, indent, lflags);
1145         BIO_puts(out, "\n");
1146     }
1147 }
1148
1149 void print_bignum_var(BIO *out, BIGNUM *in, const char *var,
1150                       int len, unsigned char *buffer)
1151 {
1152     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
1153     if (BN_is_zero(in))
1154         BIO_printf(out, "\n\t0x00");
1155     else {
1156         int i, l;
1157
1158         l = BN_bn2bin(in, buffer);
1159         for (i = 0; i < l; i++) {
1160             if ((i % 10) == 0)
1161                 BIO_printf(out, "\n\t");
1162             if (i < l - 1)
1163                 BIO_printf(out, "0x%02X, ", buffer[i]);
1164             else
1165                 BIO_printf(out, "0x%02X", buffer[i]);
1166         }
1167     }
1168     BIO_printf(out, "\n    };\n");
1169 }
1170 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1171 {
1172     int i;
1173
1174     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1175     for (i = 0; i < len; i++) {
1176         if ((i % 10) == 0)
1177             BIO_printf(out, "\n    ");
1178         if (i < len - 1)
1179             BIO_printf(out, "0x%02X, ", d[i]);
1180         else
1181             BIO_printf(out, "0x%02X", d[i]);
1182     }
1183     BIO_printf(out, "\n};\n");
1184 }
1185
1186 X509_STORE *setup_verify(char *CAfile, char *CApath, int noCAfile, int noCApath)
1187 {
1188     X509_STORE *store = X509_STORE_new();
1189     X509_LOOKUP *lookup;
1190
1191     if (store == NULL)
1192         goto end;
1193
1194     if(CAfile != NULL || !noCAfile) {
1195         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1196         if (lookup == NULL)
1197             goto end;
1198         if (CAfile) {
1199             if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1200                 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1201                 goto end;
1202             }
1203         } else
1204             X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1205     }
1206
1207     if(CApath != NULL || !noCApath) {
1208         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1209         if (lookup == NULL)
1210             goto end;
1211         if (CApath) {
1212             if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1213                 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1214                 goto end;
1215             }
1216         } else
1217             X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1218     }
1219
1220     ERR_clear_error();
1221     return store;
1222  end:
1223     X509_STORE_free(store);
1224     return NULL;
1225 }
1226
1227 #ifndef OPENSSL_NO_ENGINE
1228 /* Try to load an engine in a shareable library */
1229 static ENGINE *try_load_engine(const char *engine)
1230 {
1231     ENGINE *e = ENGINE_by_id("dynamic");
1232     if (e) {
1233         if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1234             || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1235             ENGINE_free(e);
1236             e = NULL;
1237         }
1238     }
1239     return e;
1240 }
1241
1242 ENGINE *setup_engine(const char *engine, int debug)
1243 {
1244     ENGINE *e = NULL;
1245
1246     if (engine) {
1247         if (strcmp(engine, "auto") == 0) {
1248             BIO_printf(bio_err, "enabling auto ENGINE support\n");
1249             ENGINE_register_all_complete();
1250             return NULL;
1251         }
1252         if ((e = ENGINE_by_id(engine)) == NULL
1253             && (e = try_load_engine(engine)) == NULL) {
1254             BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1255             ERR_print_errors(bio_err);
1256             return NULL;
1257         }
1258         if (debug) {
1259             ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1260         }
1261         ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1262         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1263             BIO_printf(bio_err, "can't use that engine\n");
1264             ERR_print_errors(bio_err);
1265             ENGINE_free(e);
1266             return NULL;
1267         }
1268
1269         BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1270
1271         /* Free our "structural" reference. */
1272         ENGINE_free(e);
1273     }
1274     return e;
1275 }
1276 #endif
1277
1278 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1279 {
1280     const char *n;
1281
1282     n = a[DB_serial];
1283     while (*n == '0')
1284         n++;
1285     return (lh_strhash(n));
1286 }
1287
1288 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1289                             const OPENSSL_CSTRING *b)
1290 {
1291     const char *aa, *bb;
1292
1293     for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1294     for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1295     return (strcmp(aa, bb));
1296 }
1297
1298 static int index_name_qual(char **a)
1299 {
1300     return (a[0][0] == 'V');
1301 }
1302
1303 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1304 {
1305     return (lh_strhash(a[DB_name]));
1306 }
1307
1308 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1309 {
1310     return (strcmp(a[DB_name], b[DB_name]));
1311 }
1312
1313 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1314 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1315 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1316 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1317 #undef BSIZE
1318 #define BSIZE 256
1319 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1320 {
1321     BIO *in = NULL;
1322     BIGNUM *ret = NULL;
1323     char buf[1024];
1324     ASN1_INTEGER *ai = NULL;
1325
1326     ai = ASN1_INTEGER_new();
1327     if (ai == NULL)
1328         goto err;
1329
1330     in = BIO_new_file(serialfile, "r");
1331     if (in == NULL) {
1332         if (!create) {
1333             perror(serialfile);
1334             goto err;
1335         }
1336         ERR_clear_error();
1337         ret = BN_new();
1338         if (ret == NULL || !rand_serial(ret, ai))
1339             BIO_printf(bio_err, "Out of memory\n");
1340     } else {
1341         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1342             BIO_printf(bio_err, "unable to load number from %s\n",
1343                        serialfile);
1344             goto err;
1345         }
1346         ret = ASN1_INTEGER_to_BN(ai, NULL);
1347         if (ret == NULL) {
1348             BIO_printf(bio_err,
1349                        "error converting number from bin to BIGNUM\n");
1350             goto err;
1351         }
1352     }
1353
1354     if (ret && retai) {
1355         *retai = ai;
1356         ai = NULL;
1357     }
1358  err:
1359     BIO_free(in);
1360     ASN1_INTEGER_free(ai);
1361     return (ret);
1362 }
1363
1364 int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
1365                 ASN1_INTEGER **retai)
1366 {
1367     char buf[1][BSIZE];
1368     BIO *out = NULL;
1369     int ret = 0;
1370     ASN1_INTEGER *ai = NULL;
1371     int j;
1372
1373     if (suffix == NULL)
1374         j = strlen(serialfile);
1375     else
1376         j = strlen(serialfile) + strlen(suffix) + 1;
1377     if (j >= BSIZE) {
1378         BIO_printf(bio_err, "file name too long\n");
1379         goto err;
1380     }
1381
1382     if (suffix == NULL)
1383         OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1384     else {
1385 #ifndef OPENSSL_SYS_VMS
1386         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1387 #else
1388         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1389 #endif
1390     }
1391     out = BIO_new_file(buf[0], "w");
1392     if (out == NULL) {
1393         ERR_print_errors(bio_err);
1394         goto err;
1395     }
1396
1397     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1398         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1399         goto err;
1400     }
1401     i2a_ASN1_INTEGER(out, ai);
1402     BIO_puts(out, "\n");
1403     ret = 1;
1404     if (retai) {
1405         *retai = ai;
1406         ai = NULL;
1407     }
1408  err:
1409     BIO_free_all(out);
1410     ASN1_INTEGER_free(ai);
1411     return (ret);
1412 }
1413
1414 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1415 {
1416     char buf[5][BSIZE];
1417     int i, j;
1418
1419     i = strlen(serialfile) + strlen(old_suffix);
1420     j = strlen(serialfile) + strlen(new_suffix);
1421     if (i > j)
1422         j = i;
1423     if (j + 1 >= BSIZE) {
1424         BIO_printf(bio_err, "file name too long\n");
1425         goto err;
1426     }
1427 #ifndef OPENSSL_SYS_VMS
1428     j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
1429     j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
1430 #else
1431     j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, new_suffix);
1432     j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", serialfile, old_suffix);
1433 #endif
1434     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1435 #ifdef ENOTDIR
1436         && errno != ENOTDIR
1437 #endif
1438         ) {
1439         BIO_printf(bio_err,
1440                    "unable to rename %s to %s\n", serialfile, buf[1]);
1441         perror("reason");
1442         goto err;
1443     }
1444     if (rename(buf[0], serialfile) < 0) {
1445         BIO_printf(bio_err,
1446                    "unable to rename %s to %s\n", buf[0], serialfile);
1447         perror("reason");
1448         rename(buf[1], serialfile);
1449         goto err;
1450     }
1451     return 1;
1452  err:
1453     return 0;
1454 }
1455
1456 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1457 {
1458     BIGNUM *btmp;
1459     int ret = 0;
1460
1461     if (b)
1462         btmp = b;
1463     else
1464         btmp = BN_new();
1465
1466     if (btmp == NULL)
1467         return 0;
1468
1469     if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1470         goto error;
1471     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1472         goto error;
1473
1474     ret = 1;
1475
1476  error:
1477
1478     if (btmp != b)
1479         BN_free(btmp);
1480
1481     return ret;
1482 }
1483
1484 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1485 {
1486     CA_DB *retdb = NULL;
1487     TXT_DB *tmpdb = NULL;
1488     BIO *in;
1489     CONF *dbattr_conf = NULL;
1490     char buf[BSIZE];
1491
1492     in = BIO_new_file(dbfile, "r");
1493     if (in == NULL) {
1494         ERR_print_errors(bio_err);
1495         goto err;
1496     }
1497     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1498         goto err;
1499
1500 #ifndef OPENSSL_SYS_VMS
1501     BIO_snprintf(buf, sizeof buf, "%s.attr", dbfile);
1502 #else
1503     BIO_snprintf(buf, sizeof buf, "%s-attr", dbfile);
1504 #endif
1505     dbattr_conf = app_load_config(buf);
1506
1507     retdb = app_malloc(sizeof(*retdb), "new DB");
1508     retdb->db = tmpdb;
1509     tmpdb = NULL;
1510     if (db_attr)
1511         retdb->attributes = *db_attr;
1512     else {
1513         retdb->attributes.unique_subject = 1;
1514     }
1515
1516     if (dbattr_conf) {
1517         char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1518         if (p) {
1519             retdb->attributes.unique_subject = parse_yesno(p, 1);
1520         }
1521     }
1522
1523  err:
1524     NCONF_free(dbattr_conf);
1525     TXT_DB_free(tmpdb);
1526     BIO_free_all(in);
1527     return retdb;
1528 }
1529
1530 int index_index(CA_DB *db)
1531 {
1532     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1533                              LHASH_HASH_FN(index_serial),
1534                              LHASH_COMP_FN(index_serial))) {
1535         BIO_printf(bio_err,
1536                    "error creating serial number index:(%ld,%ld,%ld)\n",
1537                    db->db->error, db->db->arg1, db->db->arg2);
1538         return 0;
1539     }
1540
1541     if (db->attributes.unique_subject
1542         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1543                                 LHASH_HASH_FN(index_name),
1544                                 LHASH_COMP_FN(index_name))) {
1545         BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1546                    db->db->error, db->db->arg1, db->db->arg2);
1547         return 0;
1548     }
1549     return 1;
1550 }
1551
1552 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1553 {
1554     char buf[3][BSIZE];
1555     BIO *out;
1556     int j;
1557
1558     j = strlen(dbfile) + strlen(suffix);
1559     if (j + 6 >= BSIZE) {
1560         BIO_printf(bio_err, "file name too long\n");
1561         goto err;
1562     }
1563 #ifndef OPENSSL_SYS_VMS
1564     j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1565     j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1566     j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1567 #else
1568     j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1569     j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1570     j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1571 #endif
1572     out = BIO_new_file(buf[0], "w");
1573     if (out == NULL) {
1574         perror(dbfile);
1575         BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1576         goto err;
1577     }
1578     j = TXT_DB_write(out, db->db);
1579     BIO_free(out);
1580     if (j <= 0)
1581         goto err;
1582
1583     out = BIO_new_file(buf[1], "w");
1584     if (out == NULL) {
1585         perror(buf[2]);
1586         BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1587         goto err;
1588     }
1589     BIO_printf(out, "unique_subject = %s\n",
1590                db->attributes.unique_subject ? "yes" : "no");
1591     BIO_free(out);
1592
1593     return 1;
1594  err:
1595     return 0;
1596 }
1597
1598 int rotate_index(const char *dbfile, const char *new_suffix,
1599                  const char *old_suffix)
1600 {
1601     char buf[5][BSIZE];
1602     int i, j;
1603
1604     i = strlen(dbfile) + strlen(old_suffix);
1605     j = strlen(dbfile) + strlen(new_suffix);
1606     if (i > j)
1607         j = i;
1608     if (j + 6 >= BSIZE) {
1609         BIO_printf(bio_err, "file name too long\n");
1610         goto err;
1611     }
1612 #ifndef OPENSSL_SYS_VMS
1613     j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1614     j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s", dbfile, old_suffix);
1615     j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s", dbfile, new_suffix);
1616     j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", dbfile, old_suffix);
1617     j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, new_suffix);
1618 #else
1619     j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1620     j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s", dbfile, old_suffix);
1621     j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s", dbfile, new_suffix);
1622     j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", dbfile, old_suffix);
1623     j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, new_suffix);
1624 #endif
1625     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1626 #ifdef ENOTDIR
1627         && errno != ENOTDIR
1628 #endif
1629         ) {
1630         BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1631         perror("reason");
1632         goto err;
1633     }
1634     if (rename(buf[0], dbfile) < 0) {
1635         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1636         perror("reason");
1637         rename(buf[1], dbfile);
1638         goto err;
1639     }
1640     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1641 #ifdef ENOTDIR
1642         && errno != ENOTDIR
1643 #endif
1644         ) {
1645         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1646         perror("reason");
1647         rename(dbfile, buf[0]);
1648         rename(buf[1], dbfile);
1649         goto err;
1650     }
1651     if (rename(buf[2], buf[4]) < 0) {
1652         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1653         perror("reason");
1654         rename(buf[3], buf[4]);
1655         rename(dbfile, buf[0]);
1656         rename(buf[1], dbfile);
1657         goto err;
1658     }
1659     return 1;
1660  err:
1661     return 0;
1662 }
1663
1664 void free_index(CA_DB *db)
1665 {
1666     if (db) {
1667         TXT_DB_free(db->db);
1668         OPENSSL_free(db);
1669     }
1670 }
1671
1672 int parse_yesno(const char *str, int def)
1673 {
1674     if (str) {
1675         switch (*str) {
1676         case 'f':              /* false */
1677         case 'F':              /* FALSE */
1678         case 'n':              /* no */
1679         case 'N':              /* NO */
1680         case '0':              /* 0 */
1681             return 0;
1682         case 't':              /* true */
1683         case 'T':              /* TRUE */
1684         case 'y':              /* yes */
1685         case 'Y':              /* YES */
1686         case '1':              /* 1 */
1687             return 1;
1688         }
1689     }
1690     return def;
1691 }
1692
1693 /*
1694  * name is expected to be in the format /type0=value0/type1=value1/type2=...
1695  * where characters may be escaped by \
1696  */
1697 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1698 {
1699     int nextismulti = 0;
1700     char *work;
1701     X509_NAME *n;
1702
1703     if (*cp++ != '/')
1704         return NULL;
1705
1706     n = X509_NAME_new();
1707     if (n == NULL)
1708         return NULL;
1709     work = OPENSSL_strdup(cp);
1710     if (work == NULL)
1711         goto err;
1712
1713     while (*cp) {
1714         char *bp = work;
1715         char *typestr = bp;
1716         unsigned char *valstr;
1717         int nid;
1718         int ismulti = nextismulti;
1719         nextismulti = 0;
1720
1721         /* Collect the type */
1722         while (*cp && *cp != '=')
1723             *bp++ = *cp++;
1724         if (*cp == '\0') {
1725             BIO_printf(bio_err,
1726                     "%s: Hit end of string before finding the equals.\n",
1727                     opt_getprog());
1728             goto err;
1729         }
1730         *bp++ = '\0';
1731         ++cp;
1732
1733         /* Collect the value. */
1734         valstr = (unsigned char *)bp;
1735         for (; *cp && *cp != '/'; *bp++ = *cp++) {
1736             if (canmulti && *cp == '+') {
1737                 nextismulti = 1;
1738                 break;
1739             }
1740             if (*cp == '\\' && *++cp == '\0') {
1741                 BIO_printf(bio_err,
1742                         "%s: escape character at end of string\n",
1743                         opt_getprog());
1744                 goto err;
1745             }
1746         }
1747         *bp++ = '\0';
1748
1749         /* If not at EOS (must be + or /), move forward. */
1750         if (*cp)
1751             ++cp;
1752
1753         /* Parse */
1754         nid = OBJ_txt2nid(typestr);
1755         if (nid == NID_undef) {
1756             BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1757                       opt_getprog(), typestr);
1758             continue;
1759         }
1760         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1761                                         valstr, strlen((char *)valstr),
1762                                         -1, ismulti ? -1 : 0))
1763             goto err;
1764     }
1765
1766     OPENSSL_free(work);
1767     return n;
1768
1769  err:
1770     X509_NAME_free(n);
1771     OPENSSL_free(work);
1772     return NULL;
1773 }
1774
1775 /*
1776  * Read whole contents of a BIO into an allocated memory buffer and return
1777  * it.
1778  */
1779
1780 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1781 {
1782     BIO *mem;
1783     int len, ret;
1784     unsigned char tbuf[1024];
1785     mem = BIO_new(BIO_s_mem());
1786     if (mem == NULL)
1787         return -1;
1788     for (;;) {
1789         if ((maxlen != -1) && maxlen < 1024)
1790             len = maxlen;
1791         else
1792             len = 1024;
1793         len = BIO_read(in, tbuf, len);
1794         if (len < 0) {
1795             BIO_free(mem);
1796             return -1;
1797         }
1798         if (len == 0)
1799             break;
1800         if (BIO_write(mem, tbuf, len) != len) {
1801             BIO_free(mem);
1802             return -1;
1803         }
1804         maxlen -= len;
1805
1806         if (maxlen == 0)
1807             break;
1808     }
1809     ret = BIO_get_mem_data(mem, (char **)out);
1810     BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1811     BIO_free(mem);
1812     return ret;
1813 }
1814
1815 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1816 {
1817     int rv;
1818     char *stmp, *vtmp = NULL;
1819     stmp = OPENSSL_strdup(value);
1820     if (!stmp)
1821         return -1;
1822     vtmp = strchr(stmp, ':');
1823     if (vtmp) {
1824         *vtmp = 0;
1825         vtmp++;
1826     }
1827     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1828     OPENSSL_free(stmp);
1829     return rv;
1830 }
1831
1832 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1833 {
1834     X509_POLICY_NODE *node;
1835     int i;
1836
1837     BIO_printf(bio_err, "%s Policies:", name);
1838     if (nodes) {
1839         BIO_puts(bio_err, "\n");
1840         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1841             node = sk_X509_POLICY_NODE_value(nodes, i);
1842             X509_POLICY_NODE_print(bio_err, node, 2);
1843         }
1844     } else
1845         BIO_puts(bio_err, " <empty>\n");
1846 }
1847
1848 void policies_print(X509_STORE_CTX *ctx)
1849 {
1850     X509_POLICY_TREE *tree;
1851     int explicit_policy;
1852     tree = X509_STORE_CTX_get0_policy_tree(ctx);
1853     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1854
1855     BIO_printf(bio_err, "Require explicit Policy: %s\n",
1856                explicit_policy ? "True" : "False");
1857
1858     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1859     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1860 }
1861
1862 /*-
1863  * next_protos_parse parses a comma separated list of strings into a string
1864  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1865  *   outlen: (output) set to the length of the resulting buffer on success.
1866  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
1867  *   in: a NUL terminated string like "abc,def,ghi"
1868  *
1869  *   returns: a malloc'd buffer or NULL on failure.
1870  */
1871 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1872 {
1873     size_t len;
1874     unsigned char *out;
1875     size_t i, start = 0;
1876
1877     len = strlen(in);
1878     if (len >= 65535)
1879         return NULL;
1880
1881     out = app_malloc(strlen(in) + 1, "NPN buffer");
1882     for (i = 0; i <= len; ++i) {
1883         if (i == len || in[i] == ',') {
1884             if (i - start > 255) {
1885                 OPENSSL_free(out);
1886                 return NULL;
1887             }
1888             out[start] = i - start;
1889             start = i + 1;
1890         } else
1891             out[i + 1] = in[i];
1892     }
1893
1894     *outlen = len + 1;
1895     return out;
1896 }
1897
1898 void print_cert_checks(BIO *bio, X509 *x,
1899                        const char *checkhost,
1900                        const char *checkemail, const char *checkip)
1901 {
1902     if (x == NULL)
1903         return;
1904     if (checkhost) {
1905         BIO_printf(bio, "Hostname %s does%s match certificate\n",
1906                    checkhost,
1907                    X509_check_host(x, checkhost, 0, 0, NULL) == 1
1908                        ? "" : " NOT");
1909     }
1910
1911     if (checkemail) {
1912         BIO_printf(bio, "Email %s does%s match certificate\n",
1913                    checkemail, X509_check_email(x, checkemail, 0, 0)
1914                    ? "" : " NOT");
1915     }
1916
1917     if (checkip) {
1918         BIO_printf(bio, "IP %s does%s match certificate\n",
1919                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1920     }
1921 }
1922
1923 /* Get first http URL from a DIST_POINT structure */
1924
1925 static const char *get_dp_url(DIST_POINT *dp)
1926 {
1927     GENERAL_NAMES *gens;
1928     GENERAL_NAME *gen;
1929     int i, gtype;
1930     ASN1_STRING *uri;
1931     if (!dp->distpoint || dp->distpoint->type != 0)
1932         return NULL;
1933     gens = dp->distpoint->name.fullname;
1934     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1935         gen = sk_GENERAL_NAME_value(gens, i);
1936         uri = GENERAL_NAME_get0_value(gen, &gtype);
1937         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1938             char *uptr = (char *)ASN1_STRING_data(uri);
1939             if (strncmp(uptr, "http://", 7) == 0)
1940                 return uptr;
1941         }
1942     }
1943     return NULL;
1944 }
1945
1946 /*
1947  * Look through a CRLDP structure and attempt to find an http URL to
1948  * downloads a CRL from.
1949  */
1950
1951 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1952 {
1953     int i;
1954     const char *urlptr = NULL;
1955     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1956         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1957         urlptr = get_dp_url(dp);
1958         if (urlptr)
1959             return load_crl(urlptr, FORMAT_HTTP);
1960     }
1961     return NULL;
1962 }
1963
1964 /*
1965  * Example of downloading CRLs from CRLDP: not usable for real world as it
1966  * always downloads, doesn't support non-blocking I/O and doesn't cache
1967  * anything.
1968  */
1969
1970 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
1971 {
1972     X509 *x;
1973     STACK_OF(X509_CRL) *crls = NULL;
1974     X509_CRL *crl;
1975     STACK_OF(DIST_POINT) *crldp;
1976
1977     crls = sk_X509_CRL_new_null();
1978     if (!crls)
1979         return NULL;
1980     x = X509_STORE_CTX_get_current_cert(ctx);
1981     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1982     crl = load_crl_crldp(crldp);
1983     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1984     if (!crl)
1985         return NULL;
1986     sk_X509_CRL_push(crls, crl);
1987     /* Try to download delta CRL */
1988     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1989     crl = load_crl_crldp(crldp);
1990     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1991     if (crl)
1992         sk_X509_CRL_push(crls, crl);
1993     return crls;
1994 }
1995
1996 void store_setup_crl_download(X509_STORE *st)
1997 {
1998     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1999 }
2000
2001 /*
2002  * Platform-specific sections
2003  */
2004 #if defined(_WIN32)
2005 # ifdef fileno
2006 #  undef fileno
2007 #  define fileno(a) (int)_fileno(a)
2008 # endif
2009
2010 # include <windows.h>
2011 # include <tchar.h>
2012
2013 static int WIN32_rename(const char *from, const char *to)
2014 {
2015     TCHAR *tfrom = NULL, *tto;
2016     DWORD err;
2017     int ret = 0;
2018
2019     if (sizeof(TCHAR) == 1) {
2020         tfrom = (TCHAR *)from;
2021         tto = (TCHAR *)to;
2022     } else {                    /* UNICODE path */
2023
2024         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2025         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2026         if (tfrom == NULL)
2027             goto err;
2028         tto = tfrom + flen;
2029 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2030         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2031 # endif
2032             for (i = 0; i < flen; i++)
2033                 tfrom[i] = (TCHAR)from[i];
2034 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2035         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2036 # endif
2037             for (i = 0; i < tlen; i++)
2038                 tto[i] = (TCHAR)to[i];
2039     }
2040
2041     if (MoveFile(tfrom, tto))
2042         goto ok;
2043     err = GetLastError();
2044     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2045         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2046             goto ok;
2047         err = GetLastError();
2048     }
2049     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2050         errno = ENOENT;
2051     else if (err == ERROR_ACCESS_DENIED)
2052         errno = EACCES;
2053     else
2054         errno = EINVAL;         /* we could map more codes... */
2055  err:
2056     ret = -1;
2057  ok:
2058     if (tfrom != NULL && tfrom != (TCHAR *)from)
2059         free(tfrom);
2060     return ret;
2061 }
2062 #endif
2063
2064 /* app_tminterval section */
2065 #if defined(_WIN32)
2066 double app_tminterval(int stop, int usertime)
2067 {
2068     FILETIME now;
2069     double ret = 0;
2070     static ULARGE_INTEGER tmstart;
2071     static int warning = 1;
2072 # ifdef _WIN32_WINNT
2073     static HANDLE proc = NULL;
2074
2075     if (proc == NULL) {
2076         if (check_winnt())
2077             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2078                                GetCurrentProcessId());
2079         if (proc == NULL)
2080             proc = (HANDLE) - 1;
2081     }
2082
2083     if (usertime && proc != (HANDLE) - 1) {
2084         FILETIME junk;
2085         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2086     } else
2087 # endif
2088     {
2089         SYSTEMTIME systime;
2090
2091         if (usertime && warning) {
2092             BIO_printf(bio_err, "To get meaningful results, run "
2093                        "this program on idle system.\n");
2094             warning = 0;
2095         }
2096         GetSystemTime(&systime);
2097         SystemTimeToFileTime(&systime, &now);
2098     }
2099
2100     if (stop == TM_START) {
2101         tmstart.u.LowPart = now.dwLowDateTime;
2102         tmstart.u.HighPart = now.dwHighDateTime;
2103     } else {
2104         ULARGE_INTEGER tmstop;
2105
2106         tmstop.u.LowPart = now.dwLowDateTime;
2107         tmstop.u.HighPart = now.dwHighDateTime;
2108
2109         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2110     }
2111
2112     return (ret);
2113 }
2114 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2115 # include <time.h>
2116
2117 double app_tminterval(int stop, int usertime)
2118 {
2119     double ret = 0;
2120 # ifdef CLOCK_REALTIME
2121     static struct timespec tmstart;
2122     struct timespec now;
2123 # else
2124     static unsigned long tmstart;
2125     unsigned long now;
2126 # endif
2127     static int warning = 1;
2128
2129     if (usertime && warning) {
2130         BIO_printf(bio_err, "To get meaningful results, run "
2131                    "this program on idle system.\n");
2132         warning = 0;
2133     }
2134 # ifdef CLOCK_REALTIME
2135     clock_gettime(CLOCK_REALTIME, &now);
2136     if (stop == TM_START)
2137         tmstart = now;
2138     else
2139         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2140                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2141 # else
2142     now = tickGet();
2143     if (stop == TM_START)
2144         tmstart = now;
2145     else
2146         ret = (now - tmstart) / (double)sysClkRateGet();
2147 # endif
2148     return (ret);
2149 }
2150
2151 #elif defined(OPENSSL_SYSTEM_VMS)
2152 # include <time.h>
2153 # include <times.h>
2154
2155 double app_tminterval(int stop, int usertime)
2156 {
2157     static clock_t tmstart;
2158     double ret = 0;
2159     clock_t now;
2160 # ifdef __TMS
2161     struct tms rus;
2162
2163     now = times(&rus);
2164     if (usertime)
2165         now = rus.tms_utime;
2166 # else
2167     if (usertime)
2168         now = clock();          /* sum of user and kernel times */
2169     else {
2170         struct timeval tv;
2171         gettimeofday(&tv, NULL);
2172         now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2173                         (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2174             );
2175     }
2176 # endif
2177     if (stop == TM_START)
2178         tmstart = now;
2179     else
2180         ret = (now - tmstart) / (double)(CLK_TCK);
2181
2182     return (ret);
2183 }
2184
2185 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2186 # include <sys/times.h>
2187
2188 double app_tminterval(int stop, int usertime)
2189 {
2190     double ret = 0;
2191     struct tms rus;
2192     clock_t now = times(&rus);
2193     static clock_t tmstart;
2194
2195     if (usertime)
2196         now = rus.tms_utime;
2197
2198     if (stop == TM_START)
2199         tmstart = now;
2200     else {
2201         long int tck = sysconf(_SC_CLK_TCK);
2202         ret = (now - tmstart) / (double)tck;
2203     }
2204
2205     return (ret);
2206 }
2207
2208 #else
2209 # include <sys/time.h>
2210 # include <sys/resource.h>
2211
2212 double app_tminterval(int stop, int usertime)
2213 {
2214     double ret = 0;
2215     struct rusage rus;
2216     struct timeval now;
2217     static struct timeval tmstart;
2218
2219     if (usertime)
2220         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2221     else
2222         gettimeofday(&now, NULL);
2223
2224     if (stop == TM_START)
2225         tmstart = now;
2226     else
2227         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2228                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2229
2230     return ret;
2231 }
2232 #endif
2233
2234 int app_access(const char* name, int flag)
2235 {
2236 #ifdef _WIN32
2237     return _access(name, flag);
2238 #else
2239     return access(name, flag);
2240 #endif
2241 }
2242
2243 /* app_isdir section */
2244 #ifdef _WIN32
2245 int app_isdir(const char *name)
2246 {
2247     HANDLE hList;
2248     WIN32_FIND_DATA FileData;
2249 # if defined(UNICODE) || defined(_UNICODE)
2250     size_t i, len_0 = strlen(name) + 1;
2251
2252     if (len_0 > OSSL_NELEM(FileData.cFileName))
2253         return -1;
2254
2255 #  if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2256     if (!MultiByteToWideChar
2257         (CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
2258 #  endif
2259         for (i = 0; i < len_0; i++)
2260             FileData.cFileName[i] = (WCHAR)name[i];
2261
2262     hList = FindFirstFile(FileData.cFileName, &FileData);
2263 # else
2264     hList = FindFirstFile(name, &FileData);
2265 # endif
2266     if (hList == INVALID_HANDLE_VALUE)
2267         return -1;
2268     FindClose(hList);
2269     return ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
2270 }
2271 #else
2272 # include <sys/stat.h>
2273 # ifndef S_ISDIR
2274 #  if defined(_S_IFMT) && defined(_S_IFDIR)
2275 #   define S_ISDIR(a)   (((a) & _S_IFMT) == _S_IFDIR)
2276 #  else
2277 #   define S_ISDIR(a)   (((a) & S_IFMT) == S_IFDIR)
2278 #  endif
2279 # endif
2280
2281 int app_isdir(const char *name)
2282 {
2283 # if defined(S_ISDIR)
2284     struct stat st;
2285
2286     if (stat(name, &st) == 0)
2287         return S_ISDIR(st.st_mode);
2288     else
2289         return -1;
2290 # else
2291     return -1;
2292 # endif
2293 }
2294 #endif
2295
2296 /* raw_read|write section */
2297 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2298 int raw_read_stdin(void *buf, int siz)
2299 {
2300     DWORD n;
2301     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2302         return (n);
2303     else
2304         return (-1);
2305 }
2306 #else
2307 int raw_read_stdin(void *buf, int siz)
2308 {
2309     return read(fileno(stdin), buf, siz);
2310 }
2311 #endif
2312
2313 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2314 int raw_write_stdout(const void *buf, int siz)
2315 {
2316     DWORD n;
2317     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2318         return (n);
2319     else
2320         return (-1);
2321 }
2322 #else
2323 int raw_write_stdout(const void *buf, int siz)
2324 {
2325     return write(fileno(stdout), buf, siz);
2326 }
2327 #endif
2328
2329 /*
2330  * Centralized handling if input and output files with format specification
2331  * The format is meant to show what the input and output is supposed to be,
2332  * and is therefore a show of intent more than anything else.  However, it
2333  * does impact behavior on some platform, such as differentiating between
2334  * text and binary input/output on non-Unix platforms
2335  */
2336 static int istext(int format)
2337 {
2338     return (format & B_FORMAT_TEXT) == B_FORMAT_TEXT;
2339 }
2340
2341 BIO *dup_bio_in(int format)
2342 {
2343     return BIO_new_fp(stdin,
2344                       BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2345 }
2346
2347 BIO *dup_bio_out(int format)
2348 {
2349     BIO *b = BIO_new_fp(stdout,
2350                         BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2351 #ifdef OPENSSL_SYS_VMS
2352     if (istext(format))
2353         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2354 #endif
2355     return b;
2356 }
2357
2358 BIO *dup_bio_err(int format)
2359 {
2360     BIO *b = BIO_new_fp(stderr,
2361                         BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2362 #ifdef OPENSSL_SYS_VMS
2363     if (istext(format))
2364         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2365 #endif
2366     return b;
2367 }
2368
2369 void unbuffer(FILE *fp)
2370 {
2371 /*
2372  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2373  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2374  * However, we trust that the C RTL will never give us a FILE pointer
2375  * above the first 4 GB of memory, so we simply turn off the warning
2376  * temporarily.
2377  */
2378 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2379 # pragma environment save
2380 # pragma message disable maylosedata2
2381 #endif
2382     setbuf(fp, NULL);
2383 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2384 # pragma environment restore
2385 #endif
2386 }
2387
2388 static const char *modestr(char mode, int format)
2389 {
2390     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2391
2392     switch (mode) {
2393     case 'a':
2394         return istext(format) ? "a" : "ab";
2395     case 'r':
2396         return istext(format) ? "r" : "rb";
2397     case 'w':
2398         return istext(format) ? "w" : "wb";
2399     }
2400     /* The assert above should make sure we never reach this point */
2401     return NULL;
2402 }
2403
2404 static const char *modeverb(char mode)
2405 {
2406     switch (mode) {
2407     case 'a':
2408         return "appending";
2409     case 'r':
2410         return "reading";
2411     case 'w':
2412         return "writing";
2413     }
2414     return "(doing something)";
2415 }
2416
2417 /*
2418  * Open a file for writing, owner-read-only.
2419  */
2420 BIO *bio_open_owner(const char *filename, int format, int private)
2421 {
2422     FILE *fp = NULL;
2423     BIO *b = NULL;
2424     int fd = -1, bflags, mode, textmode;
2425
2426     if (!private || filename == NULL || strcmp(filename, "-") == 0)
2427         return bio_open_default(filename, 'w', format);
2428
2429     mode = O_WRONLY;
2430 #ifdef O_CREAT
2431     mode |= O_CREAT;
2432 #endif
2433 #ifdef O_TRUNC
2434     mode |= O_TRUNC;
2435 #endif
2436     textmode = istext(format);
2437     if (!textmode) {
2438 #ifdef O_BINARY
2439         mode |= O_BINARY;
2440 #elif defined(_O_BINARY)
2441         mode |= _O_BINARY;
2442 #endif
2443     }
2444
2445 #ifdef OPENSSL_SYS_VMS
2446     /* VMS doesn't have O_BINARY, it just doesn't make sense.  But,
2447      * it still needs to know that we're going binary, or fdopen()
2448      * will fail with "invalid argument"...  so we tell VMS what the
2449      * context is.
2450      */
2451     if (!textmode)
2452         fd = open(filename, mode, 0600, "ctx=bin");
2453     else
2454 #endif
2455         fd = open(filename, mode, 0600);
2456     if (fd < 0)
2457         goto err;
2458     fp = fdopen(fd, modestr('w', format));
2459     if (fp == NULL)
2460         goto err;
2461     bflags = BIO_CLOSE;
2462     if (textmode)
2463         bflags |= BIO_FP_TEXT;
2464     b = BIO_new_fp(fp, bflags);
2465     if (b)
2466         return b;
2467
2468  err:
2469     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2470                opt_getprog(), filename, strerror(errno));
2471     ERR_print_errors(bio_err);
2472     /* If we have fp, then fdopen took over fd, so don't close both. */
2473     if (fp)
2474         fclose(fp);
2475     else if (fd >= 0)
2476         close(fd);
2477     return NULL;
2478 }
2479
2480 static BIO *bio_open_default_(const char *filename, char mode, int format,
2481                               int quiet)
2482 {
2483     BIO *ret;
2484
2485     if (filename == NULL || strcmp(filename, "-") == 0) {
2486         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2487         if (quiet) {
2488             ERR_clear_error();
2489             return ret;
2490         }
2491         if (ret != NULL)
2492             return ret;
2493         BIO_printf(bio_err,
2494                    "Can't open %s, %s\n",
2495                    mode == 'r' ? "stdin" : "stdout", strerror(errno));
2496     } else {
2497         ret = BIO_new_file(filename, modestr(mode, format));
2498         if (quiet) {
2499             ERR_clear_error();
2500             return ret;
2501         }
2502         if (ret != NULL)
2503             return ret;
2504         BIO_printf(bio_err,
2505                    "Can't open %s for %s, %s\n",
2506                    filename, modeverb(mode), strerror(errno));
2507     }
2508     ERR_print_errors(bio_err);
2509     return NULL;
2510 }
2511
2512 BIO *bio_open_default(const char *filename, char mode, int format)
2513 {
2514     return bio_open_default_(filename, mode, format, 0);
2515 }
2516
2517 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2518 {
2519     return bio_open_default_(filename, mode, format, 1);
2520 }
2521
2522 void wait_for_async(SSL *s)
2523 {
2524     /* On Windows select only works for sockets, so we simply don't wait  */
2525 #ifndef OPENSSL_SYS_WINDOWS
2526     int width = 0;
2527     fd_set asyncfds;
2528     OSSL_ASYNC_FD *fds;
2529     size_t numfds;
2530
2531     if (!SSL_get_all_async_fds(s, NULL, &numfds))
2532         return;
2533     if (numfds == 0)
2534         return;
2535     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2536     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2537         OPENSSL_free(fds);
2538     }
2539
2540     FD_ZERO(&asyncfds);
2541     while (numfds > 0) {
2542         if (width <= (int)*fds)
2543             width = (int)*fds + 1;
2544         openssl_fdset((int)*fds, &asyncfds);
2545         numfds--;
2546         fds++;
2547     }
2548     select(width, (void *)&asyncfds, NULL, NULL, NULL);
2549 #endif
2550 }