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