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