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