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