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