1b76dbf82563a0918b27698d4395def848159ebf
[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 <assert.h>
128 #include <openssl/err.h>
129 #include <openssl/x509.h>
130 #include <openssl/x509v3.h>
131 #include <openssl/pem.h>
132 #include <openssl/pkcs12.h>
133 #include <openssl/ui.h>
134 #include <openssl/safestack.h>
135 #ifndef OPENSSL_NO_ENGINE
136 # include <openssl/engine.h>
137 #endif
138 #ifndef OPENSSL_NO_RSA
139 # include <openssl/rsa.h>
140 #endif
141 #include <openssl/bn.h>
142 #ifndef OPENSSL_NO_JPAKE
143 # include <openssl/jpake.h>
144 #endif
145 #include <openssl/ssl.h>
146
147 #include "apps.h"
148
149 #ifdef _WIN32
150 static int WIN32_rename(const char *from, const char *to);
151 # define rename(from,to) WIN32_rename((from),(to))
152 #endif
153
154 typedef struct {
155     const char *name;
156     unsigned long flag;
157     unsigned long mask;
158 } NAME_EX_TBL;
159
160 static UI_METHOD *ui_method = NULL;
161
162 static int set_table_opts(unsigned long *flags, const char *arg,
163                           const NAME_EX_TBL * in_tbl);
164 static int set_multi_opts(unsigned long *flags, const char *arg,
165                           const NAME_EX_TBL * in_tbl);
166
167 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
168 /* Looks like this stuff is worth moving into separate function */
169 static EVP_PKEY *load_netscape_key(BIO *key, const char *file,
170                                    const char *key_descrip, int format);
171 #endif
172
173 int app_init(long mesgwin);
174
175 int chopup_args(ARGS *arg, char *buf)
176 {
177     int quoted;
178     char c, *p;
179
180     arg->argc = 0;
181     if (arg->size == 0) {
182         arg->size = 20;
183         arg->argv = app_malloc(sizeof(char *) * arg->size, "argv space");
184         if (arg->argv == NULL)
185             return 0;
186     }
187
188     for (p = buf;;) {
189         /* Skip whitespace. */
190         while (*p && isspace(*p))
191             p++;
192         if (!*p)
193             break;
194
195         /* The start of something good :-) */
196         if (arg->argc >= arg->size) {
197             arg->size += 20;
198             arg->argv = OPENSSL_realloc(arg->argv, sizeof(char *) * 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,
231                              const char *CAfile, const char *CApath)
232 {
233     if (CAfile == NULL && CApath == NULL)
234         return SSL_CTX_set_default_verify_paths(ctx);
235     return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
236 }
237
238 int dump_cert_text(BIO *out, X509 *x)
239 {
240     char *p;
241
242     p = X509_NAME_oneline(X509_get_subject_name(x), NULL, 0);
243     BIO_puts(out, "subject=");
244     BIO_puts(out, p);
245     OPENSSL_free(p);
246
247     p = X509_NAME_oneline(X509_get_issuer_name(x), NULL, 0);
248     BIO_puts(out, "\nissuer=");
249     BIO_puts(out, p);
250     BIO_puts(out, "\n");
251     OPENSSL_free(p);
252
253     return 0;
254 }
255
256 static int ui_open(UI *ui)
257 {
258     return UI_method_get_opener(UI_OpenSSL())(ui);
259 }
260
261 static int ui_read(UI *ui, UI_STRING *uis)
262 {
263     if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
264         && UI_get0_user_data(ui)) {
265         switch (UI_get_string_type(uis)) {
266         case UIT_PROMPT:
267         case UIT_VERIFY:
268             {
269                 const char *password =
270                     ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
271                 if (password && password[0] != '\0') {
272                     UI_set_result(ui, uis, password);
273                     return 1;
274                 }
275             }
276         default:
277             break;
278         }
279     }
280     return UI_method_get_reader(UI_OpenSSL())(ui, uis);
281 }
282
283 static int ui_write(UI *ui, UI_STRING *uis)
284 {
285     if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
286         && UI_get0_user_data(ui)) {
287         switch (UI_get_string_type(uis)) {
288         case UIT_PROMPT:
289         case UIT_VERIFY:
290             {
291                 const char *password =
292                     ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
293                 if (password && password[0] != '\0')
294                     return 1;
295             }
296         default:
297             break;
298         }
299     }
300     return UI_method_get_writer(UI_OpenSSL())(ui, uis);
301 }
302
303 static int ui_close(UI *ui)
304 {
305     return UI_method_get_closer(UI_OpenSSL())(ui);
306 }
307
308 int setup_ui_method(void)
309 {
310     ui_method = UI_create_method("OpenSSL application user interface");
311     UI_method_set_opener(ui_method, ui_open);
312     UI_method_set_reader(ui_method, ui_read);
313     UI_method_set_writer(ui_method, ui_write);
314     UI_method_set_closer(ui_method, ui_close);
315     return 0;
316 }
317
318 void destroy_ui_method(void)
319 {
320     if (ui_method) {
321         UI_destroy_method(ui_method);
322         ui_method = NULL;
323     }
324 }
325
326 int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
327 {
328     UI *ui = NULL;
329     int res = 0;
330     const char *prompt_info = NULL;
331     const char *password = NULL;
332     PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
333
334     if (cb_data) {
335         if (cb_data->password)
336             password = cb_data->password;
337         if (cb_data->prompt_info)
338             prompt_info = cb_data->prompt_info;
339     }
340
341     if (password) {
342         res = strlen(password);
343         if (res > bufsiz)
344             res = bufsiz;
345         memcpy(buf, password, res);
346         return res;
347     }
348
349     ui = UI_new_method(ui_method);
350     if (ui) {
351         int ok = 0;
352         char *buff = NULL;
353         int ui_flags = 0;
354         char *prompt;
355
356         prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
357         if (!prompt) {
358             BIO_printf(bio_err, "Out of memory\n");
359             UI_free(ui);
360             return 0;
361         }
362
363         ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
364         UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
365
366         if (ok >= 0)
367             ok = UI_add_input_string(ui, prompt, ui_flags, buf,
368                                      PW_MIN_LENGTH, bufsiz - 1);
369         if (ok >= 0 && verify) {
370             buff = app_malloc(bufsiz, "password buffer");
371             ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
372                                       PW_MIN_LENGTH, bufsiz - 1, buf);
373         }
374         if (ok >= 0)
375             do {
376                 ok = UI_process(ui);
377             }
378             while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
379
380         OPENSSL_clear_free(buff, (unsigned int)bufsiz);
381
382         if (ok >= 0)
383             res = strlen(buf);
384         if (ok == -1) {
385             BIO_printf(bio_err, "User interface error\n");
386             ERR_print_errors(bio_err);
387             OPENSSL_cleanse(buf, (unsigned int)bufsiz);
388             res = 0;
389         }
390         if (ok == -2) {
391             BIO_printf(bio_err, "aborted!\n");
392             OPENSSL_cleanse(buf, (unsigned int)bufsiz);
393             res = 0;
394         }
395         UI_free(ui);
396         OPENSSL_free(prompt);
397     }
398     return res;
399 }
400
401 static char *app_get_pass(char *arg, int keepbio);
402
403 int app_passwd(char *arg1, char *arg2, char **pass1, char **pass2)
404 {
405     int same;
406     if (!arg2 || !arg1 || strcmp(arg1, arg2))
407         same = 0;
408     else
409         same = 1;
410     if (arg1) {
411         *pass1 = app_get_pass(arg1, same);
412         if (!*pass1)
413             return 0;
414     } else if (pass1)
415         *pass1 = NULL;
416     if (arg2) {
417         *pass2 = app_get_pass(arg2, same ? 2 : 0);
418         if (!*pass2)
419             return 0;
420     } else if (pass2)
421         *pass2 = NULL;
422     return 1;
423 }
424
425 static char *app_get_pass(char *arg, int keepbio)
426 {
427     char *tmp, tpass[APP_PASS_LEN];
428     static BIO *pwdbio = NULL;
429     int i;
430     if (!strncmp(arg, "pass:", 5))
431         return BUF_strdup(arg + 5);
432     if (!strncmp(arg, "env:", 4)) {
433         tmp = getenv(arg + 4);
434         if (!tmp) {
435             BIO_printf(bio_err, "Can't read environment variable %s\n", arg + 4);
436             return NULL;
437         }
438         return BUF_strdup(tmp);
439     }
440     if (!keepbio || !pwdbio) {
441         if (!strncmp(arg, "file:", 5)) {
442             pwdbio = BIO_new_file(arg + 5, "r");
443             if (!pwdbio) {
444                 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
445                 return NULL;
446             }
447 #if !defined(_WIN32)
448             /*
449              * Under _WIN32, which covers even Win64 and CE, file
450              * descriptors referenced by BIO_s_fd are not inherited
451              * by child process and therefore below is not an option.
452              * It could have been an option if bss_fd.c was operating
453              * on real Windows descriptors, such as those obtained
454              * with CreateFile.
455              */
456         } else if (!strncmp(arg, "fd:", 3)) {
457             BIO *btmp;
458             i = atoi(arg + 3);
459             if (i >= 0)
460                 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
461             if ((i < 0) || !pwdbio) {
462                 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
463                 return NULL;
464             }
465             /*
466              * Can't do BIO_gets on an fd BIO so add a buffering BIO
467              */
468             btmp = BIO_new(BIO_f_buffer());
469             pwdbio = BIO_push(btmp, pwdbio);
470 #endif
471         } else if (!strcmp(arg, "stdin")) {
472             pwdbio = dup_bio_in();
473             if (!pwdbio) {
474                 BIO_printf(bio_err, "Can't open BIO for stdin\n");
475                 return NULL;
476             }
477         } else {
478             BIO_printf(bio_err, "Invalid password argument \"%s\"\n", arg);
479             return NULL;
480         }
481     }
482     i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
483     if (keepbio != 1) {
484         BIO_free_all(pwdbio);
485         pwdbio = NULL;
486     }
487     if (i <= 0) {
488         BIO_printf(bio_err, "Error reading password from BIO\n");
489         return NULL;
490     }
491     tmp = strchr(tpass, '\n');
492     if (tmp)
493         *tmp = 0;
494     return BUF_strdup(tpass);
495 }
496
497 int add_oid_section(CONF *conf)
498 {
499     char *p;
500     STACK_OF(CONF_VALUE) *sktmp;
501     CONF_VALUE *cnf;
502     int i;
503     if (!(p = NCONF_get_string(conf, NULL, "oid_section"))) {
504         ERR_clear_error();
505         return 1;
506     }
507     if (!(sktmp = NCONF_get_section(conf, p))) {
508         BIO_printf(bio_err, "problem loading oid section %s\n", p);
509         return 0;
510     }
511     for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
512         cnf = sk_CONF_VALUE_value(sktmp, i);
513         if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
514             BIO_printf(bio_err, "problem creating object %s=%s\n",
515                        cnf->name, cnf->value);
516             return 0;
517         }
518     }
519     return 1;
520 }
521
522 static int load_pkcs12(BIO *in, const char *desc,
523                        pem_password_cb *pem_cb, void *cb_data,
524                        EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
525 {
526     const char *pass;
527     char tpass[PEM_BUFSIZE];
528     int len, ret = 0;
529     PKCS12 *p12;
530     p12 = d2i_PKCS12_bio(in, NULL);
531     if (p12 == NULL) {
532         BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
533         goto die;
534     }
535     /* See if an empty password will do */
536     if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
537         pass = "";
538     else {
539         if (!pem_cb)
540             pem_cb = (pem_password_cb *)password_callback;
541         len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
542         if (len < 0) {
543             BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
544             goto die;
545         }
546         if (len < PEM_BUFSIZE)
547             tpass[len] = 0;
548         if (!PKCS12_verify_mac(p12, tpass, len)) {
549             BIO_printf(bio_err,
550                        "Mac verify error (wrong password?) in PKCS12 file for %s\n",
551                        desc);
552             goto die;
553         }
554         pass = tpass;
555     }
556     ret = PKCS12_parse(p12, pass, pkey, cert, ca);
557  die:
558     PKCS12_free(p12);
559     return ret;
560 }
561
562 int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
563 {
564     char *host = NULL, *port = NULL, *path = NULL;
565     BIO *bio = NULL;
566     OCSP_REQ_CTX *rctx = NULL;
567     int use_ssl, rv = 0;
568     if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
569         goto err;
570     if (use_ssl) {
571         BIO_puts(bio_err, "https not supported\n");
572         goto err;
573     }
574     bio = BIO_new_connect(host);
575     if (!bio || !BIO_set_conn_port(bio, port))
576         goto err;
577     rctx = OCSP_REQ_CTX_new(bio, 1024);
578     if (!rctx)
579         goto err;
580     if (!OCSP_REQ_CTX_http(rctx, "GET", path))
581         goto err;
582     if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
583         goto err;
584     if (pcert) {
585         do {
586             rv = X509_http_nbio(rctx, pcert);
587         } while (rv == -1);
588     } else {
589         do {
590             rv = X509_CRL_http_nbio(rctx, pcrl);
591         } while (rv == -1);
592     }
593
594  err:
595     OPENSSL_free(host);
596     OPENSSL_free(path);
597     OPENSSL_free(port);
598     if (bio)
599         BIO_free_all(bio);
600     OCSP_REQ_CTX_free(rctx);
601     if (rv != 1) {
602         BIO_printf(bio_err, "Error loading %s from %s\n",
603                    pcert ? "certificate" : "CRL", url);
604         ERR_print_errors(bio_err);
605     }
606     return rv;
607 }
608
609 X509 *load_cert(const char *file, int format,
610                 const char *pass, ENGINE *e, const char *cert_descrip)
611 {
612     X509 *x = NULL;
613     BIO *cert;
614
615     if (format == FORMAT_HTTP) {
616         load_cert_crl_http(file, &x, NULL);
617         return x;
618     }
619
620     if (file == NULL) {
621         unbuffer(stdin);
622         cert = dup_bio_in();
623     } else
624         cert = bio_open_default(file, RB(format));
625     if (cert == NULL)
626         goto end;
627
628     if (format == FORMAT_ASN1)
629         x = d2i_X509_bio(cert, NULL);
630     else if (format == FORMAT_NETSCAPE) {
631         NETSCAPE_X509 *nx;
632         nx = ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509), cert, NULL);
633         if (nx == NULL)
634             goto end;
635
636         if ((strncmp(NETSCAPE_CERT_HDR, (char *)nx->header->data,
637                      nx->header->length) != 0)) {
638             NETSCAPE_X509_free(nx);
639             BIO_printf(bio_err, "Error reading header on certificate\n");
640             goto end;
641         }
642         x = nx->cert;
643         nx->cert = NULL;
644         NETSCAPE_X509_free(nx);
645     } else if (format == FORMAT_PEM)
646         x = PEM_read_bio_X509_AUX(cert, NULL,
647                                   (pem_password_cb *)password_callback, NULL);
648     else if (format == FORMAT_PKCS12) {
649         if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
650             goto end;
651     } else {
652         BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
653         goto end;
654     }
655  end:
656     if (x == NULL) {
657         BIO_printf(bio_err, "unable to load certificate\n");
658         ERR_print_errors(bio_err);
659     }
660     BIO_free(cert);
661     return (x);
662 }
663
664 X509_CRL *load_crl(const char *infile, int format)
665 {
666     X509_CRL *x = NULL;
667     BIO *in = NULL;
668
669     if (format == FORMAT_HTTP) {
670         load_cert_crl_http(infile, NULL, &x);
671         return x;
672     }
673
674     in = bio_open_default(infile, RB(format));
675     if (in == NULL)
676         goto end;
677     if (format == FORMAT_ASN1)
678         x = d2i_X509_CRL_bio(in, NULL);
679     else if (format == FORMAT_PEM)
680         x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
681     else {
682         BIO_printf(bio_err, "bad input format specified for input crl\n");
683         goto end;
684     }
685     if (x == NULL) {
686         BIO_printf(bio_err, "unable to load CRL\n");
687         ERR_print_errors(bio_err);
688         goto end;
689     }
690
691  end:
692     BIO_free(in);
693     return (x);
694 }
695
696 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
697                    const char *pass, ENGINE *e, const char *key_descrip)
698 {
699     BIO *key = NULL;
700     EVP_PKEY *pkey = NULL;
701     PW_CB_DATA cb_data;
702
703     cb_data.password = pass;
704     cb_data.prompt_info = file;
705
706     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
707         BIO_printf(bio_err, "no keyfile specified\n");
708         goto end;
709     }
710 #ifndef OPENSSL_NO_ENGINE
711     if (format == FORMAT_ENGINE) {
712         if (!e)
713             BIO_printf(bio_err, "no engine specified\n");
714         else {
715             pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
716             if (!pkey) {
717                 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
718                 ERR_print_errors(bio_err);
719             }
720         }
721         goto end;
722     }
723 #endif
724     if (file == NULL && maybe_stdin) {
725         unbuffer(stdin);
726         key = dup_bio_in();
727     } else
728         key = bio_open_default(file, RB(format));
729     if (key == NULL)
730         goto end;
731     if (format == FORMAT_ASN1) {
732         pkey = d2i_PrivateKey_bio(key, NULL);
733     } else if (format == FORMAT_PEM) {
734         pkey = PEM_read_bio_PrivateKey(key, NULL,
735                                        (pem_password_cb *)password_callback,
736                                        &cb_data);
737     }
738 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
739     else if (format == FORMAT_NETSCAPE)
740         pkey = load_netscape_key(key, file, key_descrip, format);
741 #endif
742     else if (format == FORMAT_PKCS12) {
743         if (!load_pkcs12(key, key_descrip,
744                          (pem_password_cb *)password_callback, &cb_data,
745                          &pkey, NULL, NULL))
746             goto end;
747     }
748 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
749     else if (format == FORMAT_MSBLOB)
750         pkey = b2i_PrivateKey_bio(key);
751     else if (format == FORMAT_PVK)
752         pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
753                            &cb_data);
754 #endif
755     else {
756         BIO_printf(bio_err, "bad input format specified for key file\n");
757         goto end;
758     }
759  end:
760     BIO_free(key);
761     if (pkey == NULL) {
762         BIO_printf(bio_err, "unable to load %s\n", key_descrip);
763         ERR_print_errors(bio_err);
764     }
765     return (pkey);
766 }
767
768 static const char *key_file_format(int format)
769 {
770     if (format == FORMAT_PEM || format == FORMAT_PEMRSA)
771         return "r";
772     return "rb";
773 }
774
775 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
776                       const char *pass, ENGINE *e, const char *key_descrip)
777 {
778     BIO *key = NULL;
779     EVP_PKEY *pkey = NULL;
780     PW_CB_DATA cb_data;
781
782     cb_data.password = pass;
783     cb_data.prompt_info = file;
784
785     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
786         BIO_printf(bio_err, "no keyfile specified\n");
787         goto end;
788     }
789 #ifndef OPENSSL_NO_ENGINE
790     if (format == FORMAT_ENGINE) {
791         if (!e)
792             BIO_printf(bio_err, "no engine specified\n");
793         else
794             pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
795         goto end;
796     }
797 #endif
798     if (file == NULL && maybe_stdin) {
799         unbuffer(stdin);
800         key = dup_bio_in();
801     } else
802         key = bio_open_default(file, key_file_format(format));
803     if (key == NULL)
804         goto end;
805     if (format == FORMAT_ASN1) {
806         pkey = d2i_PUBKEY_bio(key, NULL);
807     }
808 #ifndef OPENSSL_NO_RSA
809     else if (format == FORMAT_ASN1RSA) {
810         RSA *rsa;
811         rsa = d2i_RSAPublicKey_bio(key, NULL);
812         if (rsa) {
813             pkey = EVP_PKEY_new();
814             if (pkey)
815                 EVP_PKEY_set1_RSA(pkey, rsa);
816             RSA_free(rsa);
817         } else
818             pkey = NULL;
819     } else if (format == FORMAT_PEMRSA) {
820         RSA *rsa;
821         rsa = PEM_read_bio_RSAPublicKey(key, NULL,
822                                         (pem_password_cb *)password_callback,
823                                         &cb_data);
824         if (rsa) {
825             pkey = EVP_PKEY_new();
826             if (pkey)
827                 EVP_PKEY_set1_RSA(pkey, rsa);
828             RSA_free(rsa);
829         } else
830             pkey = NULL;
831     }
832 #endif
833     else if (format == FORMAT_PEM) {
834         pkey = PEM_read_bio_PUBKEY(key, NULL,
835                                    (pem_password_cb *)password_callback,
836                                    &cb_data);
837     }
838 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
839     else if (format == FORMAT_NETSCAPE)
840         pkey = load_netscape_key(key, file, key_descrip, format);
841 #endif
842 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
843     else if (format == FORMAT_MSBLOB)
844         pkey = b2i_PublicKey_bio(key);
845 #endif
846  end:
847     BIO_free(key);
848     if (pkey == NULL)
849         BIO_printf(bio_err, "unable to load %s\n", key_descrip);
850     return (pkey);
851 }
852
853 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
854 static EVP_PKEY *load_netscape_key(BIO *key, const char *file,
855                                    const char *key_descrip, int format)
856 {
857     EVP_PKEY *pkey;
858     BUF_MEM *buf;
859     RSA *rsa;
860     const unsigned char *p;
861     int size, i;
862
863     buf = BUF_MEM_new();
864     pkey = EVP_PKEY_new();
865     size = 0;
866     if (buf == NULL || pkey == NULL)
867         goto error;
868     for (;;) {
869         if (!BUF_MEM_grow_clean(buf, size + 1024 * 10))
870             goto error;
871         i = BIO_read(key, &(buf->data[size]), 1024 * 10);
872         size += i;
873         if (i == 0)
874             break;
875         if (i < 0) {
876             BIO_printf(bio_err, "Error reading %s %s", key_descrip, file);
877             goto error;
878         }
879     }
880     p = (unsigned char *)buf->data;
881     rsa = d2i_RSA_NET(NULL, &p, (long)size, NULL, 0);
882     if (rsa == NULL)
883         goto error;
884     BUF_MEM_free(buf);
885     EVP_PKEY_set1_RSA(pkey, rsa);
886     return pkey;
887  error:
888     BUF_MEM_free(buf);
889     EVP_PKEY_free(pkey);
890     return NULL;
891 }
892 #endif                          /* ndef OPENSSL_NO_RC4 */
893
894 static int load_certs_crls(const char *file, int format,
895                            const char *pass, ENGINE *e, const char *desc,
896                            STACK_OF(X509) **pcerts,
897                            STACK_OF(X509_CRL) **pcrls)
898 {
899     int i;
900     BIO *bio;
901     STACK_OF(X509_INFO) *xis = NULL;
902     X509_INFO *xi;
903     PW_CB_DATA cb_data;
904     int rv = 0;
905
906     cb_data.password = pass;
907     cb_data.prompt_info = file;
908
909     if (format != FORMAT_PEM) {
910         BIO_printf(bio_err, "bad input format specified for %s\n", desc);
911         return 0;
912     }
913
914     bio = bio_open_default(file, "r");
915     if (bio == NULL)
916         return 0;
917
918     xis = PEM_X509_INFO_read_bio(bio, NULL,
919                                  (pem_password_cb *)password_callback,
920                                  &cb_data);
921
922     BIO_free(bio);
923
924     if (pcerts) {
925         *pcerts = sk_X509_new_null();
926         if (!*pcerts)
927             goto end;
928     }
929
930     if (pcrls) {
931         *pcrls = sk_X509_CRL_new_null();
932         if (!*pcrls)
933             goto end;
934     }
935
936     for (i = 0; i < sk_X509_INFO_num(xis); i++) {
937         xi = sk_X509_INFO_value(xis, i);
938         if (xi->x509 && pcerts) {
939             if (!sk_X509_push(*pcerts, xi->x509))
940                 goto end;
941             xi->x509 = NULL;
942         }
943         if (xi->crl && pcrls) {
944             if (!sk_X509_CRL_push(*pcrls, xi->crl))
945                 goto end;
946             xi->crl = NULL;
947         }
948     }
949
950     if (pcerts && sk_X509_num(*pcerts) > 0)
951         rv = 1;
952
953     if (pcrls && sk_X509_CRL_num(*pcrls) > 0)
954         rv = 1;
955
956  end:
957
958     sk_X509_INFO_pop_free(xis, X509_INFO_free);
959
960     if (rv == 0) {
961         if (pcerts) {
962             sk_X509_pop_free(*pcerts, X509_free);
963             *pcerts = NULL;
964         }
965         if (pcrls) {
966             sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
967             *pcrls = NULL;
968         }
969         BIO_printf(bio_err, "unable to load %s\n",
970                    pcerts ? "certificates" : "CRLs");
971         ERR_print_errors(bio_err);
972     }
973     return rv;
974 }
975
976 void* app_malloc(int sz, const char *what)
977 {
978     void *vp = OPENSSL_malloc(sz);
979
980     if (vp == NULL) {
981         BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
982                 opt_getprog(), sz, what);
983         ERR_print_errors(bio_err);
984         exit(1);
985     }
986     return vp;
987 }
988
989
990
991 STACK_OF(X509) *load_certs(const char *file, int format,
992                            const char *pass, ENGINE *e, const char *desc)
993 {
994     STACK_OF(X509) *certs;
995     if (!load_certs_crls(file, format, pass, e, desc, &certs, NULL))
996         return NULL;
997     return certs;
998 }
999
1000 STACK_OF(X509_CRL) *load_crls(const char *file, int format,
1001                               const char *pass, ENGINE *e, const char *desc)
1002 {
1003     STACK_OF(X509_CRL) *crls;
1004     if (!load_certs_crls(file, format, pass, e, desc, NULL, &crls))
1005         return NULL;
1006     return crls;
1007 }
1008
1009 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
1010 /* Return error for unknown extensions */
1011 #define X509V3_EXT_DEFAULT              0
1012 /* Print error for unknown extensions */
1013 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
1014 /* ASN1 parse unknown extensions */
1015 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
1016 /* BIO_dump unknown extensions */
1017 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
1018
1019 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1020                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1021
1022 int set_cert_ex(unsigned long *flags, const char *arg)
1023 {
1024     static const NAME_EX_TBL cert_tbl[] = {
1025         {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1026         {"ca_default", X509_FLAG_CA, 0xffffffffl},
1027         {"no_header", X509_FLAG_NO_HEADER, 0},
1028         {"no_version", X509_FLAG_NO_VERSION, 0},
1029         {"no_serial", X509_FLAG_NO_SERIAL, 0},
1030         {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1031         {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1032         {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1033         {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1034         {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1035         {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1036         {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1037         {"no_aux", X509_FLAG_NO_AUX, 0},
1038         {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1039         {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1040         {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1041         {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1042         {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1043         {NULL, 0, 0}
1044     };
1045     return set_multi_opts(flags, arg, cert_tbl);
1046 }
1047
1048 int set_name_ex(unsigned long *flags, const char *arg)
1049 {
1050     static const NAME_EX_TBL ex_tbl[] = {
1051         {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1052         {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1053         {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1054         {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1055         {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1056         {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1057         {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1058         {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1059         {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1060         {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1061         {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1062         {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1063         {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1064         {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1065         {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1066         {"dn_rev", XN_FLAG_DN_REV, 0},
1067         {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1068         {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1069         {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1070         {"align", XN_FLAG_FN_ALIGN, 0},
1071         {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1072         {"space_eq", XN_FLAG_SPC_EQ, 0},
1073         {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1074         {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1075         {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1076         {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1077         {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1078         {NULL, 0, 0}
1079     };
1080     return set_multi_opts(flags, arg, ex_tbl);
1081 }
1082
1083 int set_ext_copy(int *copy_type, const char *arg)
1084 {
1085     if (!strcasecmp(arg, "none"))
1086         *copy_type = EXT_COPY_NONE;
1087     else if (!strcasecmp(arg, "copy"))
1088         *copy_type = EXT_COPY_ADD;
1089     else if (!strcasecmp(arg, "copyall"))
1090         *copy_type = EXT_COPY_ALL;
1091     else
1092         return 0;
1093     return 1;
1094 }
1095
1096 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1097 {
1098     STACK_OF(X509_EXTENSION) *exts = NULL;
1099     X509_EXTENSION *ext, *tmpext;
1100     ASN1_OBJECT *obj;
1101     int i, idx, ret = 0;
1102     if (!x || !req || (copy_type == EXT_COPY_NONE))
1103         return 1;
1104     exts = X509_REQ_get_extensions(req);
1105
1106     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1107         ext = sk_X509_EXTENSION_value(exts, i);
1108         obj = X509_EXTENSION_get_object(ext);
1109         idx = X509_get_ext_by_OBJ(x, obj, -1);
1110         /* Does extension exist? */
1111         if (idx != -1) {
1112             /* If normal copy don't override existing extension */
1113             if (copy_type == EXT_COPY_ADD)
1114                 continue;
1115             /* Delete all extensions of same type */
1116             do {
1117                 tmpext = X509_get_ext(x, idx);
1118                 X509_delete_ext(x, idx);
1119                 X509_EXTENSION_free(tmpext);
1120                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1121             } while (idx != -1);
1122         }
1123         if (!X509_add_ext(x, ext, -1))
1124             goto end;
1125     }
1126
1127     ret = 1;
1128
1129  end:
1130
1131     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1132
1133     return ret;
1134 }
1135
1136 static int set_multi_opts(unsigned long *flags, const char *arg,
1137                           const NAME_EX_TBL * in_tbl)
1138 {
1139     STACK_OF(CONF_VALUE) *vals;
1140     CONF_VALUE *val;
1141     int i, ret = 1;
1142     if (!arg)
1143         return 0;
1144     vals = X509V3_parse_list(arg);
1145     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1146         val = sk_CONF_VALUE_value(vals, i);
1147         if (!set_table_opts(flags, val->name, in_tbl))
1148             ret = 0;
1149     }
1150     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1151     return ret;
1152 }
1153
1154 static int set_table_opts(unsigned long *flags, const char *arg,
1155                           const NAME_EX_TBL * in_tbl)
1156 {
1157     char c;
1158     const NAME_EX_TBL *ptbl;
1159     c = arg[0];
1160
1161     if (c == '-') {
1162         c = 0;
1163         arg++;
1164     } else if (c == '+') {
1165         c = 1;
1166         arg++;
1167     } else
1168         c = 1;
1169
1170     for (ptbl = in_tbl; ptbl->name; ptbl++) {
1171         if (!strcasecmp(arg, ptbl->name)) {
1172             *flags &= ~ptbl->mask;
1173             if (c)
1174                 *flags |= ptbl->flag;
1175             else
1176                 *flags &= ~ptbl->flag;
1177             return 1;
1178         }
1179     }
1180     return 0;
1181 }
1182
1183 void print_name(BIO *out, const char *title, X509_NAME *nm,
1184                 unsigned long lflags)
1185 {
1186     char *buf;
1187     char mline = 0;
1188     int indent = 0;
1189
1190     if (title)
1191         BIO_puts(out, title);
1192     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1193         mline = 1;
1194         indent = 4;
1195     }
1196     if (lflags == XN_FLAG_COMPAT) {
1197         buf = X509_NAME_oneline(nm, 0, 0);
1198         BIO_puts(out, buf);
1199         BIO_puts(out, "\n");
1200         OPENSSL_free(buf);
1201     } else {
1202         if (mline)
1203             BIO_puts(out, "\n");
1204         X509_NAME_print_ex(out, nm, indent, lflags);
1205         BIO_puts(out, "\n");
1206     }
1207 }
1208
1209 void print_bignum_var(BIO *out, BIGNUM *in, const char *var,
1210                       int len, unsigned char *buffer)
1211 {
1212     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
1213     if (BN_is_zero(in))
1214         BIO_printf(out, "\n\t0x00");
1215     else {
1216         int i, l;
1217
1218         l = BN_bn2bin(in, buffer);
1219         for (i = 0; i < l; i++) {
1220             if ((i % 10) == 0)
1221                 BIO_printf(out, "\n\t");
1222             if (i < l - 1)
1223                 BIO_printf(out, "0x%02X, ", buffer[i]);
1224             else
1225                 BIO_printf(out, "0x%02X", buffer[i]);
1226         }
1227     }
1228     BIO_printf(out, "\n    };\n");
1229 }
1230 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1231 {
1232     int i;
1233
1234     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1235     for (i = 0; i < len; i++) {
1236         if ((i % 10) == 0)
1237             BIO_printf(out, "\n    ");
1238         if (i < len - 1)
1239             BIO_printf(out, "0x%02X, ", d[i]);
1240         else
1241             BIO_printf(out, "0x%02X", d[i]);
1242     }
1243     BIO_printf(out, "\n};\n");
1244 }
1245
1246 X509_STORE *setup_verify(char *CAfile, char *CApath)
1247 {
1248     X509_STORE *store = X509_STORE_new();
1249     X509_LOOKUP *lookup;
1250
1251     if (!store)
1252         goto end;
1253     lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1254     if (lookup == NULL)
1255         goto end;
1256     if (CAfile) {
1257         if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1258             BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1259             goto end;
1260         }
1261     } else
1262         X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1263
1264     lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1265     if (lookup == NULL)
1266         goto end;
1267     if (CApath) {
1268         if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1269             BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1270             goto end;
1271         }
1272     } else
1273         X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1274
1275     ERR_clear_error();
1276     return store;
1277  end:
1278     X509_STORE_free(store);
1279     return NULL;
1280 }
1281
1282 #ifndef OPENSSL_NO_ENGINE
1283 /* Try to load an engine in a shareable library */
1284 static ENGINE *try_load_engine(const char *engine, int debug)
1285 {
1286     ENGINE *e = ENGINE_by_id("dynamic");
1287     if (e) {
1288         if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1289             || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1290             ENGINE_free(e);
1291             e = NULL;
1292         }
1293     }
1294     return e;
1295 }
1296
1297 ENGINE *setup_engine(const char *engine, int debug)
1298 {
1299     ENGINE *e = NULL;
1300
1301     if (engine) {
1302         if (strcmp(engine, "auto") == 0) {
1303             BIO_printf(bio_err, "enabling auto ENGINE support\n");
1304             ENGINE_register_all_complete();
1305             return NULL;
1306         }
1307         if ((e = ENGINE_by_id(engine)) == NULL
1308             && (e = try_load_engine(engine, debug)) == NULL) {
1309             BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1310             ERR_print_errors(bio_err);
1311             return NULL;
1312         }
1313         if (debug) {
1314             ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1315         }
1316         ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1317         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1318             BIO_printf(bio_err, "can't use that engine\n");
1319             ERR_print_errors(bio_err);
1320             ENGINE_free(e);
1321             return NULL;
1322         }
1323
1324         BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1325
1326         /* Free our "structural" reference. */
1327         ENGINE_free(e);
1328     }
1329     return e;
1330 }
1331 #endif
1332
1333 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1334 {
1335     const char *n;
1336
1337     n = a[DB_serial];
1338     while (*n == '0')
1339         n++;
1340     return (lh_strhash(n));
1341 }
1342
1343 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1344                             const OPENSSL_CSTRING *b)
1345 {
1346     const char *aa, *bb;
1347
1348     for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1349     for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1350     return (strcmp(aa, bb));
1351 }
1352
1353 static int index_name_qual(char **a)
1354 {
1355     return (a[0][0] == 'V');
1356 }
1357
1358 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1359 {
1360     return (lh_strhash(a[DB_name]));
1361 }
1362
1363 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1364 {
1365     return (strcmp(a[DB_name], b[DB_name]));
1366 }
1367
1368 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1369 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1370 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1371 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1372 #undef BSIZE
1373 #define BSIZE 256
1374 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1375 {
1376     BIO *in = NULL;
1377     BIGNUM *ret = NULL;
1378     char buf[1024];
1379     ASN1_INTEGER *ai = NULL;
1380
1381     ai = ASN1_INTEGER_new();
1382     if (ai == NULL)
1383         goto err;
1384
1385     in = BIO_new_file(serialfile, "r");
1386     if (in == NULL) {
1387         if (!create) {
1388             perror(serialfile);
1389             goto err;
1390         }
1391         ERR_clear_error();
1392         ret = BN_new();
1393         if (ret == NULL || !rand_serial(ret, ai))
1394             BIO_printf(bio_err, "Out of memory\n");
1395     } else {
1396         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1397             BIO_printf(bio_err, "unable to load number from %s\n",
1398                        serialfile);
1399             goto err;
1400         }
1401         ret = ASN1_INTEGER_to_BN(ai, NULL);
1402         if (ret == NULL) {
1403             BIO_printf(bio_err,
1404                        "error converting number from bin to BIGNUM\n");
1405             goto err;
1406         }
1407     }
1408
1409     if (ret && retai) {
1410         *retai = ai;
1411         ai = NULL;
1412     }
1413  err:
1414     BIO_free(in);
1415     ASN1_INTEGER_free(ai);
1416     return (ret);
1417 }
1418
1419 int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
1420                 ASN1_INTEGER **retai)
1421 {
1422     char buf[1][BSIZE];
1423     BIO *out = NULL;
1424     int ret = 0;
1425     ASN1_INTEGER *ai = NULL;
1426     int j;
1427
1428     if (suffix == NULL)
1429         j = strlen(serialfile);
1430     else
1431         j = strlen(serialfile) + strlen(suffix) + 1;
1432     if (j >= BSIZE) {
1433         BIO_printf(bio_err, "file name too long\n");
1434         goto err;
1435     }
1436
1437     if (suffix == NULL)
1438         BUF_strlcpy(buf[0], serialfile, BSIZE);
1439     else {
1440 #ifndef OPENSSL_SYS_VMS
1441         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1442 #else
1443         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1444 #endif
1445     }
1446 #ifdef RL_DEBUG
1447     BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1448 #endif
1449     out = BIO_new_file(buf[0], "w");
1450     if (out == NULL) {
1451         ERR_print_errors(bio_err);
1452         goto err;
1453     }
1454
1455     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1456         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1457         goto err;
1458     }
1459     i2a_ASN1_INTEGER(out, ai);
1460     BIO_puts(out, "\n");
1461     ret = 1;
1462     if (retai) {
1463         *retai = ai;
1464         ai = NULL;
1465     }
1466  err:
1467     BIO_free_all(out);
1468     ASN1_INTEGER_free(ai);
1469     return (ret);
1470 }
1471
1472 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1473 {
1474     char buf[5][BSIZE];
1475     int i, j;
1476
1477     i = strlen(serialfile) + strlen(old_suffix);
1478     j = strlen(serialfile) + strlen(new_suffix);
1479     if (i > j)
1480         j = i;
1481     if (j + 1 >= BSIZE) {
1482         BIO_printf(bio_err, "file name too long\n");
1483         goto err;
1484     }
1485 #ifndef OPENSSL_SYS_VMS
1486     j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
1487 #else
1488     j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, new_suffix);
1489 #endif
1490 #ifndef OPENSSL_SYS_VMS
1491     j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
1492 #else
1493     j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", serialfile, old_suffix);
1494 #endif
1495 #ifdef RL_DEBUG
1496     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1497                serialfile, buf[1]);
1498 #endif
1499     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1500 #ifdef ENOTDIR
1501         && errno != ENOTDIR
1502 #endif
1503         ) {
1504         BIO_printf(bio_err,
1505                    "unable to rename %s to %s\n", serialfile, buf[1]);
1506         perror("reason");
1507         goto err;
1508     }
1509 #ifdef RL_DEBUG
1510     BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1511                buf[0], serialfile);
1512 #endif
1513     if (rename(buf[0], serialfile) < 0) {
1514         BIO_printf(bio_err,
1515                    "unable to rename %s to %s\n", buf[0], serialfile);
1516         perror("reason");
1517         rename(buf[1], serialfile);
1518         goto err;
1519     }
1520     return 1;
1521  err:
1522     return 0;
1523 }
1524
1525 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1526 {
1527     BIGNUM *btmp;
1528     int ret = 0;
1529
1530     if (b)
1531         btmp = b;
1532     else
1533         btmp = BN_new();
1534
1535     if (!btmp)
1536         return 0;
1537
1538     if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1539         goto error;
1540     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1541         goto error;
1542
1543     ret = 1;
1544
1545  error:
1546
1547     if (btmp != b)
1548         BN_free(btmp);
1549
1550     return ret;
1551 }
1552
1553 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1554 {
1555     CA_DB *retdb = NULL;
1556     TXT_DB *tmpdb = NULL;
1557     BIO *in;
1558     CONF *dbattr_conf = NULL;
1559     char buf[1][BSIZE];
1560     long errorline = -1;
1561
1562     in = BIO_new_file(dbfile, "r");
1563     if (in == NULL) {
1564         ERR_print_errors(bio_err);
1565         goto err;
1566     }
1567     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1568         goto err;
1569
1570 #ifndef OPENSSL_SYS_VMS
1571     BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1572 #else
1573     BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1574 #endif
1575     dbattr_conf = NCONF_new(NULL);
1576     if (NCONF_load(dbattr_conf, buf[0], &errorline) <= 0) {
1577         if (errorline > 0) {
1578             BIO_printf(bio_err,
1579                        "error on line %ld of db attribute file '%s'\n",
1580                        errorline, buf[0]);
1581             goto err;
1582         } else {
1583             NCONF_free(dbattr_conf);
1584             dbattr_conf = NULL;
1585         }
1586     }
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 #ifndef OPENSSL_NO_TLSEXT
2203 /*-
2204  * next_protos_parse parses a comma separated list of strings into a string
2205  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2206  *   outlen: (output) set to the length of the resulting buffer on success.
2207  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
2208  *   in: a NUL termianted string like "abc,def,ghi"
2209  *
2210  *   returns: a malloced buffer or NULL on failure.
2211  */
2212 unsigned char *next_protos_parse(unsigned short *outlen, const char *in)
2213 {
2214     size_t len;
2215     unsigned char *out;
2216     size_t i, start = 0;
2217
2218     len = strlen(in);
2219     if (len >= 65535)
2220         return NULL;
2221
2222     out = app_malloc(strlen(in) + 1, "NPN buffer");
2223     for (i = 0; i <= len; ++i) {
2224         if (i == len || in[i] == ',') {
2225             if (i - start > 255) {
2226                 OPENSSL_free(out);
2227                 return NULL;
2228             }
2229             out[start] = i - start;
2230             start = i + 1;
2231         } else
2232             out[i + 1] = in[i];
2233     }
2234
2235     *outlen = len + 1;
2236     return out;
2237 }
2238 #endif                          /* ndef OPENSSL_NO_TLSEXT */
2239
2240 void print_cert_checks(BIO *bio, X509 *x,
2241                        const char *checkhost,
2242                        const char *checkemail, const char *checkip)
2243 {
2244     if (x == NULL)
2245         return;
2246     if (checkhost) {
2247         BIO_printf(bio, "Hostname %s does%s match certificate\n",
2248                    checkhost,
2249                    X509_check_host(x, checkhost, 0, 0, NULL) == 1
2250                        ? "" : " NOT");
2251     }
2252
2253     if (checkemail) {
2254         BIO_printf(bio, "Email %s does%s match certificate\n",
2255                    checkemail, X509_check_email(x, checkemail, 0, 0)
2256                    ? "" : " NOT");
2257     }
2258
2259     if (checkip) {
2260         BIO_printf(bio, "IP %s does%s match certificate\n",
2261                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
2262     }
2263 }
2264
2265 /* Get first http URL from a DIST_POINT structure */
2266
2267 static const char *get_dp_url(DIST_POINT *dp)
2268 {
2269     GENERAL_NAMES *gens;
2270     GENERAL_NAME *gen;
2271     int i, gtype;
2272     ASN1_STRING *uri;
2273     if (!dp->distpoint || dp->distpoint->type != 0)
2274         return NULL;
2275     gens = dp->distpoint->name.fullname;
2276     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2277         gen = sk_GENERAL_NAME_value(gens, i);
2278         uri = GENERAL_NAME_get0_value(gen, &gtype);
2279         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2280             char *uptr = (char *)ASN1_STRING_data(uri);
2281             if (!strncmp(uptr, "http://", 7))
2282                 return uptr;
2283         }
2284     }
2285     return NULL;
2286 }
2287
2288 /*
2289  * Look through a CRLDP structure and attempt to find an http URL to
2290  * downloads a CRL from.
2291  */
2292
2293 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2294 {
2295     int i;
2296     const char *urlptr = NULL;
2297     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2298         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2299         urlptr = get_dp_url(dp);
2300         if (urlptr)
2301             return load_crl(urlptr, FORMAT_HTTP);
2302     }
2303     return NULL;
2304 }
2305
2306 /*
2307  * Example of downloading CRLs from CRLDP: not usable for real world as it
2308  * always downloads, doesn't support non-blocking I/O and doesn't cache
2309  * anything.
2310  */
2311
2312 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
2313 {
2314     X509 *x;
2315     STACK_OF(X509_CRL) *crls = NULL;
2316     X509_CRL *crl;
2317     STACK_OF(DIST_POINT) *crldp;
2318
2319     crls = sk_X509_CRL_new_null();
2320     if (!crls)
2321         return NULL;
2322     x = X509_STORE_CTX_get_current_cert(ctx);
2323     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2324     crl = load_crl_crldp(crldp);
2325     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2326     if (!crl)
2327         return NULL;
2328     sk_X509_CRL_push(crls, crl);
2329     /* Try to download delta CRL */
2330     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2331     crl = load_crl_crldp(crldp);
2332     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2333     if (crl)
2334         sk_X509_CRL_push(crls, crl);
2335     return crls;
2336 }
2337
2338 void store_setup_crl_download(X509_STORE *st)
2339 {
2340     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2341 }
2342
2343 /*
2344  * Platform-specific sections
2345  */
2346 #if defined(_WIN32)
2347 # ifdef fileno
2348 #  undef fileno
2349 #  define fileno(a) (int)_fileno(a)
2350 # endif
2351
2352 # include <windows.h>
2353 # include <tchar.h>
2354
2355 static int WIN32_rename(const char *from, const char *to)
2356 {
2357     TCHAR *tfrom = NULL, *tto;
2358     DWORD err;
2359     int ret = 0;
2360
2361     if (sizeof(TCHAR) == 1) {
2362         tfrom = (TCHAR *)from;
2363         tto = (TCHAR *)to;
2364     } else {                    /* UNICODE path */
2365
2366         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2367         tfrom = (TCHAR *)malloc(sizeof(TCHAR) * (flen + tlen));
2368         if (tfrom == NULL)
2369             goto err;
2370         tto = tfrom + flen;
2371 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2372         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2373 # endif
2374             for (i = 0; i < flen; i++)
2375                 tfrom[i] = (TCHAR)from[i];
2376 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2377         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2378 # endif
2379             for (i = 0; i < tlen; i++)
2380                 tto[i] = (TCHAR)to[i];
2381     }
2382
2383     if (MoveFile(tfrom, tto))
2384         goto ok;
2385     err = GetLastError();
2386     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2387         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2388             goto ok;
2389         err = GetLastError();
2390     }
2391     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2392         errno = ENOENT;
2393     else if (err == ERROR_ACCESS_DENIED)
2394         errno = EACCES;
2395     else
2396         errno = EINVAL;         /* we could map more codes... */
2397  err:
2398     ret = -1;
2399  ok:
2400     if (tfrom != NULL && tfrom != (TCHAR *)from)
2401         free(tfrom);
2402     return ret;
2403 }
2404 #endif
2405
2406 /* app_tminterval section */
2407 #if defined(_WIN32)
2408 double app_tminterval(int stop, int usertime)
2409 {
2410     FILETIME now;
2411     double ret = 0;
2412     static ULARGE_INTEGER tmstart;
2413     static int warning = 1;
2414 # ifdef _WIN32_WINNT
2415     static HANDLE proc = NULL;
2416
2417     if (proc == NULL) {
2418         if (check_winnt())
2419             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2420                                GetCurrentProcessId());
2421         if (proc == NULL)
2422             proc = (HANDLE) - 1;
2423     }
2424
2425     if (usertime && proc != (HANDLE) - 1) {
2426         FILETIME junk;
2427         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2428     } else
2429 # endif
2430     {
2431         SYSTEMTIME systime;
2432
2433         if (usertime && warning) {
2434             BIO_printf(bio_err, "To get meaningful results, run "
2435                        "this program on idle system.\n");
2436             warning = 0;
2437         }
2438         GetSystemTime(&systime);
2439         SystemTimeToFileTime(&systime, &now);
2440     }
2441
2442     if (stop == TM_START) {
2443         tmstart.u.LowPart = now.dwLowDateTime;
2444         tmstart.u.HighPart = now.dwHighDateTime;
2445     } else {
2446         ULARGE_INTEGER tmstop;
2447
2448         tmstop.u.LowPart = now.dwLowDateTime;
2449         tmstop.u.HighPart = now.dwHighDateTime;
2450
2451         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2452     }
2453
2454     return (ret);
2455 }
2456 #elif defined(OPENSSL_SYS_NETWARE)
2457 # include <time.h>
2458
2459 double app_tminterval(int stop, int usertime)
2460 {
2461     static clock_t tmstart;
2462     static int warning = 1;
2463     double ret = 0;
2464
2465     if (usertime && warning) {
2466         BIO_printf(bio_err, "To get meaningful results, run "
2467                    "this program on idle system.\n");
2468         warning = 0;
2469     }
2470
2471     if (stop == TM_START)
2472         tmstart = clock();
2473     else
2474         ret = (clock() - tmstart) / (double)CLOCKS_PER_SEC;
2475
2476     return (ret);
2477 }
2478
2479
2480 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2481 # include <time.h>
2482
2483 double app_tminterval(int stop, int usertime)
2484 {
2485     double ret = 0;
2486 # ifdef CLOCK_REALTIME
2487     static struct timespec tmstart;
2488     struct timespec now;
2489 # else
2490     static unsigned long tmstart;
2491     unsigned long now;
2492 # endif
2493     static int warning = 1;
2494
2495     if (usertime && warning) {
2496         BIO_printf(bio_err, "To get meaningful results, run "
2497                    "this program on idle system.\n");
2498         warning = 0;
2499     }
2500 # ifdef CLOCK_REALTIME
2501     clock_gettime(CLOCK_REALTIME, &now);
2502     if (stop == TM_START)
2503         tmstart = now;
2504     else
2505         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2506                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2507 # else
2508     now = tickGet();
2509     if (stop == TM_START)
2510         tmstart = now;
2511     else
2512         ret = (now - tmstart) / (double)sysClkRateGet();
2513 # endif
2514     return (ret);
2515 }
2516
2517 #elif defined(OPENSSL_SYSTEM_VMS)
2518 # include <time.h>
2519 # include <times.h>
2520
2521 double app_tminterval(int stop, int usertime)
2522 {
2523     static clock_t tmstart;
2524     double ret = 0;
2525     clock_t now;
2526 # ifdef __TMS
2527     struct tms rus;
2528
2529     now = times(&rus);
2530     if (usertime)
2531         now = rus.tms_utime;
2532 # else
2533     if (usertime)
2534         now = clock();          /* sum of user and kernel times */
2535     else {
2536         struct timeval tv;
2537         gettimeofday(&tv, NULL);
2538         now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2539                         (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2540             );
2541     }
2542 # endif
2543     if (stop == TM_START)
2544         tmstart = now;
2545     else
2546         ret = (now - tmstart) / (double)(CLK_TCK);
2547
2548     return (ret);
2549 }
2550
2551 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2552 # include <sys/times.h>
2553
2554 double app_tminterval(int stop, int usertime)
2555 {
2556     double ret = 0;
2557     struct tms rus;
2558     clock_t now = times(&rus);
2559     static clock_t tmstart;
2560
2561     if (usertime)
2562         now = rus.tms_utime;
2563
2564     if (stop == TM_START)
2565         tmstart = now;
2566     else {
2567         long int tck = sysconf(_SC_CLK_TCK);
2568         ret = (now - tmstart) / (double)tck;
2569     }
2570
2571     return (ret);
2572 }
2573
2574 #else
2575 # include <sys/time.h>
2576 # include <sys/resource.h>
2577
2578 double app_tminterval(int stop, int usertime)
2579 {
2580     double ret = 0;
2581     struct rusage rus;
2582     struct timeval now;
2583     static struct timeval tmstart;
2584
2585     if (usertime)
2586         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2587     else
2588         gettimeofday(&now, NULL);
2589
2590     if (stop == TM_START)
2591         tmstart = now;
2592     else
2593         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2594                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2595
2596     return ret;
2597 }
2598 #endif
2599
2600 int app_access(const char* name, int flag)
2601 {
2602 #ifdef _WIN32
2603     return _access(name, flag);
2604 #else
2605     return access(name, flag);
2606 #endif
2607 }
2608
2609 int app_hex(char c)
2610 {
2611     switch (c) {
2612     default:
2613     case '0':
2614         return 0;
2615     case '1':
2616         return 1;
2617     case '2':
2618         return 2;
2619     case '3':
2620         return 3;
2621     case '4':
2622           return 4;
2623     case '5':
2624           return 5;
2625     case '6':
2626           return 6;
2627     case '7':
2628           return 7;
2629     case '8':
2630           return 8;
2631     case '9':
2632           return 9;
2633     case 'a': case 'A':
2634           return 0x0A;
2635     case 'b': case 'B':
2636           return 0x0B;
2637     case 'c': case 'C':
2638           return 0x0C;
2639     case 'd': case 'D':
2640           return 0x0D;
2641     case 'e': case 'E':
2642           return 0x0E;
2643     case 'f': case 'F':
2644           return 0x0F;
2645     }
2646 }
2647
2648 /* app_isdir section */
2649 #ifdef _WIN32
2650 int app_isdir(const char *name)
2651 {
2652     HANDLE hList;
2653     WIN32_FIND_DATA FileData;
2654 # if defined(UNICODE) || defined(_UNICODE)
2655     size_t i, len_0 = strlen(name) + 1;
2656
2657     if (len_0 > sizeof(FileData.cFileName) / sizeof(FileData.cFileName[0]))
2658         return -1;
2659
2660 #  if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2661     if (!MultiByteToWideChar
2662         (CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
2663 #  endif
2664         for (i = 0; i < len_0; i++)
2665             FileData.cFileName[i] = (WCHAR)name[i];
2666
2667     hList = FindFirstFile(FileData.cFileName, &FileData);
2668 # else
2669     hList = FindFirstFile(name, &FileData);
2670 # endif
2671     if (hList == INVALID_HANDLE_VALUE)
2672         return -1;
2673     FindClose(hList);
2674     return ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
2675 }
2676 #else
2677 # include <sys/stat.h>
2678 # ifndef S_ISDIR
2679 #  if defined(_S_IFMT) && defined(_S_IFDIR)
2680 #   define S_ISDIR(a)   (((a) & _S_IFMT) == _S_IFDIR)
2681 #  else
2682 #   define S_ISDIR(a)   (((a) & S_IFMT) == S_IFDIR)
2683 #  endif
2684 # endif
2685
2686 int app_isdir(const char *name)
2687 {
2688 # if defined(S_ISDIR)
2689     struct stat st;
2690
2691     if (stat(name, &st) == 0)
2692         return S_ISDIR(st.st_mode);
2693     else
2694         return -1;
2695 # else
2696     return -1;
2697 # endif
2698 }
2699 #endif
2700
2701 /* raw_read|write section */
2702 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2703 int raw_read_stdin(void *buf, int siz)
2704 {
2705     DWORD n;
2706     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2707         return (n);
2708     else
2709         return (-1);
2710 }
2711 #else
2712 int raw_read_stdin(void *buf, int siz)
2713 {
2714     return read(fileno(stdin), buf, siz);
2715 }
2716 #endif
2717
2718 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2719 int raw_write_stdout(const void *buf, int siz)
2720 {
2721     DWORD n;
2722     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2723         return (n);
2724     else
2725         return (-1);
2726 }
2727 #else
2728 int raw_write_stdout(const void *buf, int siz)
2729 {
2730     return write(fileno(stdout), buf, siz);
2731 }
2732 #endif