make update
[openssl.git] / apps / s_server.c
1 /* apps/s_server.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  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by 
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116
117 /* Until the key-gen callbacks are modified to use newer prototypes, we allow
118  * deprecated functions for openssl-internal code */
119 #ifdef OPENSSL_NO_DEPRECATED
120 #undef OPENSSL_NO_DEPRECATED
121 #endif
122
123 #include <assert.h>
124 #include <stdio.h>
125 #include <stdlib.h>
126 #include <string.h>
127 #include <sys/types.h>
128 #include <sys/stat.h>
129 #include <openssl/e_os2.h>
130 #ifdef OPENSSL_NO_STDIO
131 #define APPS_WIN16
132 #endif
133
134 /* With IPv6, it looks like Digital has mixed up the proper order of
135    recursive header file inclusion, resulting in the compiler complaining
136    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
137    is needed to have fileno() declared correctly...  So let's define u_int */
138 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
139 #define __U_INT
140 typedef unsigned int u_int;
141 #endif
142
143 #include <openssl/lhash.h>
144 #include <openssl/bn.h>
145 #define USE_SOCKETS
146 #include "apps.h"
147 #include <openssl/err.h>
148 #include <openssl/pem.h>
149 #include <openssl/x509.h>
150 #include <openssl/ssl.h>
151 #include <openssl/rand.h>
152 #include "s_apps.h"
153
154 #ifdef OPENSSL_SYS_WINDOWS
155 #include <conio.h>
156 #endif
157
158 #ifdef OPENSSL_SYS_WINCE
159 /* Windows CE incorrectly defines fileno as returning void*, so to avoid problems below... */
160 #ifdef fileno
161 #undef fileno
162 #endif
163 #define fileno(a) (int)_fileno(a)
164 #endif
165
166 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
167 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
168 #undef FIONBIO
169 #endif
170
171 #ifndef OPENSSL_NO_RSA
172 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength);
173 #endif
174 static int sv_body(char *hostname, int s, unsigned char *context);
175 static int www_body(char *hostname, int s, unsigned char *context);
176 static void close_accept_socket(void );
177 static void sv_usage(void);
178 static int init_ssl_connection(SSL *s);
179 static void print_stats(BIO *bp,SSL_CTX *ctx);
180 static int generate_session_id(const SSL *ssl, unsigned char *id,
181                                 unsigned int *id_len);
182 #ifndef OPENSSL_NO_DH
183 static DH *load_dh_param(char *dhfile);
184 static DH *get_dh512(void);
185 #endif
186
187 #ifdef MONOLITH
188 static void s_server_init(void);
189 #endif
190
191 #ifndef S_ISDIR
192 # if defined(_S_IFMT) && defined(_S_IFDIR)
193 #  define S_ISDIR(a)    (((a) & _S_IFMT) == _S_IFDIR)
194 # else
195 #  define S_ISDIR(a)    (((a) & S_IFMT) == S_IFDIR)
196 # endif
197 #endif
198
199 #ifndef OPENSSL_NO_DH
200 static unsigned char dh512_p[]={
201         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
202         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
203         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
204         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
205         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
206         0x47,0x74,0xE8,0x33,
207         };
208 static unsigned char dh512_g[]={
209         0x02,
210         };
211
212 static DH *get_dh512(void)
213         {
214         DH *dh=NULL;
215
216         if ((dh=DH_new()) == NULL) return(NULL);
217         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
218         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
219         if ((dh->p == NULL) || (dh->g == NULL))
220                 return(NULL);
221         return(dh);
222         }
223 #endif
224
225
226 /* static int load_CA(SSL_CTX *ctx, char *file);*/
227
228 #undef BUFSIZZ
229 #define BUFSIZZ 16*1024
230 static int bufsize=BUFSIZZ;
231 static int accept_socket= -1;
232
233 #define TEST_CERT       "server.pem"
234 #undef PROG
235 #define PROG            s_server_main
236
237 extern int verify_depth;
238
239 static char *cipher=NULL;
240 static int s_server_verify=SSL_VERIFY_NONE;
241 static int s_server_session_id_context = 1; /* anything will do */
242 static char *s_cert_file=TEST_CERT,*s_key_file=NULL;
243 static char *s_dcert_file=NULL,*s_dkey_file=NULL;
244 #ifdef FIONBIO
245 static int s_nbio=0;
246 #endif
247 static int s_nbio_test=0;
248 int s_crlf=0;
249 static SSL_CTX *ctx=NULL;
250 static int www=0;
251
252 static BIO *bio_s_out=NULL;
253 static int s_debug=0;
254 static int s_msg=0;
255 static int s_quiet=0;
256
257 static int hack=0;
258 #ifndef OPENSSL_NO_ENGINE
259 static char *engine_id=NULL;
260 #endif
261 static const char *session_id_prefix=NULL;
262
263 #ifdef MONOLITH
264 static void s_server_init(void)
265         {
266         accept_socket=-1;
267         cipher=NULL;
268         s_server_verify=SSL_VERIFY_NONE;
269         s_dcert_file=NULL;
270         s_dkey_file=NULL;
271         s_cert_file=TEST_CERT;
272         s_key_file=NULL;
273 #ifdef FIONBIO
274         s_nbio=0;
275 #endif
276         s_nbio_test=0;
277         ctx=NULL;
278         www=0;
279
280         bio_s_out=NULL;
281         s_debug=0;
282         s_msg=0;
283         s_quiet=0;
284         hack=0;
285 #ifndef OPENSSL_NO_ENGINE
286         engine_id=NULL;
287 #endif
288         }
289 #endif
290
291 static void sv_usage(void)
292         {
293         BIO_printf(bio_err,"usage: s_server [args ...]\n");
294         BIO_printf(bio_err,"\n");
295         BIO_printf(bio_err," -accept arg   - port to accept on (default is %d)\n",PORT);
296         BIO_printf(bio_err," -context arg  - set session ID context\n");
297         BIO_printf(bio_err," -verify arg   - turn on peer certificate verification\n");
298         BIO_printf(bio_err," -Verify arg   - turn on peer certificate verification, must have a cert.\n");
299         BIO_printf(bio_err," -cert arg     - certificate file to use, PEM format assumed\n");
300         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT);
301         BIO_printf(bio_err," -key arg      - Private Key file to use, PEM format assumed, in cert file if\n");
302         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT);
303         BIO_printf(bio_err," -dcert arg    - second certificate file to use (usually for DSA)\n");
304         BIO_printf(bio_err," -dkey arg     - second private key file to use (usually for DSA)\n");
305         BIO_printf(bio_err," -dhparam arg  - DH parameter file to use, in cert file if not specified\n");
306         BIO_printf(bio_err,"                 or a default set of parameters is used\n");
307 #ifndef OPENSSL_NO_ECDH
308         BIO_printf(bio_err," -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
309                            "                 Use \"openssl ecparam -list_curves\" for all names\n" \
310                            "                 (default is sect163r2).\n");
311 #endif
312 #ifdef FIONBIO
313         BIO_printf(bio_err," -nbio         - Run with non-blocking IO\n");
314 #endif
315         BIO_printf(bio_err," -nbio_test    - test with the non-blocking test bio\n");
316         BIO_printf(bio_err," -crlf         - convert LF from terminal into CRLF\n");
317         BIO_printf(bio_err," -debug        - Print more output\n");
318         BIO_printf(bio_err," -msg          - Show protocol messages\n");
319         BIO_printf(bio_err," -state        - Print the SSL states\n");
320         BIO_printf(bio_err," -CApath arg   - PEM format directory of CA's\n");
321         BIO_printf(bio_err," -CAfile arg   - PEM format file of CA's\n");
322         BIO_printf(bio_err," -nocert       - Don't use any certificates (Anon-DH)\n");
323         BIO_printf(bio_err," -cipher arg   - play with 'openssl ciphers' to see what goes here\n");
324         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences\n");
325         BIO_printf(bio_err," -quiet        - No server output\n");
326         BIO_printf(bio_err," -no_tmp_rsa   - Do not generate a tmp RSA key\n");
327         BIO_printf(bio_err," -ssl2         - Just talk SSLv2\n");
328         BIO_printf(bio_err," -ssl3         - Just talk SSLv3\n");
329         BIO_printf(bio_err," -tls1         - Just talk TLSv1\n");
330         BIO_printf(bio_err," -no_ssl2      - Just disable SSLv2\n");
331         BIO_printf(bio_err," -no_ssl3      - Just disable SSLv3\n");
332         BIO_printf(bio_err," -no_tls1      - Just disable TLSv1\n");
333 #ifndef OPENSSL_NO_DH
334         BIO_printf(bio_err," -no_dhe       - Disable ephemeral DH\n");
335 #endif
336 #ifndef OPENSSL_NO_ECDH
337         BIO_printf(bio_err," -no_ecdhe     - Disable ephemeral ECDH\n");
338 #endif
339         BIO_printf(bio_err," -bugs         - Turn on SSL bug compatibility\n");
340         BIO_printf(bio_err," -www          - Respond to a 'GET /' with a status page\n");
341         BIO_printf(bio_err," -WWW          - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
342         BIO_printf(bio_err," -HTTP         - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
343         BIO_printf(bio_err,"                 with the assumption it contains a complete HTTP response.\n");
344 #ifndef OPENSSL_NO_ENGINE
345         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
346 #endif
347         BIO_printf(bio_err," -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
348         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
349         }
350
351 static int local_argc=0;
352 static char **local_argv;
353
354 #ifdef CHARSET_EBCDIC
355 static int ebcdic_new(BIO *bi);
356 static int ebcdic_free(BIO *a);
357 static int ebcdic_read(BIO *b, char *out, int outl);
358 static int ebcdic_write(BIO *b, const char *in, int inl);
359 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
360 static int ebcdic_gets(BIO *bp, char *buf, int size);
361 static int ebcdic_puts(BIO *bp, const char *str);
362
363 #define BIO_TYPE_EBCDIC_FILTER  (18|0x0200)
364 static BIO_METHOD methods_ebcdic=
365         {
366         BIO_TYPE_EBCDIC_FILTER,
367         "EBCDIC/ASCII filter",
368         ebcdic_write,
369         ebcdic_read,
370         ebcdic_puts,
371         ebcdic_gets,
372         ebcdic_ctrl,
373         ebcdic_new,
374         ebcdic_free,
375         };
376
377 typedef struct
378 {
379         size_t  alloced;
380         char    buff[1];
381 } EBCDIC_OUTBUFF;
382
383 BIO_METHOD *BIO_f_ebcdic_filter()
384 {
385         return(&methods_ebcdic);
386 }
387
388 static int ebcdic_new(BIO *bi)
389 {
390         EBCDIC_OUTBUFF *wbuf;
391
392         wbuf = (EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + 1024);
393         wbuf->alloced = 1024;
394         wbuf->buff[0] = '\0';
395
396         bi->ptr=(char *)wbuf;
397         bi->init=1;
398         bi->flags=0;
399         return(1);
400 }
401
402 static int ebcdic_free(BIO *a)
403 {
404         if (a == NULL) return(0);
405         if (a->ptr != NULL)
406                 OPENSSL_free(a->ptr);
407         a->ptr=NULL;
408         a->init=0;
409         a->flags=0;
410         return(1);
411 }
412         
413 static int ebcdic_read(BIO *b, char *out, int outl)
414 {
415         int ret=0;
416
417         if (out == NULL || outl == 0) return(0);
418         if (b->next_bio == NULL) return(0);
419
420         ret=BIO_read(b->next_bio,out,outl);
421         if (ret > 0)
422                 ascii2ebcdic(out,out,ret);
423         return(ret);
424 }
425
426 static int ebcdic_write(BIO *b, const char *in, int inl)
427 {
428         EBCDIC_OUTBUFF *wbuf;
429         int ret=0;
430         int num;
431         unsigned char n;
432
433         if ((in == NULL) || (inl <= 0)) return(0);
434         if (b->next_bio == NULL) return(0);
435
436         wbuf=(EBCDIC_OUTBUFF *)b->ptr;
437
438         if (inl > (num = wbuf->alloced))
439         {
440                 num = num + num;  /* double the size */
441                 if (num < inl)
442                         num = inl;
443                 OPENSSL_free(wbuf);
444                 wbuf=(EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + num);
445
446                 wbuf->alloced = num;
447                 wbuf->buff[0] = '\0';
448
449                 b->ptr=(char *)wbuf;
450         }
451
452         ebcdic2ascii(wbuf->buff, in, inl);
453
454         ret=BIO_write(b->next_bio, wbuf->buff, inl);
455
456         return(ret);
457 }
458
459 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
460 {
461         long ret;
462
463         if (b->next_bio == NULL) return(0);
464         switch (cmd)
465         {
466         case BIO_CTRL_DUP:
467                 ret=0L;
468                 break;
469         default:
470                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
471                 break;
472         }
473         return(ret);
474 }
475
476 static int ebcdic_gets(BIO *bp, char *buf, int size)
477 {
478         int i, ret=0;
479         if (bp->next_bio == NULL) return(0);
480 /*      return(BIO_gets(bp->next_bio,buf,size));*/
481         for (i=0; i<size-1; ++i)
482         {
483                 ret = ebcdic_read(bp,&buf[i],1);
484                 if (ret <= 0)
485                         break;
486                 else if (buf[i] == '\n')
487                 {
488                         ++i;
489                         break;
490                 }
491         }
492         if (i < size)
493                 buf[i] = '\0';
494         return (ret < 0 && i == 0) ? ret : i;
495 }
496
497 static int ebcdic_puts(BIO *bp, const char *str)
498 {
499         if (bp->next_bio == NULL) return(0);
500         return ebcdic_write(bp, str, strlen(str));
501 }
502 #endif
503
504 int MAIN(int, char **);
505
506 int MAIN(int argc, char *argv[])
507         {
508         X509_STORE *store = NULL;
509         int vflags = 0;
510         short port=PORT;
511         char *CApath=NULL,*CAfile=NULL;
512         char *context = NULL;
513         char *dhfile = NULL;
514         char *named_curve = NULL;
515         int badop=0,bugs=0;
516         int ret=1;
517         int off=0;
518         int no_tmp_rsa=0,no_dhe=0,no_ecdhe=0,nocert=0;
519         int state=0;
520         SSL_METHOD *meth=NULL;
521 #ifndef OPENSSL_NO_ENGINE
522         ENGINE *e=NULL;
523 #endif
524         char *inrand=NULL;
525
526 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
527         meth=SSLv23_server_method();
528 #elif !defined(OPENSSL_NO_SSL3)
529         meth=SSLv3_server_method();
530 #elif !defined(OPENSSL_NO_SSL2)
531         meth=SSLv2_server_method();
532 #endif
533
534         local_argc=argc;
535         local_argv=argv;
536
537         apps_startup();
538 #ifdef MONOLITH
539         s_server_init();
540 #endif
541
542         if (bio_err == NULL)
543                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
544
545         if (!load_config(bio_err, NULL))
546                 goto end;
547
548         verify_depth=0;
549 #ifdef FIONBIO
550         s_nbio=0;
551 #endif
552         s_nbio_test=0;
553
554         argc--;
555         argv++;
556
557         while (argc >= 1)
558                 {
559                 if      ((strcmp(*argv,"-port") == 0) ||
560                          (strcmp(*argv,"-accept") == 0))
561                         {
562                         if (--argc < 1) goto bad;
563                         if (!extract_port(*(++argv),&port))
564                                 goto bad;
565                         }
566                 else if (strcmp(*argv,"-verify") == 0)
567                         {
568                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE;
569                         if (--argc < 1) goto bad;
570                         verify_depth=atoi(*(++argv));
571                         BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
572                         }
573                 else if (strcmp(*argv,"-Verify") == 0)
574                         {
575                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
576                                 SSL_VERIFY_CLIENT_ONCE;
577                         if (--argc < 1) goto bad;
578                         verify_depth=atoi(*(++argv));
579                         BIO_printf(bio_err,"verify depth is %d, must return a certificate\n",verify_depth);
580                         }
581                 else if (strcmp(*argv,"-context") == 0)
582                         {
583                         if (--argc < 1) goto bad;
584                         context= *(++argv);
585                         }
586                 else if (strcmp(*argv,"-cert") == 0)
587                         {
588                         if (--argc < 1) goto bad;
589                         s_cert_file= *(++argv);
590                         }
591                 else if (strcmp(*argv,"-key") == 0)
592                         {
593                         if (--argc < 1) goto bad;
594                         s_key_file= *(++argv);
595                         }
596                 else if (strcmp(*argv,"-dhparam") == 0)
597                         {
598                         if (--argc < 1) goto bad;
599                         dhfile = *(++argv);
600                         }
601 #ifndef OPENSSL_NO_ECDH         
602                 else if (strcmp(*argv,"-named_curve") == 0)
603                         {
604                         if (--argc < 1) goto bad;
605                         named_curve = *(++argv);
606                         }
607 #endif
608                 else if (strcmp(*argv,"-dcert") == 0)
609                         {
610                         if (--argc < 1) goto bad;
611                         s_dcert_file= *(++argv);
612                         }
613                 else if (strcmp(*argv,"-dkey") == 0)
614                         {
615                         if (--argc < 1) goto bad;
616                         s_dkey_file= *(++argv);
617                         }
618                 else if (strcmp(*argv,"-nocert") == 0)
619                         {
620                         nocert=1;
621                         }
622                 else if (strcmp(*argv,"-CApath") == 0)
623                         {
624                         if (--argc < 1) goto bad;
625                         CApath= *(++argv);
626                         }
627                 else if (strcmp(*argv,"-crl_check") == 0)
628                         {
629                         vflags |= X509_V_FLAG_CRL_CHECK;
630                         }
631                 else if (strcmp(*argv,"-crl_check") == 0)
632                         {
633                         vflags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
634                         }
635                 else if (strcmp(*argv,"-serverpref") == 0)
636                         { off|=SSL_OP_CIPHER_SERVER_PREFERENCE; }
637                 else if (strcmp(*argv,"-cipher") == 0)
638                         {
639                         if (--argc < 1) goto bad;
640                         cipher= *(++argv);
641                         }
642                 else if (strcmp(*argv,"-CAfile") == 0)
643                         {
644                         if (--argc < 1) goto bad;
645                         CAfile= *(++argv);
646                         }
647 #ifdef FIONBIO  
648                 else if (strcmp(*argv,"-nbio") == 0)
649                         { s_nbio=1; }
650 #endif
651                 else if (strcmp(*argv,"-nbio_test") == 0)
652                         {
653 #ifdef FIONBIO  
654                         s_nbio=1;
655 #endif
656                         s_nbio_test=1;
657                         }
658                 else if (strcmp(*argv,"-debug") == 0)
659                         { s_debug=1; }
660                 else if (strcmp(*argv,"-msg") == 0)
661                         { s_msg=1; }
662                 else if (strcmp(*argv,"-hack") == 0)
663                         { hack=1; }
664                 else if (strcmp(*argv,"-state") == 0)
665                         { state=1; }
666                 else if (strcmp(*argv,"-crlf") == 0)
667                         { s_crlf=1; }
668                 else if (strcmp(*argv,"-quiet") == 0)
669                         { s_quiet=1; }
670                 else if (strcmp(*argv,"-bugs") == 0)
671                         { bugs=1; }
672                 else if (strcmp(*argv,"-no_tmp_rsa") == 0)
673                         { no_tmp_rsa=1; }
674                 else if (strcmp(*argv,"-no_dhe") == 0)
675                         { no_dhe=1; }
676                 else if (strcmp(*argv,"-no_ecdhe") == 0)
677                         { no_ecdhe=1; }
678                 else if (strcmp(*argv,"-www") == 0)
679                         { www=1; }
680                 else if (strcmp(*argv,"-WWW") == 0)
681                         { www=2; }
682                 else if (strcmp(*argv,"-HTTP") == 0)
683                         { www=3; }
684                 else if (strcmp(*argv,"-no_ssl2") == 0)
685                         { off|=SSL_OP_NO_SSLv2; }
686                 else if (strcmp(*argv,"-no_ssl3") == 0)
687                         { off|=SSL_OP_NO_SSLv3; }
688                 else if (strcmp(*argv,"-no_tls1") == 0)
689                         { off|=SSL_OP_NO_TLSv1; }
690 #ifndef OPENSSL_NO_SSL2
691                 else if (strcmp(*argv,"-ssl2") == 0)
692                         { meth=SSLv2_server_method(); }
693 #endif
694 #ifndef OPENSSL_NO_SSL3
695                 else if (strcmp(*argv,"-ssl3") == 0)
696                         { meth=SSLv3_server_method(); }
697 #endif
698 #ifndef OPENSSL_NO_TLS1
699                 else if (strcmp(*argv,"-tls1") == 0)
700                         { meth=TLSv1_server_method(); }
701 #endif
702                 else if (strcmp(*argv, "-id_prefix") == 0)
703                         {
704                         if (--argc < 1) goto bad;
705                         session_id_prefix = *(++argv);
706                         }
707 #ifndef OPENSSL_NO_ENGINE
708                 else if (strcmp(*argv,"-engine") == 0)
709                         {
710                         if (--argc < 1) goto bad;
711                         engine_id= *(++argv);
712                         }
713 #endif
714                 else if (strcmp(*argv,"-rand") == 0)
715                         {
716                         if (--argc < 1) goto bad;
717                         inrand= *(++argv);
718                         }
719                 else
720                         {
721                         BIO_printf(bio_err,"unknown option %s\n",*argv);
722                         badop=1;
723                         break;
724                         }
725                 argc--;
726                 argv++;
727                 }
728         if (badop)
729                 {
730 bad:
731                 sv_usage();
732                 goto end;
733                 }
734
735         SSL_load_error_strings();
736         OpenSSL_add_ssl_algorithms();
737
738 #ifndef OPENSSL_NO_ENGINE
739         e = setup_engine(bio_err, engine_id, 1);
740 #endif
741
742         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
743                 && !RAND_status())
744                 {
745                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
746                 }
747         if (inrand != NULL)
748                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
749                         app_RAND_load_files(inrand));
750
751         if (bio_s_out == NULL)
752                 {
753                 if (s_quiet && !s_debug && !s_msg)
754                         {
755                         bio_s_out=BIO_new(BIO_s_null());
756                         }
757                 else
758                         {
759                         if (bio_s_out == NULL)
760                                 bio_s_out=BIO_new_fp(stdout,BIO_NOCLOSE);
761                         }
762                 }
763
764 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
765         if (nocert)
766 #endif
767                 {
768                 s_cert_file=NULL;
769                 s_key_file=NULL;
770                 s_dcert_file=NULL;
771                 s_dkey_file=NULL;
772                 }
773
774         ctx=SSL_CTX_new(meth);
775         if (ctx == NULL)
776                 {
777                 ERR_print_errors(bio_err);
778                 goto end;
779                 }
780         if (session_id_prefix)
781                 {
782                 if(strlen(session_id_prefix) >= 32)
783                         BIO_printf(bio_err,
784 "warning: id_prefix is too long, only one new session will be possible\n");
785                 else if(strlen(session_id_prefix) >= 16)
786                         BIO_printf(bio_err,
787 "warning: id_prefix is too long if you use SSLv2\n");
788                 if(!SSL_CTX_set_generate_session_id(ctx, generate_session_id))
789                         {
790                         BIO_printf(bio_err,"error setting 'id_prefix'\n");
791                         ERR_print_errors(bio_err);
792                         goto end;
793                         }
794                 BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
795                 }
796         SSL_CTX_set_quiet_shutdown(ctx,1);
797         if (bugs) SSL_CTX_set_options(ctx,SSL_OP_ALL);
798         if (hack) SSL_CTX_set_options(ctx,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
799         SSL_CTX_set_options(ctx,off);
800
801         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
802
803         SSL_CTX_sess_set_cache_size(ctx,128);
804
805 #if 0
806         if (cipher == NULL) cipher=getenv("SSL_CIPHER");
807 #endif
808
809 #if 0
810         if (s_cert_file == NULL)
811                 {
812                 BIO_printf(bio_err,"You must specify a certificate file for the server to use\n");
813                 goto end;
814                 }
815 #endif
816
817         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
818                 (!SSL_CTX_set_default_verify_paths(ctx)))
819                 {
820                 /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
821                 ERR_print_errors(bio_err);
822                 /* goto end; */
823                 }
824         store = SSL_CTX_get_cert_store(ctx);
825         X509_STORE_set_flags(store, vflags);
826
827 #ifndef OPENSSL_NO_DH
828         if (!no_dhe)
829                 {
830                 DH *dh=NULL;
831
832                 if (dhfile)
833                         dh = load_dh_param(dhfile);
834                 else if (s_cert_file)
835                         dh = load_dh_param(s_cert_file);
836
837                 if (dh != NULL)
838                         {
839                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
840                         }
841                 else
842                         {
843                         BIO_printf(bio_s_out,"Using default temp DH parameters\n");
844                         dh=get_dh512();
845                         }
846                 (void)BIO_flush(bio_s_out);
847
848                 SSL_CTX_set_tmp_dh(ctx,dh);
849                 DH_free(dh);
850                 }
851 #endif
852
853 #ifndef OPENSSL_NO_ECDH
854         if (!no_ecdhe)
855                 {
856                 EC_KEY *ecdh=NULL;
857
858                 ecdh = EC_KEY_new();
859                 if (ecdh == NULL)
860                         {
861                         BIO_printf(bio_err,"Could not create ECDH struct.\n");
862                         goto end;
863                         }
864
865                 if (named_curve)
866                         {
867                         int nid = OBJ_sn2nid(named_curve);
868
869                         if (nid == 0)
870                                 {
871                                 BIO_printf(bio_err, "unknown curve name (%s)\n", 
872                                         named_curve);
873                                 goto end;
874                                 }
875
876                         ecdh->group = EC_GROUP_new_by_nid(nid);
877                         if (ecdh->group == NULL)
878                                 {
879                                 BIO_printf(bio_err, "unable to create curve (%s)\n", 
880                                         named_curve);
881                                 goto end;
882                                 }
883                         }
884
885                 if (ecdh->group != NULL)
886                         {
887                         BIO_printf(bio_s_out,"Setting temp ECDH parameters\n");
888                         }
889                 else
890                         {
891                         BIO_printf(bio_s_out,"Using default temp ECDH parameters\n");
892                         ecdh->group=EC_GROUP_new_by_nid(NID_sect163r2);
893                         if (ecdh->group == NULL) 
894                                 {
895                                 BIO_printf(bio_err, "unable to create curve (sect163r2)\n");
896                                 goto end;
897                                 }
898                         }
899                 (void)BIO_flush(bio_s_out);
900
901                 SSL_CTX_set_tmp_ecdh(ctx,ecdh);
902                 EC_KEY_free(ecdh);
903                 }
904 #endif
905         
906         if (!set_cert_stuff(ctx,s_cert_file,s_key_file))
907                 goto end;
908         if (s_dcert_file != NULL)
909                 {
910                 if (!set_cert_stuff(ctx,s_dcert_file,s_dkey_file))
911                         goto end;
912                 }
913
914 #ifndef OPENSSL_NO_RSA
915 #if 1
916         if (!no_tmp_rsa)
917                 SSL_CTX_set_tmp_rsa_callback(ctx,tmp_rsa_cb);
918 #else
919         if (!no_tmp_rsa && SSL_CTX_need_tmp_RSA(ctx))
920                 {
921                 RSA *rsa;
922
923                 BIO_printf(bio_s_out,"Generating temp (512 bit) RSA key...");
924                 BIO_flush(bio_s_out);
925
926                 rsa=RSA_generate_key(512,RSA_F4,NULL);
927
928                 if (!SSL_CTX_set_tmp_rsa(ctx,rsa))
929                         {
930                         ERR_print_errors(bio_err);
931                         goto end;
932                         }
933                 RSA_free(rsa);
934                 BIO_printf(bio_s_out,"\n");
935                 }
936 #endif
937 #endif
938
939         if (cipher != NULL)
940                 if(!SSL_CTX_set_cipher_list(ctx,cipher)) {
941                 BIO_printf(bio_err,"error setting cipher list\n");
942                 ERR_print_errors(bio_err);
943                 goto end;
944         }
945         SSL_CTX_set_verify(ctx,s_server_verify,verify_callback);
946         SSL_CTX_set_session_id_context(ctx,(void*)&s_server_session_id_context,
947                 sizeof s_server_session_id_context);
948
949         if (CAfile != NULL)
950             SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAfile));
951
952         BIO_printf(bio_s_out,"ACCEPT\n");
953         if (www)
954                 do_server(port,&accept_socket,www_body, context);
955         else
956                 do_server(port,&accept_socket,sv_body, context);
957         print_stats(bio_s_out,ctx);
958         ret=0;
959 end:
960         if (ctx != NULL) SSL_CTX_free(ctx);
961         if (bio_s_out != NULL)
962                 {
963                 BIO_free(bio_s_out);
964                 bio_s_out=NULL;
965                 }
966         apps_shutdown();
967         OPENSSL_EXIT(ret);
968         }
969
970 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
971         {
972         BIO_printf(bio,"%4ld items in the session cache\n",
973                 SSL_CTX_sess_number(ssl_ctx));
974         BIO_printf(bio,"%4d client connects (SSL_connect())\n",
975                 SSL_CTX_sess_connect(ssl_ctx));
976         BIO_printf(bio,"%4d client renegotiates (SSL_connect())\n",
977                 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
978         BIO_printf(bio,"%4d client connects that finished\n",
979                 SSL_CTX_sess_connect_good(ssl_ctx));
980         BIO_printf(bio,"%4d server accepts (SSL_accept())\n",
981                 SSL_CTX_sess_accept(ssl_ctx));
982         BIO_printf(bio,"%4d server renegotiates (SSL_accept())\n",
983                 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
984         BIO_printf(bio,"%4d server accepts that finished\n",
985                 SSL_CTX_sess_accept_good(ssl_ctx));
986         BIO_printf(bio,"%4d session cache hits\n",SSL_CTX_sess_hits(ssl_ctx));
987         BIO_printf(bio,"%4d session cache misses\n",SSL_CTX_sess_misses(ssl_ctx));
988         BIO_printf(bio,"%4d session cache timeouts\n",SSL_CTX_sess_timeouts(ssl_ctx));
989         BIO_printf(bio,"%4d callback cache hits\n",SSL_CTX_sess_cb_hits(ssl_ctx));
990         BIO_printf(bio,"%4d cache full overflows (%d allowed)\n",
991                 SSL_CTX_sess_cache_full(ssl_ctx),
992                 SSL_CTX_sess_get_cache_size(ssl_ctx));
993         }
994
995 static int sv_body(char *hostname, int s, unsigned char *context)
996         {
997         char *buf=NULL;
998         fd_set readfds;
999         int ret=1,width;
1000         int k,i;
1001         unsigned long l;
1002         SSL *con=NULL;
1003         BIO *sbio;
1004 #ifdef OPENSSL_SYS_WINDOWS
1005         struct timeval tv;
1006 #endif
1007
1008         if ((buf=OPENSSL_malloc(bufsize)) == NULL)
1009                 {
1010                 BIO_printf(bio_err,"out of memory\n");
1011                 goto err;
1012                 }
1013 #ifdef FIONBIO  
1014         if (s_nbio)
1015                 {
1016                 unsigned long sl=1;
1017
1018                 if (!s_quiet)
1019                         BIO_printf(bio_err,"turning on non blocking io\n");
1020                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
1021                         ERR_print_errors(bio_err);
1022                 }
1023 #endif
1024
1025         if (con == NULL) {
1026                 con=SSL_new(ctx);
1027 #ifndef OPENSSL_NO_KRB5
1028                 if ((con->kssl_ctx = kssl_ctx_new()) != NULL)
1029                         {
1030                         kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVICE,
1031                                                                 KRB5SVC);
1032                         kssl_ctx_setstring(con->kssl_ctx, KSSL_KEYTAB,
1033                                                                 KRB5KEYTAB);
1034                         }
1035 #endif  /* OPENSSL_NO_KRB5 */
1036                 if(context)
1037                       SSL_set_session_id_context(con, context,
1038                                                  strlen((char *)context));
1039         }
1040         SSL_clear(con);
1041
1042         sbio=BIO_new_socket(s,BIO_NOCLOSE);
1043         if (s_nbio_test)
1044                 {
1045                 BIO *test;
1046
1047                 test=BIO_new(BIO_f_nbio_test());
1048                 sbio=BIO_push(test,sbio);
1049                 }
1050         SSL_set_bio(con,sbio,sbio);
1051         SSL_set_accept_state(con);
1052         /* SSL_set_fd(con,s); */
1053
1054         if (s_debug)
1055                 {
1056                 con->debug=1;
1057                 BIO_set_callback(SSL_get_rbio(con),bio_dump_cb);
1058                 BIO_set_callback_arg(SSL_get_rbio(con),bio_s_out);
1059                 }
1060         if (s_msg)
1061                 {
1062                 SSL_set_msg_callback(con, msg_cb);
1063                 SSL_set_msg_callback_arg(con, bio_s_out);
1064                 }
1065
1066         width=s+1;
1067         for (;;)
1068                 {
1069                 int read_from_terminal;
1070                 int read_from_sslcon;
1071
1072                 read_from_terminal = 0;
1073                 read_from_sslcon = SSL_pending(con);
1074
1075                 if (!read_from_sslcon)
1076                         {
1077                         FD_ZERO(&readfds);
1078 #ifndef OPENSSL_SYS_WINDOWS
1079                         FD_SET(fileno(stdin),&readfds);
1080 #endif
1081                         FD_SET(s,&readfds);
1082                         /* Note: under VMS with SOCKETSHR the second parameter is
1083                          * currently of type (int *) whereas under other systems
1084                          * it is (void *) if you don't have a cast it will choke
1085                          * the compiler: if you do have a cast then you can either
1086                          * go for (int *) or (void *).
1087                          */
1088 #ifdef OPENSSL_SYS_WINDOWS
1089                         /* Under Windows we can't select on stdin: only
1090                          * on sockets. As a workaround we timeout the select every
1091                          * second and check for any keypress. In a proper Windows
1092                          * application we wouldn't do this because it is inefficient.
1093                          */
1094                         tv.tv_sec = 1;
1095                         tv.tv_usec = 0;
1096                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
1097                         if((i < 0) || (!i && !_kbhit() ) )continue;
1098                         if(_kbhit())
1099                                 read_from_terminal = 1;
1100 #else
1101                         i=select(width,(void *)&readfds,NULL,NULL,NULL);
1102                         if (i <= 0) continue;
1103                         if (FD_ISSET(fileno(stdin),&readfds))
1104                                 read_from_terminal = 1;
1105 #endif
1106                         if (FD_ISSET(s,&readfds))
1107                                 read_from_sslcon = 1;
1108                         }
1109                 if (read_from_terminal)
1110                         {
1111                         if (s_crlf)
1112                                 {
1113                                 int j, lf_num;
1114
1115                                 i=read(fileno(stdin), buf, bufsize/2);
1116                                 lf_num = 0;
1117                                 /* both loops are skipped when i <= 0 */
1118                                 for (j = 0; j < i; j++)
1119                                         if (buf[j] == '\n')
1120                                                 lf_num++;
1121                                 for (j = i-1; j >= 0; j--)
1122                                         {
1123                                         buf[j+lf_num] = buf[j];
1124                                         if (buf[j] == '\n')
1125                                                 {
1126                                                 lf_num--;
1127                                                 i++;
1128                                                 buf[j+lf_num] = '\r';
1129                                                 }
1130                                         }
1131                                 assert(lf_num == 0);
1132                                 }
1133                         else
1134                                 i=read(fileno(stdin),buf,bufsize);
1135                         if (!s_quiet)
1136                                 {
1137                                 if ((i <= 0) || (buf[0] == 'Q'))
1138                                         {
1139                                         BIO_printf(bio_s_out,"DONE\n");
1140                                         SHUTDOWN(s);
1141                                         close_accept_socket();
1142                                         ret= -11;
1143                                         goto err;
1144                                         }
1145                                 if ((i <= 0) || (buf[0] == 'q'))
1146                                         {
1147                                         BIO_printf(bio_s_out,"DONE\n");
1148                                         SHUTDOWN(s);
1149         /*                              close_accept_socket();
1150                                         ret= -11;*/
1151                                         goto err;
1152                                         }
1153                                 if ((buf[0] == 'r') && 
1154                                         ((buf[1] == '\n') || (buf[1] == '\r')))
1155                                         {
1156                                         SSL_renegotiate(con);
1157                                         i=SSL_do_handshake(con);
1158                                         printf("SSL_do_handshake -> %d\n",i);
1159                                         i=0; /*13; */
1160                                         continue;
1161                                         /* strcpy(buf,"server side RE-NEGOTIATE\n"); */
1162                                         }
1163                                 if ((buf[0] == 'R') &&
1164                                         ((buf[1] == '\n') || (buf[1] == '\r')))
1165                                         {
1166                                         SSL_set_verify(con,
1167                                                 SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,NULL);
1168                                         SSL_renegotiate(con);
1169                                         i=SSL_do_handshake(con);
1170                                         printf("SSL_do_handshake -> %d\n",i);
1171                                         i=0; /* 13; */
1172                                         continue;
1173                                         /* strcpy(buf,"server side RE-NEGOTIATE asking for client cert\n"); */
1174                                         }
1175                                 if (buf[0] == 'P')
1176                                         {
1177                                         static char *str="Lets print some clear text\n";
1178                                         BIO_write(SSL_get_wbio(con),str,strlen(str));
1179                                         }
1180                                 if (buf[0] == 'S')
1181                                         {
1182                                         print_stats(bio_s_out,SSL_get_SSL_CTX(con));
1183                                         }
1184                                 }
1185 #ifdef CHARSET_EBCDIC
1186                         ebcdic2ascii(buf,buf,i);
1187 #endif
1188                         l=k=0;
1189                         for (;;)
1190                                 {
1191                                 /* should do a select for the write */
1192 #ifdef RENEG
1193 { static count=0; if (++count == 100) { count=0; SSL_renegotiate(con); } }
1194 #endif
1195                                 k=SSL_write(con,&(buf[l]),(unsigned int)i);
1196                                 switch (SSL_get_error(con,k))
1197                                         {
1198                                 case SSL_ERROR_NONE:
1199                                         break;
1200                                 case SSL_ERROR_WANT_WRITE:
1201                                 case SSL_ERROR_WANT_READ:
1202                                 case SSL_ERROR_WANT_X509_LOOKUP:
1203                                         BIO_printf(bio_s_out,"Write BLOCK\n");
1204                                         break;
1205                                 case SSL_ERROR_SYSCALL:
1206                                 case SSL_ERROR_SSL:
1207                                         BIO_printf(bio_s_out,"ERROR\n");
1208                                         ERR_print_errors(bio_err);
1209                                         ret=1;
1210                                         goto err;
1211                                         /* break; */
1212                                 case SSL_ERROR_ZERO_RETURN:
1213                                         BIO_printf(bio_s_out,"DONE\n");
1214                                         ret=1;
1215                                         goto err;
1216                                         }
1217                                 l+=k;
1218                                 i-=k;
1219                                 if (i <= 0) break;
1220                                 }
1221                         }
1222                 if (read_from_sslcon)
1223                         {
1224                         if (!SSL_is_init_finished(con))
1225                                 {
1226                                 i=init_ssl_connection(con);
1227                                 
1228                                 if (i < 0)
1229                                         {
1230                                         ret=0;
1231                                         goto err;
1232                                         }
1233                                 else if (i == 0)
1234                                         {
1235                                         ret=1;
1236                                         goto err;
1237                                         }
1238                                 }
1239                         else
1240                                 {
1241 again:  
1242                                 i=SSL_read(con,(char *)buf,bufsize);
1243                                 switch (SSL_get_error(con,i))
1244                                         {
1245                                 case SSL_ERROR_NONE:
1246 #ifdef CHARSET_EBCDIC
1247                                         ascii2ebcdic(buf,buf,i);
1248 #endif
1249                                         write(fileno(stdout),buf,
1250                                                 (unsigned int)i);
1251                                         if (SSL_pending(con)) goto again;
1252                                         break;
1253                                 case SSL_ERROR_WANT_WRITE:
1254                                 case SSL_ERROR_WANT_READ:
1255                                 case SSL_ERROR_WANT_X509_LOOKUP:
1256                                         BIO_printf(bio_s_out,"Read BLOCK\n");
1257                                         break;
1258                                 case SSL_ERROR_SYSCALL:
1259                                 case SSL_ERROR_SSL:
1260                                         BIO_printf(bio_s_out,"ERROR\n");
1261                                         ERR_print_errors(bio_err);
1262                                         ret=1;
1263                                         goto err;
1264                                 case SSL_ERROR_ZERO_RETURN:
1265                                         BIO_printf(bio_s_out,"DONE\n");
1266                                         ret=1;
1267                                         goto err;
1268                                         }
1269                                 }
1270                         }
1271                 }
1272 err:
1273         BIO_printf(bio_s_out,"shutting down SSL\n");
1274 #if 1
1275         SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1276 #else
1277         SSL_shutdown(con);
1278 #endif
1279         if (con != NULL) SSL_free(con);
1280         BIO_printf(bio_s_out,"CONNECTION CLOSED\n");
1281         if (buf != NULL)
1282                 {
1283                 OPENSSL_cleanse(buf,bufsize);
1284                 OPENSSL_free(buf);
1285                 }
1286         if (ret >= 0)
1287                 BIO_printf(bio_s_out,"ACCEPT\n");
1288         return(ret);
1289         }
1290
1291 static void close_accept_socket(void)
1292         {
1293         BIO_printf(bio_err,"shutdown accept socket\n");
1294         if (accept_socket >= 0)
1295                 {
1296                 SHUTDOWN2(accept_socket);
1297                 }
1298         }
1299
1300 static int init_ssl_connection(SSL *con)
1301         {
1302         int i;
1303         const char *str;
1304         X509 *peer;
1305         long verify_error;
1306         MS_STATIC char buf[BUFSIZ];
1307
1308         if ((i=SSL_accept(con)) <= 0)
1309                 {
1310                 if (BIO_sock_should_retry(i))
1311                         {
1312                         BIO_printf(bio_s_out,"DELAY\n");
1313                         return(1);
1314                         }
1315
1316                 BIO_printf(bio_err,"ERROR\n");
1317                 verify_error=SSL_get_verify_result(con);
1318                 if (verify_error != X509_V_OK)
1319                         {
1320                         BIO_printf(bio_err,"verify error:%s\n",
1321                                 X509_verify_cert_error_string(verify_error));
1322                         }
1323                 else
1324                         ERR_print_errors(bio_err);
1325                 return(0);
1326                 }
1327
1328         PEM_write_bio_SSL_SESSION(bio_s_out,SSL_get_session(con));
1329
1330         peer=SSL_get_peer_certificate(con);
1331         if (peer != NULL)
1332                 {
1333                 BIO_printf(bio_s_out,"Client certificate\n");
1334                 PEM_write_bio_X509(bio_s_out,peer);
1335                 X509_NAME_oneline(X509_get_subject_name(peer),buf,sizeof buf);
1336                 BIO_printf(bio_s_out,"subject=%s\n",buf);
1337                 X509_NAME_oneline(X509_get_issuer_name(peer),buf,sizeof buf);
1338                 BIO_printf(bio_s_out,"issuer=%s\n",buf);
1339                 X509_free(peer);
1340                 }
1341
1342         if (SSL_get_shared_ciphers(con,buf,sizeof buf) != NULL)
1343                 BIO_printf(bio_s_out,"Shared ciphers:%s\n",buf);
1344         str=SSL_CIPHER_get_name(SSL_get_current_cipher(con));
1345         BIO_printf(bio_s_out,"CIPHER is %s\n",(str != NULL)?str:"(NONE)");
1346         if (con->hit) BIO_printf(bio_s_out,"Reused session-id\n");
1347         if (SSL_ctrl(con,SSL_CTRL_GET_FLAGS,0,NULL) &
1348                 TLS1_FLAGS_TLS_PADDING_BUG)
1349                 BIO_printf(bio_s_out,"Peer has incorrect TLSv1 block padding\n");
1350
1351         return(1);
1352         }
1353
1354 #ifndef OPENSSL_NO_DH
1355 static DH *load_dh_param(char *dhfile)
1356         {
1357         DH *ret=NULL;
1358         BIO *bio;
1359
1360         if ((bio=BIO_new_file(dhfile,"r")) == NULL)
1361                 goto err;
1362         ret=PEM_read_bio_DHparams(bio,NULL,NULL,NULL);
1363 err:
1364         if (bio != NULL) BIO_free(bio);
1365         return(ret);
1366         }
1367 #endif
1368
1369 #if 0
1370 static int load_CA(SSL_CTX *ctx, char *file)
1371         {
1372         FILE *in;
1373         X509 *x=NULL;
1374
1375         if ((in=fopen(file,"r")) == NULL)
1376                 return(0);
1377
1378         for (;;)
1379                 {
1380                 if (PEM_read_X509(in,&x,NULL) == NULL)
1381                         break;
1382                 SSL_CTX_add_client_CA(ctx,x);
1383                 }
1384         if (x != NULL) X509_free(x);
1385         fclose(in);
1386         return(1);
1387         }
1388 #endif
1389
1390 static int www_body(char *hostname, int s, unsigned char *context)
1391         {
1392         char *buf=NULL;
1393         int ret=1;
1394         int i,j,k,blank,dot;
1395         struct stat st_buf;
1396         SSL *con;
1397         SSL_CIPHER *c;
1398         BIO *io,*ssl_bio,*sbio;
1399         long total_bytes;
1400
1401         buf=OPENSSL_malloc(bufsize);
1402         if (buf == NULL) return(0);
1403         io=BIO_new(BIO_f_buffer());
1404         ssl_bio=BIO_new(BIO_f_ssl());
1405         if ((io == NULL) || (ssl_bio == NULL)) goto err;
1406
1407 #ifdef FIONBIO  
1408         if (s_nbio)
1409                 {
1410                 unsigned long sl=1;
1411
1412                 if (!s_quiet)
1413                         BIO_printf(bio_err,"turning on non blocking io\n");
1414                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
1415                         ERR_print_errors(bio_err);
1416                 }
1417 #endif
1418
1419         /* lets make the output buffer a reasonable size */
1420         if (!BIO_set_write_buffer_size(io,bufsize)) goto err;
1421
1422         if ((con=SSL_new(ctx)) == NULL) goto err;
1423 #ifndef OPENSSL_NO_KRB5
1424         if ((con->kssl_ctx = kssl_ctx_new()) != NULL)
1425                 {
1426                 kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVICE, KRB5SVC);
1427                 kssl_ctx_setstring(con->kssl_ctx, KSSL_KEYTAB, KRB5KEYTAB);
1428                 }
1429 #endif  /* OPENSSL_NO_KRB5 */
1430         if(context) SSL_set_session_id_context(con, context,
1431                                                strlen((char *)context));
1432
1433         sbio=BIO_new_socket(s,BIO_NOCLOSE);
1434         if (s_nbio_test)
1435                 {
1436                 BIO *test;
1437
1438                 test=BIO_new(BIO_f_nbio_test());
1439                 sbio=BIO_push(test,sbio);
1440                 }
1441         SSL_set_bio(con,sbio,sbio);
1442         SSL_set_accept_state(con);
1443
1444         /* SSL_set_fd(con,s); */
1445         BIO_set_ssl(ssl_bio,con,BIO_CLOSE);
1446         BIO_push(io,ssl_bio);
1447 #ifdef CHARSET_EBCDIC
1448         io = BIO_push(BIO_new(BIO_f_ebcdic_filter()),io);
1449 #endif
1450
1451         if (s_debug)
1452                 {
1453                 con->debug=1;
1454                 BIO_set_callback(SSL_get_rbio(con),bio_dump_cb);
1455                 BIO_set_callback_arg(SSL_get_rbio(con),bio_s_out);
1456                 }
1457         if (s_msg)
1458                 {
1459                 SSL_set_msg_callback(con, msg_cb);
1460                 SSL_set_msg_callback_arg(con, bio_s_out);
1461                 }
1462
1463         blank=0;
1464         for (;;)
1465                 {
1466                 if (hack)
1467                         {
1468                         i=SSL_accept(con);
1469
1470                         switch (SSL_get_error(con,i))
1471                                 {
1472                         case SSL_ERROR_NONE:
1473                                 break;
1474                         case SSL_ERROR_WANT_WRITE:
1475                         case SSL_ERROR_WANT_READ:
1476                         case SSL_ERROR_WANT_X509_LOOKUP:
1477                                 continue;
1478                         case SSL_ERROR_SYSCALL:
1479                         case SSL_ERROR_SSL:
1480                         case SSL_ERROR_ZERO_RETURN:
1481                                 ret=1;
1482                                 goto err;
1483                                 /* break; */
1484                                 }
1485
1486                         SSL_renegotiate(con);
1487                         SSL_write(con,NULL,0);
1488                         }
1489
1490                 i=BIO_gets(io,buf,bufsize-1);
1491                 if (i < 0) /* error */
1492                         {
1493                         if (!BIO_should_retry(io))
1494                                 {
1495                                 if (!s_quiet)
1496                                         ERR_print_errors(bio_err);
1497                                 goto err;
1498                                 }
1499                         else
1500                                 {
1501                                 BIO_printf(bio_s_out,"read R BLOCK\n");
1502 #if !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
1503                                 sleep(1);
1504 #endif
1505                                 continue;
1506                                 }
1507                         }
1508                 else if (i == 0) /* end of input */
1509                         {
1510                         ret=1;
1511                         goto end;
1512                         }
1513
1514                 /* else we have data */
1515                 if (    ((www == 1) && (strncmp("GET ",buf,4) == 0)) ||
1516                         ((www == 2) && (strncmp("GET /stats ",buf,10) == 0)))
1517                         {
1518                         char *p;
1519                         X509 *peer;
1520                         STACK_OF(SSL_CIPHER) *sk;
1521                         static char *space="                          ";
1522
1523                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
1524                         BIO_puts(io,"<HTML><BODY BGCOLOR=\"#ffffff\">\n");
1525                         BIO_puts(io,"<pre>\n");
1526 /*                      BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
1527                         BIO_puts(io,"\n");
1528                         for (i=0; i<local_argc; i++)
1529                                 {
1530                                 BIO_puts(io,local_argv[i]);
1531                                 BIO_write(io," ",1);
1532                                 }
1533                         BIO_puts(io,"\n");
1534
1535                         /* The following is evil and should not really
1536                          * be done */
1537                         BIO_printf(io,"Ciphers supported in s_server binary\n");
1538                         sk=SSL_get_ciphers(con);
1539                         j=sk_SSL_CIPHER_num(sk);
1540                         for (i=0; i<j; i++)
1541                                 {
1542                                 c=sk_SSL_CIPHER_value(sk,i);
1543                                 BIO_printf(io,"%-11s:%-25s",
1544                                         SSL_CIPHER_get_version(c),
1545                                         SSL_CIPHER_get_name(c));
1546                                 if ((((i+1)%2) == 0) && (i+1 != j))
1547                                         BIO_puts(io,"\n");
1548                                 }
1549                         BIO_puts(io,"\n");
1550                         p=SSL_get_shared_ciphers(con,buf,bufsize);
1551                         if (p != NULL)
1552                                 {
1553                                 BIO_printf(io,"---\nCiphers common between both SSL end points:\n");
1554                                 j=i=0;
1555                                 while (*p)
1556                                         {
1557                                         if (*p == ':')
1558                                                 {
1559                                                 BIO_write(io,space,26-j);
1560                                                 i++;
1561                                                 j=0;
1562                                                 BIO_write(io,((i%3)?" ":"\n"),1);
1563                                                 }
1564                                         else
1565                                                 {
1566                                                 BIO_write(io,p,1);
1567                                                 j++;
1568                                                 }
1569                                         p++;
1570                                         }
1571                                 BIO_puts(io,"\n");
1572                                 }
1573                         BIO_printf(io,((con->hit)
1574                                 ?"---\nReused, "
1575                                 :"---\nNew, "));
1576                         c=SSL_get_current_cipher(con);
1577                         BIO_printf(io,"%s, Cipher is %s\n",
1578                                 SSL_CIPHER_get_version(c),
1579                                 SSL_CIPHER_get_name(c));
1580                         SSL_SESSION_print(io,SSL_get_session(con));
1581                         BIO_printf(io,"---\n");
1582                         print_stats(io,SSL_get_SSL_CTX(con));
1583                         BIO_printf(io,"---\n");
1584                         peer=SSL_get_peer_certificate(con);
1585                         if (peer != NULL)
1586                                 {
1587                                 BIO_printf(io,"Client certificate\n");
1588                                 X509_print(io,peer);
1589                                 PEM_write_bio_X509(io,peer);
1590                                 }
1591                         else
1592                                 BIO_puts(io,"no client certificate available\n");
1593                         BIO_puts(io,"</BODY></HTML>\r\n\r\n");
1594                         break;
1595                         }
1596                 else if ((www == 2 || www == 3)
1597                          && (strncmp("GET /",buf,5) == 0))
1598                         {
1599                         BIO *file;
1600                         char *p,*e;
1601                         static char *text="HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
1602
1603                         /* skip the '/' */
1604                         p= &(buf[5]);
1605
1606                         dot = 1;
1607                         for (e=p; *e != '\0'; e++)
1608                                 {
1609                                 if (e[0] == ' ')
1610                                         break;
1611
1612                                 switch (dot)
1613                                         {
1614                                 case 1:
1615                                         dot = (e[0] == '.') ? 2 : 0;
1616                                         break;
1617                                 case 2:
1618                                         dot = (e[0] == '.') ? 3 : 0;
1619                                         break;
1620                                 case 3:
1621                                         dot = (e[0] == '/') ? -1 : 0;
1622                                         break;
1623                                         }
1624                                 if (dot == 0)
1625                                         dot = (e[0] == '/') ? 1 : 0;
1626                                 }
1627                         dot = (dot == 3) || (dot == -1); /* filename contains ".." component */
1628
1629                         if (*e == '\0')
1630                                 {
1631                                 BIO_puts(io,text);
1632                                 BIO_printf(io,"'%s' is an invalid file name\r\n",p);
1633                                 break;
1634                                 }
1635                         *e='\0';
1636
1637                         if (dot)
1638                                 {
1639                                 BIO_puts(io,text);
1640                                 BIO_printf(io,"'%s' contains '..' reference\r\n",p);
1641                                 break;
1642                                 }
1643
1644                         if (*p == '/')
1645                                 {
1646                                 BIO_puts(io,text);
1647                                 BIO_printf(io,"'%s' is an invalid path\r\n",p);
1648                                 break;
1649                                 }
1650
1651 #if 0
1652                         /* append if a directory lookup */
1653                         if (e[-1] == '/')
1654                                 strcat(p,"index.html");
1655 #endif
1656
1657                         /* if a directory, do the index thang */
1658                         if (stat(p,&st_buf) < 0)
1659                                 {
1660                                 BIO_puts(io,text);
1661                                 BIO_printf(io,"Error accessing '%s'\r\n",p);
1662                                 ERR_print_errors(io);
1663                                 break;
1664                                 }
1665                         if (S_ISDIR(st_buf.st_mode))
1666                                 {
1667 #if 0 /* must check buffer size */
1668                                 strcat(p,"/index.html");
1669 #else
1670                                 BIO_puts(io,text);
1671                                 BIO_printf(io,"'%s' is a directory\r\n",p);
1672                                 break;
1673 #endif
1674                                 }
1675
1676                         if ((file=BIO_new_file(p,"r")) == NULL)
1677                                 {
1678                                 BIO_puts(io,text);
1679                                 BIO_printf(io,"Error opening '%s'\r\n",p);
1680                                 ERR_print_errors(io);
1681                                 break;
1682                                 }
1683
1684                         if (!s_quiet)
1685                                 BIO_printf(bio_err,"FILE:%s\n",p);
1686
1687                         if (www == 2)
1688                                 {
1689                                 i=strlen(p);
1690                                 if (    ((i > 5) && (strcmp(&(p[i-5]),".html") == 0)) ||
1691                                         ((i > 4) && (strcmp(&(p[i-4]),".php") == 0)) ||
1692                                         ((i > 4) && (strcmp(&(p[i-4]),".htm") == 0)))
1693                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
1694                                 else
1695                                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
1696                                 }
1697                         /* send the file */
1698                         total_bytes=0;
1699                         for (;;)
1700                                 {
1701                                 i=BIO_read(file,buf,bufsize);
1702                                 if (i <= 0) break;
1703
1704 #ifdef RENEG
1705                                 total_bytes+=i;
1706                                 fprintf(stderr,"%d\n",i);
1707                                 if (total_bytes > 3*1024)
1708                                         {
1709                                         total_bytes=0;
1710                                         fprintf(stderr,"RENEGOTIATE\n");
1711                                         SSL_renegotiate(con);
1712                                         }
1713 #endif
1714
1715                                 for (j=0; j<i; )
1716                                         {
1717 #ifdef RENEG
1718 { static count=0; if (++count == 13) { SSL_renegotiate(con); } }
1719 #endif
1720                                         k=BIO_write(io,&(buf[j]),i-j);
1721                                         if (k <= 0)
1722                                                 {
1723                                                 if (!BIO_should_retry(io))
1724                                                         goto write_error;
1725                                                 else
1726                                                         {
1727                                                         BIO_printf(bio_s_out,"rwrite W BLOCK\n");
1728                                                         }
1729                                                 }
1730                                         else
1731                                                 {
1732                                                 j+=k;
1733                                                 }
1734                                         }
1735                                 }
1736 write_error:
1737                         BIO_free(file);
1738                         break;
1739                         }
1740                 }
1741
1742         for (;;)
1743                 {
1744                 i=(int)BIO_flush(io);
1745                 if (i <= 0)
1746                         {
1747                         if (!BIO_should_retry(io))
1748                                 break;
1749                         }
1750                 else
1751                         break;
1752                 }
1753 end:
1754 #if 1
1755         /* make sure we re-use sessions */
1756         SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1757 #else
1758         /* This kills performance */
1759 /*      SSL_shutdown(con); A shutdown gets sent in the
1760  *      BIO_free_all(io) procession */
1761 #endif
1762
1763 err:
1764
1765         if (ret >= 0)
1766                 BIO_printf(bio_s_out,"ACCEPT\n");
1767
1768         if (buf != NULL) OPENSSL_free(buf);
1769         if (io != NULL) BIO_free_all(io);
1770 /*      if (ssl_bio != NULL) BIO_free(ssl_bio);*/
1771         return(ret);
1772         }
1773
1774 #ifndef OPENSSL_NO_RSA
1775 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
1776         {
1777         static RSA *rsa_tmp=NULL;
1778
1779         if (rsa_tmp == NULL)
1780                 {
1781                 if (!s_quiet)
1782                         {
1783                         BIO_printf(bio_err,"Generating temp (%d bit) RSA key...",keylength);
1784                         (void)BIO_flush(bio_err);
1785                         }
1786                 rsa_tmp=RSA_generate_key(keylength,RSA_F4,NULL,NULL);
1787                 if (!s_quiet)
1788                         {
1789                         BIO_printf(bio_err,"\n");
1790                         (void)BIO_flush(bio_err);
1791                         }
1792                 }
1793         return(rsa_tmp);
1794         }
1795 #endif
1796
1797 #define MAX_SESSION_ID_ATTEMPTS 10
1798 static int generate_session_id(const SSL *ssl, unsigned char *id,
1799                                 unsigned int *id_len)
1800         {
1801         unsigned int count = 0;
1802         do      {
1803                 RAND_pseudo_bytes(id, *id_len);
1804                 /* Prefix the session_id with the required prefix. NB: If our
1805                  * prefix is too long, clip it - but there will be worse effects
1806                  * anyway, eg. the server could only possibly create 1 session
1807                  * ID (ie. the prefix!) so all future session negotiations will
1808                  * fail due to conflicts. */
1809                 memcpy(id, session_id_prefix,
1810                         (strlen(session_id_prefix) < *id_len) ?
1811                         strlen(session_id_prefix) : *id_len);
1812                 }
1813         while(SSL_has_matching_session_id(ssl, id, *id_len) &&
1814                 (++count < MAX_SESSION_ID_ATTEMPTS));
1815         if(count >= MAX_SESSION_ID_ATTEMPTS)
1816                 return 0;
1817         return 1;
1818         }