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