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