Add -no_resumption_on_reneg to SSL_CONF.
[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-2006 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  * Copyright 2005 Nokia. All rights reserved.
118  *
119  * The portions of the attached software ("Contribution") is developed by
120  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
121  * license.
122  *
123  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
124  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
125  * support (see RFC 4279) to OpenSSL.
126  *
127  * No patent licenses or other rights except those expressly stated in
128  * the OpenSSL open source license shall be deemed granted or received
129  * expressly, by implication, estoppel, or otherwise.
130  *
131  * No assurances are provided by Nokia that the Contribution does not
132  * infringe the patent or other intellectual property rights of any third
133  * party or that the license provides you with all the necessary rights
134  * to make use of the Contribution.
135  *
136  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
137  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
138  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
139  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
140  * OTHERWISE.
141  */
142
143 /* Until the key-gen callbacks are modified to use newer prototypes, we allow
144  * deprecated functions for openssl-internal code */
145 #ifdef OPENSSL_NO_DEPRECATED
146 #undef OPENSSL_NO_DEPRECATED
147 #endif
148
149 #include <assert.h>
150 #include <ctype.h>
151 #include <stdio.h>
152 #include <stdlib.h>
153 #include <string.h>
154
155 #include <openssl/e_os2.h>
156 #ifdef OPENSSL_NO_STDIO
157 #define APPS_WIN16
158 #endif
159
160 #if !defined(OPENSSL_SYS_NETWARE)  /* conflicts with winsock2 stuff on netware */
161 #include <sys/types.h>
162 #endif
163
164 /* With IPv6, it looks like Digital has mixed up the proper order of
165    recursive header file inclusion, resulting in the compiler complaining
166    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
167    is needed to have fileno() declared correctly...  So let's define u_int */
168 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
169 #define __U_INT
170 typedef unsigned int u_int;
171 #endif
172
173 #include <openssl/lhash.h>
174 #include <openssl/bn.h>
175 #define USE_SOCKETS
176 #include "apps.h"
177 #include <openssl/err.h>
178 #include <openssl/pem.h>
179 #include <openssl/x509.h>
180 #include <openssl/ssl.h>
181 #include <openssl/rand.h>
182 #include <openssl/ocsp.h>
183 #ifndef OPENSSL_NO_DH
184 #include <openssl/dh.h>
185 #endif
186 #ifndef OPENSSL_NO_RSA
187 #include <openssl/rsa.h>
188 #endif
189 #ifndef OPENSSL_NO_SRP
190 #include <openssl/srp.h>
191 #endif
192 #include "s_apps.h"
193 #include "timeouts.h"
194
195 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
196 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
197 #undef FIONBIO
198 #endif
199
200 #if defined(OPENSSL_SYS_BEOS_R5)
201 #include <fcntl.h>
202 #endif
203
204 #ifndef OPENSSL_NO_RSA
205 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength);
206 #endif
207 static int sv_body(char *hostname, int s, int stype, unsigned char *context);
208 static int www_body(char *hostname, int s, int stype, unsigned char *context);
209 static int rev_body(char *hostname, int s, int stype, unsigned char *context);
210 static void close_accept_socket(void );
211 static void sv_usage(void);
212 static int init_ssl_connection(SSL *s);
213 static void print_stats(BIO *bp,SSL_CTX *ctx);
214 static int generate_session_id(const SSL *ssl, unsigned char *id,
215                                 unsigned int *id_len);
216 static void init_session_cache_ctx(SSL_CTX *sctx);
217 static void free_sessions(void);
218 #ifndef OPENSSL_NO_DH
219 static DH *load_dh_param(const char *dhfile);
220 static DH *get_dh512(void);
221 #endif
222
223 #ifdef MONOLITH
224 static void s_server_init(void);
225 #endif
226
227 #ifndef OPENSSL_NO_TLSEXT
228
229 static const unsigned char auth_ext_data[]={TLSEXT_AUTHZDATAFORMAT_dtcp};
230
231 static unsigned char *generated_supp_data = NULL;
232
233 static const unsigned char *most_recent_supplemental_data = NULL;
234 static size_t most_recent_supplemental_data_length = 0;
235
236 static int client_provided_server_authz = 0;
237 static int client_provided_client_authz = 0;
238
239 #endif
240
241 #ifndef OPENSSL_NO_DH
242 static unsigned char dh512_p[]={
243         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
244         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
245         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
246         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
247         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
248         0x47,0x74,0xE8,0x33,
249         };
250 static unsigned char dh512_g[]={
251         0x02,
252         };
253
254 static DH *get_dh512(void)
255         {
256         DH *dh=NULL;
257
258         if ((dh=DH_new()) == NULL) return(NULL);
259         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
260         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
261         if ((dh->p == NULL) || (dh->g == NULL))
262                 return(NULL);
263         return(dh);
264         }
265 #endif
266
267
268 /* static int load_CA(SSL_CTX *ctx, char *file);*/
269
270 #undef BUFSIZZ
271 #define BUFSIZZ 16*1024
272 static int bufsize=BUFSIZZ;
273 static int accept_socket= -1;
274
275 #define TEST_CERT       "server.pem"
276 #ifndef OPENSSL_NO_TLSEXT
277 #define TEST_CERT2      "server2.pem"
278 #endif
279 #undef PROG
280 #define PROG            s_server_main
281
282 extern int verify_depth, verify_return_error, verify_quiet;
283
284 static int s_server_verify=SSL_VERIFY_NONE;
285 static int s_server_session_id_context = 1; /* anything will do */
286 static const char *s_cert_file=TEST_CERT,*s_key_file=NULL, *s_chain_file=NULL;
287 #ifndef OPENSSL_NO_TLSEXT
288 static const char *s_cert_file2=TEST_CERT2,*s_key_file2=NULL;
289 #endif
290 static char *s_dcert_file=NULL,*s_dkey_file=NULL, *s_dchain_file=NULL;
291 #ifdef FIONBIO
292 static int s_nbio=0;
293 #endif
294 static int s_nbio_test=0;
295 int s_crlf=0;
296 static SSL_CTX *ctx=NULL;
297 #ifndef OPENSSL_NO_TLSEXT
298 static SSL_CTX *ctx2=NULL;
299 #endif
300 static int www=0;
301
302 static BIO *bio_s_out=NULL;
303 static BIO *bio_s_msg = NULL;
304 static int s_debug=0;
305 #ifndef OPENSSL_NO_TLSEXT
306 static int s_tlsextdebug=0;
307 static int s_tlsextstatus=0;
308 static int cert_status_cb(SSL *s, void *arg);
309 #endif
310 static int no_resume_ephemeral = 0;
311 static int s_msg=0;
312 static int s_quiet=0;
313 static int s_ign_eof=0;
314 static int s_brief=0;
315
316 static char *keymatexportlabel=NULL;
317 static int keymatexportlen=20;
318
319 static int hack=0;
320 #ifndef OPENSSL_NO_ENGINE
321 static char *engine_id=NULL;
322 #endif
323 static const char *session_id_prefix=NULL;
324
325 static int enable_timeouts = 0;
326 static long socket_mtu;
327 #ifndef OPENSSL_NO_DTLS1
328 static int cert_chain = 0;
329 #endif
330
331 #ifndef OPENSSL_NO_TLSEXT
332 static int suppdata_cb(SSL *s, unsigned short supp_data_type,
333                        const unsigned char *in,
334                        unsigned short inlen, int *al,
335                        void *arg);
336
337 static int auth_suppdata_generate_cb(SSL *s, unsigned short supp_data_type,
338                                      const unsigned char **out,
339                                      unsigned short *outlen, int *al, void *arg);
340
341 static int authz_tlsext_generate_cb(SSL *s, unsigned short ext_type,
342                                     const unsigned char **out, unsigned short *outlen,
343                                     int *al, void *arg);
344
345 static int authz_tlsext_cb(SSL *s, unsigned short ext_type,
346                            const unsigned char *in,
347                            unsigned short inlen, int *al,
348                            void *arg);
349
350 static BIO *serverinfo_in = NULL;
351 static const char *s_serverinfo_file = NULL;
352
353 static int c_auth = 0;
354 static int c_auth_require_reneg = 0;
355 #endif
356
357 #ifndef OPENSSL_NO_PSK
358 static char *psk_identity="Client_identity";
359 char *psk_key=NULL; /* by default PSK is not used */
360
361 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
362         unsigned char *psk, unsigned int max_psk_len)
363         {
364         unsigned int psk_len = 0;
365         int ret;
366         BIGNUM *bn = NULL;
367
368         if (s_debug)
369                 BIO_printf(bio_s_out,"psk_server_cb\n");
370         if (!identity)
371                 {
372                 BIO_printf(bio_err,"Error: client did not send PSK identity\n");
373                 goto out_err;
374                 }
375         if (s_debug)
376                 BIO_printf(bio_s_out,"identity_len=%d identity=%s\n",
377                         identity ? (int)strlen(identity) : 0, identity);
378
379         /* here we could lookup the given identity e.g. from a database */
380         if (strcmp(identity, psk_identity) != 0)
381                 {
382                 BIO_printf(bio_s_out, "PSK error: client identity not found"
383                            " (got '%s' expected '%s')\n", identity,
384                            psk_identity);
385                 goto out_err;
386                 }
387         if (s_debug)
388                 BIO_printf(bio_s_out, "PSK client identity found\n");
389
390         /* convert the PSK key to binary */
391         ret = BN_hex2bn(&bn, psk_key);
392         if (!ret)
393                 {
394                 BIO_printf(bio_err,"Could not convert PSK key '%s' to BIGNUM\n", psk_key);
395                 if (bn)
396                         BN_free(bn);
397                 return 0;
398                 }
399         if (BN_num_bytes(bn) > (int)max_psk_len)
400                 {
401                 BIO_printf(bio_err,"psk buffer of callback is too small (%d) for key (%d)\n",
402                         max_psk_len, BN_num_bytes(bn));
403                 BN_free(bn);
404                 return 0;
405                 }
406
407         ret = BN_bn2bin(bn, psk);
408         BN_free(bn);
409
410         if (ret < 0)
411                 goto out_err;
412         psk_len = (unsigned int)ret;
413
414         if (s_debug)
415                 BIO_printf(bio_s_out, "fetched PSK len=%d\n", psk_len);
416         return psk_len;
417  out_err:
418         if (s_debug)
419                 BIO_printf(bio_err, "Error in PSK server callback\n");
420         return 0;
421         }
422 #endif
423
424 #ifndef OPENSSL_NO_SRP
425 /* This is a context that we pass to callbacks */
426 typedef struct srpsrvparm_st
427         {
428         char *login;
429         SRP_VBASE *vb;
430         SRP_user_pwd *user;
431         } srpsrvparm;
432
433 /* This callback pretends to require some asynchronous logic in order to obtain
434    a verifier. When the callback is called for a new connection we return
435    with a negative value. This will provoke the accept etc to return with
436    an LOOKUP_X509. The main logic of the reinvokes the suspended call 
437    (which would normally occur after a worker has finished) and we
438    set the user parameters. 
439 */
440 static int MS_CALLBACK ssl_srp_server_param_cb(SSL *s, int *ad, void *arg)
441         {
442         srpsrvparm *p = (srpsrvparm *)arg;
443         if (p->login == NULL && p->user == NULL )
444                 {
445                 p->login = SSL_get_srp_username(s);
446                 BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login);
447                 return (-1) ;
448                 }
449
450         if (p->user == NULL)
451                 {
452                 BIO_printf(bio_err, "User %s doesn't exist\n", p->login);
453                 return SSL3_AL_FATAL;
454                 }
455         if (SSL_set_srp_server_param(s, p->user->N, p->user->g, p->user->s, p->user->v,
456                                      p->user->info) < 0)
457                 {
458                 *ad = SSL_AD_INTERNAL_ERROR;
459                 return SSL3_AL_FATAL;
460                 }
461         BIO_printf(bio_err, "SRP parameters set: username = \"%s\" info=\"%s\" \n", p->login,p->user->info);
462         /* need to check whether there are memory leaks */
463         p->user = NULL;
464         p->login = NULL;
465         return SSL_ERROR_NONE;
466         }
467
468 #endif
469
470 #ifdef MONOLITH
471 static void s_server_init(void)
472         {
473         accept_socket=-1;
474         s_server_verify=SSL_VERIFY_NONE;
475         s_dcert_file=NULL;
476         s_dkey_file=NULL;
477         s_dchain_file=NULL;
478         s_cert_file=TEST_CERT;
479         s_key_file=NULL;
480         s_chain_file=NULL;
481 #ifndef OPENSSL_NO_TLSEXT
482         s_cert_file2=TEST_CERT2;
483         s_key_file2=NULL;
484         ctx2=NULL;
485 #endif
486 #ifdef FIONBIO
487         s_nbio=0;
488 #endif
489         s_nbio_test=0;
490         ctx=NULL;
491         www=0;
492
493         bio_s_out=NULL;
494         s_debug=0;
495         s_msg=0;
496         s_quiet=0;
497         s_brief=0;
498         hack=0;
499 #ifndef OPENSSL_NO_ENGINE
500         engine_id=NULL;
501 #endif
502         }
503 #endif
504
505 static void sv_usage(void)
506         {
507         BIO_printf(bio_err,"usage: s_server [args ...]\n");
508         BIO_printf(bio_err,"\n");
509         BIO_printf(bio_err," -accept arg   - port to accept on (default is %d)\n",PORT);
510         BIO_printf(bio_err," -checkhost host - check peer certificate matches \"host\"\n");
511         BIO_printf(bio_err," -checkemail email - check peer certificate matches \"email\"\n");
512         BIO_printf(bio_err," -checkip ipaddr - check peer certificate matches \"ipaddr\"\n");
513         BIO_printf(bio_err," -context arg  - set session ID context\n");
514         BIO_printf(bio_err," -verify arg   - turn on peer certificate verification\n");
515         BIO_printf(bio_err," -Verify arg   - turn on peer certificate verification, must have a cert.\n");
516         BIO_printf(bio_err," -cert arg     - certificate file to use\n");
517         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT);
518 #ifndef OPENSSL_NO_TLSEXT
519         BIO_printf(bio_err," -serverinfo arg - PEM serverinfo file for certificate\n");
520         BIO_printf(bio_err," -auth               - send and receive RFC 5878 TLS auth extensions and supplemental data\n");
521         BIO_printf(bio_err," -auth_require_reneg - Do not send TLS auth extensions until renegotiation\n");
522 #endif
523         BIO_printf(bio_err," -no_resumption_on_reneg - set SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION flag\n");
524         BIO_printf(bio_err," -crl_check    - check the peer certificate has not been revoked by its CA.\n" \
525                            "                 The CRL(s) are appended to the certificate file\n");
526         BIO_printf(bio_err," -crl_check_all - check the peer certificate has not been revoked by its CA\n" \
527                            "                 or any other CRL in the CA chain. CRL(s) are appened to the\n" \
528                            "                 the certificate file.\n");
529         BIO_printf(bio_err," -certform arg - certificate format (PEM or DER) PEM default\n");
530         BIO_printf(bio_err," -key arg      - Private Key file to use, in cert file if\n");
531         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT);
532         BIO_printf(bio_err," -keyform arg  - key format (PEM, DER or ENGINE) PEM default\n");
533         BIO_printf(bio_err," -pass arg     - private key file pass phrase source\n");
534         BIO_printf(bio_err," -dcert arg    - second certificate file to use (usually for DSA)\n");
535         BIO_printf(bio_err," -dcertform x  - second certificate format (PEM or DER) PEM default\n");
536         BIO_printf(bio_err," -dkey arg     - second private key file to use (usually for DSA)\n");
537         BIO_printf(bio_err," -dkeyform arg - second key format (PEM, DER or ENGINE) PEM default\n");
538         BIO_printf(bio_err," -dpass arg    - second private key file pass phrase source\n");
539         BIO_printf(bio_err," -dhparam arg  - DH parameter file to use, in cert file if not specified\n");
540         BIO_printf(bio_err,"                 or a default set of parameters is used\n");
541 #ifndef OPENSSL_NO_ECDH
542         BIO_printf(bio_err," -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
543                            "                 Use \"openssl ecparam -list_curves\" for all names\n" \
544                            "                 (default is nistp256).\n");
545 #endif
546 #ifdef FIONBIO
547         BIO_printf(bio_err," -nbio         - Run with non-blocking IO\n");
548 #endif
549         BIO_printf(bio_err," -nbio_test    - test with the non-blocking test bio\n");
550         BIO_printf(bio_err," -crlf         - convert LF from terminal into CRLF\n");
551         BIO_printf(bio_err," -debug        - Print more output\n");
552         BIO_printf(bio_err," -msg          - Show protocol messages\n");
553         BIO_printf(bio_err," -state        - Print the SSL states\n");
554         BIO_printf(bio_err," -CApath arg   - PEM format directory of CA's\n");
555         BIO_printf(bio_err," -CAfile arg   - PEM format file of CA's\n");
556         BIO_printf(bio_err," -nocert       - Don't use any certificates (Anon-DH)\n");
557         BIO_printf(bio_err," -cipher arg   - play with 'openssl ciphers' to see what goes here\n");
558         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences\n");
559         BIO_printf(bio_err," -quiet        - No server output\n");
560         BIO_printf(bio_err," -no_tmp_rsa   - Do not generate a tmp RSA key\n");
561 #ifndef OPENSSL_NO_PSK
562         BIO_printf(bio_err," -psk_hint arg - PSK identity hint to use\n");
563         BIO_printf(bio_err," -psk arg      - PSK in hex (without 0x)\n");
564 # ifndef OPENSSL_NO_JPAKE
565         BIO_printf(bio_err," -jpake arg    - JPAKE secret to use\n");
566 # endif
567 #endif
568 #ifndef OPENSSL_NO_SRP
569         BIO_printf(bio_err," -srpvfile file      - The verifier file for SRP\n");
570         BIO_printf(bio_err," -srpuserseed string - A seed string for a default user salt.\n");
571 #endif
572         BIO_printf(bio_err," -ssl2         - Just talk SSLv2\n");
573         BIO_printf(bio_err," -ssl3         - Just talk SSLv3\n");
574         BIO_printf(bio_err," -tls1_2       - Just talk TLSv1.2\n");
575         BIO_printf(bio_err," -tls1_1       - Just talk TLSv1.1\n");
576         BIO_printf(bio_err," -tls1         - Just talk TLSv1\n");
577         BIO_printf(bio_err," -dtls1        - Just talk DTLSv1\n");
578         BIO_printf(bio_err," -dtls1_2      - Just talk DTLSv1.2\n");
579         BIO_printf(bio_err," -timeout      - Enable timeouts\n");
580         BIO_printf(bio_err," -mtu          - Set link layer MTU\n");
581         BIO_printf(bio_err," -chain        - Read a certificate chain\n");
582         BIO_printf(bio_err," -no_ssl2      - Just disable SSLv2\n");
583         BIO_printf(bio_err," -no_ssl3      - Just disable SSLv3\n");
584         BIO_printf(bio_err," -no_tls1      - Just disable TLSv1\n");
585         BIO_printf(bio_err," -no_tls1_1    - Just disable TLSv1.1\n");
586         BIO_printf(bio_err," -no_tls1_2    - Just disable TLSv1.2\n");
587 #ifndef OPENSSL_NO_DH
588         BIO_printf(bio_err," -no_dhe       - Disable ephemeral DH\n");
589 #endif
590 #ifndef OPENSSL_NO_ECDH
591         BIO_printf(bio_err," -no_ecdhe     - Disable ephemeral ECDH\n");
592 #endif
593         BIO_printf(bio_err," -bugs         - Turn on SSL bug compatibility\n");
594         BIO_printf(bio_err," -www          - Respond to a 'GET /' with a status page\n");
595         BIO_printf(bio_err," -WWW          - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
596         BIO_printf(bio_err," -HTTP         - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
597         BIO_printf(bio_err,"                 with the assumption it contains a complete HTTP response.\n");
598 #ifndef OPENSSL_NO_ENGINE
599         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
600 #endif
601         BIO_printf(bio_err," -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
602         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
603 #ifndef OPENSSL_NO_TLSEXT
604         BIO_printf(bio_err," -servername host - servername for HostName TLS extension\n");
605         BIO_printf(bio_err," -servername_fatal - on mismatch send fatal alert (default warning alert)\n");
606         BIO_printf(bio_err," -cert2 arg    - certificate file to use for servername\n");
607         BIO_printf(bio_err,"                 (default is %s)\n",TEST_CERT2);
608         BIO_printf(bio_err," -key2 arg     - Private Key file to use for servername, in cert file if\n");
609         BIO_printf(bio_err,"                 not specified (default is %s)\n",TEST_CERT2);
610         BIO_printf(bio_err," -tlsextdebug  - hex dump of all TLS extensions received\n");
611         BIO_printf(bio_err," -no_ticket    - disable use of RFC4507bis session tickets\n");
612         BIO_printf(bio_err," -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n");
613 # ifndef OPENSSL_NO_NEXTPROTONEG
614         BIO_printf(bio_err," -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n");
615 # endif
616         BIO_printf(bio_err," -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n");
617         BIO_printf(bio_err," -alpn arg  - set the advertised protocols for the ALPN extension (comma-separated list)\n");
618 #endif
619         BIO_printf(bio_err," -keymatexport label   - Export keying material using label\n");
620         BIO_printf(bio_err," -keymatexportlen len  - Export len bytes of keying material (default 20)\n");
621         }
622
623 static int local_argc=0;
624 static char **local_argv;
625
626 #ifdef CHARSET_EBCDIC
627 static int ebcdic_new(BIO *bi);
628 static int ebcdic_free(BIO *a);
629 static int ebcdic_read(BIO *b, char *out, int outl);
630 static int ebcdic_write(BIO *b, const char *in, int inl);
631 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr);
632 static int ebcdic_gets(BIO *bp, char *buf, int size);
633 static int ebcdic_puts(BIO *bp, const char *str);
634
635 #define BIO_TYPE_EBCDIC_FILTER  (18|0x0200)
636 static BIO_METHOD methods_ebcdic=
637         {
638         BIO_TYPE_EBCDIC_FILTER,
639         "EBCDIC/ASCII filter",
640         ebcdic_write,
641         ebcdic_read,
642         ebcdic_puts,
643         ebcdic_gets,
644         ebcdic_ctrl,
645         ebcdic_new,
646         ebcdic_free,
647         };
648
649 typedef struct
650 {
651         size_t  alloced;
652         char    buff[1];
653 } EBCDIC_OUTBUFF;
654
655 BIO_METHOD *BIO_f_ebcdic_filter()
656 {
657         return(&methods_ebcdic);
658 }
659
660 static int ebcdic_new(BIO *bi)
661 {
662         EBCDIC_OUTBUFF *wbuf;
663
664         wbuf = (EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + 1024);
665         wbuf->alloced = 1024;
666         wbuf->buff[0] = '\0';
667
668         bi->ptr=(char *)wbuf;
669         bi->init=1;
670         bi->flags=0;
671         return(1);
672 }
673
674 static int ebcdic_free(BIO *a)
675 {
676         if (a == NULL) return(0);
677         if (a->ptr != NULL)
678                 OPENSSL_free(a->ptr);
679         a->ptr=NULL;
680         a->init=0;
681         a->flags=0;
682         return(1);
683 }
684         
685 static int ebcdic_read(BIO *b, char *out, int outl)
686 {
687         int ret=0;
688
689         if (out == NULL || outl == 0) return(0);
690         if (b->next_bio == NULL) return(0);
691
692         ret=BIO_read(b->next_bio,out,outl);
693         if (ret > 0)
694                 ascii2ebcdic(out,out,ret);
695         return(ret);
696 }
697
698 static int ebcdic_write(BIO *b, const char *in, int inl)
699 {
700         EBCDIC_OUTBUFF *wbuf;
701         int ret=0;
702         int num;
703         unsigned char n;
704
705         if ((in == NULL) || (inl <= 0)) return(0);
706         if (b->next_bio == NULL) return(0);
707
708         wbuf=(EBCDIC_OUTBUFF *)b->ptr;
709
710         if (inl > (num = wbuf->alloced))
711         {
712                 num = num + num;  /* double the size */
713                 if (num < inl)
714                         num = inl;
715                 OPENSSL_free(wbuf);
716                 wbuf=(EBCDIC_OUTBUFF *)OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + num);
717
718                 wbuf->alloced = num;
719                 wbuf->buff[0] = '\0';
720
721                 b->ptr=(char *)wbuf;
722         }
723
724         ebcdic2ascii(wbuf->buff, in, inl);
725
726         ret=BIO_write(b->next_bio, wbuf->buff, inl);
727
728         return(ret);
729 }
730
731 static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr)
732 {
733         long ret;
734
735         if (b->next_bio == NULL) return(0);
736         switch (cmd)
737         {
738         case BIO_CTRL_DUP:
739                 ret=0L;
740                 break;
741         default:
742                 ret=BIO_ctrl(b->next_bio,cmd,num,ptr);
743                 break;
744         }
745         return(ret);
746 }
747
748 static int ebcdic_gets(BIO *bp, char *buf, int size)
749 {
750         int i, ret=0;
751         if (bp->next_bio == NULL) return(0);
752 /*      return(BIO_gets(bp->next_bio,buf,size));*/
753         for (i=0; i<size-1; ++i)
754         {
755                 ret = ebcdic_read(bp,&buf[i],1);
756                 if (ret <= 0)
757                         break;
758                 else if (buf[i] == '\n')
759                 {
760                         ++i;
761                         break;
762                 }
763         }
764         if (i < size)
765                 buf[i] = '\0';
766         return (ret < 0 && i == 0) ? ret : i;
767 }
768
769 static int ebcdic_puts(BIO *bp, const char *str)
770 {
771         if (bp->next_bio == NULL) return(0);
772         return ebcdic_write(bp, str, strlen(str));
773 }
774 #endif
775
776 #ifndef OPENSSL_NO_TLSEXT
777
778 /* This is a context that we pass to callbacks */
779 typedef struct tlsextctx_st {
780    char * servername;
781    BIO * biodebug;
782    int extension_error;
783 } tlsextctx;
784
785
786 static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg)
787         {
788         tlsextctx * p = (tlsextctx *) arg;
789         const char * servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
790         if (servername && p->biodebug) 
791                 BIO_printf(p->biodebug,"Hostname in TLS extension: \"%s\"\n",servername);
792         
793         if (!p->servername)
794                 return SSL_TLSEXT_ERR_NOACK;
795         
796         if (servername)
797                 {
798                 if (strcmp(servername,p->servername)) 
799                         return p->extension_error;
800                 if (ctx2)
801                         {
802                         BIO_printf(p->biodebug,"Switching server context.\n");
803                         SSL_set_SSL_CTX(s,ctx2);
804                         }     
805                 }
806         return SSL_TLSEXT_ERR_OK;
807 }
808
809 /* Structure passed to cert status callback */
810
811 typedef struct tlsextstatusctx_st {
812    /* Default responder to use */
813    char *host, *path, *port;
814    int use_ssl;
815    int timeout;
816    BIO *err;
817    int verbose;
818 } tlsextstatusctx;
819
820 static tlsextstatusctx tlscstatp = {NULL, NULL, NULL, 0, -1, NULL, 0};
821
822 /* Certificate Status callback. This is called when a client includes a
823  * certificate status request extension.
824  *
825  * This is a simplified version. It examines certificates each time and
826  * makes one OCSP responder query for each request.
827  *
828  * A full version would store details such as the OCSP certificate IDs and
829  * minimise the number of OCSP responses by caching them until they were
830  * considered "expired".
831  */
832
833 static int cert_status_cb(SSL *s, void *arg)
834         {
835         tlsextstatusctx *srctx = arg;
836         BIO *err = srctx->err;
837         char *host, *port, *path;
838         int use_ssl;
839         unsigned char *rspder = NULL;
840         int rspderlen;
841         STACK_OF(OPENSSL_STRING) *aia = NULL;
842         X509 *x = NULL;
843         X509_STORE_CTX inctx;
844         X509_OBJECT obj;
845         OCSP_REQUEST *req = NULL;
846         OCSP_RESPONSE *resp = NULL;
847         OCSP_CERTID *id = NULL;
848         STACK_OF(X509_EXTENSION) *exts;
849         int ret = SSL_TLSEXT_ERR_NOACK;
850         int i;
851 #if 0
852 STACK_OF(OCSP_RESPID) *ids;
853 SSL_get_tlsext_status_ids(s, &ids);
854 BIO_printf(err, "cert_status: received %d ids\n", sk_OCSP_RESPID_num(ids));
855 #endif
856         if (srctx->verbose)
857                 BIO_puts(err, "cert_status: callback called\n");
858         /* Build up OCSP query from server certificate */
859         x = SSL_get_certificate(s);
860         aia = X509_get1_ocsp(x);
861         if (aia)
862                 {
863                 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
864                         &host, &port, &path, &use_ssl))
865                         {
866                         BIO_puts(err, "cert_status: can't parse AIA URL\n");
867                         goto err;
868                         }
869                 if (srctx->verbose)
870                         BIO_printf(err, "cert_status: AIA URL: %s\n",
871                                         sk_OPENSSL_STRING_value(aia, 0));
872                 }
873         else
874                 {
875                 if (!srctx->host)
876                         {
877                         BIO_puts(srctx->err, "cert_status: no AIA and no default responder URL\n");
878                         goto done;
879                         }
880                 host = srctx->host;
881                 path = srctx->path;
882                 port = srctx->port;
883                 use_ssl = srctx->use_ssl;
884                 }
885                 
886         if (!X509_STORE_CTX_init(&inctx,
887                                 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
888                                 NULL, NULL))
889                 goto err;
890         if (X509_STORE_get_by_subject(&inctx,X509_LU_X509,
891                                 X509_get_issuer_name(x),&obj) <= 0)
892                 {
893                 BIO_puts(err, "cert_status: Can't retrieve issuer certificate.\n");
894                 X509_STORE_CTX_cleanup(&inctx);
895                 goto done;
896                 }
897         req = OCSP_REQUEST_new();
898         if (!req)
899                 goto err;
900         id = OCSP_cert_to_id(NULL, x, obj.data.x509);
901         X509_free(obj.data.x509);
902         X509_STORE_CTX_cleanup(&inctx);
903         if (!id)
904                 goto err;
905         if (!OCSP_request_add0_id(req, id))
906                 goto err;
907         id = NULL;
908         /* Add any extensions to the request */
909         SSL_get_tlsext_status_exts(s, &exts);
910         for (i = 0; i < sk_X509_EXTENSION_num(exts); i++)
911                 {
912                 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
913                 if (!OCSP_REQUEST_add_ext(req, ext, -1))
914                         goto err;
915                 }
916         resp = process_responder(err, req, host, path, port, use_ssl, NULL,
917                                         srctx->timeout);
918         if (!resp)
919                 {
920                 BIO_puts(err, "cert_status: error querying responder\n");
921                 goto done;
922                 }
923         rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
924         if (rspderlen <= 0)
925                 goto err;
926         SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
927         if (srctx->verbose)
928                 {
929                 BIO_puts(err, "cert_status: ocsp response sent:\n");
930                 OCSP_RESPONSE_print(err, resp, 2);
931                 }
932         ret = SSL_TLSEXT_ERR_OK;
933         done:
934         if (ret != SSL_TLSEXT_ERR_OK)
935                 ERR_print_errors(err);
936         if (aia)
937                 {
938                 OPENSSL_free(host);
939                 OPENSSL_free(path);
940                 OPENSSL_free(port);
941                 X509_email_free(aia);
942                 }
943         if (id)
944                 OCSP_CERTID_free(id);
945         if (req)
946                 OCSP_REQUEST_free(req);
947         if (resp)
948                 OCSP_RESPONSE_free(resp);
949         return ret;
950         err:
951         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
952         goto done;
953         }
954
955 # ifndef OPENSSL_NO_NEXTPROTONEG
956 /* This is the context that we pass to next_proto_cb */
957 typedef struct tlsextnextprotoctx_st {
958         unsigned char *data;
959         unsigned int len;
960 } tlsextnextprotoctx;
961
962 static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg)
963         {
964         tlsextnextprotoctx *next_proto = arg;
965
966         *data = next_proto->data;
967         *len = next_proto->len;
968
969         return SSL_TLSEXT_ERR_OK;
970         }
971 # endif  /* ndef OPENSSL_NO_NEXTPROTONEG */
972
973 /* This the context that we pass to alpn_cb */
974 typedef struct tlsextalpnctx_st {
975         unsigned char *data;
976         unsigned short len;
977 } tlsextalpnctx;
978
979 static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
980         {
981         tlsextalpnctx *alpn_ctx = arg;
982
983         if (!s_quiet)
984                 {
985                 /* We can assume that |in| is syntactically valid. */
986                 unsigned i;
987                 BIO_printf(bio_s_out, "ALPN protocols advertised by the client: ");
988                 for (i = 0; i < inlen; )
989                         {
990                         if (i)
991                                 BIO_write(bio_s_out, ", ", 2);
992                         BIO_write(bio_s_out, &in[i + 1], in[i]);
993                         i += in[i] + 1;
994                         }
995                 BIO_write(bio_s_out, "\n", 1);
996                 }
997
998         if (SSL_select_next_proto((unsigned char**) out, outlen, alpn_ctx->data, alpn_ctx->len, in, inlen) !=
999             OPENSSL_NPN_NEGOTIATED)
1000                 {
1001                 return SSL_TLSEXT_ERR_NOACK;
1002                 }
1003
1004         if (!s_quiet)
1005                 {
1006                 BIO_printf(bio_s_out, "ALPN protocols selected: ");
1007                 BIO_write(bio_s_out, *out, *outlen);
1008                 BIO_write(bio_s_out, "\n", 1);
1009                 }
1010
1011         return SSL_TLSEXT_ERR_OK;
1012         }
1013 #endif  /* ndef OPENSSL_NO_TLSEXT */
1014
1015 int MAIN(int, char **);
1016
1017 #ifndef OPENSSL_NO_JPAKE
1018 static char *jpake_secret = NULL;
1019 #define no_jpake !jpake_secret
1020 #else
1021 #define no_jpake 1
1022 #endif
1023 #ifndef OPENSSL_NO_SRP
1024         static srpsrvparm srp_callback_parm;
1025 #endif
1026 static char *srtp_profiles = NULL;
1027
1028 int MAIN(int argc, char *argv[])
1029         {
1030         X509_VERIFY_PARAM *vpm = NULL;
1031         int badarg = 0;
1032         short port=PORT;
1033         char *CApath=NULL,*CAfile=NULL;
1034         char *chCApath=NULL,*chCAfile=NULL;
1035         char *vfyCApath=NULL,*vfyCAfile=NULL;
1036         unsigned char *context = NULL;
1037         char *dhfile = NULL;
1038         int badop=0;
1039         int ret=1;
1040         int build_chain = 0;
1041         int no_tmp_rsa=0,no_dhe=0,no_ecdhe=0,nocert=0;
1042         int state=0;
1043         const SSL_METHOD *meth=NULL;
1044         int socket_type=SOCK_STREAM;
1045         ENGINE *e=NULL;
1046         char *inrand=NULL;
1047         int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
1048         char *passarg = NULL, *pass = NULL;
1049         char *dpassarg = NULL, *dpass = NULL;
1050         int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
1051         X509 *s_cert = NULL, *s_dcert = NULL;
1052         STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL;
1053         EVP_PKEY *s_key = NULL, *s_dkey = NULL;
1054         int no_cache = 0, ext_cache = 0;
1055         int rev = 0, naccept = -1;
1056 #ifndef OPENSSL_NO_TLSEXT
1057         EVP_PKEY *s_key2 = NULL;
1058         X509 *s_cert2 = NULL;
1059         tlsextctx tlsextcbp = {NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING};
1060 # ifndef OPENSSL_NO_NEXTPROTONEG
1061         const char *next_proto_neg_in = NULL;
1062         tlsextnextprotoctx next_proto = { NULL, 0};
1063 # endif
1064         const char *alpn_in = NULL;
1065         tlsextalpnctx alpn_ctx = { NULL, 0};
1066 #endif
1067 #ifndef OPENSSL_NO_PSK
1068         /* by default do not send a PSK identity hint */
1069         static char *psk_identity_hint=NULL;
1070 #endif
1071 #ifndef OPENSSL_NO_SRP
1072         char *srpuserseed = NULL;
1073         char *srp_verifier_file = NULL;
1074 #endif
1075         SSL_EXCERT *exc = NULL;
1076         SSL_CONF_CTX *cctx = NULL;
1077         STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
1078
1079         char *crl_file = NULL;
1080         int crl_format = FORMAT_PEM;
1081         int crl_download = 0;
1082         STACK_OF(X509_CRL) *crls = NULL;
1083
1084         meth=SSLv23_server_method();
1085
1086         local_argc=argc;
1087         local_argv=argv;
1088
1089         apps_startup();
1090 #ifdef MONOLITH
1091         s_server_init();
1092 #endif
1093
1094         if (bio_err == NULL)
1095                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
1096
1097         if (!load_config(bio_err, NULL))
1098                 goto end;
1099
1100         cctx = SSL_CONF_CTX_new();
1101         if (!cctx)
1102                 goto end;
1103         SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER);
1104         SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CMDLINE);
1105
1106         verify_depth=0;
1107 #ifdef FIONBIO
1108         s_nbio=0;
1109 #endif
1110         s_nbio_test=0;
1111
1112         argc--;
1113         argv++;
1114
1115         while (argc >= 1)
1116                 {
1117                 if      ((strcmp(*argv,"-port") == 0) ||
1118                          (strcmp(*argv,"-accept") == 0))
1119                         {
1120                         if (--argc < 1) goto bad;
1121                         if (!extract_port(*(++argv),&port))
1122                                 goto bad;
1123                         }
1124                 else if (strcmp(*argv,"-naccept") == 0)
1125                         {
1126                         if (--argc < 1) goto bad;
1127                         naccept = atol(*(++argv));
1128                         if (naccept <= 0)
1129                                 {
1130                                 BIO_printf(bio_err, "bad accept value %s\n",
1131                                                         *argv);
1132                                 goto bad;
1133                                 }
1134                         }
1135                 else if (strcmp(*argv,"-verify") == 0)
1136                         {
1137                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE;
1138                         if (--argc < 1) goto bad;
1139                         verify_depth=atoi(*(++argv));
1140                         if (!s_quiet)
1141                                 BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
1142                         }
1143                 else if (strcmp(*argv,"-Verify") == 0)
1144                         {
1145                         s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
1146                                 SSL_VERIFY_CLIENT_ONCE;
1147                         if (--argc < 1) goto bad;
1148                         verify_depth=atoi(*(++argv));
1149                         if (!s_quiet)
1150                                 BIO_printf(bio_err,"verify depth is %d, must return a certificate\n",verify_depth);
1151                         }
1152                 else if (strcmp(*argv,"-context") == 0)
1153                         {
1154                         if (--argc < 1) goto bad;
1155                         context= (unsigned char *)*(++argv);
1156                         }
1157                 else if (strcmp(*argv,"-cert") == 0)
1158                         {
1159                         if (--argc < 1) goto bad;
1160                         s_cert_file= *(++argv);
1161                         }
1162                 else if (strcmp(*argv,"-CRL") == 0)
1163                         {
1164                         if (--argc < 1) goto bad;
1165                         crl_file= *(++argv);
1166                         }
1167                 else if (strcmp(*argv,"-crl_download") == 0)
1168                         crl_download = 1;
1169 #ifndef OPENSSL_NO_TLSEXT
1170                 else if (strcmp(*argv,"-serverinfo") == 0)
1171                         {
1172                         if (--argc < 1) goto bad;
1173                         s_serverinfo_file = *(++argv);
1174                         }
1175                 else if (strcmp(*argv,"-auth") == 0)
1176                         {
1177                         c_auth = 1;
1178                         }
1179 #endif
1180                 else if (strcmp(*argv,"-auth_require_reneg") == 0)
1181                         {
1182                         c_auth_require_reneg = 1;
1183                         }
1184                 else if (strcmp(*argv,"-certform") == 0)
1185                         {
1186                         if (--argc < 1) goto bad;
1187                         s_cert_format = str2fmt(*(++argv));
1188                         }
1189                 else if (strcmp(*argv,"-key") == 0)
1190                         {
1191                         if (--argc < 1) goto bad;
1192                         s_key_file= *(++argv);
1193                         }
1194                 else if (strcmp(*argv,"-keyform") == 0)
1195                         {
1196                         if (--argc < 1) goto bad;
1197                         s_key_format = str2fmt(*(++argv));
1198                         }
1199                 else if (strcmp(*argv,"-pass") == 0)
1200                         {
1201                         if (--argc < 1) goto bad;
1202                         passarg = *(++argv);
1203                         }
1204                 else if (strcmp(*argv,"-cert_chain") == 0)
1205                         {
1206                         if (--argc < 1) goto bad;
1207                         s_chain_file= *(++argv);
1208                         }
1209                 else if (strcmp(*argv,"-dhparam") == 0)
1210                         {
1211                         if (--argc < 1) goto bad;
1212                         dhfile = *(++argv);
1213                         }
1214                 else if (strcmp(*argv,"-dcertform") == 0)
1215                         {
1216                         if (--argc < 1) goto bad;
1217                         s_dcert_format = str2fmt(*(++argv));
1218                         }
1219                 else if (strcmp(*argv,"-dcert") == 0)
1220                         {
1221                         if (--argc < 1) goto bad;
1222                         s_dcert_file= *(++argv);
1223                         }
1224                 else if (strcmp(*argv,"-dkeyform") == 0)
1225                         {
1226                         if (--argc < 1) goto bad;
1227                         s_dkey_format = str2fmt(*(++argv));
1228                         }
1229                 else if (strcmp(*argv,"-dpass") == 0)
1230                         {
1231                         if (--argc < 1) goto bad;
1232                         dpassarg = *(++argv);
1233                         }
1234                 else if (strcmp(*argv,"-dkey") == 0)
1235                         {
1236                         if (--argc < 1) goto bad;
1237                         s_dkey_file= *(++argv);
1238                         }
1239                 else if (strcmp(*argv,"-dcert_chain") == 0)
1240                         {
1241                         if (--argc < 1) goto bad;
1242                         s_dchain_file= *(++argv);
1243                         }
1244                 else if (strcmp(*argv,"-nocert") == 0)
1245                         {
1246                         nocert=1;
1247                         }
1248                 else if (strcmp(*argv,"-CApath") == 0)
1249                         {
1250                         if (--argc < 1) goto bad;
1251                         CApath= *(++argv);
1252                         }
1253                 else if (strcmp(*argv,"-chainCApath") == 0)
1254                         {
1255                         if (--argc < 1) goto bad;
1256                         chCApath= *(++argv);
1257                         }
1258                 else if (strcmp(*argv,"-verifyCApath") == 0)
1259                         {
1260                         if (--argc < 1) goto bad;
1261                         vfyCApath= *(++argv);
1262                         }
1263                 else if (strcmp(*argv,"-no_cache") == 0)
1264                         no_cache = 1;
1265                 else if (strcmp(*argv,"-ext_cache") == 0)
1266                         ext_cache = 1;
1267                 else if (strcmp(*argv,"-CRLform") == 0)
1268                         {
1269                         if (--argc < 1) goto bad;
1270                         crl_format = str2fmt(*(++argv));
1271                         }
1272                 else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm))
1273                         {
1274                         if (badarg)
1275                                 goto bad;
1276                         continue;
1277                         }
1278                 else if (args_excert(&argv, &argc, &badarg, bio_err, &exc))
1279                         {
1280                         if (badarg)
1281                                 goto bad;
1282                         continue;
1283                         }
1284                 else if (args_ssl(&argv, &argc, cctx, &badarg, bio_err, &ssl_args))
1285                         {
1286                         if (badarg)
1287                                 goto bad;
1288                         continue;
1289                         }
1290                 else if (strcmp(*argv,"-verify_return_error") == 0)
1291                         verify_return_error = 1;
1292                 else if (strcmp(*argv,"-verify_quiet") == 0)
1293                         verify_quiet = 1;
1294                 else if (strcmp(*argv,"-build_chain") == 0)
1295                         build_chain = 1;
1296                 else if (strcmp(*argv,"-CAfile") == 0)
1297                         {
1298                         if (--argc < 1) goto bad;
1299                         CAfile= *(++argv);
1300                         }
1301                 else if (strcmp(*argv,"-chainCAfile") == 0)
1302                         {
1303                         if (--argc < 1) goto bad;
1304                         chCAfile= *(++argv);
1305                         }
1306                 else if (strcmp(*argv,"-verifyCAfile") == 0)
1307                         {
1308                         if (--argc < 1) goto bad;
1309                         vfyCAfile= *(++argv);
1310                         }
1311 #ifdef FIONBIO  
1312                 else if (strcmp(*argv,"-nbio") == 0)
1313                         { s_nbio=1; }
1314 #endif
1315                 else if (strcmp(*argv,"-nbio_test") == 0)
1316                         {
1317 #ifdef FIONBIO  
1318                         s_nbio=1;
1319 #endif
1320                         s_nbio_test=1;
1321                         }
1322                 else if (strcmp(*argv,"-ign_eof") == 0)
1323                         s_ign_eof=1;
1324                 else if (strcmp(*argv,"-no_ign_eof") == 0)
1325                         s_ign_eof=0;
1326                 else if (strcmp(*argv,"-debug") == 0)
1327                         { s_debug=1; }
1328 #ifndef OPENSSL_NO_TLSEXT
1329                 else if (strcmp(*argv,"-tlsextdebug") == 0)
1330                         s_tlsextdebug=1;
1331                 else if (strcmp(*argv,"-status") == 0)
1332                         s_tlsextstatus=1;
1333                 else if (strcmp(*argv,"-status_verbose") == 0)
1334                         {
1335                         s_tlsextstatus=1;
1336                         tlscstatp.verbose = 1;
1337                         }
1338                 else if (!strcmp(*argv, "-status_timeout"))
1339                         {
1340                         s_tlsextstatus=1;
1341                         if (--argc < 1) goto bad;
1342                         tlscstatp.timeout = atoi(*(++argv));
1343                         }
1344                 else if (!strcmp(*argv, "-status_url"))
1345                         {
1346                         s_tlsextstatus=1;
1347                         if (--argc < 1) goto bad;
1348                         if (!OCSP_parse_url(*(++argv),
1349                                         &tlscstatp.host,
1350                                         &tlscstatp.port,
1351                                         &tlscstatp.path,
1352                                         &tlscstatp.use_ssl))
1353                                 {
1354                                 BIO_printf(bio_err, "Error parsing URL\n");
1355                                 goto bad;
1356                                 }
1357                         }
1358 #endif
1359                 else if (strcmp(*argv,"-msg") == 0)
1360                         { s_msg=1; }
1361                 else if (strcmp(*argv,"-msgfile") == 0)
1362                         {
1363                         if (--argc < 1) goto bad;
1364                         bio_s_msg = BIO_new_file(*(++argv), "w");
1365                         }
1366 #ifndef OPENSSL_NO_SSL_TRACE
1367                 else if (strcmp(*argv,"-trace") == 0)
1368                         { s_msg=2; }
1369 #endif
1370                 else if (strcmp(*argv,"-hack") == 0)
1371                         { hack=1; }
1372                 else if (strcmp(*argv,"-state") == 0)
1373                         { state=1; }
1374                 else if (strcmp(*argv,"-crlf") == 0)
1375                         { s_crlf=1; }
1376                 else if (strcmp(*argv,"-quiet") == 0)
1377                         { s_quiet=1; }
1378                 else if (strcmp(*argv,"-brief") == 0)
1379                         {
1380                         s_quiet=1;
1381                         s_brief=1;
1382                         verify_quiet=1;
1383                         }
1384                 else if (strcmp(*argv,"-no_tmp_rsa") == 0)
1385                         { no_tmp_rsa=1; }
1386                 else if (strcmp(*argv,"-no_dhe") == 0)
1387                         { no_dhe=1; }
1388                 else if (strcmp(*argv,"-no_ecdhe") == 0)
1389                         { no_ecdhe=1; }
1390                 else if (strcmp(*argv,"-no_resume_ephemeral") == 0)
1391                         { no_resume_ephemeral = 1; }
1392 #ifndef OPENSSL_NO_PSK
1393                 else if (strcmp(*argv,"-psk_hint") == 0)
1394                         {
1395                         if (--argc < 1) goto bad;
1396                         psk_identity_hint= *(++argv);
1397                         }
1398                 else if (strcmp(*argv,"-psk") == 0)
1399                         {
1400                         size_t i;
1401
1402                         if (--argc < 1) goto bad;
1403                         psk_key=*(++argv);
1404                         for (i=0; i<strlen(psk_key); i++)
1405                                 {
1406                                 if (isxdigit((unsigned char)psk_key[i]))
1407                                         continue;
1408                                 BIO_printf(bio_err,"Not a hex number '%s'\n",*argv);
1409                                 goto bad;
1410                                 }
1411                         }
1412 #endif
1413 #ifndef OPENSSL_NO_SRP
1414                 else if (strcmp(*argv, "-srpvfile") == 0)
1415                         {
1416                         if (--argc < 1) goto bad;
1417                         srp_verifier_file = *(++argv);
1418                         meth = TLSv1_server_method();
1419                         }
1420                 else if (strcmp(*argv, "-srpuserseed") == 0)
1421                         {
1422                         if (--argc < 1) goto bad;
1423                         srpuserseed = *(++argv);
1424                         meth = TLSv1_server_method();
1425                         }
1426 #endif
1427                 else if (strcmp(*argv,"-rev") == 0)
1428                         { rev=1; }
1429                 else if (strcmp(*argv,"-www") == 0)
1430                         { www=1; }
1431                 else if (strcmp(*argv,"-WWW") == 0)
1432                         { www=2; }
1433                 else if (strcmp(*argv,"-HTTP") == 0)
1434                         { www=3; }
1435 #ifndef OPENSSL_NO_SSL2
1436                 else if (strcmp(*argv,"-ssl2") == 0)
1437                         { meth=SSLv2_server_method(); }
1438 #endif
1439 #ifndef OPENSSL_NO_SSL3
1440                 else if (strcmp(*argv,"-ssl3") == 0)
1441                         { meth=SSLv3_server_method(); }
1442 #endif
1443 #ifndef OPENSSL_NO_TLS1
1444                 else if (strcmp(*argv,"-tls1") == 0)
1445                         { meth=TLSv1_server_method(); }
1446                 else if (strcmp(*argv,"-tls1_1") == 0)
1447                         { meth=TLSv1_1_server_method(); }
1448                 else if (strcmp(*argv,"-tls1_2") == 0)
1449                         { meth=TLSv1_2_server_method(); }
1450 #endif
1451 #ifndef OPENSSL_NO_DTLS1
1452                 else if (strcmp(*argv,"-dtls") == 0)
1453                         { 
1454                         meth=DTLS_server_method();
1455                         socket_type = SOCK_DGRAM;
1456                         }
1457                 else if (strcmp(*argv,"-dtls1") == 0)
1458                         { 
1459                         meth=DTLSv1_server_method();
1460                         socket_type = SOCK_DGRAM;
1461                         }
1462                 else if (strcmp(*argv,"-dtls1_2") == 0)
1463                         { 
1464                         meth=DTLSv1_2_server_method();
1465                         socket_type = SOCK_DGRAM;
1466                         }
1467                 else if (strcmp(*argv,"-timeout") == 0)
1468                         enable_timeouts = 1;
1469                 else if (strcmp(*argv,"-mtu") == 0)
1470                         {
1471                         if (--argc < 1) goto bad;
1472                         socket_mtu = atol(*(++argv));
1473                         }
1474                 else if (strcmp(*argv, "-chain") == 0)
1475                         cert_chain = 1;
1476 #endif
1477                 else if (strcmp(*argv, "-id_prefix") == 0)
1478                         {
1479                         if (--argc < 1) goto bad;
1480                         session_id_prefix = *(++argv);
1481                         }
1482 #ifndef OPENSSL_NO_ENGINE
1483                 else if (strcmp(*argv,"-engine") == 0)
1484                         {
1485                         if (--argc < 1) goto bad;
1486                         engine_id= *(++argv);
1487                         }
1488 #endif
1489                 else if (strcmp(*argv,"-rand") == 0)
1490                         {
1491                         if (--argc < 1) goto bad;
1492                         inrand= *(++argv);
1493                         }
1494 #ifndef OPENSSL_NO_TLSEXT
1495                 else if (strcmp(*argv,"-servername") == 0)
1496                         {
1497                         if (--argc < 1) goto bad;
1498                         tlsextcbp.servername= *(++argv);
1499                         }
1500                 else if (strcmp(*argv,"-servername_fatal") == 0)
1501                         { tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; }
1502                 else if (strcmp(*argv,"-cert2") == 0)
1503                         {
1504                         if (--argc < 1) goto bad;
1505                         s_cert_file2= *(++argv);
1506                         }
1507                 else if (strcmp(*argv,"-key2") == 0)
1508                         {
1509                         if (--argc < 1) goto bad;
1510                         s_key_file2= *(++argv);
1511                         }
1512 # ifndef OPENSSL_NO_NEXTPROTONEG
1513                 else if (strcmp(*argv,"-nextprotoneg") == 0)
1514                         {
1515                         if (--argc < 1) goto bad;
1516                         next_proto_neg_in = *(++argv);
1517                         }
1518 # endif
1519                 else if (strcmp(*argv,"-alpn") == 0)
1520                         {
1521                         if (--argc < 1) goto bad;
1522                         alpn_in = *(++argv);
1523                         }
1524 #endif
1525 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1526                 else if (strcmp(*argv,"-jpake") == 0)
1527                         {
1528                         if (--argc < 1) goto bad;
1529                         jpake_secret = *(++argv);
1530                         }
1531 #endif
1532                 else if (strcmp(*argv,"-use_srtp") == 0)
1533                         {
1534                         if (--argc < 1) goto bad;
1535                         srtp_profiles = *(++argv);
1536                         }
1537                 else if (strcmp(*argv,"-keymatexport") == 0)
1538                         {
1539                         if (--argc < 1) goto bad;
1540                         keymatexportlabel= *(++argv);
1541                         }
1542                 else if (strcmp(*argv,"-keymatexportlen") == 0)
1543                         {
1544                         if (--argc < 1) goto bad;
1545                         keymatexportlen=atoi(*(++argv));
1546                         if (keymatexportlen == 0) goto bad;
1547                         }
1548                 else
1549                         {
1550                         BIO_printf(bio_err,"unknown option %s\n",*argv);
1551                         badop=1;
1552                         break;
1553                         }
1554                 argc--;
1555                 argv++;
1556                 }
1557         if (badop)
1558                 {
1559 bad:
1560                 sv_usage();
1561                 goto end;
1562                 }
1563
1564 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1565         if (jpake_secret)
1566                 {
1567                 if (psk_key)
1568                         {
1569                         BIO_printf(bio_err,
1570                                    "Can't use JPAKE and PSK together\n");
1571                         goto end;
1572                         }
1573                 psk_identity = "JPAKE";
1574                 }
1575 #endif
1576
1577         SSL_load_error_strings();
1578         OpenSSL_add_ssl_algorithms();
1579
1580 #ifndef OPENSSL_NO_ENGINE
1581         e = setup_engine(bio_err, engine_id, 1);
1582 #endif
1583
1584         if (!app_passwd(bio_err, passarg, dpassarg, &pass, &dpass))
1585                 {
1586                 BIO_printf(bio_err, "Error getting password\n");
1587                 goto end;
1588                 }
1589
1590
1591         if (s_key_file == NULL)
1592                 s_key_file = s_cert_file;
1593 #ifndef OPENSSL_NO_TLSEXT
1594         if (s_key_file2 == NULL)
1595                 s_key_file2 = s_cert_file2;
1596 #endif
1597
1598         if (!load_excert(&exc, bio_err))
1599                 goto end;
1600
1601         if (nocert == 0)
1602                 {
1603                 s_key = load_key(bio_err, s_key_file, s_key_format, 0, pass, e,
1604                        "server certificate private key file");
1605                 if (!s_key)
1606                         {
1607                         ERR_print_errors(bio_err);
1608                         goto end;
1609                         }
1610
1611                 s_cert = load_cert(bio_err,s_cert_file,s_cert_format,
1612                         NULL, e, "server certificate file");
1613
1614                 if (!s_cert)
1615                         {
1616                         ERR_print_errors(bio_err);
1617                         goto end;
1618                         }
1619                 if (s_chain_file)
1620                         {
1621                         s_chain = load_certs(bio_err, s_chain_file,FORMAT_PEM,
1622                                         NULL, e, "server certificate chain");
1623                         if (!s_chain)
1624                                 goto end;
1625                         }
1626
1627 #ifndef OPENSSL_NO_TLSEXT
1628                 if (tlsextcbp.servername) 
1629                         {
1630                         s_key2 = load_key(bio_err, s_key_file2, s_key_format, 0, pass, e,
1631                                 "second server certificate private key file");
1632                         if (!s_key2)
1633                                 {
1634                                 ERR_print_errors(bio_err);
1635                                 goto end;
1636                                 }
1637                         
1638                         s_cert2 = load_cert(bio_err,s_cert_file2,s_cert_format,
1639                                 NULL, e, "second server certificate file");
1640                         
1641                         if (!s_cert2)
1642                                 {
1643                                 ERR_print_errors(bio_err);
1644                                 goto end;
1645                                 }
1646                         }
1647 #endif /* OPENSSL_NO_TLSEXT */
1648                 }
1649
1650 #if !defined(OPENSSL_NO_TLSEXT)
1651 # if !defined(OPENSSL_NO_NEXTPROTONEG) 
1652         if (next_proto_neg_in)
1653                 {
1654                 unsigned short len;
1655                 next_proto.data = next_protos_parse(&len, next_proto_neg_in);
1656                 if (next_proto.data == NULL)
1657                         goto end;
1658                 next_proto.len = len;
1659                 }
1660         else
1661                 {
1662                 next_proto.data = NULL;
1663                 }
1664 # endif
1665         alpn_ctx.data = NULL;
1666         if (alpn_in)
1667                 {
1668                 unsigned short len;
1669                 alpn_ctx.data = next_protos_parse(&len, alpn_in);
1670                 if (alpn_ctx.data == NULL)
1671                         goto end;
1672                 alpn_ctx.len = len;
1673                 }
1674 #endif
1675
1676         if (crl_file)
1677                 {
1678                 X509_CRL *crl;
1679                 crl = load_crl(crl_file, crl_format);
1680                 if (!crl)
1681                         {
1682                         BIO_puts(bio_err, "Error loading CRL\n");
1683                         ERR_print_errors(bio_err);
1684                         goto end;
1685                         }
1686                 crls = sk_X509_CRL_new_null();
1687                 if (!crls || !sk_X509_CRL_push(crls, crl))
1688                         {
1689                         BIO_puts(bio_err, "Error adding CRL\n");
1690                         ERR_print_errors(bio_err);
1691                         X509_CRL_free(crl);
1692                         goto end;
1693                         }
1694                 }
1695
1696
1697         if (s_dcert_file)
1698                 {
1699
1700                 if (s_dkey_file == NULL)
1701                         s_dkey_file = s_dcert_file;
1702
1703                 s_dkey = load_key(bio_err, s_dkey_file, s_dkey_format,
1704                                 0, dpass, e,
1705                                "second certificate private key file");
1706                 if (!s_dkey)
1707                         {
1708                         ERR_print_errors(bio_err);
1709                         goto end;
1710                         }
1711
1712                 s_dcert = load_cert(bio_err,s_dcert_file,s_dcert_format,
1713                                 NULL, e, "second server certificate file");
1714
1715                 if (!s_dcert)
1716                         {
1717                         ERR_print_errors(bio_err);
1718                         goto end;
1719                         }
1720                 if (s_dchain_file)
1721                         {
1722                         s_dchain = load_certs(bio_err, s_dchain_file,FORMAT_PEM,
1723                                 NULL, e, "second server certificate chain");
1724                         if (!s_dchain)
1725                                 goto end;
1726                         }
1727
1728                 }
1729
1730         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
1731                 && !RAND_status())
1732                 {
1733                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
1734                 }
1735         if (inrand != NULL)
1736                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
1737                         app_RAND_load_files(inrand));
1738
1739         if (bio_s_out == NULL)
1740                 {
1741                 if (s_quiet && !s_debug)
1742                         {
1743                         bio_s_out=BIO_new(BIO_s_null());
1744                         if (s_msg && !bio_s_msg)
1745                                 bio_s_msg=BIO_new_fp(stdout,BIO_NOCLOSE);
1746                         }
1747                 else
1748                         {
1749                         if (bio_s_out == NULL)
1750                                 bio_s_out=BIO_new_fp(stdout,BIO_NOCLOSE);
1751                         }
1752                 }
1753
1754 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1755         if (nocert)
1756 #endif
1757                 {
1758                 s_cert_file=NULL;
1759                 s_key_file=NULL;
1760                 s_dcert_file=NULL;
1761                 s_dkey_file=NULL;
1762 #ifndef OPENSSL_NO_TLSEXT
1763                 s_cert_file2=NULL;
1764                 s_key_file2=NULL;
1765 #endif
1766                 }
1767
1768         ctx=SSL_CTX_new(meth);
1769         if (ctx == NULL)
1770                 {
1771                 ERR_print_errors(bio_err);
1772                 goto end;
1773                 }
1774         if (session_id_prefix)
1775                 {
1776                 if(strlen(session_id_prefix) >= 32)
1777                         BIO_printf(bio_err,
1778 "warning: id_prefix is too long, only one new session will be possible\n");
1779                 else if(strlen(session_id_prefix) >= 16)
1780                         BIO_printf(bio_err,
1781 "warning: id_prefix is too long if you use SSLv2\n");
1782                 if(!SSL_CTX_set_generate_session_id(ctx, generate_session_id))
1783                         {
1784                         BIO_printf(bio_err,"error setting 'id_prefix'\n");
1785                         ERR_print_errors(bio_err);
1786                         goto end;
1787                         }
1788                 BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
1789                 }
1790         SSL_CTX_set_quiet_shutdown(ctx,1);
1791         if (hack) SSL_CTX_set_options(ctx,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1792         if (exc) ssl_ctx_set_excert(ctx, exc);
1793         /* DTLS: partial reads end up discarding unread UDP bytes :-( 
1794          * Setting read ahead solves this problem.
1795          */
1796         if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1);
1797
1798         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
1799         if (no_cache)
1800                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1801         else if (ext_cache)
1802                 init_session_cache_ctx(ctx);
1803         else
1804                 SSL_CTX_sess_set_cache_size(ctx,128);
1805
1806         if (srtp_profiles != NULL)
1807                 SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
1808
1809 #if 0
1810         if (cipher == NULL) cipher=getenv("SSL_CIPHER");
1811 #endif
1812
1813 #if 0
1814         if (s_cert_file == NULL)
1815                 {
1816                 BIO_printf(bio_err,"You must specify a certificate file for the server to use\n");
1817                 goto end;
1818                 }
1819 #endif
1820
1821         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
1822                 (!SSL_CTX_set_default_verify_paths(ctx)))
1823                 {
1824                 /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
1825                 ERR_print_errors(bio_err);
1826                 /* goto end; */
1827                 }
1828         if (vpm)
1829                 SSL_CTX_set1_param(ctx, vpm);
1830
1831         ssl_ctx_add_crls(ctx, crls, 0);
1832
1833         if (!args_ssl_call(ctx, bio_err, cctx, ssl_args, no_ecdhe, no_jpake))
1834                 goto end;
1835
1836         if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1837                                                 crls, crl_download))
1838                 {
1839                 BIO_printf(bio_err, "Error loading store locations\n");
1840                 ERR_print_errors(bio_err);
1841                 goto end;
1842                 }
1843
1844 #ifndef OPENSSL_NO_TLSEXT
1845         if (s_cert2)
1846                 {
1847                 ctx2=SSL_CTX_new(meth);
1848                 if (ctx2 == NULL)
1849                         {
1850                         ERR_print_errors(bio_err);
1851                         goto end;
1852                         }
1853                 }
1854         
1855         if (ctx2)
1856                 {
1857                 BIO_printf(bio_s_out,"Setting secondary ctx parameters\n");
1858
1859                 if (session_id_prefix)
1860                         {
1861                         if(strlen(session_id_prefix) >= 32)
1862                                 BIO_printf(bio_err,
1863                                         "warning: id_prefix is too long, only one new session will be possible\n");
1864                         else if(strlen(session_id_prefix) >= 16)
1865                                 BIO_printf(bio_err,
1866                                         "warning: id_prefix is too long if you use SSLv2\n");
1867                         if(!SSL_CTX_set_generate_session_id(ctx2, generate_session_id))
1868                                 {
1869                                 BIO_printf(bio_err,"error setting 'id_prefix'\n");
1870                                 ERR_print_errors(bio_err);
1871                                 goto end;
1872                                 }
1873                         BIO_printf(bio_err,"id_prefix '%s' set.\n", session_id_prefix);
1874                         }
1875                 SSL_CTX_set_quiet_shutdown(ctx2,1);
1876                 if (hack) SSL_CTX_set_options(ctx2,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1877                 if (exc) ssl_ctx_set_excert(ctx2, exc);
1878                 /* DTLS: partial reads end up discarding unread UDP bytes :-( 
1879                  * Setting read ahead solves this problem.
1880                  */
1881                 if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx2, 1);
1882
1883                 if (state) SSL_CTX_set_info_callback(ctx2,apps_ssl_info_callback);
1884
1885                 if (no_cache)
1886                         SSL_CTX_set_session_cache_mode(ctx2,SSL_SESS_CACHE_OFF);
1887                 else if (ext_cache)
1888                         init_session_cache_ctx(ctx2);
1889                 else
1890                         SSL_CTX_sess_set_cache_size(ctx2,128);
1891
1892                 if ((!SSL_CTX_load_verify_locations(ctx2,CAfile,CApath)) ||
1893                         (!SSL_CTX_set_default_verify_paths(ctx2)))
1894                         {
1895                         ERR_print_errors(bio_err);
1896                         }
1897                 if (vpm)
1898                         SSL_CTX_set1_param(ctx2, vpm);
1899
1900                 ssl_ctx_add_crls(ctx2, crls, 0);
1901
1902                 if (!args_ssl_call(ctx2, bio_err, cctx, ssl_args, no_ecdhe, no_jpake))
1903                         goto end;
1904
1905                 }
1906
1907 # ifndef OPENSSL_NO_NEXTPROTONEG
1908         if (next_proto.data)
1909                 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto);
1910 # endif
1911         if (alpn_ctx.data)
1912                 SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx);
1913 #endif 
1914
1915 #ifndef OPENSSL_NO_DH
1916         if (!no_dhe)
1917                 {
1918                 DH *dh=NULL;
1919
1920                 if (dhfile)
1921                         dh = load_dh_param(dhfile);
1922                 else if (s_cert_file)
1923                         dh = load_dh_param(s_cert_file);
1924
1925                 if (dh != NULL)
1926                         {
1927                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
1928                         }
1929                 else
1930                         {
1931                         BIO_printf(bio_s_out,"Using default temp DH parameters\n");
1932                         dh=get_dh512();
1933                         }
1934                 (void)BIO_flush(bio_s_out);
1935
1936                 SSL_CTX_set_tmp_dh(ctx,dh);
1937 #ifndef OPENSSL_NO_TLSEXT
1938                 if (ctx2)
1939                         {
1940                         if (!dhfile)
1941                                 { 
1942                                 DH *dh2=load_dh_param(s_cert_file2);
1943                                 if (dh2 != NULL)
1944                                         {
1945                                         BIO_printf(bio_s_out,"Setting temp DH parameters\n");
1946                                         (void)BIO_flush(bio_s_out);
1947
1948                                         DH_free(dh);
1949                                         dh = dh2;
1950                                         }
1951                                 }
1952                         SSL_CTX_set_tmp_dh(ctx2,dh);
1953                         }
1954 #endif
1955                 DH_free(dh);
1956                 }
1957 #endif
1958
1959         if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain))
1960                 goto end;
1961 #ifndef OPENSSL_NO_TLSEXT
1962         if (s_serverinfo_file != NULL
1963             && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file))
1964                 {
1965                 ERR_print_errors(bio_err);
1966                 goto end;
1967                 }
1968         if (c_auth)
1969                 {
1970                 SSL_CTX_set_custom_srv_ext(ctx, TLSEXT_TYPE_client_authz, authz_tlsext_cb, authz_tlsext_generate_cb, bio_err);
1971                 SSL_CTX_set_custom_srv_ext(ctx, TLSEXT_TYPE_server_authz, authz_tlsext_cb, authz_tlsext_generate_cb, bio_err);
1972                 SSL_CTX_set_srv_supp_data(ctx, TLSEXT_SUPPLEMENTALDATATYPE_authz_data, auth_suppdata_generate_cb, suppdata_cb, bio_err);
1973                 }
1974 #endif
1975 #ifndef OPENSSL_NO_TLSEXT
1976         if (ctx2 && !set_cert_key_stuff(ctx2,s_cert2,s_key2, NULL, build_chain))
1977                 goto end; 
1978 #endif
1979         if (s_dcert != NULL)
1980                 {
1981                 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain))
1982                         goto end;
1983                 }
1984
1985 #ifndef OPENSSL_NO_RSA
1986 #if 1
1987         if (!no_tmp_rsa)
1988                 {
1989                 SSL_CTX_set_tmp_rsa_callback(ctx,tmp_rsa_cb);
1990 #ifndef OPENSSL_NO_TLSEXT
1991                 if (ctx2) 
1992                         SSL_CTX_set_tmp_rsa_callback(ctx2,tmp_rsa_cb);
1993 #endif          
1994                 }
1995 #else
1996         if (!no_tmp_rsa && SSL_CTX_need_tmp_RSA(ctx))
1997                 {
1998                 RSA *rsa;
1999
2000                 BIO_printf(bio_s_out,"Generating temp (512 bit) RSA key...");
2001                 BIO_flush(bio_s_out);
2002
2003                 rsa=RSA_generate_key(512,RSA_F4,NULL);
2004
2005                 if (!SSL_CTX_set_tmp_rsa(ctx,rsa))
2006                         {
2007                         ERR_print_errors(bio_err);
2008                         goto end;
2009                         }
2010 #ifndef OPENSSL_NO_TLSEXT
2011                         if (ctx2)
2012                                 {
2013                                 if (!SSL_CTX_set_tmp_rsa(ctx2,rsa))
2014                                         {
2015                                         ERR_print_errors(bio_err);
2016                                         goto end;
2017                                         }
2018                                 }
2019 #endif
2020                 RSA_free(rsa);
2021                 BIO_printf(bio_s_out,"\n");
2022                 }
2023 #endif
2024 #endif
2025
2026 #ifndef OPENSSL_NO_PSK
2027 #ifdef OPENSSL_NO_JPAKE
2028         if (psk_key != NULL)
2029 #else
2030         if (psk_key != NULL || jpake_secret)
2031 #endif
2032                 {
2033                 if (s_debug)
2034                         BIO_printf(bio_s_out, "PSK key given or JPAKE in use, setting server callback\n");
2035                 SSL_CTX_set_psk_server_callback(ctx, psk_server_cb);
2036                 }
2037
2038         if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint))
2039                 {
2040                 BIO_printf(bio_err,"error setting PSK identity hint to context\n");
2041                 ERR_print_errors(bio_err);
2042                 goto end;
2043                 }
2044 #endif
2045
2046         SSL_CTX_set_verify(ctx,s_server_verify,verify_callback);
2047         SSL_CTX_set_session_id_context(ctx,(void*)&s_server_session_id_context,
2048                 sizeof s_server_session_id_context);
2049
2050         /* Set DTLS cookie generation and verification callbacks */
2051         SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
2052         SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
2053
2054 #ifndef OPENSSL_NO_TLSEXT
2055         if (ctx2)
2056                 {
2057                 SSL_CTX_set_verify(ctx2,s_server_verify,verify_callback);
2058                 SSL_CTX_set_session_id_context(ctx2,(void*)&s_server_session_id_context,
2059                         sizeof s_server_session_id_context);
2060
2061                 tlsextcbp.biodebug = bio_s_out;
2062                 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
2063                 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
2064                 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
2065                 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
2066                 }
2067 #endif
2068
2069 #ifndef OPENSSL_NO_SRP
2070         if (srp_verifier_file != NULL)
2071                 {
2072                 srp_callback_parm.vb = SRP_VBASE_new(srpuserseed);
2073                 srp_callback_parm.user = NULL;
2074                 srp_callback_parm.login = NULL;
2075                 if ((ret = SRP_VBASE_init(srp_callback_parm.vb, srp_verifier_file)) != SRP_NO_ERROR)
2076                         {
2077                         BIO_printf(bio_err,
2078                                    "Cannot initialize SRP verifier file \"%s\":ret=%d\n",
2079                                    srp_verifier_file, ret);
2080                                 goto end;
2081                         }
2082                 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE,verify_callback);
2083                 SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm);                        
2084                 SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb);
2085                 }
2086         else
2087 #endif
2088         if (CAfile != NULL)
2089                 {
2090                 SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAfile));
2091 #ifndef OPENSSL_NO_TLSEXT
2092                 if (ctx2) 
2093                         SSL_CTX_set_client_CA_list(ctx2,SSL_load_client_CA_file(CAfile));
2094 #endif
2095                 }
2096
2097         BIO_printf(bio_s_out,"ACCEPT\n");
2098         (void)BIO_flush(bio_s_out);
2099         if (rev)
2100                 do_server(port,socket_type,&accept_socket,rev_body, context, naccept);
2101         else if (www)
2102                 do_server(port,socket_type,&accept_socket,www_body, context, naccept);
2103         else
2104                 do_server(port,socket_type,&accept_socket,sv_body, context, naccept);
2105         print_stats(bio_s_out,ctx);
2106         ret=0;
2107 end:
2108         if (ctx != NULL) SSL_CTX_free(ctx);
2109         if (s_cert)
2110                 X509_free(s_cert);
2111         if (crls)
2112                 sk_X509_CRL_pop_free(crls, X509_CRL_free);
2113         if (s_dcert)
2114                 X509_free(s_dcert);
2115         if (s_key)
2116                 EVP_PKEY_free(s_key);
2117         if (s_dkey)
2118                 EVP_PKEY_free(s_dkey);
2119         if (s_chain)
2120                 sk_X509_pop_free(s_chain, X509_free);
2121         if (s_dchain)
2122                 sk_X509_pop_free(s_dchain, X509_free);
2123         if (pass)
2124                 OPENSSL_free(pass);
2125         if (dpass)
2126                 OPENSSL_free(dpass);
2127         if (vpm)
2128                 X509_VERIFY_PARAM_free(vpm);
2129         free_sessions();
2130 #ifndef OPENSSL_NO_TLSEXT
2131         if (tlscstatp.host)
2132                 OPENSSL_free(tlscstatp.host);
2133         if (tlscstatp.port)
2134                 OPENSSL_free(tlscstatp.port);
2135         if (tlscstatp.path)
2136                 OPENSSL_free(tlscstatp.path);
2137         if (ctx2 != NULL) SSL_CTX_free(ctx2);
2138         if (s_cert2)
2139                 X509_free(s_cert2);
2140         if (s_key2)
2141                 EVP_PKEY_free(s_key2);
2142         if (serverinfo_in != NULL)
2143                 BIO_free(serverinfo_in);
2144 # ifndef OPENSSL_NO_NEXTPROTONEG
2145         if (next_proto.data)
2146                 OPENSSL_free(next_proto.data);
2147 # endif
2148         if (alpn_ctx.data)
2149                 OPENSSL_free(alpn_ctx.data);
2150 #endif
2151         ssl_excert_free(exc);
2152         if (ssl_args)
2153                 sk_OPENSSL_STRING_free(ssl_args);
2154         if (cctx)
2155                 SSL_CONF_CTX_free(cctx);
2156 #ifndef OPENSSL_NO_JPAKE
2157         if (jpake_secret && psk_key)
2158                 OPENSSL_free(psk_key);
2159 #endif
2160         if (bio_s_out != NULL)
2161                 {
2162                 BIO_free(bio_s_out);
2163                 bio_s_out=NULL;
2164                 }
2165         if (bio_s_msg != NULL)
2166                 {
2167                 BIO_free(bio_s_msg);
2168                 bio_s_msg = NULL;
2169                 }
2170         apps_shutdown();
2171         OPENSSL_EXIT(ret);
2172         }
2173
2174 static void print_stats(BIO *bio, SSL_CTX *ssl_ctx)
2175         {
2176         BIO_printf(bio,"%4ld items in the session cache\n",
2177                 SSL_CTX_sess_number(ssl_ctx));
2178         BIO_printf(bio,"%4ld client connects (SSL_connect())\n",
2179                 SSL_CTX_sess_connect(ssl_ctx));
2180         BIO_printf(bio,"%4ld client renegotiates (SSL_connect())\n",
2181                 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
2182         BIO_printf(bio,"%4ld client connects that finished\n",
2183                 SSL_CTX_sess_connect_good(ssl_ctx));
2184         BIO_printf(bio,"%4ld server accepts (SSL_accept())\n",
2185                 SSL_CTX_sess_accept(ssl_ctx));
2186         BIO_printf(bio,"%4ld server renegotiates (SSL_accept())\n",
2187                 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
2188         BIO_printf(bio,"%4ld server accepts that finished\n",
2189                 SSL_CTX_sess_accept_good(ssl_ctx));
2190         BIO_printf(bio,"%4ld session cache hits\n",SSL_CTX_sess_hits(ssl_ctx));
2191         BIO_printf(bio,"%4ld session cache misses\n",SSL_CTX_sess_misses(ssl_ctx));
2192         BIO_printf(bio,"%4ld session cache timeouts\n",SSL_CTX_sess_timeouts(ssl_ctx));
2193         BIO_printf(bio,"%4ld callback cache hits\n",SSL_CTX_sess_cb_hits(ssl_ctx));
2194         BIO_printf(bio,"%4ld cache full overflows (%ld allowed)\n",
2195                 SSL_CTX_sess_cache_full(ssl_ctx),
2196                 SSL_CTX_sess_get_cache_size(ssl_ctx));
2197         }
2198
2199 static int sv_body(char *hostname, int s, int stype, unsigned char *context)
2200         {
2201         char *buf=NULL;
2202         fd_set readfds;
2203         int ret=1,width;
2204         int k,i;
2205         unsigned long l;
2206         SSL *con=NULL;
2207         BIO *sbio;
2208 #ifndef OPENSSL_NO_KRB5
2209         KSSL_CTX *kctx;
2210 #endif
2211         struct timeval timeout;
2212 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
2213         struct timeval tv;
2214 #else
2215         struct timeval *timeoutp;
2216 #endif
2217
2218         if ((buf=OPENSSL_malloc(bufsize)) == NULL)
2219                 {
2220                 BIO_printf(bio_err,"out of memory\n");
2221                 goto err;
2222                 }
2223 #ifdef FIONBIO  
2224         if (s_nbio)
2225                 {
2226                 unsigned long sl=1;
2227
2228                 if (!s_quiet)
2229                         BIO_printf(bio_err,"turning on non blocking io\n");
2230                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
2231                         ERR_print_errors(bio_err);
2232                 }
2233 #endif
2234
2235         if (con == NULL) {
2236                 con=SSL_new(ctx);
2237 #ifndef OPENSSL_NO_TLSEXT
2238         if (s_tlsextdebug)
2239                 {
2240                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2241                 SSL_set_tlsext_debug_arg(con, bio_s_out);
2242                 }
2243         if (s_tlsextstatus)
2244                 {
2245                 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
2246                 tlscstatp.err = bio_err;
2247                 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
2248                 }
2249 #endif
2250 #ifndef OPENSSL_NO_KRB5
2251                 if ((kctx = kssl_ctx_new()) != NULL)
2252                         {
2253                         SSL_set0_kssl_ctx(con, kctx);
2254                         kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
2255                         kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
2256                         }
2257 #endif  /* OPENSSL_NO_KRB5 */
2258                 if(context)
2259                       SSL_set_session_id_context(con, context,
2260                                                  strlen((char *)context));
2261         }
2262         SSL_clear(con);
2263 #if 0
2264 #ifdef TLSEXT_TYPE_opaque_prf_input
2265         SSL_set_tlsext_opaque_prf_input(con, "Test server", 11);
2266 #endif
2267 #endif
2268
2269         if (stype == SOCK_DGRAM)
2270                 {
2271
2272                 sbio=BIO_new_dgram(s,BIO_NOCLOSE);
2273
2274                 if (enable_timeouts)
2275                         {
2276                         timeout.tv_sec = 0;
2277                         timeout.tv_usec = DGRAM_RCV_TIMEOUT;
2278                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
2279                         
2280                         timeout.tv_sec = 0;
2281                         timeout.tv_usec = DGRAM_SND_TIMEOUT;
2282                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
2283                         }
2284
2285                 if (socket_mtu > 28)
2286                         {
2287                         SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
2288                         SSL_set_mtu(con, socket_mtu - 28);
2289                         }
2290                 else
2291                         /* want to do MTU discovery */
2292                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
2293
2294         /* turn on cookie exchange */
2295         SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
2296                 }
2297         else
2298                 sbio=BIO_new_socket(s,BIO_NOCLOSE);
2299
2300         if (s_nbio_test)
2301                 {
2302                 BIO *test;
2303
2304                 test=BIO_new(BIO_f_nbio_test());
2305                 sbio=BIO_push(test,sbio);
2306                 }
2307 #ifndef OPENSSL_NO_JPAKE
2308         if(jpake_secret)
2309                 jpake_server_auth(bio_s_out, sbio, jpake_secret);
2310 #endif
2311
2312         SSL_set_bio(con,sbio,sbio);
2313         SSL_set_accept_state(con);
2314         /* SSL_set_fd(con,s); */
2315
2316         if (s_debug)
2317                 {
2318                 SSL_set_debug(con, 1);
2319                 BIO_set_callback(SSL_get_rbio(con),bio_dump_callback);
2320                 BIO_set_callback_arg(SSL_get_rbio(con),(char *)bio_s_out);
2321                 }
2322         if (s_msg)
2323                 {
2324 #ifndef OPENSSL_NO_SSL_TRACE
2325                 if (s_msg == 2)
2326                         SSL_set_msg_callback(con, SSL_trace);
2327                 else
2328 #endif
2329                         SSL_set_msg_callback(con, msg_cb);
2330                 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2331                 }
2332 #ifndef OPENSSL_NO_TLSEXT
2333         if (s_tlsextdebug)
2334                 {
2335                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
2336                 SSL_set_tlsext_debug_arg(con, bio_s_out);
2337                 }
2338 #endif
2339
2340         width=s+1;
2341         for (;;)
2342                 {
2343                 int read_from_terminal;
2344                 int read_from_sslcon;
2345
2346                 read_from_terminal = 0;
2347                 read_from_sslcon = SSL_pending(con);
2348
2349                 if (!read_from_sslcon)
2350                         {
2351                         FD_ZERO(&readfds);
2352 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined(OPENSSL_SYS_BEOS_R5)
2353                         openssl_fdset(fileno(stdin),&readfds);
2354 #endif
2355                         openssl_fdset(s,&readfds);
2356                         /* Note: under VMS with SOCKETSHR the second parameter is
2357                          * currently of type (int *) whereas under other systems
2358                          * it is (void *) if you don't have a cast it will choke
2359                          * the compiler: if you do have a cast then you can either
2360                          * go for (int *) or (void *).
2361                          */
2362 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
2363                         /* Under DOS (non-djgpp) and Windows we can't select on stdin: only
2364                          * on sockets. As a workaround we timeout the select every
2365                          * second and check for any keypress. In a proper Windows
2366                          * application we wouldn't do this because it is inefficient.
2367                          */
2368                         tv.tv_sec = 1;
2369                         tv.tv_usec = 0;
2370                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
2371                         if((i < 0) || (!i && !_kbhit() ) )continue;
2372                         if(_kbhit())
2373                                 read_from_terminal = 1;
2374 #elif defined(OPENSSL_SYS_BEOS_R5)
2375                         /* Under BeOS-R5 the situation is similar to DOS */
2376                         tv.tv_sec = 1;
2377                         tv.tv_usec = 0;
2378                         (void)fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
2379                         i=select(width,(void *)&readfds,NULL,NULL,&tv);
2380                         if ((i < 0) || (!i && read(fileno(stdin), buf, 0) < 0))
2381                                 continue;
2382                         if (read(fileno(stdin), buf, 0) >= 0)
2383                                 read_from_terminal = 1;
2384                         (void)fcntl(fileno(stdin), F_SETFL, 0);
2385 #else
2386                         if ((SSL_version(con) == DTLS1_VERSION) &&
2387                                 DTLSv1_get_timeout(con, &timeout))
2388                                 timeoutp = &timeout;
2389                         else
2390                                 timeoutp = NULL;
2391
2392                         i=select(width,(void *)&readfds,NULL,NULL,timeoutp);
2393
2394                         if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0)
2395                                 {
2396                                 BIO_printf(bio_err,"TIMEOUT occured\n");
2397                                 }
2398
2399                         if (i <= 0) continue;
2400                         if (FD_ISSET(fileno(stdin),&readfds))
2401                                 read_from_terminal = 1;
2402 #endif
2403                         if (FD_ISSET(s,&readfds))
2404                                 read_from_sslcon = 1;
2405                         }
2406                 if (read_from_terminal)
2407                         {
2408                         if (s_crlf)
2409                                 {
2410                                 int j, lf_num;
2411
2412                                 i=raw_read_stdin(buf, bufsize/2);
2413                                 lf_num = 0;
2414                                 /* both loops are skipped when i <= 0 */
2415                                 for (j = 0; j < i; j++)
2416                                         if (buf[j] == '\n')
2417                                                 lf_num++;
2418                                 for (j = i-1; j >= 0; j--)
2419                                         {
2420                                         buf[j+lf_num] = buf[j];
2421                                         if (buf[j] == '\n')
2422                                                 {
2423                                                 lf_num--;
2424                                                 i++;
2425                                                 buf[j+lf_num] = '\r';
2426                                                 }
2427                                         }
2428                                 assert(lf_num == 0);
2429                                 }
2430                         else
2431                                 i=raw_read_stdin(buf,bufsize);
2432                         if (!s_quiet && !s_brief)
2433                                 {
2434                                 if ((i <= 0) || (buf[0] == 'Q'))
2435                                         {
2436                                         BIO_printf(bio_s_out,"DONE\n");
2437                                         SHUTDOWN(s);
2438                                         close_accept_socket();
2439                                         ret= -11;
2440                                         goto err;
2441                                         }
2442                                 if ((i <= 0) || (buf[0] == 'q'))
2443                                         {
2444                                         BIO_printf(bio_s_out,"DONE\n");
2445                                         if (SSL_version(con) != DTLS1_VERSION)
2446                         SHUTDOWN(s);
2447         /*                              close_accept_socket();
2448                                         ret= -11;*/
2449                                         goto err;
2450                                         }
2451
2452 #ifndef OPENSSL_NO_HEARTBEATS
2453                                 if ((buf[0] == 'B') &&
2454                                         ((buf[1] == '\n') || (buf[1] == '\r')))
2455                                         {
2456                                         BIO_printf(bio_err,"HEARTBEATING\n");
2457                                         SSL_heartbeat(con);
2458                                         i=0;
2459                                         continue;
2460                                         }
2461 #endif
2462                                 if ((buf[0] == 'r') && 
2463                                         ((buf[1] == '\n') || (buf[1] == '\r')))
2464                                         {
2465                                         SSL_renegotiate(con);
2466                                         i=SSL_do_handshake(con);
2467                                         printf("SSL_do_handshake -> %d\n",i);
2468                                         i=0; /*13; */
2469                                         continue;
2470                                         /* strcpy(buf,"server side RE-NEGOTIATE\n"); */
2471                                         }
2472                                 if ((buf[0] == 'R') &&
2473                                         ((buf[1] == '\n') || (buf[1] == '\r')))
2474                                         {
2475                                         SSL_set_verify(con,
2476                                                 SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,NULL);
2477                                         SSL_renegotiate(con);
2478                                         i=SSL_do_handshake(con);
2479                                         printf("SSL_do_handshake -> %d\n",i);
2480                                         i=0; /* 13; */
2481                                         continue;
2482                                         /* strcpy(buf,"server side RE-NEGOTIATE asking for client cert\n"); */
2483                                         }
2484                                 if (buf[0] == 'P')
2485                                         {
2486                                         static const char *str="Lets print some clear text\n";
2487                                         BIO_write(SSL_get_wbio(con),str,strlen(str));
2488                                         }
2489                                 if (buf[0] == 'S')
2490                                         {
2491                                         print_stats(bio_s_out,SSL_get_SSL_CTX(con));
2492                                         }
2493                                 }
2494 #ifdef CHARSET_EBCDIC
2495                         ebcdic2ascii(buf,buf,i);
2496 #endif
2497                         l=k=0;
2498                         for (;;)
2499                                 {
2500                                 /* should do a select for the write */
2501 #ifdef RENEG
2502 { static count=0; if (++count == 100) { count=0; SSL_renegotiate(con); } }
2503 #endif
2504                                 k=SSL_write(con,&(buf[l]),(unsigned int)i);
2505 #ifndef OPENSSL_NO_SRP
2506                                 while (SSL_get_error(con,k) == SSL_ERROR_WANT_X509_LOOKUP)
2507                                         {
2508                                         BIO_printf(bio_s_out,"LOOKUP renego during write\n");
2509                                         srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); 
2510                                         if (srp_callback_parm.user) 
2511                                                 BIO_printf(bio_s_out,"LOOKUP done %s\n",srp_callback_parm.user->info);
2512                                         else 
2513                                                 BIO_printf(bio_s_out,"LOOKUP not successful\n");
2514                                                 k=SSL_write(con,&(buf[l]),(unsigned int)i);
2515                                         }
2516 #endif
2517                                 switch (SSL_get_error(con,k))
2518                                         {
2519                                 case SSL_ERROR_NONE:
2520                                         break;
2521                                 case SSL_ERROR_WANT_WRITE:
2522                                 case SSL_ERROR_WANT_READ:
2523                                 case SSL_ERROR_WANT_X509_LOOKUP:
2524                                         BIO_printf(bio_s_out,"Write BLOCK\n");
2525                                         break;
2526                                 case SSL_ERROR_SYSCALL:
2527                                 case SSL_ERROR_SSL:
2528                                         BIO_printf(bio_s_out,"ERROR\n");
2529                                         ERR_print_errors(bio_err);
2530                                         ret=1;
2531                                         goto err;
2532                                         /* break; */
2533                                 case SSL_ERROR_ZERO_RETURN:
2534                                         BIO_printf(bio_s_out,"DONE\n");
2535                                         ret=1;
2536                                         goto err;
2537                                         }
2538                                 l+=k;
2539                                 i-=k;
2540                                 if (i <= 0) break;
2541                                 }
2542                         }
2543                 if (read_from_sslcon)
2544                         {
2545                         if (!SSL_is_init_finished(con))
2546                                 {
2547                                 i=init_ssl_connection(con);
2548                                 
2549                                 if (i < 0)
2550                                         {
2551                                         ret=0;
2552                                         goto err;
2553                                         }
2554                                 else if (i == 0)
2555                                         {
2556                                         ret=1;
2557                                         goto err;
2558                                         }
2559                                 }
2560                         else
2561                                 {
2562 again:  
2563                                 i=SSL_read(con,(char *)buf,bufsize);
2564 #ifndef OPENSSL_NO_SRP
2565                                 while (SSL_get_error(con,i) == SSL_ERROR_WANT_X509_LOOKUP)
2566                                         {
2567                                         BIO_printf(bio_s_out,"LOOKUP renego during read\n");
2568                                         srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); 
2569                                         if (srp_callback_parm.user) 
2570                                                 BIO_printf(bio_s_out,"LOOKUP done %s\n",srp_callback_parm.user->info);
2571                                         else 
2572                                                 BIO_printf(bio_s_out,"LOOKUP not successful\n");
2573                                         i=SSL_read(con,(char *)buf,bufsize);
2574                                         }
2575 #endif
2576                                 switch (SSL_get_error(con,i))
2577                                         {
2578                                 case SSL_ERROR_NONE:
2579 #ifdef CHARSET_EBCDIC
2580                                         ascii2ebcdic(buf,buf,i);
2581 #endif
2582                                         raw_write_stdout(buf,
2583                                                 (unsigned int)i);
2584                                         if (SSL_pending(con)) goto again;
2585                                         break;
2586                                 case SSL_ERROR_WANT_WRITE:
2587                                 case SSL_ERROR_WANT_READ:
2588                                         BIO_printf(bio_s_out,"Read BLOCK\n");
2589                                         break;
2590                                 case SSL_ERROR_SYSCALL:
2591                                 case SSL_ERROR_SSL:
2592                                         BIO_printf(bio_s_out,"ERROR\n");
2593                                         ERR_print_errors(bio_err);
2594                                         ret=1;
2595                                         goto err;
2596                                 case SSL_ERROR_ZERO_RETURN:
2597                                         BIO_printf(bio_s_out,"DONE\n");
2598                                         ret=1;
2599                                         goto err;
2600                                         }
2601                                 }
2602                         }
2603                 }
2604 err:
2605         if (con != NULL)
2606                 {
2607                 BIO_printf(bio_s_out,"shutting down SSL\n");
2608 #if 1
2609                 SSL_set_shutdown(con,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
2610 #else
2611                 SSL_shutdown(con);
2612 #endif
2613                 SSL_free(con);
2614                 }
2615         BIO_printf(bio_s_out,"CONNECTION CLOSED\n");
2616         if (buf != NULL)
2617                 {
2618                 OPENSSL_cleanse(buf,bufsize);
2619                 OPENSSL_free(buf);
2620                 }
2621         if (ret >= 0)
2622                 BIO_printf(bio_s_out,"ACCEPT\n");
2623         return(ret);
2624         }
2625
2626 static void close_accept_socket(void)
2627         {
2628         BIO_printf(bio_err,"shutdown accept socket\n");
2629         if (accept_socket >= 0)
2630                 {
2631                 SHUTDOWN2(accept_socket);
2632                 }
2633         }
2634
2635 static int init_ssl_connection(SSL *con)
2636         {
2637         int i;
2638         const char *str;
2639         X509 *peer;
2640         long verify_error;
2641         MS_STATIC char buf[BUFSIZ];
2642 #ifndef OPENSSL_NO_KRB5
2643         char *client_princ;
2644 #endif
2645 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2646         const unsigned char *next_proto_neg;
2647         unsigned next_proto_neg_len;
2648 #endif
2649         unsigned char *exportedkeymat;
2650
2651
2652         i=SSL_accept(con);
2653 #ifdef CERT_CB_TEST_RETRY
2654         {
2655         while (i <= 0 && SSL_get_error(con,i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) 
2656                 {
2657                 fprintf(stderr, "LOOKUP from certificate callback during accept\n");
2658                 i=SSL_accept(con);
2659                 }
2660         }
2661 #endif
2662 #ifndef OPENSSL_NO_SRP
2663         while (i <= 0 &&  SSL_get_error(con,i) == SSL_ERROR_WANT_X509_LOOKUP) 
2664                 {
2665                         BIO_printf(bio_s_out,"LOOKUP during accept %s\n",srp_callback_parm.login);
2666                         srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); 
2667                         if (srp_callback_parm.user) 
2668                                 BIO_printf(bio_s_out,"LOOKUP done %s\n",srp_callback_parm.user->info);
2669                         else 
2670                                 BIO_printf(bio_s_out,"LOOKUP not successful\n");
2671                         i=SSL_accept(con);
2672                 }
2673 #endif
2674         /*handshake is complete - free the generated supp data allocated in the callback */
2675         if (generated_supp_data)
2676                 {
2677                 OPENSSL_free(generated_supp_data);
2678                 generated_supp_data = NULL;
2679                 }
2680
2681         if (i <= 0)
2682                 {
2683                 if (BIO_sock_should_retry(i))
2684                         {
2685                         BIO_printf(bio_s_out,"DELAY\n");
2686                         return(1);
2687                         }
2688
2689                 BIO_printf(bio_err,"ERROR\n");
2690                 verify_error=SSL_get_verify_result(con);
2691                 if (verify_error != X509_V_OK)
2692                         {
2693                         BIO_printf(bio_err,"verify error:%s\n",
2694                                 X509_verify_cert_error_string(verify_error));
2695                         }
2696                 /* Always print any error messages */
2697                 ERR_print_errors(bio_err);
2698                 return(0);
2699                 }
2700
2701         if (s_brief)
2702                 print_ssl_summary(bio_err, con);
2703
2704         PEM_write_bio_SSL_SESSION(bio_s_out,SSL_get_session(con));
2705
2706         peer=SSL_get_peer_certificate(con);
2707         if (peer != NULL)
2708                 {
2709                 BIO_printf(bio_s_out,"Client certificate\n");
2710                 PEM_write_bio_X509(bio_s_out,peer);
2711                 X509_NAME_oneline(X509_get_subject_name(peer),buf,sizeof buf);
2712                 BIO_printf(bio_s_out,"subject=%s\n",buf);
2713                 X509_NAME_oneline(X509_get_issuer_name(peer),buf,sizeof buf);
2714                 BIO_printf(bio_s_out,"issuer=%s\n",buf);
2715                 X509_free(peer);
2716                 }
2717
2718         if (SSL_get_shared_ciphers(con,buf,sizeof buf) != NULL)
2719                 BIO_printf(bio_s_out,"Shared ciphers:%s\n",buf);
2720         str=SSL_CIPHER_get_name(SSL_get_current_cipher(con));
2721         ssl_print_sigalgs(bio_s_out, con);
2722 #ifndef OPENSSL_NO_EC
2723         ssl_print_point_formats(bio_s_out, con);
2724         ssl_print_curves(bio_s_out, con, 0);
2725 #endif
2726         BIO_printf(bio_s_out,"CIPHER is %s\n",(str != NULL)?str:"(NONE)");
2727
2728 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2729         SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
2730         if (next_proto_neg)
2731                 {
2732                 BIO_printf(bio_s_out,"NEXTPROTO is ");
2733                 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
2734                 BIO_printf(bio_s_out, "\n");
2735                 }
2736 #endif
2737         {
2738         SRTP_PROTECTION_PROFILE *srtp_profile
2739           = SSL_get_selected_srtp_profile(con);
2740
2741         if(srtp_profile)
2742                 BIO_printf(bio_s_out,"SRTP Extension negotiated, profile=%s\n",
2743                            srtp_profile->name);
2744         }
2745         if (SSL_cache_hit(con)) BIO_printf(bio_s_out,"Reused session-id\n");
2746         if (SSL_ctrl(con,SSL_CTRL_GET_FLAGS,0,NULL) &
2747                 TLS1_FLAGS_TLS_PADDING_BUG)
2748                 BIO_printf(bio_s_out,
2749                            "Peer has incorrect TLSv1 block padding\n");
2750 #ifndef OPENSSL_NO_KRB5
2751         client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
2752         if (client_princ != NULL)
2753                 {
2754                 BIO_printf(bio_s_out,"Kerberos peer principal is %s\n",
2755                                                                 client_princ);
2756                 }
2757 #endif /* OPENSSL_NO_KRB5 */
2758         BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
2759                       SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
2760         if (keymatexportlabel != NULL)
2761                 {
2762                 BIO_printf(bio_s_out, "Keying material exporter:\n");
2763                 BIO_printf(bio_s_out, "    Label: '%s'\n", keymatexportlabel);
2764                 BIO_printf(bio_s_out, "    Length: %i bytes\n",
2765                            keymatexportlen);
2766                 exportedkeymat = OPENSSL_malloc(keymatexportlen);
2767                 if (exportedkeymat != NULL)
2768                         {
2769                         if (!SSL_export_keying_material(con, exportedkeymat,
2770                                                         keymatexportlen,
2771                                                         keymatexportlabel,
2772                                                         strlen(keymatexportlabel),
2773                                                         NULL, 0, 0))
2774                                 {
2775                                 BIO_printf(bio_s_out, "    Error\n");
2776                                 }
2777                         else
2778                                 {
2779                                 BIO_printf(bio_s_out, "    Keying material: ");
2780                                 for (i=0; i<keymatexportlen; i++)
2781                                         BIO_printf(bio_s_out, "%02X",
2782                                                    exportedkeymat[i]);
2783                                 BIO_printf(bio_s_out, "\n");
2784                                 }
2785                         OPENSSL_free(exportedkeymat);
2786                         }
2787                 }
2788
2789         return(1);
2790         }
2791
2792 #ifndef OPENSSL_NO_DH
2793 static DH *load_dh_param(const char *dhfile)
2794         {
2795         DH *ret=NULL;
2796         BIO *bio;
2797
2798         if ((bio=BIO_new_file(dhfile,"r")) == NULL)
2799                 goto err;
2800         ret=PEM_read_bio_DHparams(bio,NULL,NULL,NULL);
2801 err:
2802         if (bio != NULL) BIO_free(bio);
2803         return(ret);
2804         }
2805 #endif
2806 #ifndef OPENSSL_NO_KRB5
2807         char *client_princ;
2808 #endif
2809
2810 #if 0
2811 static int load_CA(SSL_CTX *ctx, char *file)
2812         {
2813         FILE *in;
2814         X509 *x=NULL;
2815
2816         if ((in=fopen(file,"r")) == NULL)
2817                 return(0);
2818
2819         for (;;)
2820                 {
2821                 if (PEM_read_X509(in,&x,NULL) == NULL)
2822                         break;
2823                 SSL_CTX_add_client_CA(ctx,x);
2824                 }
2825         if (x != NULL) X509_free(x);
2826         fclose(in);
2827         return(1);
2828         }
2829 #endif
2830
2831 static int www_body(char *hostname, int s, int stype, unsigned char *context)
2832         {
2833         char *buf=NULL;
2834         int ret=1;
2835         int i,j,k,dot;
2836         SSL *con;
2837         const SSL_CIPHER *c;
2838         BIO *io,*ssl_bio,*sbio;
2839 #ifndef OPENSSL_NO_KRB5
2840         KSSL_CTX *kctx;
2841 #endif
2842
2843         buf=OPENSSL_malloc(bufsize);
2844         if (buf == NULL) return(0);
2845         io=BIO_new(BIO_f_buffer());
2846         ssl_bio=BIO_new(BIO_f_ssl());
2847         if ((io == NULL) || (ssl_bio == NULL)) goto err;
2848
2849 #ifdef FIONBIO  
2850         if (s_nbio)
2851                 {
2852                 unsigned long sl=1;
2853
2854                 if (!s_quiet)
2855                         BIO_printf(bio_err,"turning on non blocking io\n");
2856                 if (BIO_socket_ioctl(s,FIONBIO,&sl) < 0)
2857                         ERR_print_errors(bio_err);
2858                 }
2859 #endif
2860
2861         /* lets make the output buffer a reasonable size */
2862         if (!BIO_set_write_buffer_size(io,bufsize)) goto err;
2863
2864         if ((con=SSL_new(ctx)) == NULL) goto err;
2865 #ifndef OPENSSL_NO_TLSEXT
2866                 if (s_tlsextdebug)
2867                         {
2868                         SSL_set_tlsext_debug_callback(con, tlsext_cb);
2869                         SSL_set_tlsext_debug_arg(con, bio_s_out);
2870                         }
2871 #endif
2872 #ifndef OPENSSL_NO_KRB5
2873         if ((kctx = kssl_ctx_new()) != NULL)
2874                 {
2875                 kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
2876                 kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
2877                 }
2878 #endif  /* OPENSSL_NO_KRB5 */
2879         if(context) SSL_set_session_id_context(con, context,
2880                                                strlen((char *)context));
2881
2882         sbio=BIO_new_socket(s,BIO_NOCLOSE);
2883         if (s_nbio_test)
2884                 {
2885                 BIO *test;
2886
2887                 test=BIO_new(BIO_f_nbio_test());
2888                 sbio=BIO_push(test,sbio);
2889                 }
2890         SSL_set_bio(con,sbio,sbio);
2891         SSL_set_accept_state(con);
2892
2893         /* SSL_set_fd(con,s); */
2894         BIO_set_ssl(ssl_bio,con,BIO_CLOSE);
2895         BIO_push(io,ssl_bio);
2896 #ifdef CHARSET_EBCDIC
2897         io = BIO_push(BIO_new(BIO_f_ebcdic_filter()),io);
2898 #endif
2899
2900         if (s_debug)
2901                 {
2902                 SSL_set_debug(con, 1);
2903                 BIO_set_callback(SSL_get_rbio(con),bio_dump_callback);
2904                 BIO_set_callback_arg(SSL_get_rbio(con),(char *)bio_s_out);
2905                 }
2906         if (s_msg)
2907                 {
2908 #ifndef OPENSSL_NO_SSL_TRACE
2909                 if (s_msg == 2)
2910                         SSL_set_msg_callback(con, SSL_trace);
2911                 else
2912 #endif
2913                         SSL_set_msg_callback(con, msg_cb);
2914                 SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
2915                 }
2916
2917         for (;;)
2918                 {
2919                 if (hack)
2920                         {
2921                         i=SSL_accept(con);
2922 #ifndef OPENSSL_NO_SRP
2923                         while (i <= 0 &&  SSL_get_error(con,i) == SSL_ERROR_WANT_X509_LOOKUP) 
2924                 {
2925                         BIO_printf(bio_s_out,"LOOKUP during accept %s\n",srp_callback_parm.login);
2926                         srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); 
2927                         if (srp_callback_parm.user) 
2928                                 BIO_printf(bio_s_out,"LOOKUP done %s\n",srp_callback_parm.user->info);
2929                         else 
2930                                 BIO_printf(bio_s_out,"LOOKUP not successful\n");
2931                         i=SSL_accept(con);
2932                 }
2933 #endif
2934                         switch (SSL_get_error(con,i))
2935                                 {
2936                         case SSL_ERROR_NONE:
2937                                 break;
2938                         case SSL_ERROR_WANT_WRITE:
2939                         case SSL_ERROR_WANT_READ:
2940                         case SSL_ERROR_WANT_X509_LOOKUP:
2941                                 continue;
2942                         case SSL_ERROR_SYSCALL:
2943                         case SSL_ERROR_SSL:
2944                         case SSL_ERROR_ZERO_RETURN:
2945                                 ret=1;
2946                                 goto err;
2947                                 /* break; */
2948                                 }
2949
2950                         SSL_renegotiate(con);
2951                         SSL_write(con,NULL,0);
2952                         }
2953
2954                 i=BIO_gets(io,buf,bufsize-1);
2955                 if (i < 0) /* error */
2956                         {
2957                         if (!BIO_should_retry(io))
2958                                 {
2959                                 if (!s_quiet)
2960                                         ERR_print_errors(bio_err);
2961                                 goto err;
2962                                 }
2963                         else
2964                                 {
2965                                 BIO_printf(bio_s_out,"read R BLOCK\n");
2966 #if defined(OPENSSL_SYS_NETWARE)
2967             delay(1000);
2968 #elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
2969                                 sleep(1);
2970 #endif
2971                                 continue;
2972                                 }
2973                         }
2974                 else if (i == 0) /* end of input */
2975                         {
2976                         ret=1;
2977                         goto end;
2978                         }
2979
2980                 /* else we have data */
2981                 if (    ((www == 1) && (strncmp("GET ",buf,4) == 0)) ||
2982                         ((www == 2) && (strncmp("GET /stats ",buf,10) == 0)))
2983                         {
2984                         char *p;
2985                         X509 *peer;
2986                         STACK_OF(SSL_CIPHER) *sk;
2987                         static const char *space="                          ";
2988
2989                         BIO_puts(io,"HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2990                         BIO_puts(io,"<HTML><BODY BGCOLOR=\"#ffffff\">\n");
2991                         BIO_puts(io,"<pre>\n");
2992 /*                      BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
2993                         BIO_puts(io,"\n");
2994                         for (i=0; i<local_argc; i++)
2995                                 {
2996                                 BIO_puts(io,local_argv[i]);
2997                                 BIO_write(io," ",1);
2998                                 }
2999                         BIO_puts(io,"\n");
3000
3001                         BIO_printf(io,
3002                                 "Secure Renegotiation IS%s supported\n",
3003                                 SSL_get_secure_renegotiation_support(con) ?
3004                                                         "" : " NOT");
3005
3006                         /* The following is evil and should not really
3007                          * be done */
3008                         BIO_printf(io,"Ciphers supported in s_server binary\n");
3009                         sk=SSL_get_ciphers(con);
3010                         j=sk_SSL_CIPHER_num(sk);
3011                         for (i=0; i<j; i++)
3012                                 {
3013                                 c=sk_SSL_CIPHER_value(sk,i);
3014                                 BIO_printf(io,"%-11s:%-25s",
3015                                         SSL_CIPHER_get_version(c),
3016                                         SSL_CIPHER_get_name(c));
3017                                 if ((((i+1)%2) == 0) && (i+1 != j))
3018                                         BIO_puts(io,"\n");
3019                                 }
3020                         BIO_puts(io,"\n");
3021                         p=SSL_get_shared_ciphers(con,buf,bufsize);
3022                         if (p != NULL)
3023                                 {
3024                                 BIO_printf(io,"---\nCiphers common between both SSL end points:\n");
3025                                 j=i=0;
3026                                 while (*p)
3027                                         {
3028                                         if (*p == ':')
3029                                                 {
3030                                                 BIO_write(io,space,26-j);
3031                                                 i++;
3032                                                 j=0;
3033                                                 BIO_write(io,((i%3)?" ":"\n"),1);
3034                                                 }
3035                                         else
3036                                                 {
3037                                                 BIO_write(io,p,1);
3038                                                 j++;
3039                                                 }
3040                                         p++;
3041                                         }
3042                                 BIO_puts(io,"\n");
3043                                 }
3044                         ssl_print_sigalgs(io, con);
3045 #ifndef OPENSSL_NO_EC
3046                         ssl_print_curves(io, con, 0);
3047 #endif
3048                         BIO_printf(io,(SSL_cache_hit(con)
3049                                 ?"---\nReused, "
3050                                 :"---\nNew, "));
3051                         c=SSL_get_current_cipher(con);
3052                         BIO_printf(io,"%s, Cipher is %s\n",
3053                                 SSL_CIPHER_get_version(c),
3054                                 SSL_CIPHER_get_name(c));
3055                         SSL_SESSION_print(io,SSL_get_session(con));
3056                         BIO_printf(io,"---\n");
3057                         print_stats(io,SSL_get_SSL_CTX(con));
3058                         BIO_printf(io,"---\n");
3059                         peer=SSL_get_peer_certificate(con);
3060                         if (peer != NULL)
3061                                 {
3062                                 BIO_printf(io,"Client certificate\n");
3063                                 X509_print(io,peer);
3064                                 PEM_write_bio_X509(io,peer);
3065                                 }
3066                         else
3067                                 BIO_puts(io,"no client certificate available\n");
3068                         BIO_puts(io,"</BODY></HTML>\r\n\r\n");
3069                         break;
3070                         }
3071                 else if ((www == 2 || www == 3)
3072                          && (strncmp("GET /",buf,5) == 0))
3073                         {
3074                         BIO *file;
3075                         char *p,*e;
3076                         static const char *text="HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
3077
3078                         /* skip the '/' */
3079                         p= &(buf[5]);
3080
3081                         dot = 1;
3082                         for (e=p; *e != '\0'; e++)
3083                                 {
3084                                 if (e[0] == ' ')
3085                                         break;
3086
3087                                 switch (dot)
3088                                         {
3089                                 case 1:
3090                                         dot = (e[0] == '.') ? 2 : 0;
3091                                         break;
3092                                 case 2:
3093                                         dot = (e[0] == '.') ? 3 : 0;
3094                                         break;
3095                                 case 3:
3096                                         dot = (e[0] == '/') ? -1 : 0;
3097                                         break;
3098                                         }
3099                                 if (dot == 0)
3100                                         dot = (e[0] == '/') ? 1 : 0;
3101                                 }
3102                         dot = (dot == 3) || (dot == -1); /* filename contains ".." component */
3103
3104                         if (*e == '\0')
3105                                 {
3106                                 BIO_puts(io,text);
3107                                 BIO_printf(io,"'%s' is an invalid file name\r\n",p);
3108                                 break;
3109                                 }
3110                         *e='\0';
3111
3112                         if (dot)
3113                                 {
3114                                 BIO_puts(io,text);
3115                                 BIO_printf(io,"'%s' contains '..' reference\r\n",p);
3116                                 break;
3117                                 }
3118
3119                         if (*p == '/')
3120                                 {
3121                                 BIO_puts(io,text);
3122                                 BIO_printf(io,"'%s' is an invalid path\r\n",p);
3123                                 break;
3124                                 }
3125
3126 #if 0
3127                         /* append if a directory lookup */
3128                         if (e[-1] == '/')
3129                                 strcat(p,"index.html");
3130 #endif
3131
3132                         /* if a directory, do the index thang */
3133                         if (app_isdir(p)>0)
3134                                 {
3135 #if 0 /* must check buffer size */
3136                                 strcat(p,"/index.html");
3137 #else
3138                                 BIO_puts(io,text);
3139                                 BIO_printf(io,"'%s' is a directory\r\n",p);
3140                                 break;
3141 #endif
3142                                 }
3143
3144                         if ((file=BIO_new_file(p,"r")) == NULL)
3145                                 {
3146                                 BIO_puts(io,text);
3147                                 BIO_printf(io,"Error opening '%s'\r\n",p);
3148                                 ERR_print_errors(io);
3149                                 break;
3150                                 }
3151
3152                         if (!s_quiet)
3153                                 BIO_printf(bio_err,"FILE:%s\n",p);
3154