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