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