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