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