7bac3f3e299d8418b6e4323a8022dbe7d71de1f5
[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         static int load_config_called = 0;
1441         if (load_config_called)
1442                 return 1;
1443         load_config_called = 1;
1444         if (!cnf)
1445                 cnf = config;
1446         if (!cnf)
1447                 return 1;
1448
1449         OPENSSL_load_builtin_modules();
1450
1451         if (CONF_modules_load(cnf, NULL, 0) <= 0)
1452                 {
1453                 BIO_printf(err, "Error configuring OpenSSL\n");
1454                 ERR_print_errors(err);
1455                 return 0;
1456                 }
1457         return 1;
1458         }
1459
1460 char *make_config_name()
1461         {
1462         const char *t=X509_get_default_cert_area();
1463         size_t len;
1464         char *p;
1465
1466         len=strlen(t)+strlen(OPENSSL_CONF)+2;
1467         p=OPENSSL_malloc(len);
1468         BUF_strlcpy(p,t,len);
1469 #ifndef OPENSSL_SYS_VMS
1470         BUF_strlcat(p,"/",len);
1471 #endif
1472         BUF_strlcat(p,OPENSSL_CONF,len);
1473
1474         return p;
1475         }
1476
1477 static unsigned long index_serial_hash(const char **a)
1478         {
1479         const char *n;
1480
1481         n=a[DB_serial];
1482         while (*n == '0') n++;
1483         return(lh_strhash(n));
1484         }
1485
1486 static int index_serial_cmp(const char **a, const char **b)
1487         {
1488         const char *aa,*bb;
1489
1490         for (aa=a[DB_serial]; *aa == '0'; aa++);
1491         for (bb=b[DB_serial]; *bb == '0'; bb++);
1492         return(strcmp(aa,bb));
1493         }
1494
1495 static int index_name_qual(char **a)
1496         { return(a[0][0] == 'V'); }
1497
1498 static unsigned long index_name_hash(const char **a)
1499         { return(lh_strhash(a[DB_name])); }
1500
1501 int index_name_cmp(const char **a, const char **b)
1502         { return(strcmp(a[DB_name],
1503              b[DB_name])); }
1504
1505 static IMPLEMENT_LHASH_HASH_FN(index_serial_hash,const char **)
1506 static IMPLEMENT_LHASH_COMP_FN(index_serial_cmp,const char **)
1507 static IMPLEMENT_LHASH_HASH_FN(index_name_hash,const char **)
1508 static IMPLEMENT_LHASH_COMP_FN(index_name_cmp,const char **)
1509
1510 #undef BSIZE
1511 #define BSIZE 256
1512
1513 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1514         {
1515         BIO *in=NULL;
1516         BIGNUM *ret=NULL;
1517         MS_STATIC char buf[1024];
1518         ASN1_INTEGER *ai=NULL;
1519
1520         ai=ASN1_INTEGER_new();
1521         if (ai == NULL) goto err;
1522
1523         if ((in=BIO_new(BIO_s_file())) == NULL)
1524                 {
1525                 ERR_print_errors(bio_err);
1526                 goto err;
1527                 }
1528
1529         if (BIO_read_filename(in,serialfile) <= 0)
1530                 {
1531                 if (!create)
1532                         {
1533                         perror(serialfile);
1534                         goto err;
1535                         }
1536                 else
1537                         {
1538                         ret=BN_new();
1539                         if (ret == NULL || !rand_serial(ret, ai))
1540                                 BIO_printf(bio_err, "Out of memory\n");
1541                         }
1542                 }
1543         else
1544                 {
1545                 if (!a2i_ASN1_INTEGER(in,ai,buf,1024))
1546                         {
1547                         BIO_printf(bio_err,"unable to load number from %s\n",
1548                                 serialfile);
1549                         goto err;
1550                         }
1551                 ret=ASN1_INTEGER_to_BN(ai,NULL);
1552                 if (ret == NULL)
1553                         {
1554                         BIO_printf(bio_err,"error converting number from bin to BIGNUM\n");
1555                         goto err;
1556                         }
1557                 }
1558
1559         if (ret && retai)
1560                 {
1561                 *retai = ai;
1562                 ai = NULL;
1563                 }
1564  err:
1565         if (in != NULL) BIO_free(in);
1566         if (ai != NULL) ASN1_INTEGER_free(ai);
1567         return(ret);
1568         }
1569
1570 int save_serial(char *serialfile, char *suffix, BIGNUM *serial, ASN1_INTEGER **retai)
1571         {
1572         char buf[1][BSIZE];
1573         BIO *out = NULL;
1574         int ret=0;
1575         ASN1_INTEGER *ai=NULL;
1576         int j;
1577
1578         if (suffix == NULL)
1579                 j = strlen(serialfile);
1580         else
1581                 j = strlen(serialfile) + strlen(suffix) + 1;
1582         if (j >= BSIZE)
1583                 {
1584                 BIO_printf(bio_err,"file name too long\n");
1585                 goto err;
1586                 }
1587
1588         if (suffix == NULL)
1589                 BUF_strlcpy(buf[0], serialfile, BSIZE);
1590         else
1591                 {
1592 #ifndef OPENSSL_SYS_VMS
1593                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1594 #else
1595                 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1596 #endif
1597                 }
1598 #ifdef RL_DEBUG
1599         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1600 #endif
1601         out=BIO_new(BIO_s_file());
1602         if (out == NULL)
1603                 {
1604                 ERR_print_errors(bio_err);
1605                 goto err;
1606                 }
1607         if (BIO_write_filename(out,buf[0]) <= 0)
1608                 {
1609                 perror(serialfile);
1610                 goto err;
1611                 }
1612
1613         if ((ai=BN_to_ASN1_INTEGER(serial,NULL)) == NULL)
1614                 {
1615                 BIO_printf(bio_err,"error converting serial to ASN.1 format\n");
1616                 goto err;
1617                 }
1618         i2a_ASN1_INTEGER(out,ai);
1619         BIO_puts(out,"\n");
1620         ret=1;
1621         if (retai)
1622                 {
1623                 *retai = ai;
1624                 ai = NULL;
1625                 }
1626 err:
1627         if (out != NULL) BIO_free_all(out);
1628         if (ai != NULL) ASN1_INTEGER_free(ai);
1629         return(ret);
1630         }
1631
1632 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1633         {
1634         char buf[5][BSIZE];
1635         int i,j;
1636
1637         i = strlen(serialfile) + strlen(old_suffix);
1638         j = strlen(serialfile) + strlen(new_suffix);
1639         if (i > j) j = i;
1640         if (j + 1 >= BSIZE)
1641                 {
1642                 BIO_printf(bio_err,"file name too long\n");
1643                 goto err;
1644                 }
1645
1646 #ifndef OPENSSL_SYS_VMS
1647         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1648                 serialfile, new_suffix);
1649 #else
1650         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1651                 serialfile, new_suffix);
1652 #endif
1653 #ifndef OPENSSL_SYS_VMS
1654         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1655                 serialfile, old_suffix);
1656 #else
1657         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1658                 serialfile, old_suffix);
1659 #endif
1660 #ifdef RL_DEBUG
1661         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1662                 serialfile, buf[1]);
1663 #endif
1664         if (rename(serialfile,buf[1]) < 0 && errno != ENOENT
1665 #ifdef ENOTDIR
1666                         && errno != ENOTDIR
1667 #endif
1668            )            {
1669                         BIO_printf(bio_err,
1670                                 "unable to rename %s to %s\n",
1671                                 serialfile, buf[1]);
1672                         perror("reason");
1673                         goto err;
1674                         }
1675 #ifdef RL_DEBUG
1676         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1677                 buf[0],serialfile);
1678 #endif
1679         if (rename(buf[0],serialfile) < 0)
1680                 {
1681                 BIO_printf(bio_err,
1682                         "unable to rename %s to %s\n",
1683                         buf[0],serialfile);
1684                 perror("reason");
1685                 rename(buf[1],serialfile);
1686                 goto err;
1687                 }
1688         return 1;
1689  err:
1690         return 0;
1691         }
1692
1693 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1694         {
1695         BIGNUM *btmp;
1696         int ret = 0;
1697         if (b)
1698                 btmp = b;
1699         else
1700                 btmp = BN_new();
1701
1702         if (!btmp)
1703                 return 0;
1704
1705         if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1706                 goto error;
1707         if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1708                 goto error;
1709
1710         ret = 1;
1711         
1712         error:
1713
1714         if (!b)
1715                 BN_free(btmp);
1716         
1717         return ret;
1718         }
1719
1720 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1721         {
1722         CA_DB *retdb = NULL;
1723         TXT_DB *tmpdb = NULL;
1724         BIO *in = BIO_new(BIO_s_file());
1725         CONF *dbattr_conf = NULL;
1726         char buf[1][BSIZE];
1727         long errorline= -1;
1728
1729         if (in == NULL)
1730                 {
1731                 ERR_print_errors(bio_err);
1732                 goto err;
1733                 }
1734         if (BIO_read_filename(in,dbfile) <= 0)
1735                 {
1736                 perror(dbfile);
1737                 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
1738                 goto err;
1739                 }
1740         if ((tmpdb = TXT_DB_read(in,DB_NUMBER)) == NULL)
1741                 goto err;
1742
1743 #ifndef OPENSSL_SYS_VMS
1744         BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1745 #else
1746         BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1747 #endif
1748         dbattr_conf = NCONF_new(NULL);
1749         if (NCONF_load(dbattr_conf,buf[0],&errorline) <= 0)
1750                 {
1751                 if (errorline > 0)
1752                         {
1753                         BIO_printf(bio_err,
1754                                 "error on line %ld of db attribute file '%s'\n"
1755                                 ,errorline,buf[0]);
1756                         goto err;
1757                         }
1758                 else
1759                         {
1760                         NCONF_free(dbattr_conf);
1761                         dbattr_conf = NULL;
1762                         }
1763                 }
1764
1765         if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL)
1766                 {
1767                 fprintf(stderr, "Out of memory\n");
1768                 goto err;
1769                 }
1770
1771         retdb->db = tmpdb;
1772         tmpdb = NULL;
1773         if (db_attr)
1774                 retdb->attributes = *db_attr;
1775         else
1776                 {
1777                 retdb->attributes.unique_subject = 1;
1778                 }
1779
1780         if (dbattr_conf)
1781                 {
1782                 char *p = NCONF_get_string(dbattr_conf,NULL,"unique_subject");
1783                 if (p)
1784                         {
1785 #ifdef RL_DEBUG
1786                         BIO_printf(bio_err, "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
1787 #endif
1788                         retdb->attributes.unique_subject = parse_yesno(p,1);
1789                         }
1790                 }
1791
1792  err:
1793         if (dbattr_conf) NCONF_free(dbattr_conf);
1794         if (tmpdb) TXT_DB_free(tmpdb);
1795         if (in) BIO_free_all(in);
1796         return retdb;
1797         }
1798
1799 int index_index(CA_DB *db)
1800         {
1801         if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1802                                 LHASH_HASH_FN(index_serial_hash),
1803                                 LHASH_COMP_FN(index_serial_cmp)))
1804                 {
1805                 BIO_printf(bio_err,
1806                   "error creating serial number index:(%ld,%ld,%ld)\n",
1807                                         db->db->error,db->db->arg1,db->db->arg2);
1808                         return 0;
1809                 }
1810
1811         if (db->attributes.unique_subject
1812                 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1813                         LHASH_HASH_FN(index_name_hash),
1814                         LHASH_COMP_FN(index_name_cmp)))
1815                 {
1816                 BIO_printf(bio_err,"error creating name index:(%ld,%ld,%ld)\n",
1817                         db->db->error,db->db->arg1,db->db->arg2);
1818                 return 0;
1819                 }
1820         return 1;
1821         }
1822
1823 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1824         {
1825         char buf[3][BSIZE];
1826         BIO *out = BIO_new(BIO_s_file());
1827         int j;
1828
1829         if (out == NULL)
1830                 {
1831                 ERR_print_errors(bio_err);
1832                 goto err;
1833                 }
1834
1835         j = strlen(dbfile) + strlen(suffix);
1836         if (j + 6 >= BSIZE)
1837                 {
1838                 BIO_printf(bio_err,"file name too long\n");
1839                 goto err;
1840                 }
1841
1842 #ifndef OPENSSL_SYS_VMS
1843         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1844 #else
1845         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1846 #endif
1847 #ifndef OPENSSL_SYS_VMS
1848         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1849 #else
1850         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1851 #endif
1852 #ifndef OPENSSL_SYS_VMS
1853         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1854 #else
1855         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1856 #endif
1857 #ifdef RL_DEBUG
1858         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1859 #endif
1860         if (BIO_write_filename(out,buf[0]) <= 0)
1861                 {
1862                 perror(dbfile);
1863                 BIO_printf(bio_err,"unable to open '%s'\n", dbfile);
1864                 goto err;
1865                 }
1866         j=TXT_DB_write(out,db->db);
1867         if (j <= 0) goto err;
1868                         
1869         BIO_free(out);
1870
1871         out = BIO_new(BIO_s_file());
1872 #ifdef RL_DEBUG
1873         BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
1874 #endif
1875         if (BIO_write_filename(out,buf[1]) <= 0)
1876                 {
1877                 perror(buf[2]);
1878                 BIO_printf(bio_err,"unable to open '%s'\n", buf[2]);
1879                 goto err;
1880                 }
1881         BIO_printf(out,"unique_subject = %s\n",
1882                 db->attributes.unique_subject ? "yes" : "no");
1883         BIO_free(out);
1884
1885         return 1;
1886  err:
1887         return 0;
1888         }
1889
1890 int rotate_index(const char *dbfile, const char *new_suffix, const char *old_suffix)
1891         {
1892         char buf[5][BSIZE];
1893         int i,j;
1894
1895         i = strlen(dbfile) + strlen(old_suffix);
1896         j = strlen(dbfile) + strlen(new_suffix);
1897         if (i > j) j = i;
1898         if (j + 6 >= BSIZE)
1899                 {
1900                 BIO_printf(bio_err,"file name too long\n");
1901                 goto err;
1902                 }
1903
1904 #ifndef OPENSSL_SYS_VMS
1905         j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1906 #else
1907         j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1908 #endif
1909 #ifndef OPENSSL_SYS_VMS
1910         j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s",
1911                 dbfile, new_suffix);
1912 #else
1913         j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s",
1914                 dbfile, new_suffix);
1915 #endif
1916 #ifndef OPENSSL_SYS_VMS
1917         j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1918                 dbfile, new_suffix);
1919 #else
1920         j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1921                 dbfile, new_suffix);
1922 #endif
1923 #ifndef OPENSSL_SYS_VMS
1924         j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1925                 dbfile, old_suffix);
1926 #else
1927         j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1928                 dbfile, old_suffix);
1929 #endif
1930 #ifndef OPENSSL_SYS_VMS
1931         j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s",
1932                 dbfile, old_suffix);
1933 #else
1934         j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s",
1935                 dbfile, old_suffix);
1936 #endif
1937 #ifdef RL_DEBUG
1938         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1939                 dbfile, buf[1]);
1940 #endif
1941         if (rename(dbfile,buf[1]) < 0 && errno != ENOENT
1942 #ifdef ENOTDIR
1943                 && errno != ENOTDIR
1944 #endif
1945            )            {
1946                         BIO_printf(bio_err,
1947                                 "unable to rename %s to %s\n",
1948                                 dbfile, buf[1]);
1949                         perror("reason");
1950                         goto err;
1951                         }
1952 #ifdef RL_DEBUG
1953         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1954                 buf[0],dbfile);
1955 #endif
1956         if (rename(buf[0],dbfile) < 0)
1957                 {
1958                 BIO_printf(bio_err,
1959                         "unable to rename %s to %s\n",
1960                         buf[0],dbfile);
1961                 perror("reason");
1962                 rename(buf[1],dbfile);
1963                 goto err;
1964                 }
1965 #ifdef RL_DEBUG
1966         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1967                 buf[4],buf[3]);
1968 #endif
1969         if (rename(buf[4],buf[3]) < 0 && errno != ENOENT
1970 #ifdef ENOTDIR
1971                 && errno != ENOTDIR
1972 #endif
1973            )            {
1974                         BIO_printf(bio_err,
1975                                 "unable to rename %s to %s\n",
1976                                 buf[4], buf[3]);
1977                         perror("reason");
1978                         rename(dbfile,buf[0]);
1979                         rename(buf[1],dbfile);
1980                         goto err;
1981                         }
1982 #ifdef RL_DEBUG
1983         BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1984                 buf[2],buf[4]);
1985 #endif
1986         if (rename(buf[2],buf[4]) < 0)
1987                 {
1988                 BIO_printf(bio_err,
1989                         "unable to rename %s to %s\n",
1990                         buf[2],buf[4]);
1991                 perror("reason");
1992                 rename(buf[3],buf[4]);
1993                 rename(dbfile,buf[0]);
1994                 rename(buf[1],dbfile);
1995                 goto err;
1996                 }
1997         return 1;
1998  err:
1999         return 0;
2000         }
2001
2002 void free_index(CA_DB *db)
2003         {
2004         if (db)
2005                 {
2006                 if (db->db) TXT_DB_free(db->db);
2007                 OPENSSL_free(db);
2008                 }
2009         }
2010
2011 int parse_yesno(const char *str, int def)
2012         {
2013         int ret = def;
2014         if (str)
2015                 {
2016                 switch (*str)
2017                         {
2018                 case 'f': /* false */
2019                 case 'F': /* FALSE */
2020                 case 'n': /* no */
2021                 case 'N': /* NO */
2022                 case '0': /* 0 */
2023                         ret = 0;
2024                         break;
2025                 case 't': /* true */
2026                 case 'T': /* TRUE */
2027                 case 'y': /* yes */
2028                 case 'Y': /* YES */
2029                 case '1': /* 1 */
2030                         ret = 0;
2031                         break;
2032                 default:
2033                         ret = def;
2034                         break;
2035                         }
2036                 }
2037         return ret;
2038         }
2039
2040 /*
2041  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
2042  * where characters may be escaped by \
2043  */
2044 X509_NAME *parse_name(char *subject, long chtype, int multirdn)
2045         {
2046         size_t buflen = strlen(subject)+1; /* to copy the types and values into. due to escaping, the copy can only become shorter */
2047         char *buf = OPENSSL_malloc(buflen);
2048         size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
2049         char **ne_types = OPENSSL_malloc(max_ne * sizeof (char *));
2050         char **ne_values = OPENSSL_malloc(max_ne * sizeof (char *));
2051         int *mval = OPENSSL_malloc (max_ne * sizeof (int));
2052
2053         char *sp = subject, *bp = buf;
2054         int i, ne_num = 0;
2055
2056         X509_NAME *n = NULL;
2057         int nid;
2058
2059         if (!buf || !ne_types || !ne_values)
2060                 {
2061                 BIO_printf(bio_err, "malloc error\n");
2062                 goto error;
2063                 }       
2064
2065         if (*subject != '/')
2066                 {
2067                 BIO_printf(bio_err, "Subject does not start with '/'.\n");
2068                 goto error;
2069                 }
2070         sp++; /* skip leading / */
2071
2072         /* no multivalued RDN by default */
2073         mval[ne_num] = 0;
2074
2075         while (*sp)
2076                 {
2077                 /* collect type */
2078                 ne_types[ne_num] = bp;
2079                 while (*sp)
2080                         {
2081                         if (*sp == '\\') /* is there anything to escape in the type...? */
2082                                 {
2083                                 if (*++sp)
2084                                         *bp++ = *sp++;
2085                                 else    
2086                                         {
2087                                         BIO_printf(bio_err, "escape character at end of string\n");
2088                                         goto error;
2089                                         }
2090                                 }       
2091                         else if (*sp == '=')
2092                                 {
2093                                 sp++;
2094                                 *bp++ = '\0';
2095                                 break;
2096                                 }
2097                         else
2098                                 *bp++ = *sp++;
2099                         }
2100                 if (!*sp)
2101                         {
2102                         BIO_printf(bio_err, "end of string encountered while processing type of subject name element #%d\n", ne_num);
2103                         goto error;
2104                         }
2105                 ne_values[ne_num] = bp;
2106                 while (*sp)
2107                         {
2108                         if (*sp == '\\')
2109                                 {
2110                                 if (*++sp)
2111                                         *bp++ = *sp++;
2112                                 else
2113                                         {
2114                                         BIO_printf(bio_err, "escape character at end of string\n");
2115                                         goto error;
2116                                         }
2117                                 }
2118                         else if (*sp == '/')
2119                                 {
2120                                 sp++;
2121                                 /* no multivalued RDN by default */
2122                                 mval[ne_num+1] = 0;
2123                                 break;
2124                                 }
2125                         else if (*sp == '+' && multirdn)
2126                                 {
2127                                 /* a not escaped + signals a mutlivalued RDN */
2128                                 sp++;
2129                                 mval[ne_num+1] = -1;
2130                                 break;
2131                                 }
2132                         else
2133                                 *bp++ = *sp++;
2134                         }
2135                 *bp++ = '\0';
2136                 ne_num++;
2137                 }       
2138
2139         if (!(n = X509_NAME_new()))
2140                 goto error;
2141
2142         for (i = 0; i < ne_num; i++)
2143                 {
2144                 if ((nid=OBJ_txt2nid(ne_types[i])) == NID_undef)
2145                         {
2146                         BIO_printf(bio_err, "Subject Attribute %s has no known NID, skipped\n", ne_types[i]);
2147                         continue;
2148                         }
2149
2150                 if (!*ne_values[i])
2151                         {
2152                         BIO_printf(bio_err, "No value provided for Subject Attribute %s, skipped\n", ne_types[i]);
2153                         continue;
2154                         }
2155
2156                 if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char*)ne_values[i], -1,-1,mval[i]))
2157                         goto error;
2158                 }
2159
2160         OPENSSL_free(ne_values);
2161         OPENSSL_free(ne_types);
2162         OPENSSL_free(buf);
2163         return n;
2164
2165 error:
2166         X509_NAME_free(n);
2167         if (ne_values)
2168                 OPENSSL_free(ne_values);
2169         if (ne_types)
2170                 OPENSSL_free(ne_types);
2171         if (buf)
2172                 OPENSSL_free(buf);
2173         return NULL;
2174 }
2175
2176 int args_verify(char ***pargs, int *pargc,
2177                         int *badarg, BIO *err, X509_VERIFY_PARAM **pm)
2178         {
2179         ASN1_OBJECT *otmp = NULL;
2180         unsigned long flags = 0;
2181         int i;
2182         int purpose = 0;
2183         char **oldargs = *pargs;
2184         char *arg = **pargs, *argn = (*pargs)[1];
2185         if (!strcmp(arg, "-policy"))
2186                 {
2187                 if (!argn)
2188                         *badarg = 1;
2189                 else
2190                         {
2191                         otmp = OBJ_txt2obj(argn, 0);
2192                         if (!otmp)
2193                                 {
2194                                 BIO_printf(err, "Invalid Policy \"%s\"\n",
2195                                                                         argn);
2196                                 *badarg = 1;
2197                                 }
2198                         }
2199                 (*pargs)++;
2200                 }
2201         else if (strcmp(arg,"-purpose") == 0)
2202                 {
2203                 X509_PURPOSE *xptmp;
2204                 if (!argn)
2205                         *badarg = 1;
2206                 else
2207                         {
2208                         i = X509_PURPOSE_get_by_sname(argn);
2209                         if(i < 0)
2210                                 {
2211                                 BIO_printf(err, "unrecognized purpose\n");
2212                                 *badarg = 1;
2213                                 }
2214                         else
2215                                 {
2216                                 xptmp = X509_PURPOSE_get0(i);
2217                                 purpose = X509_PURPOSE_get_id(xptmp);
2218                                 }
2219                         }
2220                 (*pargs)++;
2221                 }
2222         else if (!strcmp(arg, "-ignore_critical"))
2223                 flags |= X509_V_FLAG_IGNORE_CRITICAL;
2224         else if (!strcmp(arg, "-issuer_checks"))
2225                 flags |= X509_V_FLAG_CB_ISSUER_CHECK;
2226         else if (!strcmp(arg, "-crl_check"))
2227                 flags |=  X509_V_FLAG_CRL_CHECK;
2228         else if (!strcmp(arg, "-crl_check_all"))
2229                 flags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
2230         else if (!strcmp(arg, "-policy_check"))
2231                 flags |= X509_V_FLAG_POLICY_CHECK;
2232         else if (!strcmp(arg, "-explicit_policy"))
2233                 flags |= X509_V_FLAG_EXPLICIT_POLICY;
2234         else if (!strcmp(arg, "-x509_strict"))
2235                 flags |= X509_V_FLAG_X509_STRICT;
2236         else if (!strcmp(arg, "-policy_print"))
2237                 flags |= X509_V_FLAG_NOTIFY_POLICY;
2238         else
2239                 return 0;
2240
2241         if (*badarg)
2242                 {
2243                 if (*pm)
2244                         X509_VERIFY_PARAM_free(*pm);
2245                 *pm = NULL;
2246                 goto end;
2247                 }
2248
2249         if (!*pm && !(*pm = X509_VERIFY_PARAM_new()))
2250                 {
2251                 *badarg = 1;
2252                 goto end;
2253                 }
2254
2255         if (otmp)
2256                 X509_VERIFY_PARAM_add0_policy(*pm, otmp);
2257         if (flags)
2258                 X509_VERIFY_PARAM_set_flags(*pm, flags);
2259
2260         if (purpose)
2261                 X509_VERIFY_PARAM_set_purpose(*pm, purpose);
2262
2263         end:
2264
2265         (*pargs)++;
2266
2267         if (pargc)
2268                 *pargc -= *pargs - oldargs;
2269
2270         return 1;
2271
2272         }
2273
2274 /* Read whole contents of a BIO into an allocated memory buffer and
2275  * return it.
2276  */
2277
2278 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
2279         {
2280         BIO *mem;
2281         int len, ret;
2282         unsigned char tbuf[1024];
2283         mem = BIO_new(BIO_s_mem());
2284         if (!mem)
2285                 return -1;
2286         for(;;)
2287                 {
2288                 if ((maxlen != -1) && maxlen < 1024)
2289                         len = maxlen;
2290                 else
2291                         len = 1024;
2292                 len = BIO_read(in, tbuf, len);
2293                 if (len <= 0)
2294                         break;
2295                 if (BIO_write(mem, tbuf, len) != len)
2296                         {
2297                         BIO_free(mem);
2298                         return -1;
2299                         }
2300                 maxlen -= len;
2301
2302                 if (maxlen == 0)
2303                         break;
2304                 }
2305         ret = BIO_get_mem_data(mem, (char **)out);
2306         BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
2307         BIO_free(mem);
2308         return ret;
2309         }
2310
2311 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, char *value)
2312         {
2313         int rv;
2314         char *stmp, *vtmp = NULL;
2315         stmp = BUF_strdup(value);
2316         if (!stmp)
2317                 return -1;
2318         vtmp = strchr(stmp, ':');
2319         if (vtmp)
2320                 {
2321                 *vtmp = 0;
2322                 vtmp++;
2323                 }
2324         rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2325         OPENSSL_free(stmp);
2326         return rv;
2327         }
2328
2329 static void nodes_print(BIO *out, const char *name,
2330         STACK_OF(X509_POLICY_NODE) *nodes)
2331         {
2332         X509_POLICY_NODE *node;
2333         int i;
2334         BIO_printf(out, "%s Policies:", name);
2335         if (nodes)
2336                 {
2337                 BIO_puts(out, "\n");
2338                 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++)
2339                         {
2340                         node = sk_X509_POLICY_NODE_value(nodes, i);
2341                         X509_POLICY_NODE_print(out, node, 2);
2342                         }
2343                 }
2344         else
2345                 BIO_puts(out, " <empty>\n");
2346         }
2347
2348 void policies_print(BIO *out, X509_STORE_CTX *ctx)
2349         {
2350         X509_POLICY_TREE *tree;
2351         int explicit_policy;
2352         int free_out = 0;
2353         if (out == NULL)
2354                 {
2355                 out = BIO_new_fp(stderr, BIO_NOCLOSE);
2356                 free_out = 1;
2357                 }
2358         tree = X509_STORE_CTX_get0_policy_tree(ctx);
2359         explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2360
2361         BIO_printf(out, "Require explicit Policy: %s\n",
2362                                 explicit_policy ? "True" : "False");
2363
2364         nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
2365         nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
2366         if (free_out)
2367                 BIO_free(out);
2368         }
2369
2370 /*
2371  * Platform-specific sections
2372  */
2373 #if defined(_WIN32)
2374 # ifdef fileno
2375 #  undef fileno
2376 #  define fileno(a) (int)_fileno(a)
2377 # endif
2378
2379 # include <windows.h>
2380 # include <tchar.h>
2381
2382 static int WIN32_rename(const char *from, const char *to)
2383         {
2384         TCHAR  *tfrom=NULL,*tto;
2385         DWORD   err;
2386         int     ret=0;
2387
2388         if (sizeof(TCHAR) == 1)
2389                 {
2390                 tfrom = (TCHAR *)from;
2391                 tto   = (TCHAR *)to;
2392                 }
2393         else    /* UNICODE path */
2394                 {
2395                 size_t i,flen=strlen(from)+1,tlen=strlen(to)+1;
2396                 tfrom = (TCHAR *)malloc(sizeof(TCHAR)*(flen+tlen));
2397                 if (tfrom==NULL) goto err;
2398                 tto=tfrom+flen;
2399 #if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2400                 if (!MultiByteToWideChar(CP_ACP,0,from,flen,(WCHAR *)tfrom,flen))
2401 #endif
2402                         for (i=0;i<flen;i++)    tfrom[i]=(TCHAR)from[i];
2403 #if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2404                 if (!MultiByteToWideChar(CP_ACP,0,to,  tlen,(WCHAR *)tto,  tlen))
2405 #endif
2406                         for (i=0;i<tlen;i++)    tto[i]  =(TCHAR)to[i];
2407                 }
2408
2409         if (MoveFile(tfrom,tto))        goto ok;
2410         err=GetLastError();
2411         if (err==ERROR_ALREADY_EXISTS || err==ERROR_FILE_EXISTS)
2412                 {
2413                 if (DeleteFile(tto) && MoveFile(tfrom,tto))
2414                         goto ok;
2415                 err=GetLastError();
2416                 }
2417         if (err==ERROR_FILE_NOT_FOUND || err==ERROR_PATH_NOT_FOUND)
2418                 errno = ENOENT;
2419         else if (err==ERROR_ACCESS_DENIED)
2420                 errno = EACCES;
2421         else
2422                 errno = EINVAL; /* we could map more codes... */
2423 err:
2424         ret=-1;
2425 ok:
2426         if (tfrom!=NULL && tfrom!=(TCHAR *)from)        free(tfrom);
2427         return ret;
2428         }
2429 #endif
2430
2431 /* app_tminterval section */
2432 #if defined(_WIN32)
2433 double app_tminterval(int stop,int usertime)
2434         {
2435         FILETIME                now;
2436         double                  ret=0;
2437         static ULARGE_INTEGER   tmstart;
2438         static int              warning=1;
2439 #ifdef _WIN32_WINNT
2440         static HANDLE           proc=NULL;
2441
2442         if (proc==NULL)
2443                 {
2444                 if (GetVersion() < 0x80000000)
2445                         proc = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,
2446                                                 GetCurrentProcessId());
2447                 if (proc==NULL) proc = (HANDLE)-1;
2448                 }
2449
2450         if (usertime && proc!=(HANDLE)-1)
2451                 {
2452                 FILETIME junk;
2453                 GetProcessTimes(proc,&junk,&junk,&junk,&now);
2454                 }
2455         else
2456 #endif
2457                 {
2458                 SYSTEMTIME systime;
2459
2460                 if (usertime && warning)
2461                         {
2462                         BIO_printf(bio_err,"To get meaningful results, run "
2463                                            "this program on idle system.\n");
2464                         warning=0;
2465                         }
2466                 GetSystemTime(&systime);
2467                 SystemTimeToFileTime(&systime,&now);
2468                 }
2469
2470         if (stop==TM_START)
2471                 {
2472                 tmstart.u.LowPart  = now.dwLowDateTime;
2473                 tmstart.u.HighPart = now.dwHighDateTime;
2474                 }
2475         else    {
2476                 ULARGE_INTEGER tmstop;
2477
2478                 tmstop.u.LowPart   = now.dwLowDateTime;
2479                 tmstop.u.HighPart  = now.dwHighDateTime;
2480
2481                 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart)*1e-7;
2482                 }
2483
2484         return (ret);
2485         }
2486
2487 #elif defined(OPENSSL_SYSTEM_NETWARE)
2488 #include <time.h>
2489
2490 double app_tminterval(int stop,int usertime)
2491         {
2492         double          ret=0;
2493         static clock_t  tmstart;
2494         static int      warning=1;
2495
2496         if (usertime && warning)
2497                 {
2498                 BIO_printf(bio_err,"To get meaningful results, run "
2499                                    "this program on idle system.\n");
2500                 warning=0;
2501                 }
2502
2503         if (stop==TM_START)     tmstart = clock();
2504         else                    ret     = (clock()-tmstart)/(double)CLOCKS_PER_SEC;
2505
2506         return (ret);
2507         }
2508
2509 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2510 #include <time.h>
2511
2512 double app_tminterval(int stop,int usertime)
2513         {
2514         double ret=0;
2515 #ifdef CLOCK_REALTIME
2516         static struct timespec  tmstart;
2517         struct timespec         now;
2518 #else
2519         static unsigned long    tmstart;
2520         unsigned long           now;
2521 #endif
2522         static int warning=1;
2523
2524         if (usertime && warning)
2525                 {
2526                 BIO_printf(bio_err,"To get meaningful results, run "
2527                                    "this program on idle system.\n");
2528                 warning=0;
2529                 }
2530
2531 #ifdef CLOCK_REALTIME
2532         clock_gettime(CLOCK_REALTIME,&now);
2533         if (stop==TM_START)     tmstart = now;
2534         else    ret = ( (now.tv_sec+now.tv_nsec*1e-9)
2535                         - (tmstart.tv_sec+tmstart.tv_nsec*1e-9) );
2536 #else
2537         now = tickGet();
2538         if (stop==TM_START)     tmstart = now;
2539         else                    ret = (now - tmstart)/(double)sysClkRateGet();
2540 #endif
2541         return (ret);
2542         }
2543
2544 #elif defined(OPENSSL_SYSTEM_VMS)
2545 #include <time.h>
2546 #include <times.h>
2547
2548 double app_tminterval(int stop,int usertime)
2549         {
2550         static clock_t  tmstart;
2551         double          ret = 0;
2552         clock_t         now;
2553 #ifdef __TMS
2554         struct tms      rus;
2555
2556         now = times(&rus);
2557         if (usertime)   now = rus.tms_utime;
2558 #else
2559         if (usertime)
2560                 now = clock(); /* sum of user and kernel times */
2561         else    {
2562                 struct timeval tv;
2563                 gettimeofday(&tv,NULL);
2564                 now = (clock_t)(
2565                         (unsigned long long)tv.tv_sec*CLK_TCK +
2566                         (unsigned long long)tv.tv_usec*(1000000/CLK_TCK)
2567                         );
2568                 }
2569 #endif
2570         if (stop==TM_START)     tmstart = now;
2571         else                    ret = (now - tmstart)/(double)(CLK_TCK);
2572
2573         return (ret);
2574         }
2575
2576 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2577 #include <sys/times.h>
2578
2579 double app_tminterval(int stop,int usertime)
2580         {
2581         double          ret = 0;
2582         struct tms      rus;
2583         clock_t         now = times(&rus);
2584         static clock_t  tmstart;
2585
2586         if (usertime)           now = rus.tms_utime;
2587
2588         if (stop==TM_START)     tmstart = now;
2589         else                    ret = (now - tmstart)/(double)sysconf(_SC_CLK_TCK);
2590
2591         return (ret);
2592         }
2593
2594 #else
2595 #include <sys/time.h>
2596 #include <sys/resource.h>
2597
2598 double app_tminterval(int stop,int usertime)
2599         {
2600         double          ret = 0;
2601         struct rusage   rus;
2602         struct timeval  now;
2603         static struct timeval tmstart;
2604
2605         if (usertime)           getrusage(RUSAGE_SELF,&rus), now = rus.ru_utime;
2606         else                    gettimeofday(&now,NULL);
2607
2608         if (stop==TM_START)     tmstart = now;
2609         else                    ret = ( (now.tv_sec+now.tv_usec*1e-6)
2610                                         - (tmstart.tv_sec+tmstart.tv_usec*1e-6) );
2611
2612         return ret;
2613         }
2614 #endif
2615
2616 /* app_isdir section */
2617 #ifdef _WIN32
2618 int app_isdir(const char *name)
2619         {
2620         HANDLE          hList;
2621         WIN32_FIND_DATA FileData;
2622 #if defined(UNICODE) || defined(_UNICODE)
2623         size_t i, len_0 = strlen(name)+1;
2624
2625         if (len_0 > sizeof(FileData.cFileName)/sizeof(FileData.cFileName[0]))
2626                 return -1;
2627
2628 #if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2629         if (!MultiByteToWideChar(CP_ACP,0,name,len_0,FileData.cFileName,len_0))
2630 #endif
2631                 for (i=0;i<len_0;i++)
2632                         FileData.cFileName[i] = (WCHAR)name[i];
2633
2634         hList = FindFirstFile(FileData.cFileName,&FileData);
2635 #else
2636         hList = FindFirstFile(name,&FileData);
2637 #endif
2638         if (hList == INVALID_HANDLE_VALUE)      return -1;
2639         FindClose(hList);
2640         return ((FileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0);
2641         }
2642 #else
2643 #include <sys/stat.h>
2644 #ifndef S_ISDIR
2645 # if defined(_S_IFMT) && defined(_S_IFDIR)
2646 #  define S_ISDIR(a)   (((a) & _S_IFMT) == _S_IFDIR)
2647 # else 
2648 #  define S_ISDIR(a)   (((a) & S_IFMT) == S_IFDIR)
2649 # endif 
2650 #endif 
2651
2652 int app_isdir(const char *name)
2653         {
2654 #if defined(S_ISDIR)
2655         struct stat st;
2656
2657         if (stat(name,&st)==0)  return S_ISDIR(st.st_mode);
2658         else                    return -1;
2659 #else
2660         return -1;
2661 #endif
2662         }
2663 #endif
2664
2665 /* raw_read|write section */
2666 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2667 int raw_read_stdin(void *buf,int siz)
2668         {
2669         DWORD n;
2670         if (ReadFile(GetStdHandle(STD_INPUT_HANDLE),buf,siz,&n,NULL))
2671                 return (n);
2672         else    return (-1);
2673         }
2674 #else
2675 int raw_read_stdin(void *buf,int siz)
2676         {       return read(fileno(stdin),buf,siz);     }
2677 #endif
2678
2679 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2680 int raw_write_stdout(const void *buf,int siz)
2681         {
2682         DWORD n;
2683         if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),buf,siz,&n,NULL))
2684                 return (n);
2685         else    return (-1);
2686         }
2687 #else
2688 int raw_write_stdout(const void *buf,int siz)
2689         {       return write(fileno(stdout),buf,siz);   }
2690 #endif