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