Avoid test_errstr in a cross compiled configuration
[openssl.git] / test / ssltestlib.c
1 /*
2  * Copyright 2016-2018 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 #include <string.h>
11
12 #include "internal/nelem.h"
13 #include "ssltestlib.h"
14 #include "testutil.h"
15 #include "e_os.h"
16
17 #ifdef OPENSSL_SYS_UNIX
18 # include <unistd.h>
19
20 static ossl_inline void ossl_sleep(unsigned int millis) {
21     usleep(millis * 1000);
22 }
23 #elif defined(_WIN32)
24 # include <windows.h>
25
26 static ossl_inline void ossl_sleep(unsigned int millis) {
27     Sleep(millis);
28 }
29 #else
30 /* Fallback to a busy wait */
31 static ossl_inline void ossl_sleep(unsigned int millis) {
32     struct timeval start, now;
33     unsigned int elapsedms;
34
35     gettimeofday(&start, NULL);
36     do {
37         gettimeofday(&now, NULL);
38         elapsedms = (((now.tv_sec - start.tv_sec) * 1000000)
39                      + now.tv_usec - start.tv_usec) / 1000;
40     } while (elapsedms < millis);
41 }
42 #endif
43
44 static int tls_dump_new(BIO *bi);
45 static int tls_dump_free(BIO *a);
46 static int tls_dump_read(BIO *b, char *out, int outl);
47 static int tls_dump_write(BIO *b, const char *in, int inl);
48 static long tls_dump_ctrl(BIO *b, int cmd, long num, void *ptr);
49 static int tls_dump_gets(BIO *bp, char *buf, int size);
50 static int tls_dump_puts(BIO *bp, const char *str);
51
52 /* Choose a sufficiently large type likely to be unused for this custom BIO */
53 #define BIO_TYPE_TLS_DUMP_FILTER  (0x80 | BIO_TYPE_FILTER)
54 #define BIO_TYPE_MEMPACKET_TEST    0x81
55
56 static BIO_METHOD *method_tls_dump = NULL;
57 static BIO_METHOD *meth_mem = NULL;
58
59 /* Note: Not thread safe! */
60 const BIO_METHOD *bio_f_tls_dump_filter(void)
61 {
62     if (method_tls_dump == NULL) {
63         method_tls_dump = BIO_meth_new(BIO_TYPE_TLS_DUMP_FILTER,
64                                         "TLS dump filter");
65         if (   method_tls_dump == NULL
66             || !BIO_meth_set_write(method_tls_dump, tls_dump_write)
67             || !BIO_meth_set_read(method_tls_dump, tls_dump_read)
68             || !BIO_meth_set_puts(method_tls_dump, tls_dump_puts)
69             || !BIO_meth_set_gets(method_tls_dump, tls_dump_gets)
70             || !BIO_meth_set_ctrl(method_tls_dump, tls_dump_ctrl)
71             || !BIO_meth_set_create(method_tls_dump, tls_dump_new)
72             || !BIO_meth_set_destroy(method_tls_dump, tls_dump_free))
73             return NULL;
74     }
75     return method_tls_dump;
76 }
77
78 void bio_f_tls_dump_filter_free(void)
79 {
80     BIO_meth_free(method_tls_dump);
81 }
82
83 static int tls_dump_new(BIO *bio)
84 {
85     BIO_set_init(bio, 1);
86     return 1;
87 }
88
89 static int tls_dump_free(BIO *bio)
90 {
91     BIO_set_init(bio, 0);
92
93     return 1;
94 }
95
96 static void copy_flags(BIO *bio)
97 {
98     int flags;
99     BIO *next = BIO_next(bio);
100
101     flags = BIO_test_flags(next, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
102     BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
103     BIO_set_flags(bio, flags);
104 }
105
106 #define RECORD_CONTENT_TYPE     0
107 #define RECORD_VERSION_HI       1
108 #define RECORD_VERSION_LO       2
109 #define RECORD_EPOCH_HI         3
110 #define RECORD_EPOCH_LO         4
111 #define RECORD_SEQUENCE_START   5
112 #define RECORD_SEQUENCE_END     10
113 #define RECORD_LEN_HI           11
114 #define RECORD_LEN_LO           12
115
116 #define MSG_TYPE                0
117 #define MSG_LEN_HI              1
118 #define MSG_LEN_MID             2
119 #define MSG_LEN_LO              3
120 #define MSG_SEQ_HI              4
121 #define MSG_SEQ_LO              5
122 #define MSG_FRAG_OFF_HI         6
123 #define MSG_FRAG_OFF_MID        7
124 #define MSG_FRAG_OFF_LO         8
125 #define MSG_FRAG_LEN_HI         9
126 #define MSG_FRAG_LEN_MID        10
127 #define MSG_FRAG_LEN_LO         11
128
129
130 static void dump_data(const char *data, int len)
131 {
132     int rem, i, content, reclen, msglen, fragoff, fraglen, epoch;
133     unsigned char *rec;
134
135     printf("---- START OF PACKET ----\n");
136
137     rem = len;
138     rec = (unsigned char *)data;
139
140     while (rem > 0) {
141         if (rem != len)
142             printf("*\n");
143         printf("*---- START OF RECORD ----\n");
144         if (rem < DTLS1_RT_HEADER_LENGTH) {
145             printf("*---- RECORD TRUNCATED ----\n");
146             break;
147         }
148         content = rec[RECORD_CONTENT_TYPE];
149         printf("** Record Content-type: %d\n", content);
150         printf("** Record Version: %02x%02x\n",
151                rec[RECORD_VERSION_HI], rec[RECORD_VERSION_LO]);
152         epoch = (rec[RECORD_EPOCH_HI] << 8) | rec[RECORD_EPOCH_LO];
153         printf("** Record Epoch: %d\n", epoch);
154         printf("** Record Sequence: ");
155         for (i = RECORD_SEQUENCE_START; i <= RECORD_SEQUENCE_END; i++)
156             printf("%02x", rec[i]);
157         reclen = (rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO];
158         printf("\n** Record Length: %d\n", reclen);
159
160         /* Now look at message */
161         rec += DTLS1_RT_HEADER_LENGTH;
162         rem -= DTLS1_RT_HEADER_LENGTH;
163         if (content == SSL3_RT_HANDSHAKE) {
164             printf("**---- START OF HANDSHAKE MESSAGE FRAGMENT ----\n");
165             if (epoch > 0) {
166                 printf("**---- HANDSHAKE MESSAGE FRAGMENT ENCRYPTED ----\n");
167             } else if (rem < DTLS1_HM_HEADER_LENGTH
168                     || reclen < DTLS1_HM_HEADER_LENGTH) {
169                 printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
170             } else {
171                 printf("*** Message Type: %d\n", rec[MSG_TYPE]);
172                 msglen = (rec[MSG_LEN_HI] << 16) | (rec[MSG_LEN_MID] << 8)
173                          | rec[MSG_LEN_LO];
174                 printf("*** Message Length: %d\n", msglen);
175                 printf("*** Message sequence: %d\n",
176                        (rec[MSG_SEQ_HI] << 8) | rec[MSG_SEQ_LO]);
177                 fragoff = (rec[MSG_FRAG_OFF_HI] << 16)
178                           | (rec[MSG_FRAG_OFF_MID] << 8)
179                           | rec[MSG_FRAG_OFF_LO];
180                 printf("*** Message Fragment offset: %d\n", fragoff);
181                 fraglen = (rec[MSG_FRAG_LEN_HI] << 16)
182                           | (rec[MSG_FRAG_LEN_MID] << 8)
183                           | rec[MSG_FRAG_LEN_LO];
184                 printf("*** Message Fragment len: %d\n", fraglen);
185                 if (fragoff + fraglen > msglen)
186                     printf("***---- HANDSHAKE MESSAGE FRAGMENT INVALID ----\n");
187                 else if (reclen < fraglen)
188                     printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
189                 else
190                     printf("**---- END OF HANDSHAKE MESSAGE FRAGMENT ----\n");
191             }
192         }
193         if (rem < reclen) {
194             printf("*---- RECORD TRUNCATED ----\n");
195             rem = 0;
196         } else {
197             rec += reclen;
198             rem -= reclen;
199             printf("*---- END OF RECORD ----\n");
200         }
201     }
202     printf("---- END OF PACKET ----\n\n");
203     fflush(stdout);
204 }
205
206 static int tls_dump_read(BIO *bio, char *out, int outl)
207 {
208     int ret;
209     BIO *next = BIO_next(bio);
210
211     ret = BIO_read(next, out, outl);
212     copy_flags(bio);
213
214     if (ret > 0) {
215         dump_data(out, ret);
216     }
217
218     return ret;
219 }
220
221 static int tls_dump_write(BIO *bio, const char *in, int inl)
222 {
223     int ret;
224     BIO *next = BIO_next(bio);
225
226     ret = BIO_write(next, in, inl);
227     copy_flags(bio);
228
229     return ret;
230 }
231
232 static long tls_dump_ctrl(BIO *bio, int cmd, long num, void *ptr)
233 {
234     long ret;
235     BIO *next = BIO_next(bio);
236
237     if (next == NULL)
238         return 0;
239
240     switch (cmd) {
241     case BIO_CTRL_DUP:
242         ret = 0L;
243         break;
244     default:
245         ret = BIO_ctrl(next, cmd, num, ptr);
246         break;
247     }
248     return ret;
249 }
250
251 static int tls_dump_gets(BIO *bio, char *buf, int size)
252 {
253     /* We don't support this - not needed anyway */
254     return -1;
255 }
256
257 static int tls_dump_puts(BIO *bio, const char *str)
258 {
259     return tls_dump_write(bio, str, strlen(str));
260 }
261
262
263 struct mempacket_st {
264     unsigned char *data;
265     int len;
266     unsigned int num;
267     unsigned int type;
268 };
269
270 static void mempacket_free(MEMPACKET *pkt)
271 {
272     if (pkt->data != NULL)
273         OPENSSL_free(pkt->data);
274     OPENSSL_free(pkt);
275 }
276
277 typedef struct mempacket_test_ctx_st {
278     STACK_OF(MEMPACKET) *pkts;
279     unsigned int epoch;
280     unsigned int currrec;
281     unsigned int currpkt;
282     unsigned int lastpkt;
283     unsigned int injected;
284     unsigned int noinject;
285     unsigned int dropepoch;
286     int droprec;
287     int duprec;
288 } MEMPACKET_TEST_CTX;
289
290 static int mempacket_test_new(BIO *bi);
291 static int mempacket_test_free(BIO *a);
292 static int mempacket_test_read(BIO *b, char *out, int outl);
293 static int mempacket_test_write(BIO *b, const char *in, int inl);
294 static long mempacket_test_ctrl(BIO *b, int cmd, long num, void *ptr);
295 static int mempacket_test_gets(BIO *bp, char *buf, int size);
296 static int mempacket_test_puts(BIO *bp, const char *str);
297
298 const BIO_METHOD *bio_s_mempacket_test(void)
299 {
300     if (meth_mem == NULL) {
301         if (!TEST_ptr(meth_mem = BIO_meth_new(BIO_TYPE_MEMPACKET_TEST,
302                                               "Mem Packet Test"))
303             || !TEST_true(BIO_meth_set_write(meth_mem, mempacket_test_write))
304             || !TEST_true(BIO_meth_set_read(meth_mem, mempacket_test_read))
305             || !TEST_true(BIO_meth_set_puts(meth_mem, mempacket_test_puts))
306             || !TEST_true(BIO_meth_set_gets(meth_mem, mempacket_test_gets))
307             || !TEST_true(BIO_meth_set_ctrl(meth_mem, mempacket_test_ctrl))
308             || !TEST_true(BIO_meth_set_create(meth_mem, mempacket_test_new))
309             || !TEST_true(BIO_meth_set_destroy(meth_mem, mempacket_test_free)))
310             return NULL;
311     }
312     return meth_mem;
313 }
314
315 void bio_s_mempacket_test_free(void)
316 {
317     BIO_meth_free(meth_mem);
318 }
319
320 static int mempacket_test_new(BIO *bio)
321 {
322     MEMPACKET_TEST_CTX *ctx;
323
324     if (!TEST_ptr(ctx = OPENSSL_zalloc(sizeof(*ctx))))
325         return 0;
326     if (!TEST_ptr(ctx->pkts = sk_MEMPACKET_new_null())) {
327         OPENSSL_free(ctx);
328         return 0;
329     }
330     ctx->dropepoch = 0;
331     ctx->droprec = -1;
332     BIO_set_init(bio, 1);
333     BIO_set_data(bio, ctx);
334     return 1;
335 }
336
337 static int mempacket_test_free(BIO *bio)
338 {
339     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
340
341     sk_MEMPACKET_pop_free(ctx->pkts, mempacket_free);
342     OPENSSL_free(ctx);
343     BIO_set_data(bio, NULL);
344     BIO_set_init(bio, 0);
345     return 1;
346 }
347
348 /* Record Header values */
349 #define EPOCH_HI        3
350 #define EPOCH_LO        4
351 #define RECORD_SEQUENCE 10
352 #define RECORD_LEN_HI   11
353 #define RECORD_LEN_LO   12
354
355 #define STANDARD_PACKET                 0
356
357 static int mempacket_test_read(BIO *bio, char *out, int outl)
358 {
359     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
360     MEMPACKET *thispkt;
361     unsigned char *rec;
362     int rem;
363     unsigned int seq, offset, len, epoch;
364
365     BIO_clear_retry_flags(bio);
366     thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
367     if (thispkt == NULL || thispkt->num != ctx->currpkt) {
368         /* Probably run out of data */
369         BIO_set_retry_read(bio);
370         return -1;
371     }
372     (void)sk_MEMPACKET_shift(ctx->pkts);
373     ctx->currpkt++;
374
375     if (outl > thispkt->len)
376         outl = thispkt->len;
377
378     if (thispkt->type != INJECT_PACKET_IGNORE_REC_SEQ
379             && (ctx->injected || ctx->droprec >= 0)) {
380         /*
381          * Overwrite the record sequence number. We strictly number them in
382          * the order received. Since we are actually a reliable transport
383          * we know that there won't be any re-ordering. We overwrite to deal
384          * with any packets that have been injected
385          */
386         for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len) {
387             if (rem < DTLS1_RT_HEADER_LENGTH)
388                 return -1;
389             epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO];
390             if (epoch != ctx->epoch) {
391                 ctx->epoch = epoch;
392                 ctx->currrec = 0;
393             }
394             seq = ctx->currrec;
395             offset = 0;
396             do {
397                 rec[RECORD_SEQUENCE - offset] = seq & 0xFF;
398                 seq >>= 8;
399                 offset++;
400             } while (seq > 0);
401
402             len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO])
403                   + DTLS1_RT_HEADER_LENGTH;
404             if (rem < (int)len)
405                 return -1;
406             if (ctx->droprec == (int)ctx->currrec && ctx->dropepoch == epoch) {
407                 if (rem > (int)len)
408                     memmove(rec, rec + len, rem - len);
409                 outl -= len;
410                 ctx->droprec = -1;
411                 if (outl == 0)
412                     BIO_set_retry_read(bio);
413             } else {
414                 rec += len;
415             }
416
417             ctx->currrec++;
418         }
419     }
420
421     memcpy(out, thispkt->data, outl);
422     mempacket_free(thispkt);
423     return outl;
424 }
425
426 int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum,
427                           int type)
428 {
429     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
430     MEMPACKET *thispkt = NULL, *looppkt, *nextpkt, *allpkts[3];
431     int i, duprec = ctx->duprec > 0;
432     const unsigned char *inu = (const unsigned char *)in;
433     size_t len = ((inu[RECORD_LEN_HI] << 8) | inu[RECORD_LEN_LO])
434                  + DTLS1_RT_HEADER_LENGTH;
435
436     if (ctx == NULL)
437         return -1;
438
439     if ((size_t)inl < len)
440         return -1;
441
442     if ((size_t)inl == len)
443         duprec = 0;
444
445     /* We don't support arbitrary injection when duplicating records */
446     if (duprec && pktnum != -1)
447         return -1;
448
449     /* We only allow injection before we've started writing any data */
450     if (pktnum >= 0) {
451         if (ctx->noinject)
452             return -1;
453         ctx->injected  = 1;
454     } else {
455         ctx->noinject = 1;
456     }
457
458     for (i = 0; i < (duprec ? 3 : 1); i++) {
459         if (!TEST_ptr(allpkts[i] = OPENSSL_malloc(sizeof(*thispkt))))
460             goto err;
461         thispkt = allpkts[i];
462
463         if (!TEST_ptr(thispkt->data = OPENSSL_malloc(inl)))
464             goto err;
465         /*
466          * If we are duplicating the packet, we duplicate it three times. The
467          * first two times we drop the first record if there are more than one.
468          * In this way we know that libssl will not be able to make progress
469          * until it receives the last packet, and hence will be forced to
470          * buffer these records.
471          */
472         if (duprec && i != 2) {
473             memcpy(thispkt->data, in + len, inl - len);
474             thispkt->len = inl - len;
475         } else {
476             memcpy(thispkt->data, in, inl);
477             thispkt->len = inl;
478         }
479         thispkt->num = (pktnum >= 0) ? (unsigned int)pktnum : ctx->lastpkt + i;
480         thispkt->type = type;
481     }
482
483     for(i = 0; (looppkt = sk_MEMPACKET_value(ctx->pkts, i)) != NULL; i++) {
484         /* Check if we found the right place to insert this packet */
485         if (looppkt->num > thispkt->num) {
486             if (sk_MEMPACKET_insert(ctx->pkts, thispkt, i) == 0)
487                 goto err;
488             /* If we're doing up front injection then we're done */
489             if (pktnum >= 0)
490                 return inl;
491             /*
492              * We need to do some accounting on lastpkt. We increment it first,
493              * but it might now equal the value of injected packets, so we need
494              * to skip over those
495              */
496             ctx->lastpkt++;
497             do {
498                 i++;
499                 nextpkt = sk_MEMPACKET_value(ctx->pkts, i);
500                 if (nextpkt != NULL && nextpkt->num == ctx->lastpkt)
501                     ctx->lastpkt++;
502                 else
503                     return inl;
504             } while(1);
505         } else if (looppkt->num == thispkt->num) {
506             if (!ctx->noinject) {
507                 /* We injected two packets with the same packet number! */
508                 goto err;
509             }
510             ctx->lastpkt++;
511             thispkt->num++;
512         }
513     }
514     /*
515      * We didn't find any packets with a packet number equal to or greater than
516      * this one, so we just add it onto the end
517      */
518     for (i = 0; i < (duprec ? 3 : 1); i++) {
519         thispkt = allpkts[i];
520         if (!sk_MEMPACKET_push(ctx->pkts, thispkt))
521             goto err;
522
523         if (pktnum < 0)
524             ctx->lastpkt++;
525     }
526
527     return inl;
528
529  err:
530     for (i = 0; i < (ctx->duprec > 0 ? 3 : 1); i++)
531         mempacket_free(allpkts[i]);
532     return -1;
533 }
534
535 static int mempacket_test_write(BIO *bio, const char *in, int inl)
536 {
537     return mempacket_test_inject(bio, in, inl, -1, STANDARD_PACKET);
538 }
539
540 static long mempacket_test_ctrl(BIO *bio, int cmd, long num, void *ptr)
541 {
542     long ret = 1;
543     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
544     MEMPACKET *thispkt;
545
546     switch (cmd) {
547     case BIO_CTRL_EOF:
548         ret = (long)(sk_MEMPACKET_num(ctx->pkts) == 0);
549         break;
550     case BIO_CTRL_GET_CLOSE:
551         ret = BIO_get_shutdown(bio);
552         break;
553     case BIO_CTRL_SET_CLOSE:
554         BIO_set_shutdown(bio, (int)num);
555         break;
556     case BIO_CTRL_WPENDING:
557         ret = 0L;
558         break;
559     case BIO_CTRL_PENDING:
560         thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
561         if (thispkt == NULL)
562             ret = 0;
563         else
564             ret = thispkt->len;
565         break;
566     case BIO_CTRL_FLUSH:
567         ret = 1;
568         break;
569     case MEMPACKET_CTRL_SET_DROP_EPOCH:
570         ctx->dropepoch = (unsigned int)num;
571         break;
572     case MEMPACKET_CTRL_SET_DROP_REC:
573         ctx->droprec = (int)num;
574         break;
575     case MEMPACKET_CTRL_GET_DROP_REC:
576         ret = ctx->droprec;
577         break;
578     case MEMPACKET_CTRL_SET_DUPLICATE_REC:
579         ctx->duprec = (int)num;
580         break;
581     case BIO_CTRL_RESET:
582     case BIO_CTRL_DUP:
583     case BIO_CTRL_PUSH:
584     case BIO_CTRL_POP:
585     default:
586         ret = 0;
587         break;
588     }
589     return ret;
590 }
591
592 static int mempacket_test_gets(BIO *bio, char *buf, int size)
593 {
594     /* We don't support this - not needed anyway */
595     return -1;
596 }
597
598 static int mempacket_test_puts(BIO *bio, const char *str)
599 {
600     return mempacket_test_write(bio, str, strlen(str));
601 }
602
603 int create_ssl_ctx_pair(const SSL_METHOD *sm, const SSL_METHOD *cm,
604                         int min_proto_version, int max_proto_version,
605                         SSL_CTX **sctx, SSL_CTX **cctx, char *certfile,
606                         char *privkeyfile)
607 {
608     SSL_CTX *serverctx = NULL;
609     SSL_CTX *clientctx = NULL;
610
611     if (!TEST_ptr(serverctx = SSL_CTX_new(sm))
612             || (cctx != NULL && !TEST_ptr(clientctx = SSL_CTX_new(cm))))
613         goto err;
614
615     if ((min_proto_version > 0
616          && !TEST_true(SSL_CTX_set_min_proto_version(serverctx,
617                                                      min_proto_version)))
618         || (max_proto_version > 0
619             && !TEST_true(SSL_CTX_set_max_proto_version(serverctx,
620                                                         max_proto_version))))
621         goto err;
622     if (clientctx != NULL
623         && ((min_proto_version > 0
624              && !TEST_true(SSL_CTX_set_min_proto_version(clientctx,
625                                                          min_proto_version)))
626             || (max_proto_version > 0
627                 && !TEST_true(SSL_CTX_set_max_proto_version(clientctx,
628                                                             max_proto_version)))))
629         goto err;
630
631     if (certfile != NULL && privkeyfile != NULL) {
632         if (!TEST_int_eq(SSL_CTX_use_certificate_file(serverctx, certfile,
633                                                       SSL_FILETYPE_PEM), 1)
634                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(serverctx,
635                                                             privkeyfile,
636                                                             SSL_FILETYPE_PEM), 1)
637                 || !TEST_int_eq(SSL_CTX_check_private_key(serverctx), 1))
638             goto err;
639     }
640
641 #ifndef OPENSSL_NO_DH
642     SSL_CTX_set_dh_auto(serverctx, 1);
643 #endif
644
645     *sctx = serverctx;
646     if (cctx != NULL)
647         *cctx = clientctx;
648     return 1;
649
650  err:
651     SSL_CTX_free(serverctx);
652     SSL_CTX_free(clientctx);
653     return 0;
654 }
655
656 #define MAXLOOPS    1000000
657
658 /*
659  * NOTE: Transfers control of the BIOs - this function will free them on error
660  */
661 int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
662                           SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio)
663 {
664     SSL *serverssl = NULL, *clientssl = NULL;
665     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
666
667     if (*sssl != NULL)
668         serverssl = *sssl;
669     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
670         goto error;
671     if (*cssl != NULL)
672         clientssl = *cssl;
673     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
674         goto error;
675
676     if (SSL_is_dtls(clientssl)) {
677         if (!TEST_ptr(s_to_c_bio = BIO_new(bio_s_mempacket_test()))
678                 || !TEST_ptr(c_to_s_bio = BIO_new(bio_s_mempacket_test())))
679             goto error;
680     } else {
681         if (!TEST_ptr(s_to_c_bio = BIO_new(BIO_s_mem()))
682                 || !TEST_ptr(c_to_s_bio = BIO_new(BIO_s_mem())))
683             goto error;
684     }
685
686     if (s_to_c_fbio != NULL
687             && !TEST_ptr(s_to_c_bio = BIO_push(s_to_c_fbio, s_to_c_bio)))
688         goto error;
689     if (c_to_s_fbio != NULL
690             && !TEST_ptr(c_to_s_bio = BIO_push(c_to_s_fbio, c_to_s_bio)))
691         goto error;
692
693     /* Set Non-blocking IO behaviour */
694     BIO_set_mem_eof_return(s_to_c_bio, -1);
695     BIO_set_mem_eof_return(c_to_s_bio, -1);
696
697     /* Up ref these as we are passing them to two SSL objects */
698     SSL_set_bio(serverssl, c_to_s_bio, s_to_c_bio);
699     BIO_up_ref(s_to_c_bio);
700     BIO_up_ref(c_to_s_bio);
701     SSL_set_bio(clientssl, s_to_c_bio, c_to_s_bio);
702     *sssl = serverssl;
703     *cssl = clientssl;
704     return 1;
705
706  error:
707     SSL_free(serverssl);
708     SSL_free(clientssl);
709     BIO_free(s_to_c_bio);
710     BIO_free(c_to_s_bio);
711     BIO_free(s_to_c_fbio);
712     BIO_free(c_to_s_fbio);
713
714     return 0;
715 }
716
717 /*
718  * Create an SSL connection, but does not ready any post-handshake
719  * NewSessionTicket messages.
720  */
721 int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want)
722 {
723     int retc = -1, rets = -1, err, abortctr = 0;
724     int clienterr = 0, servererr = 0;
725     int isdtls = SSL_is_dtls(serverssl);
726
727     do {
728         err = SSL_ERROR_WANT_WRITE;
729         while (!clienterr && retc <= 0 && err == SSL_ERROR_WANT_WRITE) {
730             retc = SSL_connect(clientssl);
731             if (retc <= 0)
732                 err = SSL_get_error(clientssl, retc);
733         }
734
735         if (!clienterr && retc <= 0 && err != SSL_ERROR_WANT_READ) {
736             TEST_info("SSL_connect() failed %d, %d", retc, err);
737             clienterr = 1;
738         }
739         if (want != SSL_ERROR_NONE && err == want)
740             return 0;
741
742         err = SSL_ERROR_WANT_WRITE;
743         while (!servererr && rets <= 0 && err == SSL_ERROR_WANT_WRITE) {
744             rets = SSL_accept(serverssl);
745             if (rets <= 0)
746                 err = SSL_get_error(serverssl, rets);
747         }
748
749         if (!servererr && rets <= 0
750                 && err != SSL_ERROR_WANT_READ
751                 && err != SSL_ERROR_WANT_X509_LOOKUP) {
752             TEST_info("SSL_accept() failed %d, %d", rets, err);
753             servererr = 1;
754         }
755         if (want != SSL_ERROR_NONE && err == want)
756             return 0;
757         if (clienterr && servererr)
758             return 0;
759         if (isdtls) {
760             if (rets > 0 && retc <= 0)
761                 DTLSv1_handle_timeout(serverssl);
762             if (retc > 0 && rets <= 0)
763                 DTLSv1_handle_timeout(clientssl);
764         }
765         if (++abortctr == MAXLOOPS) {
766             TEST_info("No progress made");
767             return 0;
768         }
769         if (isdtls && abortctr <= 50 && (abortctr % 10) == 0) {
770             /*
771              * It looks like we're just spinning. Pause for a short period to
772              * give the DTLS timer a chance to do something. We only do this for
773              * the first few times to prevent hangs.
774              */
775             ossl_sleep(50);
776         }
777     } while (retc <=0 || rets <= 0);
778
779     return 1;
780 }
781
782 /*
783  * Create an SSL connection including any post handshake NewSessionTicket
784  * messages.
785  */
786 int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want)
787 {
788     int i;
789     unsigned char buf;
790     size_t readbytes;
791
792     if (!create_bare_ssl_connection(serverssl, clientssl, want))
793         return 0;
794
795     /*
796      * We attempt to read some data on the client side which we expect to fail.
797      * This will ensure we have received the NewSessionTicket in TLSv1.3 where
798      * appropriate. We do this twice because there are 2 NewSesionTickets.
799      */
800     for (i = 0; i < 2; i++) {
801         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
802             if (!TEST_ulong_eq(readbytes, 0))
803                 return 0;
804         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
805                                 SSL_ERROR_WANT_READ)) {
806             return 0;
807         }
808     }
809
810     return 1;
811 }
812
813 void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl)
814 {
815     SSL_shutdown(clientssl);
816     SSL_shutdown(serverssl);
817     SSL_free(serverssl);
818     SSL_free(clientssl);
819 }