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