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