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