Constify d2i, s2i, c2i and r2i functions and other associated
[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 #include <stdio.h>
113 #include <stdlib.h>
114 #include <string.h>
115 #include <sys/types.h>
116 #include <sys/stat.h>
117 #include <ctype.h>
118 #include <openssl/err.h>
119 #include <openssl/x509.h>
120 #include <openssl/x509v3.h>
121 #include <openssl/pem.h>
122 #include <openssl/pkcs12.h>
123 #include <openssl/ui.h>
124 #include <openssl/safestack.h>
125 #ifndef OPENSSL_NO_ENGINE
126 #include <openssl/engine.h>
127 #endif
128
129 #define NON_MAIN
130 #include "apps.h"
131 #undef NON_MAIN
132
133 typedef struct {
134         char *name;
135         unsigned long flag;
136         unsigned long mask;
137 } NAME_EX_TBL;
138
139 static UI_METHOD *ui_method = NULL;
140
141 static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
142 static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
143
144 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
145 /* Looks like this stuff is worth moving into separate function */
146 static EVP_PKEY *
147 load_netscape_key(BIO *err, BIO *key, const char *file,
148                 const char *key_descrip, int format);
149 #endif
150
151 int app_init(long mesgwin);
152 #ifdef undef /* never finished - probably never will be :-) */
153 int args_from_file(char *file, int *argc, char **argv[])
154         {
155         FILE *fp;
156         int num,i;
157         unsigned int len;
158         static char *buf=NULL;
159         static char **arg=NULL;
160         char *p;
161         struct stat stbuf;
162
163         if (stat(file,&stbuf) < 0) return(0);
164
165         fp=fopen(file,"r");
166         if (fp == NULL)
167                 return(0);
168
169         *argc=0;
170         *argv=NULL;
171
172         len=(unsigned int)stbuf.st_size;
173         if (buf != NULL) OPENSSL_free(buf);
174         buf=(char *)OPENSSL_malloc(len+1);
175         if (buf == NULL) return(0);
176
177         len=fread(buf,1,len,fp);
178         if (len <= 1) return(0);
179         buf[len]='\0';
180
181         i=0;
182         for (p=buf; *p; p++)
183                 if (*p == '\n') i++;
184         if (arg != NULL) OPENSSL_free(arg);
185         arg=(char **)OPENSSL_malloc(sizeof(char *)*(i*2));
186
187         *argv=arg;
188         num=0;
189         p=buf;
190         for (;;)
191                 {
192                 if (!*p) break;
193                 if (*p == '#') /* comment line */
194                         {
195                         while (*p && (*p != '\n')) p++;
196                         continue;
197                         }
198                 /* else we have a line */
199                 *(arg++)=p;
200                 num++;
201                 while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
202                         p++;
203                 if (!*p) break;
204                 if (*p == '\n')
205                         {
206                         *(p++)='\0';
207                         continue;
208                         }
209                 /* else it is a tab or space */
210                 p++;
211                 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
212                         p++;
213                 if (!*p) break;
214                 if (*p == '\n')
215                         {
216                         p++;
217                         continue;
218                         }
219                 *(arg++)=p++;
220                 num++;
221                 while (*p && (*p != '\n')) p++;
222                 if (!*p) break;
223                 /* else *p == '\n' */
224                 *(p++)='\0';
225                 }
226         *argc=num;
227         return(1);
228         }
229 #endif
230
231 int str2fmt(char *s)
232         {
233         if      ((*s == 'D') || (*s == 'd'))
234                 return(FORMAT_ASN1);
235         else if ((*s == 'T') || (*s == 't'))
236                 return(FORMAT_TEXT);
237         else if ((*s == 'P') || (*s == 'p'))
238                 return(FORMAT_PEM);
239         else if ((*s == 'N') || (*s == 'n'))
240                 return(FORMAT_NETSCAPE);
241         else if ((*s == 'S') || (*s == 's'))
242                 return(FORMAT_SMIME);
243         else if ((*s == '1')
244                 || (strcmp(s,"PKCS12") == 0) || (strcmp(s,"pkcs12") == 0)
245                 || (strcmp(s,"P12") == 0) || (strcmp(s,"p12") == 0))
246                 return(FORMAT_PKCS12);
247         else if ((*s == 'E') || (*s == 'e'))
248                 return(FORMAT_ENGINE);
249         else
250                 return(FORMAT_UNDEF);
251         }
252
253 #if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_NETWARE)
254 void program_name(char *in, char *out, int size)
255         {
256         int i,n;
257         char *p=NULL;
258
259         n=strlen(in);
260         /* find the last '/', '\' or ':' */
261         for (i=n-1; i>0; i--)
262                 {
263                 if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':'))
264                         {
265                         p= &(in[i+1]);
266                         break;
267                         }
268                 }
269         if (p == NULL)
270                 p=in;
271         n=strlen(p);
272
273 #if defined(OPENSSL_SYS_NETWARE)
274    /* strip off trailing .nlm if present. */
275    if ((n > 4) && (p[n-4] == '.') &&
276       ((p[n-3] == 'n') || (p[n-3] == 'N')) &&
277       ((p[n-2] == 'l') || (p[n-2] == 'L')) &&
278       ((p[n-1] == 'm') || (p[n-1] == 'M')))
279       n-=4;
280 #else
281         /* strip off trailing .exe if present. */
282         if ((n > 4) && (p[n-4] == '.') &&
283                 ((p[n-3] == 'e') || (p[n-3] == 'E')) &&
284                 ((p[n-2] == 'x') || (p[n-2] == 'X')) &&
285                 ((p[n-1] == 'e') || (p[n-1] == 'E')))
286                 n-=4;
287 #endif
288
289         if (n > size-1)
290                 n=size-1;
291
292         for (i=0; i<n; i++)
293                 {
294                 if ((p[i] >= 'A') && (p[i] <= 'Z'))
295                         out[i]=p[i]-'A'+'a';
296                 else
297                         out[i]=p[i];
298                 }
299         out[n]='\0';
300         }
301 #else
302 #ifdef OPENSSL_SYS_VMS
303 void program_name(char *in, char *out, int size)
304         {
305         char *p=in, *q;
306         char *chars=":]>";
307
308         while(*chars != '\0')
309                 {
310                 q=strrchr(p,*chars);
311                 if (q > p)
312                         p = q + 1;
313                 chars++;
314                 }
315
316         q=strrchr(p,'.');
317         if (q == NULL)
318                 q = p + strlen(p);
319         strncpy(out,p,size-1);
320         if (q-p >= size)
321                 {
322                 out[size-1]='\0';
323                 }
324         else
325                 {
326                 out[q-p]='\0';
327                 }
328         }
329 #else
330 void program_name(char *in, char *out, int size)
331         {
332         char *p;
333
334         p=strrchr(in,'/');
335         if (p != NULL)
336                 p++;
337         else
338                 p=in;
339         BUF_strlcpy(out,p,size);
340         }
341 #endif
342 #endif
343
344 #ifdef OPENSSL_SYS_WIN32
345 int WIN32_rename(char *from, char *to)
346         {
347 #ifndef OPENSSL_SYS_WINCE
348         /* Windows rename gives an error if 'to' exists, so delete it
349          * first and ignore file not found errror
350          */
351         if((remove(to) != 0) && (errno != ENOENT))
352                 return -1;
353 #undef rename
354         return rename(from, to);
355 #else
356         /* convert strings to UNICODE */
357         {
358         BOOL result = FALSE;
359         WCHAR* wfrom;
360         WCHAR* wto;
361         int i;
362         wfrom = malloc((strlen(from)+1)*2);
363         wto = malloc((strlen(to)+1)*2);
364         if (wfrom != NULL && wto != NULL)
365                 {
366                 for (i=0; i<(int)strlen(from)+1; i++)
367                         wfrom[i] = (short)from[i];
368                 for (i=0; i<(int)strlen(to)+1; i++)
369                         wto[i] = (short)to[i];
370                 result = MoveFile(wfrom, wto);
371                 }
372         if (wfrom != NULL)
373                 free(wfrom);
374         if (wto != NULL)
375                 free(wto);
376         return result;
377         }
378 #endif
379         }
380 #endif
381
382 int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
383         {
384         int num,len,i;
385         char *p;
386
387         *argc=0;
388         *argv=NULL;
389
390         len=strlen(buf);
391         i=0;
392         if (arg->count == 0)
393                 {
394                 arg->count=20;
395                 arg->data=(char **)OPENSSL_malloc(sizeof(char *)*arg->count);
396                 }
397         for (i=0; i<arg->count; i++)
398                 arg->data[i]=NULL;
399
400         num=0;
401         p=buf;
402         for (;;)
403                 {
404                 /* first scan over white space */
405                 if (!*p) break;
406                 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
407                         p++;
408                 if (!*p) break;
409
410                 /* The start of something good :-) */
411                 if (num >= arg->count)
412                         {
413                         arg->count+=20;
414                         arg->data=(char **)OPENSSL_realloc(arg->data,
415                                 sizeof(char *)*arg->count);
416                         if (argc == 0) return(0);
417                         }
418                 arg->data[num++]=p;
419
420                 /* now look for the end of this */
421                 if ((*p == '\'') || (*p == '\"')) /* scan for closing quote */
422                         {
423                         i= *(p++);
424                         arg->data[num-1]++; /* jump over quote */
425                         while (*p && (*p != i))
426                                 p++;
427                         *p='\0';
428                         }
429                 else
430                         {
431                         while (*p && ((*p != ' ') &&
432                                 (*p != '\t') && (*p != '\n')))
433                                 p++;
434
435                         if (*p == '\0')
436                                 p--;
437                         else
438                                 *p='\0';
439                         }
440                 p++;
441                 }
442         *argc=num;
443         *argv=arg->data;
444         return(1);
445         }
446
447 #ifndef APP_INIT
448 int app_init(long mesgwin)
449         {
450         return(1);
451         }
452 #endif
453
454
455 int dump_cert_text (BIO *out, X509 *x)
456 {
457         char *p;
458
459         p=X509_NAME_oneline(X509_get_subject_name(x),NULL,0);
460         BIO_puts(out,"subject=");
461         BIO_puts(out,p);
462         OPENSSL_free(p);
463
464         p=X509_NAME_oneline(X509_get_issuer_name(x),NULL,0);
465         BIO_puts(out,"\nissuer=");
466         BIO_puts(out,p);
467         BIO_puts(out,"\n");
468         OPENSSL_free(p);
469
470         return 0;
471 }
472
473 static int ui_open(UI *ui)
474         {
475         return UI_method_get_opener(UI_OpenSSL())(ui);
476         }
477 static int ui_read(UI *ui, UI_STRING *uis)
478         {
479         if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
480                 && UI_get0_user_data(ui))
481                 {
482                 switch(UI_get_string_type(uis))
483                         {
484                 case UIT_PROMPT:
485                 case UIT_VERIFY:
486                         {
487                         const char *password =
488                                 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
489                         if (password && password[0] != '\0')
490                                 {
491                                 UI_set_result(ui, uis, password);
492                                 return 1;
493                                 }
494                         }
495                 default:
496                         break;
497                         }
498                 }
499         return UI_method_get_reader(UI_OpenSSL())(ui, uis);
500         }
501 static int ui_write(UI *ui, UI_STRING *uis)
502         {
503         if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
504                 && UI_get0_user_data(ui))
505                 {
506                 switch(UI_get_string_type(uis))
507                         {
508                 case UIT_PROMPT:
509                 case UIT_VERIFY:
510                         {
511                         const char *password =
512                                 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
513                         if (password && password[0] != '\0')
514                                 return 1;
515                         }
516                 default:
517                         break;
518                         }
519                 }
520         return UI_method_get_writer(UI_OpenSSL())(ui, uis);
521         }
522 static int ui_close(UI *ui)
523         {
524         return UI_method_get_closer(UI_OpenSSL())(ui);
525         }
526 int setup_ui_method(void)
527         {
528         ui_method = UI_create_method("OpenSSL application user interface");
529         UI_method_set_opener(ui_method, ui_open);
530         UI_method_set_reader(ui_method, ui_read);
531         UI_method_set_writer(ui_method, ui_write);
532         UI_method_set_closer(ui_method, ui_close);
533         return 0;
534         }
535 void destroy_ui_method(void)
536         {
537         if(ui_method)
538                 {
539                 UI_destroy_method(ui_method);
540                 ui_method = NULL;
541                 }
542         }
543 int password_callback(char *buf, int bufsiz, int verify,
544         PW_CB_DATA *cb_tmp)
545         {
546         UI *ui = NULL;
547         int res = 0;
548         const char *prompt_info = NULL;
549         const char *password = NULL;
550         PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
551
552         if (cb_data)
553                 {
554                 if (cb_data->password)
555                         password = cb_data->password;
556                 if (cb_data->prompt_info)
557                         prompt_info = cb_data->prompt_info;
558                 }
559
560         if (password)
561                 {
562                 res = strlen(password);
563                 if (res > bufsiz)
564                         res = bufsiz;
565                 memcpy(buf, password, res);
566                 return res;
567                 }
568
569         ui = UI_new_method(ui_method);
570         if (ui)
571                 {
572                 int ok = 0;
573                 char *buff = NULL;
574                 int ui_flags = 0;
575                 char *prompt = NULL;
576
577                 prompt = UI_construct_prompt(ui, "pass phrase",
578                         cb_data->prompt_info);
579
580                 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
581                 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
582
583                 if (ok >= 0)
584                         ok = UI_add_input_string(ui,prompt,ui_flags,buf,
585                                 PW_MIN_LENGTH,BUFSIZ-1);
586                 if (ok >= 0 && verify)
587                         {
588                         buff = (char *)OPENSSL_malloc(bufsiz);
589                         ok = UI_add_verify_string(ui,prompt,ui_flags,buff,
590                                 PW_MIN_LENGTH,BUFSIZ-1, buf);
591                         }
592                 if (ok >= 0)
593                         do
594                                 {
595                                 ok = UI_process(ui);
596                                 }
597                         while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
598
599                 if (buff)
600                         {
601                         OPENSSL_cleanse(buff,(unsigned int)bufsiz);
602                         OPENSSL_free(buff);
603                         }
604
605                 if (ok >= 0)
606                         res = strlen(buf);
607                 if (ok == -1)
608                         {
609                         BIO_printf(bio_err, "User interface error\n");
610                         ERR_print_errors(bio_err);
611                         OPENSSL_cleanse(buf,(unsigned int)bufsiz);
612                         res = 0;
613                         }
614                 if (ok == -2)
615                         {
616                         BIO_printf(bio_err,"aborted!\n");
617                         OPENSSL_cleanse(buf,(unsigned int)bufsiz);
618                         res = 0;
619                         }
620                 UI_free(ui);
621                 OPENSSL_free(prompt);
622                 }
623         return res;
624         }
625
626 static char *app_get_pass(BIO *err, char *arg, int keepbio);
627
628 int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
629 {
630         int same;
631         if(!arg2 || !arg1 || strcmp(arg1, arg2)) same = 0;
632         else same = 1;
633         if(arg1) {
634                 *pass1 = app_get_pass(err, arg1, same);
635                 if(!*pass1) return 0;
636         } else if(pass1) *pass1 = NULL;
637         if(arg2) {
638                 *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
639                 if(!*pass2) return 0;
640         } else if(pass2) *pass2 = NULL;
641         return 1;
642 }
643
644 static char *app_get_pass(BIO *err, char *arg, int keepbio)
645 {
646         char *tmp, tpass[APP_PASS_LEN];
647         static BIO *pwdbio = NULL;
648         int i;
649         if(!strncmp(arg, "pass:", 5)) return BUF_strdup(arg + 5);
650         if(!strncmp(arg, "env:", 4)) {
651                 tmp = getenv(arg + 4);
652                 if(!tmp) {
653                         BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
654                         return NULL;
655                 }
656                 return BUF_strdup(tmp);
657         }
658         if(!keepbio || !pwdbio) {
659                 if(!strncmp(arg, "file:", 5)) {
660                         pwdbio = BIO_new_file(arg + 5, "r");
661                         if(!pwdbio) {
662                                 BIO_printf(err, "Can't open file %s\n", arg + 5);
663                                 return NULL;
664                         }
665                 } else if(!strncmp(arg, "fd:", 3)) {
666                         BIO *btmp;
667                         i = atoi(arg + 3);
668                         if(i >= 0) pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
669                         if((i < 0) || !pwdbio) {
670                                 BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
671                                 return NULL;
672                         }
673                         /* Can't do BIO_gets on an fd BIO so add a buffering BIO */
674                         btmp = BIO_new(BIO_f_buffer());
675                         pwdbio = BIO_push(btmp, pwdbio);
676                 } else if(!strcmp(arg, "stdin")) {
677                         pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
678                         if(!pwdbio) {
679                                 BIO_printf(err, "Can't open BIO for stdin\n");
680                                 return NULL;
681                         }
682                 } else {
683                         BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
684                         return NULL;
685                 }
686         }
687         i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
688         if(keepbio != 1) {
689                 BIO_free_all(pwdbio);
690                 pwdbio = NULL;
691         }
692         if(i <= 0) {
693                 BIO_printf(err, "Error reading password from BIO\n");
694                 return NULL;
695         }
696         tmp = strchr(tpass, '\n');
697         if(tmp) *tmp = 0;
698         return BUF_strdup(tpass);
699 }
700
701 int add_oid_section(BIO *err, CONF *conf)
702 {       
703         char *p;
704         STACK_OF(CONF_VALUE) *sktmp;
705         CONF_VALUE *cnf;
706         int i;
707         if(!(p=NCONF_get_string(conf,NULL,"oid_section")))
708                 {
709                 ERR_clear_error();
710                 return 1;
711                 }
712         if(!(sktmp = NCONF_get_section(conf, p))) {
713                 BIO_printf(err, "problem loading oid section %s\n", p);
714                 return 0;
715         }
716         for(i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
717                 cnf = sk_CONF_VALUE_value(sktmp, i);
718                 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
719                         BIO_printf(err, "problem creating object %s=%s\n",
720                                                          cnf->name, cnf->value);
721                         return 0;
722                 }
723         }
724         return 1;
725 }
726
727 X509 *load_cert(BIO *err, const char *file, int format,
728         const char *pass, ENGINE *e, const char *cert_descrip)
729         {
730         ASN1_HEADER *ah=NULL;
731         BUF_MEM *buf=NULL;
732         X509 *x=NULL;
733         BIO *cert;
734
735         if ((cert=BIO_new(BIO_s_file())) == NULL)
736                 {
737                 ERR_print_errors(err);
738                 goto end;
739                 }
740
741         if (file == NULL)
742                 {
743                 setvbuf(stdin, NULL, _IONBF, 0);
744                 BIO_set_fp(cert,stdin,BIO_NOCLOSE);
745                 }
746         else
747                 {
748                 if (BIO_read_filename(cert,file) <= 0)
749                         {
750                         BIO_printf(err, "Error opening %s %s\n",
751                                 cert_descrip, file);
752                         ERR_print_errors(err);
753                         goto end;
754                         }
755                 }
756
757         if      (format == FORMAT_ASN1)
758                 x=d2i_X509_bio(cert,NULL);
759         else if (format == FORMAT_NETSCAPE)
760                 {
761                 const unsigned char *p,*op;
762                 int size=0,i;
763
764                 /* We sort of have to do it this way because it is sort of nice
765                  * to read the header first and check it, then
766                  * try to read the certificate */
767                 buf=BUF_MEM_new();
768                 for (;;)
769                         {
770                         if ((buf == NULL) || (!BUF_MEM_grow(buf,size+1024*10)))
771                                 goto end;
772                         i=BIO_read(cert,&(buf->data[size]),1024*10);
773                         size+=i;
774                         if (i == 0) break;
775                         if (i < 0)
776                                 {
777                                 perror("reading certificate");
778                                 goto end;
779                                 }
780                         }
781                 p=(unsigned char *)buf->data;
782                 op=p;
783
784                 /* First load the header */
785                 if ((ah=d2i_ASN1_HEADER(NULL,&p,(long)size)) == NULL)
786                         goto end;
787                 if ((ah->header == NULL) || (ah->header->data == NULL) ||
788                         (strncmp(NETSCAPE_CERT_HDR,(char *)ah->header->data,
789                         ah->header->length) != 0))
790                         {
791                         BIO_printf(err,"Error reading header on certificate\n");
792                         goto end;
793                         }
794                 /* header is ok, so now read the object */
795                 p=op;
796                 ah->meth=X509_asn1_meth();
797                 if ((ah=d2i_ASN1_HEADER(&ah,&p,(long)size)) == NULL)
798                         goto end;
799                 x=(X509 *)ah->data;
800                 ah->data=NULL;
801                 }
802         else if (format == FORMAT_PEM)
803                 x=PEM_read_bio_X509_AUX(cert,NULL,
804                         (pem_password_cb *)password_callback, NULL);
805         else if (format == FORMAT_PKCS12)
806                 {
807                 PKCS12 *p12 = d2i_PKCS12_bio(cert, NULL);
808
809                 PKCS12_parse(p12, NULL, NULL, &x, NULL);
810                 PKCS12_free(p12);
811                 p12 = NULL;
812                 }
813         else    {
814                 BIO_printf(err,"bad input format specified for %s\n",
815                         cert_descrip);
816                 goto end;
817                 }
818 end:
819         if (x == NULL)
820                 {
821                 BIO_printf(err,"unable to load certificate\n");
822                 ERR_print_errors(err);
823                 }
824         if (ah != NULL) ASN1_HEADER_free(ah);
825         if (cert != NULL) BIO_free(cert);
826         if (buf != NULL) BUF_MEM_free(buf);
827         return(x);
828         }
829
830 EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
831         const char *pass, ENGINE *e, const char *key_descrip)
832         {
833         BIO *key=NULL;
834         EVP_PKEY *pkey=NULL;
835         PW_CB_DATA cb_data;
836
837         cb_data.password = pass;
838         cb_data.prompt_info = file;
839
840         if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
841                 {
842                 BIO_printf(err,"no keyfile specified\n");
843                 goto end;
844                 }
845 #ifndef OPENSSL_NO_ENGINE
846         if (format == FORMAT_ENGINE)
847                 {
848                 if (!e)
849                         BIO_printf(bio_err,"no engine specified\n");
850                 else
851                         pkey = ENGINE_load_private_key(e, file,
852                                 ui_method, &cb_data);
853                 goto end;
854                 }
855 #endif
856         key=BIO_new(BIO_s_file());
857         if (key == NULL)
858                 {
859                 ERR_print_errors(err);
860                 goto end;
861                 }
862         if (file == NULL && maybe_stdin)
863                 {
864                 setvbuf(stdin, NULL, _IONBF, 0);
865                 BIO_set_fp(key,stdin,BIO_NOCLOSE);
866                 }
867         else
868                 if (BIO_read_filename(key,file) <= 0)
869                         {
870                         BIO_printf(err, "Error opening %s %s\n",
871                                 key_descrip, file);
872                         ERR_print_errors(err);
873                         goto end;
874                         }
875         if (format == FORMAT_ASN1)
876                 {
877                 pkey=d2i_PrivateKey_bio(key, NULL);
878                 }
879         else if (format == FORMAT_PEM)
880                 {
881                 pkey=PEM_read_bio_PrivateKey(key,NULL,
882                         (pem_password_cb *)password_callback, &cb_data);
883                 }
884 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
885         else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
886                 pkey = load_netscape_key(err, key, file, key_descrip, format);
887 #endif
888         else if (format == FORMAT_PKCS12)
889                 {
890                 PKCS12 *p12 = d2i_PKCS12_bio(key, NULL);
891
892                 PKCS12_parse(p12, pass, &pkey, NULL, NULL);
893                 PKCS12_free(p12);
894                 p12 = NULL;
895                 }
896         else
897                 {
898                 BIO_printf(err,"bad input format specified for key file\n");
899                 goto end;
900                 }
901  end:
902         if (key != NULL) BIO_free(key);
903         if (pkey == NULL)
904                 BIO_printf(err,"unable to load %s\n", key_descrip);
905         return(pkey);
906         }
907
908 EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
909         const char *pass, ENGINE *e, const char *key_descrip)
910         {
911         BIO *key=NULL;
912         EVP_PKEY *pkey=NULL;
913         PW_CB_DATA cb_data;
914
915         cb_data.password = pass;
916         cb_data.prompt_info = file;
917
918         if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
919                 {
920                 BIO_printf(err,"no keyfile specified\n");
921                 goto end;
922                 }
923 #ifndef OPENSSL_NO_ENGINE
924         if (format == FORMAT_ENGINE)
925                 {
926                 if (!e)
927                         BIO_printf(bio_err,"no engine specified\n");
928                 else
929                         pkey = ENGINE_load_public_key(e, file,
930                                 ui_method, &cb_data);
931                 goto end;
932                 }
933 #endif
934         key=BIO_new(BIO_s_file());
935         if (key == NULL)
936                 {
937                 ERR_print_errors(err);
938                 goto end;
939                 }
940         if (file == NULL && maybe_stdin)
941                 {
942                 setvbuf(stdin, NULL, _IONBF, 0);
943                 BIO_set_fp(key,stdin,BIO_NOCLOSE);
944                 }
945         else
946                 if (BIO_read_filename(key,file) <= 0)
947                         {
948                         BIO_printf(err, "Error opening %s %s\n",
949                                 key_descrip, file);
950                         ERR_print_errors(err);
951                         goto end;
952                 }
953         if (format == FORMAT_ASN1)
954                 {
955                 pkey=d2i_PUBKEY_bio(key, NULL);
956                 }
957         else if (format == FORMAT_PEM)
958                 {
959                 pkey=PEM_read_bio_PUBKEY(key,NULL,
960                         (pem_password_cb *)password_callback, &cb_data);
961                 }
962 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
963         else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
964                 pkey = load_netscape_key(err, key, file, key_descrip, format);
965 #endif
966         else
967                 {
968                 BIO_printf(err,"bad input format specified for key file\n");
969                 goto end;
970                 }
971  end:
972         if (key != NULL) BIO_free(key);
973         if (pkey == NULL)
974                 BIO_printf(err,"unable to load %s\n", key_descrip);
975         return(pkey);
976         }
977
978 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
979 static EVP_PKEY *
980 load_netscape_key(BIO *err, BIO *key, const char *file,
981                 const char *key_descrip, int format)
982         {
983         EVP_PKEY *pkey;
984         BUF_MEM *buf;
985         RSA     *rsa;
986         const unsigned char *p;
987         int size, i;
988
989         buf=BUF_MEM_new();
990         pkey = EVP_PKEY_new();
991         size = 0;
992         if (buf == NULL || pkey == NULL)
993                 goto error;
994         for (;;)
995                 {
996                 if (!BUF_MEM_grow_clean(buf,size+1024*10))
997                         goto error;
998                 i = BIO_read(key, &(buf->data[size]), 1024*10);
999                 size += i;
1000                 if (i == 0)
1001                         break;
1002                 if (i < 0)
1003                         {
1004                                 BIO_printf(err, "Error reading %s %s",
1005                                         key_descrip, file);
1006                                 goto error;
1007                         }
1008                 }
1009         p=(unsigned char *)buf->data;
1010         rsa = d2i_RSA_NET(NULL,&p,(long)size,NULL,
1011                 (format == FORMAT_IISSGC ? 1 : 0));
1012         if (rsa == NULL)
1013                 goto error;
1014         BUF_MEM_free(buf);
1015         EVP_PKEY_set1_RSA(pkey, rsa);
1016         return pkey;
1017 error:
1018         BUF_MEM_free(buf);
1019         EVP_PKEY_free(pkey);
1020         return NULL;
1021         }
1022 #endif /* ndef OPENSSL_NO_RC4 */
1023
1024 STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
1025         const char *pass, ENGINE *e, const char *cert_descrip)
1026         {
1027         BIO *certs;
1028         int i;
1029         STACK_OF(X509) *othercerts = NULL;
1030         STACK_OF(X509_INFO) *allcerts = NULL;
1031         X509_INFO *xi;
1032         PW_CB_DATA cb_data;
1033
1034         cb_data.password = pass;
1035         cb_data.prompt_info = file;
1036
1037         if((certs = BIO_new(BIO_s_file())) == NULL)
1038                 {
1039                 ERR_print_errors(err);
1040                 goto end;
1041                 }
1042
1043         if (file == NULL)
1044                 BIO_set_fp(certs,stdin,BIO_NOCLOSE);
1045         else
1046                 {
1047                 if (BIO_read_filename(certs,file) <= 0)
1048                         {
1049                         BIO_printf(err, "Error opening %s %s\n",
1050                                 cert_descrip, file);
1051                         ERR_print_errors(err);
1052                         goto end;
1053                         }
1054                 }
1055
1056         if      (format == FORMAT_PEM)
1057                 {
1058                 othercerts = sk_X509_new_null();
1059                 if(!othercerts)
1060                         {
1061                         sk_X509_free(othercerts);
1062                         othercerts = NULL;
1063                         goto end;
1064                         }
1065                 allcerts = PEM_X509_INFO_read_bio(certs, NULL,
1066                                 (pem_password_cb *)password_callback, &cb_data);
1067                 for(i = 0; i < sk_X509_INFO_num(allcerts); i++)
1068                         {
1069                         xi = sk_X509_INFO_value (allcerts, i);
1070                         if (xi->x509)
1071                                 {
1072                                 sk_X509_push(othercerts, xi->x509);
1073                                 xi->x509 = NULL;
1074                                 }
1075                         }
1076                 goto end;
1077                 }
1078         else    {
1079                 BIO_printf(err,"bad input format specified for %s\n",
1080                         cert_descrip);
1081                 goto end;
1082                 }
1083 end:
1084         if (othercerts == NULL)
1085                 {
1086                 BIO_printf(err,"unable to load certificates\n");
1087                 ERR_print_errors(err);
1088                 }
1089         if (allcerts) sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
1090         if (certs != NULL) BIO_free(certs);
1091         return(othercerts);
1092         }
1093
1094
1095 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
1096 /* Return error for unknown extensions */
1097 #define X509V3_EXT_DEFAULT              0
1098 /* Print error for unknown extensions */
1099 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
1100 /* ASN1 parse unknown extensions */
1101 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
1102 /* BIO_dump unknown extensions */
1103 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
1104
1105 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1106                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1107
1108 int set_cert_ex(unsigned long *flags, const char *arg)
1109 {
1110         static const NAME_EX_TBL cert_tbl[] = {
1111                 { "compatible", X509_FLAG_COMPAT, 0xffffffffl},
1112                 { "ca_default", X509_FLAG_CA, 0xffffffffl},
1113                 { "no_header", X509_FLAG_NO_HEADER, 0},
1114                 { "no_version", X509_FLAG_NO_VERSION, 0},
1115                 { "no_serial", X509_FLAG_NO_SERIAL, 0},
1116                 { "no_signame", X509_FLAG_NO_SIGNAME, 0},
1117                 { "no_validity", X509_FLAG_NO_VALIDITY, 0},
1118                 { "no_subject", X509_FLAG_NO_SUBJECT, 0},
1119                 { "no_issuer", X509_FLAG_NO_ISSUER, 0},
1120                 { "no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1121                 { "no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1122                 { "no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1123                 { "no_aux", X509_FLAG_NO_AUX, 0},
1124                 { "no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1125                 { "ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1126                 { "ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1127                 { "ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1128                 { "ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1129                 { NULL, 0, 0}
1130         };
1131         return set_multi_opts(flags, arg, cert_tbl);
1132 }
1133
1134 int set_name_ex(unsigned long *flags, const char *arg)
1135 {
1136         static const NAME_EX_TBL ex_tbl[] = {
1137                 { "esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1138                 { "esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1139                 { "esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1140                 { "use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1141                 { "utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1142                 { "ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1143                 { "show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1144                 { "dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1145                 { "dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1146                 { "dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1147                 { "compat", XN_FLAG_COMPAT, 0xffffffffL},
1148                 { "sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1149                 { "sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1150                 { "sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1151                 { "sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1152                 { "dn_rev", XN_FLAG_DN_REV, 0},
1153                 { "nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1154                 { "sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1155                 { "lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1156                 { "align", XN_FLAG_FN_ALIGN, 0},
1157                 { "oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1158                 { "space_eq", XN_FLAG_SPC_EQ, 0},
1159                 { "dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1160                 { "RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1161                 { "oneline", XN_FLAG_ONELINE, 0xffffffffL},
1162                 { "multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1163                 { "ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1164                 { NULL, 0, 0}
1165         };
1166         return set_multi_opts(flags, arg, ex_tbl);
1167 }
1168
1169 int set_ext_copy(int *copy_type, const char *arg)
1170 {
1171         if (!strcasecmp(arg, "none"))
1172                 *copy_type = EXT_COPY_NONE;
1173         else if (!strcasecmp(arg, "copy"))
1174                 *copy_type = EXT_COPY_ADD;
1175         else if (!strcasecmp(arg, "copyall"))
1176                 *copy_type = EXT_COPY_ALL;
1177         else
1178                 return 0;
1179         return 1;
1180 }
1181
1182 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1183 {
1184         STACK_OF(X509_EXTENSION) *exts = NULL;
1185         X509_EXTENSION *ext, *tmpext;
1186         ASN1_OBJECT *obj;
1187         int i, idx, ret = 0;
1188         if (!x || !req || (copy_type == EXT_COPY_NONE))
1189                 return 1;
1190         exts = X509_REQ_get_extensions(req);
1191
1192         for(i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1193                 ext = sk_X509_EXTENSION_value(exts, i);
1194                 obj = X509_EXTENSION_get_object(ext);
1195                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1196                 /* Does extension exist? */
1197                 if (idx != -1) {
1198                         /* If normal copy don't override existing extension */
1199                         if (copy_type == EXT_COPY_ADD)
1200                                 continue;
1201                         /* Delete all extensions of same type */
1202                         do {
1203                                 tmpext = X509_get_ext(x, idx);
1204                                 X509_delete_ext(x, idx);
1205                                 X509_EXTENSION_free(tmpext);
1206                                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1207                         } while (idx != -1);
1208                 }
1209                 if (!X509_add_ext(x, ext, -1))
1210                         goto end;
1211         }
1212
1213         ret = 1;
1214
1215         end:
1216
1217         sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1218
1219         return ret;
1220 }
1221                 
1222                 
1223                         
1224
1225 static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1226 {
1227         STACK_OF(CONF_VALUE) *vals;
1228         CONF_VALUE *val;
1229         int i, ret = 1;
1230         if(!arg) return 0;
1231         vals = X509V3_parse_list(arg);
1232         for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1233                 val = sk_CONF_VALUE_value(vals, i);
1234                 if (!set_table_opts(flags, val->name, in_tbl))
1235                         ret = 0;
1236         }
1237         sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1238         return ret;
1239 }
1240
1241 static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1242 {
1243         char c;
1244         const NAME_EX_TBL *ptbl;
1245         c = arg[0];
1246
1247         if(c == '-') {
1248                 c = 0;
1249                 arg++;
1250         } else if (c == '+') {
1251                 c = 1;
1252                 arg++;
1253         } else c = 1;
1254
1255         for(ptbl = in_tbl; ptbl->name; ptbl++) {
1256                 if(!strcasecmp(arg, ptbl->name)) {
1257                         *flags &= ~ptbl->mask;
1258                         if(c) *flags |= ptbl->flag;
1259                         else *flags &= ~ptbl->flag;
1260                         return 1;
1261                 }
1262         }
1263         return 0;
1264 }
1265
1266 void print_name(BIO *out, char *title, X509_NAME *nm, unsigned long lflags)
1267 {
1268         char *buf;
1269         char mline = 0;
1270         int indent = 0;
1271
1272         if(title) BIO_puts(out, title);
1273         if((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1274                 mline = 1;
1275                 indent = 4;
1276         }
1277         if(lflags == XN_FLAG_COMPAT) {
1278                 buf = X509_NAME_oneline(nm, 0, 0);
1279                 BIO_puts(out, buf);
1280                 BIO_puts(out, "\n");
1281                 OPENSSL_free(buf);
1282         } else {
1283                 if(mline) BIO_puts(out, "\n");
1284                 X509_NAME_print_ex(out, nm, indent, lflags);
1285                 BIO_puts(out, "\n");
1286         }
1287 }
1288
1289 X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
1290 {
1291         X509_STORE *store;
1292         X509_LOOKUP *lookup;
1293         if(!(store = X509_STORE_new())) goto end;
1294         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
1295         if (lookup == NULL) goto end;
1296         if (CAfile) {
1297                 if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
1298                         BIO_printf(bp, "Error loading file %s\n", CAfile);
1299                         goto end;
1300                 }
1301         } else X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
1302                 
1303         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
1304         if (lookup == NULL) goto end;
1305         if (CApath) {
1306                 if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
1307                         BIO_printf(bp, "Error loading directory %s\n", CApath);
1308                         goto end;
1309                 }
1310         } else X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
1311
1312         ERR_clear_error();
1313         return store;
1314         end:
1315         X509_STORE_free(store);
1316         return NULL;
1317 }
1318
1319 #ifndef OPENSSL_NO_ENGINE
1320 /* Try to load an engine in a shareable library */
1321 static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
1322         {
1323         ENGINE *e = ENGINE_by_id("dynamic");
1324         if (e)
1325                 {
1326                 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1327                         || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
1328                         {
1329                         ENGINE_free(e);
1330                         e = NULL;
1331                         }
1332                 }
1333         return e;
1334         }
1335
1336 ENGINE *setup_engine(BIO *err, const char *engine, int debug)
1337         {
1338         ENGINE *e = NULL;
1339
1340         if (engine)
1341                 {
1342                 if(strcmp(engine, "auto") == 0)
1343                         {
1344                         BIO_printf(err,"enabling auto ENGINE support\n");
1345                         ENGINE_register_all_complete();
1346                         return NULL;
1347                         }
1348                 if((e = ENGINE_by_id(engine)) == NULL
1349                         && (e = try_load_engine(err, engine, debug)) == NULL)
1350                         {
1351                         BIO_printf(err,"invalid engine \"%s\"\n", engine);
1352                         ERR_print_errors(err);
1353                         return NULL;
1354                         }
1355                 if (debug)
1356                         {
1357                         ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM,
1358                                 0, err, 0);
1359                         }
1360                 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1361                 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
1362                         {
1363                         BIO_printf(err,"can't use that engine\n");
1364                         ERR_print_errors(err);
1365                         ENGINE_free(e);
1366                         return NULL;
1367                         }
1368
1369                 BIO_printf(err,"engine \"%s\" set.\n", ENGINE_get_id(e));
1370
1371                 /* Free our "structural" reference. */
1372                 ENGINE_free(e);
1373                 }
1374         return e;
1375         }
1376 #endif
1377
1378 int load_config(BIO *err, CONF *cnf)
1379         {
1380         if (!cnf)
1381                 cnf = config;
1382         if (!cnf)
1383                 return 1;
1384
1385         OPENSSL_load_builtin_modules();
1386
1387         if (CONF_modules_load(cnf, NULL, 0) <= 0)
1388                 {
1389                 BIO_printf(err, "Error configuring OpenSSL\n");
1390                 ERR_print_errors(err);
1391                 return 0;
1392                 }
1393         return 1;
1394         }
1395
1396 char *make_config_name()
1397         {
1398         const char *t=X509_get_default_cert_area();
1399         size_t len;
1400         char *p;
1401
1402         len=strlen(t)+strlen(OPENSSL_CONF)+2;
1403         p=OPENSSL_malloc(len);
1404         BUF_strlcpy(p,t,len);
1405 #ifndef OPENSSL_SYS_VMS
1406         BUF_strlcat(p,"/",len);
1407 #endif
1408         BUF_strlcat(p,OPENSSL_CONF,len);
1409
1410         return p;
1411         }
1412
1413 static unsigned long index_serial_hash(const char **a)
1414         {
1415         const char *n;
1416
1417         n=a[DB_serial];
1418         while (*n == '0') n++;
1419         return(lh_strhash(n));
1420         }
1421
1422 static int index_serial_cmp(const char **a, const char **b)
1423         {
1424         const char *aa,*bb;
1425
1426         for (aa=a[DB_serial]; *aa == '0'; aa++);
1427         for (bb=b[DB_serial]; *bb == '0'; bb++);
1428         return(strcmp(aa,bb));
1429         }
1430
1431 static int index_name_qual(char **a)
1432         { return(a[0][0] == 'V'); }
1433
1434 static unsigned long index_name_hash(const char **a)
1435         { return(lh_strhash(a[DB_name])); }
1436
1437 int index_name_cmp(const char **a, const char **b)
1438         { return(strcmp(a[DB_name],
1439              b[DB_name])); }
1440
1441 static IMPLEMENT_LHASH_HASH_FN(index_serial_hash,const char **)
1442 static IMPLEMENT_LHASH_COMP_FN(index_serial_cmp,const char **)
1443 static IMPLEMENT_LHASH_HASH_FN(index_name_hash,const char **)
1444 static IMPLEMENT_LHASH_COMP_FN(index_name_cmp,const char **)
1445
1446 #undef BSIZE
1447 #define BSIZE 256
1448
1449 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1450         {
1451         BIO *in=NULL;
1452         BIGNUM *ret=NULL;
1453         MS_STATIC char buf[1024];
1454         ASN1_INTEGER *ai=NULL;
1455
1456         ai=ASN1_INTEGER_new();
1457         if (ai == NULL) goto err;
1458
1459         if ((in=BIO_new(BIO_s_file())) == NULL)
1460                 {
1461                 ERR_print_errors(bio_err);
1462                 goto err;
1463                 }
1464
1465         if (BIO_read_filename(in,serialfile) <= 0)
1466                 {
1467                 if (!create)
1468                         {
1469                         perror(serialfile);
1470                         goto err;
1471                         }
1472                 else
1473                         {
1474                         ASN1_INTEGER_set(ai,1);
1475                         ret=BN_new();
1476                         if (ret == NULL)
1477                                 BIO_printf(bio_err, "Out of memory\n");
1478                         else
1479                                 BN_one(ret);
1480                         }
1481                 }
1482         else
1483                 {
1484                 if (!a2i_ASN1_INTEGER(in,ai,buf,1024))
1485                         {
1486                         BIO_printf(bio_err,"unable to load number from %s\n",
1487                                 serialfile);
1488                         goto err;
1489                         }
1490                 ret=ASN1_INTEGER_to_BN(ai,NULL);
1491                 if (ret == NULL)
1492                         {
1493                         BIO_printf(bio_err,"error converting number from bin to BIGNUM\n");
1494                         goto err;
1495                         }
1496                 }
1497
1498         if (ret && retai)
1499                 {
1500                 *retai = ai;
1501                 ai = NULL;
1502                 }
1503  err:
1504         if (in != NULL) BIO_free(in);
1505         if (ai != NULL) ASN1_INTEGER_free(ai);
1506         return(ret);
1507         }
1508
1509 int save_serial(char *serialfile, char *suffix, BIGNUM *serial, ASN1_INTEGER **retai)
1510         {
1511         char buf[1][BSIZE];
1512         BIO *out = NULL;
1513         int ret=0;
1514         ASN1_INTEGER *ai=NULL;
1515         int j;
1516
1517         if (suffix == NULL)
1518                 j = strlen(serialfile);
1519         else
1520                 j = strlen(serialfile) + strlen(suffix) + 1;
1521         if (j >= BSIZE)
1522                 {
1523                 BIO_printf(bio_err,"file name too long\n");
1524                 goto err;
1525                 }
1526
1527         if (suffix == NULL)
1528                 BUF_strlcpy(buf[0], serialfile, BSIZE);
1529         else
1530                 {
1531 #ifndef OPENSSL_SYS_VMS
1532                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1533 #else
1534                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1535 #endif
1536                 }
1537 #ifdef RL_DEBUG
1538         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1539 #endif
1540         out=BIO_new(BIO_s_file());
1541         if (out == NULL)
1542                 {
1543                 ERR_print_errors(bio_err);
1544                 goto err;
1545                 }
1546         if (BIO_write_filename(out,buf[0]) <= 0)
1547                 {
1548                 perror(serialfile);
1549                 goto err;
1550                 }
1551
1552         if ((ai=BN_to_ASN1_INTEGER(serial,NULL)) == NULL)
1553                 {
1554                 BIO_printf(bio_err,"error converting serial to ASN.1 format\n");
1555                 goto err;
1556                 }
1557         i2a_ASN1_INTEGER(out,ai);
1558         BIO_puts(out,"\n");
1559         ret=1;
1560         if (retai)
1561                 {
1562                 *retai = ai;
1563                 ai = NULL;
1564                 }
1565 err:
1566         if (out != NULL) BIO_free_all(out);
1567         if (ai != NULL) ASN1_INTEGER_free(ai);
1568         return(ret);
1569         }
1570
1571 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1572         {
1573         char buf[5][BSIZE];
1574         int i,j;
1575         struct stat sb;
1576
1577         i = strlen(serialfile) + strlen(old_suffix);
1578         j = strlen(serialfile) + strlen(new_suffix);
1579         if (i > j) j = i;
1580         if (j + 1 >= BSIZE)
1581                 {
1582                 BIO_printf(bio_err,"file name too long\n");
1583                 goto err;
1584                 }
1585
1586 #ifndef OPENSSL_SYS_VMS
1587         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1588                 serialfile, new_suffix);
1589 #else
1590         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1591                 serialfile, new_suffix);
1592 #endif
1593 #ifndef OPENSSL_SYS_VMS
1594         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1595                 serialfile, old_suffix);
1596 #else
1597         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1598                 serialfile, old_suffix);
1599 #endif
1600         if (stat(serialfile,&sb) < 0)
1601                 {
1602                 if (errno != ENOENT 
1603 #ifdef ENOTDIR
1604                         && errno != ENOTDIR)
1605 #endif
1606                         goto err;
1607                 }
1608         else
1609                 {
1610 #ifdef RL_DEBUG
1611                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1612                         serialfile, buf[1]);
1613 #endif
1614                 if (rename(serialfile,buf[1]) < 0)
1615                         {
1616                         BIO_printf(bio_err,
1617                                 "unable to rename %s to %s\n",
1618                                 serialfile, buf[1]);
1619                         perror("reason");
1620                         goto err;
1621                         }
1622                 }
1623 #ifdef RL_DEBUG
1624         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1625                 buf[0],serialfile);
1626 #endif
1627         if (rename(buf[0],serialfile) < 0)
1628                 {
1629                 BIO_printf(bio_err,
1630                         "unable to rename %s to %s\n",
1631                         buf[0],serialfile);
1632                 perror("reason");
1633                 rename(buf[1],serialfile);
1634                 goto err;
1635                 }
1636         return 1;
1637  err:
1638         return 0;
1639         }
1640
1641 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1642         {
1643         CA_DB *retdb = NULL;
1644         TXT_DB *tmpdb = NULL;
1645         BIO *in = BIO_new(BIO_s_file());
1646         CONF *dbattr_conf = NULL;
1647         char buf[1][BSIZE];
1648         long errorline= -1;
1649
1650         if (in == NULL)
1651                 {
1652                 ERR_print_errors(bio_err);
1653                 goto err;
1654                 }
1655         if (BIO_read_filename(in,dbfile) <= 0)
1656                 {
1657                 perror(dbfile);
1658                 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
1659                 goto err;
1660                 }
1661         if ((tmpdb = TXT_DB_read(in,DB_NUMBER)) == NULL)
1662                 {
1663                 if (tmpdb != NULL) TXT_DB_free(tmpdb);
1664                 goto err;
1665                 }
1666
1667 #ifndef OPENSSL_SYS_VMS
1668         BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1669 #else
1670         BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1671 #endif
1672         dbattr_conf = NCONF_new(NULL);
1673         if (NCONF_load(dbattr_conf,buf[0],&errorline) <= 0)
1674                 {
1675                 if (errorline > 0)
1676                         {
1677                         BIO_printf(bio_err,
1678                                 "error on line %ld of db attribute file '%s'\n"
1679                                 ,errorline,buf[0]);
1680                         goto err;
1681                         }
1682                 else
1683                         {
1684                         NCONF_free(dbattr_conf);
1685                         dbattr_conf = NULL;
1686                         }
1687                 }
1688
1689         if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL)
1690                 {
1691                 fprintf(stderr, "Out of memory\n");
1692                 goto err;
1693                 }
1694
1695         retdb->db = tmpdb;
1696         tmpdb = NULL;
1697         if (db_attr)
1698                 retdb->attributes = *db_attr;
1699         else
1700                 {
1701                 retdb->attributes.unique_subject = 1;
1702                 }
1703
1704         if (dbattr_conf)
1705                 {
1706                 char *p = NCONF_get_string(dbattr_conf,NULL,"unique_subject");
1707                 if (p)
1708                         {
1709 #ifdef RL_DEBUG
1710                         BIO_printf(bio_err, "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
1711 #endif
1712                         retdb->attributes.unique_subject = parse_yesno(p,1);
1713                         }
1714                 }
1715
1716  err:
1717         if (dbattr_conf) NCONF_free(dbattr_conf);
1718         if (tmpdb) TXT_DB_free(tmpdb);
1719         if (in) BIO_free_all(in);
1720         return retdb;
1721         }
1722
1723 int index_index(CA_DB *db)
1724         {
1725         if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1726                                 LHASH_HASH_FN(index_serial_hash),
1727                                 LHASH_COMP_FN(index_serial_cmp)))
1728                 {
1729                 BIO_printf(bio_err,
1730                   "error creating serial number index:(%ld,%ld,%ld)\n",
1731                                         db->db->error,db->db->arg1,db->db->arg2);
1732                         return 0;
1733                 }
1734
1735         if (db->attributes.unique_subject
1736                 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1737                         LHASH_HASH_FN(index_name_hash),
1738                         LHASH_COMP_FN(index_name_cmp)))
1739                 {
1740                 BIO_printf(bio_err,"error creating name index:(%ld,%ld,%ld)\n",
1741                         db->db->error,db->db->arg1,db->db->arg2);
1742                 return 0;
1743                 }
1744         return 1;
1745         }
1746
1747 int save_index(char *dbfile, char *suffix, CA_DB *db)
1748         {
1749         char buf[3][BSIZE];
1750         BIO *out = BIO_new(BIO_s_file());
1751         int j;
1752
1753         if (out == NULL)
1754                 {
1755                 ERR_print_errors(bio_err);
1756                 goto err;
1757                 }
1758
1759         j = strlen(dbfile) + strlen(suffix);
1760         if (j + 6 >= BSIZE)
1761                 {
1762                 BIO_printf(bio_err,"file name too long\n");
1763                 goto err;
1764                 }
1765
1766 #ifndef OPENSSL_SYS_VMS
1767         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1768 #else
1769         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1770 #endif
1771 #ifndef OPENSSL_SYS_VMS
1772         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1773 #else
1774         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1775 #endif
1776 #ifndef OPENSSL_SYS_VMS
1777         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1778 #else
1779         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1780 #endif
1781 #ifdef RL_DEBUG
1782         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1783 #endif
1784         if (BIO_write_filename(out,buf[0]) <= 0)
1785                 {
1786                 perror(dbfile);
1787                 BIO_printf(bio_err,"unable to open '%s'\n", dbfile);
1788                 goto err;
1789                 }
1790         j=TXT_DB_write(out,db->db);
1791         if (j <= 0) goto err;
1792                         
1793         BIO_free(out);
1794
1795         out = BIO_new(BIO_s_file());
1796 #ifdef RL_DEBUG
1797         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
1798 #endif
1799         if (BIO_write_filename(out,buf[1]) <= 0)
1800                 {
1801                 perror(buf[2]);
1802                 BIO_printf(bio_err,"unable to open '%s'\n", buf[2]);
1803                 goto err;
1804                 }
1805         BIO_printf(out,"unique_subject = %s\n",
1806                 db->attributes.unique_subject ? "yes" : "no");
1807         BIO_free(out);
1808
1809         return 1;
1810  err:
1811         return 0;
1812         }
1813
1814 int rotate_index(char *dbfile, char *new_suffix, char *old_suffix)
1815         {
1816         char buf[5][BSIZE];
1817         int i,j;
1818         struct stat sb;
1819
1820         i = strlen(dbfile) + strlen(old_suffix);
1821         j = strlen(dbfile) + strlen(new_suffix);
1822         if (i > j) j = i;
1823         if (j + 6 >= BSIZE)
1824                 {
1825                 BIO_printf(bio_err,"file name too long\n");
1826                 goto err;
1827                 }
1828
1829 #ifndef OPENSSL_SYS_VMS
1830         j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1831 #else
1832         j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1833 #endif
1834 #ifndef OPENSSL_SYS_VMS
1835         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s",
1836                 dbfile, new_suffix);
1837 #else
1838         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s",
1839                 dbfile, new_suffix);
1840 #endif
1841 #ifndef OPENSSL_SYS_VMS
1842         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1843                 dbfile, new_suffix);
1844 #else
1845         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1846                 dbfile, new_suffix);
1847 #endif
1848 #ifndef OPENSSL_SYS_VMS
1849         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1850                 dbfile, old_suffix);
1851 #else
1852         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1853                 dbfile, old_suffix);
1854 #endif
1855 #ifndef OPENSSL_SYS_VMS
1856         j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s",
1857                 dbfile, old_suffix);
1858 #else
1859         j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s",
1860                 dbfile, old_suffix);
1861 #endif
1862         if (stat(dbfile,&sb) < 0)
1863                 {
1864                 if (errno != ENOENT 
1865 #ifdef ENOTDIR
1866                         && errno != ENOTDIR)
1867 #endif
1868                         goto err;
1869                 }
1870         else
1871                 {
1872 #ifdef RL_DEBUG
1873                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1874                         dbfile, buf[1]);
1875 #endif
1876                 if (rename(dbfile,buf[1]) < 0)
1877                         {
1878                         BIO_printf(bio_err,
1879                                 "unable to rename %s to %s\n",
1880                                 dbfile, buf[1]);
1881                         perror("reason");
1882                         goto err;
1883                         }
1884                 }
1885 #ifdef RL_DEBUG
1886         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1887                 buf[0],dbfile);
1888 #endif
1889         if (rename(buf[0],dbfile) < 0)
1890                 {
1891                 BIO_printf(bio_err,
1892                         "unable to rename %s to %s\n",
1893                         buf[0],dbfile);
1894                 perror("reason");
1895                 rename(buf[1],dbfile);
1896                 goto err;
1897                 }
1898         if (stat(buf[4],&sb) < 0)
1899                 {
1900                 if (errno != ENOENT 
1901 #ifdef ENOTDIR
1902                         && errno != ENOTDIR)
1903 #endif
1904                         goto err;
1905                 }
1906         else
1907                 {
1908 #ifdef RL_DEBUG
1909                 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1910                         buf[4],buf[3]);
1911 #endif
1912                 if (rename(buf[4],buf[3]) < 0)
1913                         {
1914                         BIO_printf(bio_err,
1915                                 "unable to rename %s to %s\n",
1916                                 buf[4], buf[3]);
1917                         perror("reason");
1918                         rename(dbfile,buf[0]);
1919                         rename(buf[1],dbfile);
1920                         goto err;
1921                         }
1922                 }
1923 #ifdef RL_DEBUG
1924         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1925                 buf[2],buf[4]);
1926 #endif
1927         if (rename(buf[2],buf[4]) < 0)
1928                 {
1929                 BIO_printf(bio_err,
1930                         "unable to rename %s to %s\n",
1931                         buf[2],buf[4]);
1932                 perror("reason");
1933                 rename(buf[3],buf[4]);
1934                 rename(dbfile,buf[0]);
1935                 rename(buf[1],dbfile);
1936                 goto err;
1937                 }
1938         return 1;
1939  err:
1940         return 0;
1941         }
1942
1943 void free_index(CA_DB *db)
1944         {
1945         if (db)
1946                 {
1947                 if (db->db) TXT_DB_free(db->db);
1948                 OPENSSL_free(db);
1949                 }
1950         }
1951
1952 int parse_yesno(char *str, int def)
1953         {
1954         int ret = def;
1955         if (str)
1956                 {
1957                 switch (*str)
1958                         {
1959                 case 'f': /* false */
1960                 case 'F': /* FALSE */
1961                 case 'n': /* no */
1962                 case 'N': /* NO */
1963                 case '0': /* 0 */
1964                         ret = 0;
1965                         break;
1966                 case 't': /* true */
1967                 case 'T': /* TRUE */
1968                 case 'y': /* yes */
1969                 case 'Y': /* YES */
1970                 case '1': /* 1 */
1971                         ret = 0;
1972                         break;
1973                 default:
1974                         ret = def;
1975                         break;
1976                         }
1977                 }
1978         return ret;
1979         }
1980
1981 /*
1982  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1983  * where characters may be escaped by \
1984  */
1985 X509_NAME *parse_name(char *subject, long chtype, int multirdn)
1986         {
1987         size_t buflen = strlen(subject)+1; /* to copy the types and values into. due to escaping, the copy can only become shorter */
1988         char *buf = OPENSSL_malloc(buflen);
1989         size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
1990         char **ne_types = OPENSSL_malloc(max_ne * sizeof (char *));
1991         char **ne_values = OPENSSL_malloc(max_ne * sizeof (char *));
1992         int *mval = OPENSSL_malloc (max_ne * sizeof (int));
1993
1994         char *sp = subject, *bp = buf;
1995         int i, ne_num = 0;
1996
1997         X509_NAME *n = NULL;
1998         int nid;
1999
2000         if (!buf || !ne_types || !ne_values)
2001                 {
2002                 BIO_printf(bio_err, "malloc error\n");
2003                 goto error;
2004                 }       
2005
2006         if (*subject != '/')
2007                 {
2008                 BIO_printf(bio_err, "Subject does not start with '/'.\n");
2009                 goto error;
2010                 }
2011         sp++; /* skip leading / */
2012
2013         /* no multivalued RDN by default */
2014         mval[ne_num] = 0;
2015
2016         while (*sp)
2017                 {
2018                 /* collect type */
2019                 ne_types[ne_num] = bp;
2020                 while (*sp)
2021                         {
2022                         if (*sp == '\\') /* is there anything to escape in the type...? */
2023                                 {
2024                                 if (*++sp)
2025                                         *bp++ = *sp++;
2026                                 else    
2027                                         {
2028                                         BIO_printf(bio_err, "escape character at end of string\n");
2029                                         goto error;
2030                                         }
2031                                 }       
2032                         else if (*sp == '=')
2033                                 {
2034                                 sp++;
2035                                 *bp++ = '\0';
2036                                 break;
2037                                 }
2038                         else
2039                                 *bp++ = *sp++;
2040                         }
2041                 if (!*sp)
2042                         {
2043                         BIO_printf(bio_err, "end of string encountered while processing type of subject name element #%d\n", ne_num);
2044                         goto error;
2045                         }
2046                 ne_values[ne_num] = bp;
2047                 while (*sp)
2048                         {
2049                         if (*sp == '\\')
2050                                 {
2051                                 if (*++sp)
2052                                         *bp++ = *sp++;
2053                                 else
2054                                         {
2055                                         BIO_printf(bio_err, "escape character at end of string\n");
2056                                         goto error;
2057                                         }
2058                                 }
2059                         else if (*sp == '/')
2060                                 {
2061                                 sp++;
2062                                 /* no multivalued RDN by default */
2063                                 mval[ne_num+1] = 0;
2064                                 break;
2065                                 }
2066                         else if (*sp == '+' && multirdn)
2067                                 {
2068                                 /* a not escaped + signals a mutlivalued RDN */
2069                                 sp++;
2070                                 mval[ne_num+1] = -1;
2071                                 break;
2072                                 }
2073                         else
2074                                 *bp++ = *sp++;
2075                         }
2076                 *bp++ = '\0';
2077                 ne_num++;
2078                 }       
2079
2080         if (!(n = X509_NAME_new()))
2081                 goto error;
2082
2083         for (i = 0; i < ne_num; i++)
2084                 {
2085                 if ((nid=OBJ_txt2nid(ne_types[i])) == NID_undef)
2086                         {
2087                         BIO_printf(bio_err, "Subject Attribute %s has no known NID, skipped\n", ne_types[i]);
2088                         continue;
2089                         }
2090
2091                 if (!*ne_values[i])
2092                         {
2093                         BIO_printf(bio_err, "No value provided for Subject Attribute %s, skipped\n", ne_types[i]);
2094                         continue;
2095                         }
2096
2097                 if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char*)ne_values[i], -1,-1,mval[i]))
2098                         goto error;
2099                 }
2100
2101         OPENSSL_free(ne_values);
2102         OPENSSL_free(ne_types);
2103         OPENSSL_free(buf);
2104         return n;
2105
2106 error:
2107         X509_NAME_free(n);
2108         if (ne_values)
2109                 OPENSSL_free(ne_values);
2110         if (ne_types)
2111                 OPENSSL_free(ne_types);
2112         if (buf)
2113                 OPENSSL_free(buf);
2114         return NULL;
2115 }
2116