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