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