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