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