Few cleanups in s_client, s_server apps.
[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[2][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
1786     mem = BIO_new(BIO_s_mem());
1787     if (mem == NULL)
1788         return -1;
1789     for (;;) {
1790         if ((maxlen != -1) && maxlen < 1024)
1791             len = maxlen;
1792         else
1793             len = 1024;
1794         len = BIO_read(in, tbuf, len);
1795         if (len < 0) {
1796             BIO_free(mem);
1797             return -1;
1798         }
1799         if (len == 0)
1800             break;
1801         if (BIO_write(mem, tbuf, len) != len) {
1802             BIO_free(mem);
1803             return -1;
1804         }
1805         maxlen -= len;
1806
1807         if (maxlen == 0)
1808             break;
1809     }
1810     ret = BIO_get_mem_data(mem, (char **)out);
1811     BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1812     BIO_free(mem);
1813     return ret;
1814 }
1815
1816 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1817 {
1818     int rv;
1819     char *stmp, *vtmp = NULL;
1820     stmp = OPENSSL_strdup(value);
1821     if (!stmp)
1822         return -1;
1823     vtmp = strchr(stmp, ':');
1824     if (vtmp) {
1825         *vtmp = 0;
1826         vtmp++;
1827     }
1828     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1829     OPENSSL_free(stmp);
1830     return rv;
1831 }
1832
1833 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1834 {
1835     X509_POLICY_NODE *node;
1836     int i;
1837
1838     BIO_printf(bio_err, "%s Policies:", name);
1839     if (nodes) {
1840         BIO_puts(bio_err, "\n");
1841         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1842             node = sk_X509_POLICY_NODE_value(nodes, i);
1843             X509_POLICY_NODE_print(bio_err, node, 2);
1844         }
1845     } else
1846         BIO_puts(bio_err, " <empty>\n");
1847 }
1848
1849 void policies_print(X509_STORE_CTX *ctx)
1850 {
1851     X509_POLICY_TREE *tree;
1852     int explicit_policy;
1853     tree = X509_STORE_CTX_get0_policy_tree(ctx);
1854     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1855
1856     BIO_printf(bio_err, "Require explicit Policy: %s\n",
1857                explicit_policy ? "True" : "False");
1858
1859     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1860     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1861 }
1862
1863 /*-
1864  * next_protos_parse parses a comma separated list of strings into a string
1865  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1866  *   outlen: (output) set to the length of the resulting buffer on success.
1867  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
1868  *   in: a NUL terminated string like "abc,def,ghi"
1869  *
1870  *   returns: a malloc'd buffer or NULL on failure.
1871  */
1872 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1873 {
1874     size_t len;
1875     unsigned char *out;
1876     size_t i, start = 0;
1877
1878     len = strlen(in);
1879     if (len >= 65535)
1880         return NULL;
1881
1882     out = app_malloc(strlen(in) + 1, "NPN buffer");
1883     for (i = 0; i <= len; ++i) {
1884         if (i == len || in[i] == ',') {
1885             if (i - start > 255) {
1886                 OPENSSL_free(out);
1887                 return NULL;
1888             }
1889             out[start] = i - start;
1890             start = i + 1;
1891         } else
1892             out[i + 1] = in[i];
1893     }
1894
1895     *outlen = len + 1;
1896     return out;
1897 }
1898
1899 void print_cert_checks(BIO *bio, X509 *x,
1900                        const char *checkhost,
1901                        const char *checkemail, const char *checkip)
1902 {
1903     if (x == NULL)
1904         return;
1905     if (checkhost) {
1906         BIO_printf(bio, "Hostname %s does%s match certificate\n",
1907                    checkhost,
1908                    X509_check_host(x, checkhost, 0, 0, NULL) == 1
1909                        ? "" : " NOT");
1910     }
1911
1912     if (checkemail) {
1913         BIO_printf(bio, "Email %s does%s match certificate\n",
1914                    checkemail, X509_check_email(x, checkemail, 0, 0)
1915                    ? "" : " NOT");
1916     }
1917
1918     if (checkip) {
1919         BIO_printf(bio, "IP %s does%s match certificate\n",
1920                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1921     }
1922 }
1923
1924 /* Get first http URL from a DIST_POINT structure */
1925
1926 static const char *get_dp_url(DIST_POINT *dp)
1927 {
1928     GENERAL_NAMES *gens;
1929     GENERAL_NAME *gen;
1930     int i, gtype;
1931     ASN1_STRING *uri;
1932     if (!dp->distpoint || dp->distpoint->type != 0)
1933         return NULL;
1934     gens = dp->distpoint->name.fullname;
1935     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1936         gen = sk_GENERAL_NAME_value(gens, i);
1937         uri = GENERAL_NAME_get0_value(gen, &gtype);
1938         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1939             char *uptr = (char *)ASN1_STRING_data(uri);
1940             if (strncmp(uptr, "http://", 7) == 0)
1941                 return uptr;
1942         }
1943     }
1944     return NULL;
1945 }
1946
1947 /*
1948  * Look through a CRLDP structure and attempt to find an http URL to
1949  * downloads a CRL from.
1950  */
1951
1952 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1953 {
1954     int i;
1955     const char *urlptr = NULL;
1956     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1957         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1958         urlptr = get_dp_url(dp);
1959         if (urlptr)
1960             return load_crl(urlptr, FORMAT_HTTP);
1961     }
1962     return NULL;
1963 }
1964
1965 /*
1966  * Example of downloading CRLs from CRLDP: not usable for real world as it
1967  * always downloads, doesn't support non-blocking I/O and doesn't cache
1968  * anything.
1969  */
1970
1971 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
1972 {
1973     X509 *x;
1974     STACK_OF(X509_CRL) *crls = NULL;
1975     X509_CRL *crl;
1976     STACK_OF(DIST_POINT) *crldp;
1977
1978     crls = sk_X509_CRL_new_null();
1979     if (!crls)
1980         return NULL;
1981     x = X509_STORE_CTX_get_current_cert(ctx);
1982     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1983     crl = load_crl_crldp(crldp);
1984     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1985     if (!crl)
1986         return NULL;
1987     sk_X509_CRL_push(crls, crl);
1988     /* Try to download delta CRL */
1989     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1990     crl = load_crl_crldp(crldp);
1991     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1992     if (crl)
1993         sk_X509_CRL_push(crls, crl);
1994     return crls;
1995 }
1996
1997 void store_setup_crl_download(X509_STORE *st)
1998 {
1999     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2000 }
2001
2002 /*
2003  * Platform-specific sections
2004  */
2005 #if defined(_WIN32)
2006 # ifdef fileno
2007 #  undef fileno
2008 #  define fileno(a) (int)_fileno(a)
2009 # endif
2010
2011 # include <windows.h>
2012 # include <tchar.h>
2013
2014 static int WIN32_rename(const char *from, const char *to)
2015 {
2016     TCHAR *tfrom = NULL, *tto;
2017     DWORD err;
2018     int ret = 0;
2019
2020     if (sizeof(TCHAR) == 1) {
2021         tfrom = (TCHAR *)from;
2022         tto = (TCHAR *)to;
2023     } else {                    /* UNICODE path */
2024
2025         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2026         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2027         if (tfrom == NULL)
2028             goto err;
2029         tto = tfrom + flen;
2030 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2031         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2032 # endif
2033             for (i = 0; i < flen; i++)
2034                 tfrom[i] = (TCHAR)from[i];
2035 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2036         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2037 # endif
2038             for (i = 0; i < tlen; i++)
2039                 tto[i] = (TCHAR)to[i];
2040     }
2041
2042     if (MoveFile(tfrom, tto))
2043         goto ok;
2044     err = GetLastError();
2045     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2046         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2047             goto ok;
2048         err = GetLastError();
2049     }
2050     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2051         errno = ENOENT;
2052     else if (err == ERROR_ACCESS_DENIED)
2053         errno = EACCES;
2054     else
2055         errno = EINVAL;         /* we could map more codes... */
2056  err:
2057     ret = -1;
2058  ok:
2059     if (tfrom != NULL && tfrom != (TCHAR *)from)
2060         free(tfrom);
2061     return ret;
2062 }
2063 #endif
2064
2065 /* app_tminterval section */
2066 #if defined(_WIN32)
2067 double app_tminterval(int stop, int usertime)
2068 {
2069     FILETIME now;
2070     double ret = 0;
2071     static ULARGE_INTEGER tmstart;
2072     static int warning = 1;
2073 # ifdef _WIN32_WINNT
2074     static HANDLE proc = NULL;
2075
2076     if (proc == NULL) {
2077         if (check_winnt())
2078             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2079                                GetCurrentProcessId());
2080         if (proc == NULL)
2081             proc = (HANDLE) - 1;
2082     }
2083
2084     if (usertime && proc != (HANDLE) - 1) {
2085         FILETIME junk;
2086         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2087     } else
2088 # endif
2089     {
2090         SYSTEMTIME systime;
2091
2092         if (usertime && warning) {
2093             BIO_printf(bio_err, "To get meaningful results, run "
2094                        "this program on idle system.\n");
2095             warning = 0;
2096         }
2097         GetSystemTime(&systime);
2098         SystemTimeToFileTime(&systime, &now);
2099     }
2100
2101     if (stop == TM_START) {
2102         tmstart.u.LowPart = now.dwLowDateTime;
2103         tmstart.u.HighPart = now.dwHighDateTime;
2104     } else {
2105         ULARGE_INTEGER tmstop;
2106
2107         tmstop.u.LowPart = now.dwLowDateTime;
2108         tmstop.u.HighPart = now.dwHighDateTime;
2109
2110         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2111     }
2112
2113     return (ret);
2114 }
2115 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2116 # include <time.h>
2117
2118 double app_tminterval(int stop, int usertime)
2119 {
2120     double ret = 0;
2121 # ifdef CLOCK_REALTIME
2122     static struct timespec tmstart;
2123     struct timespec now;
2124 # else
2125     static unsigned long tmstart;
2126     unsigned long now;
2127 # endif
2128     static int warning = 1;
2129
2130     if (usertime && warning) {
2131         BIO_printf(bio_err, "To get meaningful results, run "
2132                    "this program on idle system.\n");
2133         warning = 0;
2134     }
2135 # ifdef CLOCK_REALTIME
2136     clock_gettime(CLOCK_REALTIME, &now);
2137     if (stop == TM_START)
2138         tmstart = now;
2139     else
2140         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2141                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2142 # else
2143     now = tickGet();
2144     if (stop == TM_START)
2145         tmstart = now;
2146     else
2147         ret = (now - tmstart) / (double)sysClkRateGet();
2148 # endif
2149     return (ret);
2150 }
2151
2152 #elif defined(OPENSSL_SYSTEM_VMS)
2153 # include <time.h>
2154 # include <times.h>
2155
2156 double app_tminterval(int stop, int usertime)
2157 {
2158     static clock_t tmstart;
2159     double ret = 0;
2160     clock_t now;
2161 # ifdef __TMS
2162     struct tms rus;
2163
2164     now = times(&rus);
2165     if (usertime)
2166         now = rus.tms_utime;
2167 # else
2168     if (usertime)
2169         now = clock();          /* sum of user and kernel times */
2170     else {
2171         struct timeval tv;
2172         gettimeofday(&tv, NULL);
2173         now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2174                         (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2175             );
2176     }
2177 # endif
2178     if (stop == TM_START)
2179         tmstart = now;
2180     else
2181         ret = (now - tmstart) / (double)(CLK_TCK);
2182
2183     return (ret);
2184 }
2185
2186 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2187 # include <sys/times.h>
2188
2189 double app_tminterval(int stop, int usertime)
2190 {
2191     double ret = 0;
2192     struct tms rus;
2193     clock_t now = times(&rus);
2194     static clock_t tmstart;
2195
2196     if (usertime)
2197         now = rus.tms_utime;
2198
2199     if (stop == TM_START)
2200         tmstart = now;
2201     else {
2202         long int tck = sysconf(_SC_CLK_TCK);
2203         ret = (now - tmstart) / (double)tck;
2204     }
2205
2206     return (ret);
2207 }
2208
2209 #else
2210 # include <sys/time.h>
2211 # include <sys/resource.h>
2212
2213 double app_tminterval(int stop, int usertime)
2214 {
2215     double ret = 0;
2216     struct rusage rus;
2217     struct timeval now;
2218     static struct timeval tmstart;
2219
2220     if (usertime)
2221         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2222     else
2223         gettimeofday(&now, NULL);
2224
2225     if (stop == TM_START)
2226         tmstart = now;
2227     else
2228         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2229                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2230
2231     return ret;
2232 }
2233 #endif
2234
2235 int app_access(const char* name, int flag)
2236 {
2237 #ifdef _WIN32
2238     return _access(name, flag);
2239 #else
2240     return access(name, flag);
2241 #endif
2242 }
2243
2244 /* app_isdir section */
2245 #ifdef _WIN32
2246 int app_isdir(const char *name)
2247 {
2248     HANDLE hList;
2249     WIN32_FIND_DATA FileData;
2250 # if defined(UNICODE) || defined(_UNICODE)
2251     size_t i, len_0 = strlen(name) + 1;
2252
2253     if (len_0 > OSSL_NELEM(FileData.cFileName))
2254         return -1;
2255
2256 #  if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2257     if (!MultiByteToWideChar
2258         (CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
2259 #  endif
2260         for (i = 0; i < len_0; i++)
2261             FileData.cFileName[i] = (WCHAR)name[i];
2262
2263     hList = FindFirstFile(FileData.cFileName, &FileData);
2264 # else
2265     hList = FindFirstFile(name, &FileData);
2266 # endif
2267     if (hList == INVALID_HANDLE_VALUE)
2268         return -1;
2269     FindClose(hList);
2270     return ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
2271 }
2272 #else
2273 # include <sys/stat.h>
2274 # ifndef S_ISDIR
2275 #  if defined(_S_IFMT) && defined(_S_IFDIR)
2276 #   define S_ISDIR(a)   (((a) & _S_IFMT) == _S_IFDIR)
2277 #  else
2278 #   define S_ISDIR(a)   (((a) & S_IFMT) == S_IFDIR)
2279 #  endif
2280 # endif
2281
2282 int app_isdir(const char *name)
2283 {
2284 # if defined(S_ISDIR)
2285     struct stat st;
2286
2287     if (stat(name, &st) == 0)
2288         return S_ISDIR(st.st_mode);
2289     else
2290         return -1;
2291 # else
2292     return -1;
2293 # endif
2294 }
2295 #endif
2296
2297 /* raw_read|write section */
2298 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2299 int raw_read_stdin(void *buf, int siz)
2300 {
2301     DWORD n;
2302     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2303         return (n);
2304     else
2305         return (-1);
2306 }
2307 #else
2308 int raw_read_stdin(void *buf, int siz)
2309 {
2310     return read(fileno(stdin), buf, siz);
2311 }
2312 #endif
2313
2314 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2315 int raw_write_stdout(const void *buf, int siz)
2316 {
2317     DWORD n;
2318     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2319         return (n);
2320     else
2321         return (-1);
2322 }
2323 #else
2324 int raw_write_stdout(const void *buf, int siz)
2325 {
2326     return write(fileno(stdout), buf, siz);
2327 }
2328 #endif
2329
2330 /*
2331  * Centralized handling if input and output files with format specification
2332  * The format is meant to show what the input and output is supposed to be,
2333  * and is therefore a show of intent more than anything else.  However, it
2334  * does impact behavior on some platform, such as differentiating between
2335  * text and binary input/output on non-Unix platforms
2336  */
2337 static int istext(int format)
2338 {
2339     return (format & B_FORMAT_TEXT) == B_FORMAT_TEXT;
2340 }
2341
2342 BIO *dup_bio_in(int format)
2343 {
2344     return BIO_new_fp(stdin,
2345                       BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2346 }
2347
2348 BIO *dup_bio_out(int format)
2349 {
2350     BIO *b = BIO_new_fp(stdout,
2351                         BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2352 #ifdef OPENSSL_SYS_VMS
2353     if (istext(format))
2354         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2355 #endif
2356     return b;
2357 }
2358
2359 BIO *dup_bio_err(int format)
2360 {
2361     BIO *b = BIO_new_fp(stderr,
2362                         BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2363 #ifdef OPENSSL_SYS_VMS
2364     if (istext(format))
2365         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2366 #endif
2367     return b;
2368 }
2369
2370 void unbuffer(FILE *fp)
2371 {
2372 /*
2373  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2374  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2375  * However, we trust that the C RTL will never give us a FILE pointer
2376  * above the first 4 GB of memory, so we simply turn off the warning
2377  * temporarily.
2378  */
2379 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2380 # pragma environment save
2381 # pragma message disable maylosedata2
2382 #endif
2383     setbuf(fp, NULL);
2384 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2385 # pragma environment restore
2386 #endif
2387 }
2388
2389 static const char *modestr(char mode, int format)
2390 {
2391     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2392
2393     switch (mode) {
2394     case 'a':
2395         return istext(format) ? "a" : "ab";
2396     case 'r':
2397         return istext(format) ? "r" : "rb";
2398     case 'w':
2399         return istext(format) ? "w" : "wb";
2400     }
2401     /* The assert above should make sure we never reach this point */
2402     return NULL;
2403 }
2404
2405 static const char *modeverb(char mode)
2406 {
2407     switch (mode) {
2408     case 'a':
2409         return "appending";
2410     case 'r':
2411         return "reading";
2412     case 'w':
2413         return "writing";
2414     }
2415     return "(doing something)";
2416 }
2417
2418 /*
2419  * Open a file for writing, owner-read-only.
2420  */
2421 BIO *bio_open_owner(const char *filename, int format, int private)
2422 {
2423     FILE *fp = NULL;
2424     BIO *b = NULL;
2425     int fd = -1, bflags, mode, textmode;
2426
2427     if (!private || filename == NULL || strcmp(filename, "-") == 0)
2428         return bio_open_default(filename, 'w', format);
2429
2430     mode = O_WRONLY;
2431 #ifdef O_CREAT
2432     mode |= O_CREAT;
2433 #endif
2434 #ifdef O_TRUNC
2435     mode |= O_TRUNC;
2436 #endif
2437     textmode = istext(format);
2438     if (!textmode) {
2439 #ifdef O_BINARY
2440         mode |= O_BINARY;
2441 #elif defined(_O_BINARY)
2442         mode |= _O_BINARY;
2443 #endif
2444     }
2445
2446 #ifdef OPENSSL_SYS_VMS
2447     /* VMS doesn't have O_BINARY, it just doesn't make sense.  But,
2448      * it still needs to know that we're going binary, or fdopen()
2449      * will fail with "invalid argument"...  so we tell VMS what the
2450      * context is.
2451      */
2452     if (!textmode)
2453         fd = open(filename, mode, 0600, "ctx=bin");
2454     else
2455 #endif
2456         fd = open(filename, mode, 0600);
2457     if (fd < 0)
2458         goto err;
2459     fp = fdopen(fd, modestr('w', format));
2460     if (fp == NULL)
2461         goto err;
2462     bflags = BIO_CLOSE;
2463     if (textmode)
2464         bflags |= BIO_FP_TEXT;
2465     b = BIO_new_fp(fp, bflags);
2466     if (b)
2467         return b;
2468
2469  err:
2470     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2471                opt_getprog(), filename, strerror(errno));
2472     ERR_print_errors(bio_err);
2473     /* If we have fp, then fdopen took over fd, so don't close both. */
2474     if (fp)
2475         fclose(fp);
2476     else if (fd >= 0)
2477         close(fd);
2478     return NULL;
2479 }
2480
2481 static BIO *bio_open_default_(const char *filename, char mode, int format,
2482                               int quiet)
2483 {
2484     BIO *ret;
2485
2486     if (filename == NULL || strcmp(filename, "-") == 0) {
2487         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2488         if (quiet) {
2489             ERR_clear_error();
2490             return ret;
2491         }
2492         if (ret != NULL)
2493             return ret;
2494         BIO_printf(bio_err,
2495                    "Can't open %s, %s\n",
2496                    mode == 'r' ? "stdin" : "stdout", strerror(errno));
2497     } else {
2498         ret = BIO_new_file(filename, modestr(mode, format));
2499         if (quiet) {
2500             ERR_clear_error();
2501             return ret;
2502         }
2503         if (ret != NULL)
2504             return ret;
2505         BIO_printf(bio_err,
2506                    "Can't open %s for %s, %s\n",
2507                    filename, modeverb(mode), strerror(errno));
2508     }
2509     ERR_print_errors(bio_err);
2510     return NULL;
2511 }
2512
2513 BIO *bio_open_default(const char *filename, char mode, int format)
2514 {
2515     return bio_open_default_(filename, mode, format, 0);
2516 }
2517
2518 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2519 {
2520     return bio_open_default_(filename, mode, format, 1);
2521 }
2522
2523 void wait_for_async(SSL *s)
2524 {
2525     /* On Windows select only works for sockets, so we simply don't wait  */
2526 #ifndef OPENSSL_SYS_WINDOWS
2527     int width = 0;
2528     fd_set asyncfds;
2529     OSSL_ASYNC_FD *fds;
2530     size_t numfds;
2531
2532     if (!SSL_get_all_async_fds(s, NULL, &numfds))
2533         return;
2534     if (numfds == 0)
2535         return;
2536     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2537     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2538         OPENSSL_free(fds);
2539     }
2540
2541     FD_ZERO(&asyncfds);
2542     while (numfds > 0) {
2543         if (width <= (int)*fds)
2544             width = (int)*fds + 1;
2545         openssl_fdset((int)*fds, &asyncfds);
2546         numfds--;
2547         fds++;
2548     }
2549     select(width, (void *)&asyncfds, NULL, NULL, NULL);
2550 #endif
2551 }