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