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