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