Minimal adaptation of tests back to how it was before
[openssl.git] / test / ssltestlib.c
1 /*
2  * Copyright 2016-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #ifndef OPENSSL_NO_KTLS
20 # include <netinet/in.h>
21 # include <netinet/in.h>
22 # include <arpa/inet.h>
23 # include <sys/socket.h>
24 # include <unistd.h>
25 # include <fcntl.h>
26 #endif
27
28 static ossl_inline void ossl_sleep(unsigned int millis)
29 {
30 # ifdef OPENSSL_SYS_VXWORKS
31     struct timespec ts;
32     ts.tv_sec = (long int) (millis / 1000);
33     ts.tv_nsec = (long int) (millis % 1000) * 1000000ul;
34     nanosleep(&ts, NULL);
35 # else
36     usleep(millis * 1000);
37 # endif
38 }
39 #elif defined(_WIN32)
40 # include <windows.h>
41
42 static ossl_inline void ossl_sleep(unsigned int millis)
43 {
44     Sleep(millis);
45 }
46 #else
47 /* Fallback to a busy wait */
48 static ossl_inline void ossl_sleep(unsigned int millis)
49 {
50     struct timeval start, now;
51     unsigned int elapsedms;
52
53     gettimeofday(&start, NULL);
54     do {
55         gettimeofday(&now, NULL);
56         elapsedms = (((now.tv_sec - start.tv_sec) * 1000000)
57                      + now.tv_usec - start.tv_usec) / 1000;
58     } while (elapsedms < millis);
59 }
60 #endif
61
62 static int tls_dump_new(BIO *bi);
63 static int tls_dump_free(BIO *a);
64 static int tls_dump_read(BIO *b, char *out, int outl);
65 static int tls_dump_write(BIO *b, const char *in, int inl);
66 static long tls_dump_ctrl(BIO *b, int cmd, long num, void *ptr);
67 static int tls_dump_gets(BIO *bp, char *buf, int size);
68 static int tls_dump_puts(BIO *bp, const char *str);
69
70 /* Choose a sufficiently large type likely to be unused for this custom BIO */
71 #define BIO_TYPE_TLS_DUMP_FILTER  (0x80 | BIO_TYPE_FILTER)
72 #define BIO_TYPE_MEMPACKET_TEST    0x81
73 #define BIO_TYPE_ALWAYS_RETRY      0x82
74
75 static BIO_METHOD *method_tls_dump = NULL;
76 static BIO_METHOD *meth_mem = NULL;
77 static BIO_METHOD *meth_always_retry = NULL;
78
79 /* Note: Not thread safe! */
80 const BIO_METHOD *bio_f_tls_dump_filter(void)
81 {
82     if (method_tls_dump == NULL) {
83         method_tls_dump = BIO_meth_new(BIO_TYPE_TLS_DUMP_FILTER,
84                                         "TLS dump filter");
85         if (   method_tls_dump == NULL
86             || !BIO_meth_set_write(method_tls_dump, tls_dump_write)
87             || !BIO_meth_set_read(method_tls_dump, tls_dump_read)
88             || !BIO_meth_set_puts(method_tls_dump, tls_dump_puts)
89             || !BIO_meth_set_gets(method_tls_dump, tls_dump_gets)
90             || !BIO_meth_set_ctrl(method_tls_dump, tls_dump_ctrl)
91             || !BIO_meth_set_create(method_tls_dump, tls_dump_new)
92             || !BIO_meth_set_destroy(method_tls_dump, tls_dump_free))
93             return NULL;
94     }
95     return method_tls_dump;
96 }
97
98 void bio_f_tls_dump_filter_free(void)
99 {
100     BIO_meth_free(method_tls_dump);
101 }
102
103 static int tls_dump_new(BIO *bio)
104 {
105     BIO_set_init(bio, 1);
106     return 1;
107 }
108
109 static int tls_dump_free(BIO *bio)
110 {
111     BIO_set_init(bio, 0);
112
113     return 1;
114 }
115
116 static void copy_flags(BIO *bio)
117 {
118     int flags;
119     BIO *next = BIO_next(bio);
120
121     flags = BIO_test_flags(next, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
122     BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
123     BIO_set_flags(bio, flags);
124 }
125
126 #define RECORD_CONTENT_TYPE     0
127 #define RECORD_VERSION_HI       1
128 #define RECORD_VERSION_LO       2
129 #define RECORD_EPOCH_HI         3
130 #define RECORD_EPOCH_LO         4
131 #define RECORD_SEQUENCE_START   5
132 #define RECORD_SEQUENCE_END     10
133 #define RECORD_LEN_HI           11
134 #define RECORD_LEN_LO           12
135
136 #define MSG_TYPE                0
137 #define MSG_LEN_HI              1
138 #define MSG_LEN_MID             2
139 #define MSG_LEN_LO              3
140 #define MSG_SEQ_HI              4
141 #define MSG_SEQ_LO              5
142 #define MSG_FRAG_OFF_HI         6
143 #define MSG_FRAG_OFF_MID        7
144 #define MSG_FRAG_OFF_LO         8
145 #define MSG_FRAG_LEN_HI         9
146 #define MSG_FRAG_LEN_MID        10
147 #define MSG_FRAG_LEN_LO         11
148
149
150 static void dump_data(const char *data, int len)
151 {
152     int rem, i, content, reclen, msglen, fragoff, fraglen, epoch;
153     unsigned char *rec;
154
155     printf("---- START OF PACKET ----\n");
156
157     rem = len;
158     rec = (unsigned char *)data;
159
160     while (rem > 0) {
161         if (rem != len)
162             printf("*\n");
163         printf("*---- START OF RECORD ----\n");
164         if (rem < DTLS1_RT_HEADER_LENGTH) {
165             printf("*---- RECORD TRUNCATED ----\n");
166             break;
167         }
168         content = rec[RECORD_CONTENT_TYPE];
169         printf("** Record Content-type: %d\n", content);
170         printf("** Record Version: %02x%02x\n",
171                rec[RECORD_VERSION_HI], rec[RECORD_VERSION_LO]);
172         epoch = (rec[RECORD_EPOCH_HI] << 8) | rec[RECORD_EPOCH_LO];
173         printf("** Record Epoch: %d\n", epoch);
174         printf("** Record Sequence: ");
175         for (i = RECORD_SEQUENCE_START; i <= RECORD_SEQUENCE_END; i++)
176             printf("%02x", rec[i]);
177         reclen = (rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO];
178         printf("\n** Record Length: %d\n", reclen);
179
180         /* Now look at message */
181         rec += DTLS1_RT_HEADER_LENGTH;
182         rem -= DTLS1_RT_HEADER_LENGTH;
183         if (content == SSL3_RT_HANDSHAKE) {
184             printf("**---- START OF HANDSHAKE MESSAGE FRAGMENT ----\n");
185             if (epoch > 0) {
186                 printf("**---- HANDSHAKE MESSAGE FRAGMENT ENCRYPTED ----\n");
187             } else if (rem < DTLS1_HM_HEADER_LENGTH
188                     || reclen < DTLS1_HM_HEADER_LENGTH) {
189                 printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
190             } else {
191                 printf("*** Message Type: %d\n", rec[MSG_TYPE]);
192                 msglen = (rec[MSG_LEN_HI] << 16) | (rec[MSG_LEN_MID] << 8)
193                          | rec[MSG_LEN_LO];
194                 printf("*** Message Length: %d\n", msglen);
195                 printf("*** Message sequence: %d\n",
196                        (rec[MSG_SEQ_HI] << 8) | rec[MSG_SEQ_LO]);
197                 fragoff = (rec[MSG_FRAG_OFF_HI] << 16)
198                           | (rec[MSG_FRAG_OFF_MID] << 8)
199                           | rec[MSG_FRAG_OFF_LO];
200                 printf("*** Message Fragment offset: %d\n", fragoff);
201                 fraglen = (rec[MSG_FRAG_LEN_HI] << 16)
202                           | (rec[MSG_FRAG_LEN_MID] << 8)
203                           | rec[MSG_FRAG_LEN_LO];
204                 printf("*** Message Fragment len: %d\n", fraglen);
205                 if (fragoff + fraglen > msglen)
206                     printf("***---- HANDSHAKE MESSAGE FRAGMENT INVALID ----\n");
207                 else if (reclen < fraglen)
208                     printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
209                 else
210                     printf("**---- END OF HANDSHAKE MESSAGE FRAGMENT ----\n");
211             }
212         }
213         if (rem < reclen) {
214             printf("*---- RECORD TRUNCATED ----\n");
215             rem = 0;
216         } else {
217             rec += reclen;
218             rem -= reclen;
219             printf("*---- END OF RECORD ----\n");
220         }
221     }
222     printf("---- END OF PACKET ----\n\n");
223     fflush(stdout);
224 }
225
226 static int tls_dump_read(BIO *bio, char *out, int outl)
227 {
228     int ret;
229     BIO *next = BIO_next(bio);
230
231     ret = BIO_read(next, out, outl);
232     copy_flags(bio);
233
234     if (ret > 0) {
235         dump_data(out, ret);
236     }
237
238     return ret;
239 }
240
241 static int tls_dump_write(BIO *bio, const char *in, int inl)
242 {
243     int ret;
244     BIO *next = BIO_next(bio);
245
246     ret = BIO_write(next, in, inl);
247     copy_flags(bio);
248
249     return ret;
250 }
251
252 static long tls_dump_ctrl(BIO *bio, int cmd, long num, void *ptr)
253 {
254     long ret;
255     BIO *next = BIO_next(bio);
256
257     if (next == NULL)
258         return 0;
259
260     switch (cmd) {
261     case BIO_CTRL_DUP:
262         ret = 0L;
263         break;
264     default:
265         ret = BIO_ctrl(next, cmd, num, ptr);
266         break;
267     }
268     return ret;
269 }
270
271 static int tls_dump_gets(BIO *bio, char *buf, int size)
272 {
273     /* We don't support this - not needed anyway */
274     return -1;
275 }
276
277 static int tls_dump_puts(BIO *bio, const char *str)
278 {
279     return tls_dump_write(bio, str, strlen(str));
280 }
281
282
283 struct mempacket_st {
284     unsigned char *data;
285     int len;
286     unsigned int num;
287     unsigned int type;
288 };
289
290 static void mempacket_free(MEMPACKET *pkt)
291 {
292     if (pkt->data != NULL)
293         OPENSSL_free(pkt->data);
294     OPENSSL_free(pkt);
295 }
296
297 typedef struct mempacket_test_ctx_st {
298     STACK_OF(MEMPACKET) *pkts;
299     unsigned int epoch;
300     unsigned int currrec;
301     unsigned int currpkt;
302     unsigned int lastpkt;
303     unsigned int injected;
304     unsigned int noinject;
305     unsigned int dropepoch;
306     int droprec;
307     int duprec;
308 } MEMPACKET_TEST_CTX;
309
310 static int mempacket_test_new(BIO *bi);
311 static int mempacket_test_free(BIO *a);
312 static int mempacket_test_read(BIO *b, char *out, int outl);
313 static int mempacket_test_write(BIO *b, const char *in, int inl);
314 static long mempacket_test_ctrl(BIO *b, int cmd, long num, void *ptr);
315 static int mempacket_test_gets(BIO *bp, char *buf, int size);
316 static int mempacket_test_puts(BIO *bp, const char *str);
317
318 const BIO_METHOD *bio_s_mempacket_test(void)
319 {
320     if (meth_mem == NULL) {
321         if (!TEST_ptr(meth_mem = BIO_meth_new(BIO_TYPE_MEMPACKET_TEST,
322                                               "Mem Packet Test"))
323             || !TEST_true(BIO_meth_set_write(meth_mem, mempacket_test_write))
324             || !TEST_true(BIO_meth_set_read(meth_mem, mempacket_test_read))
325             || !TEST_true(BIO_meth_set_puts(meth_mem, mempacket_test_puts))
326             || !TEST_true(BIO_meth_set_gets(meth_mem, mempacket_test_gets))
327             || !TEST_true(BIO_meth_set_ctrl(meth_mem, mempacket_test_ctrl))
328             || !TEST_true(BIO_meth_set_create(meth_mem, mempacket_test_new))
329             || !TEST_true(BIO_meth_set_destroy(meth_mem, mempacket_test_free)))
330             return NULL;
331     }
332     return meth_mem;
333 }
334
335 void bio_s_mempacket_test_free(void)
336 {
337     BIO_meth_free(meth_mem);
338 }
339
340 static int mempacket_test_new(BIO *bio)
341 {
342     MEMPACKET_TEST_CTX *ctx;
343
344     if (!TEST_ptr(ctx = OPENSSL_zalloc(sizeof(*ctx))))
345         return 0;
346     if (!TEST_ptr(ctx->pkts = sk_MEMPACKET_new_null())) {
347         OPENSSL_free(ctx);
348         return 0;
349     }
350     ctx->dropepoch = 0;
351     ctx->droprec = -1;
352     BIO_set_init(bio, 1);
353     BIO_set_data(bio, ctx);
354     return 1;
355 }
356
357 static int mempacket_test_free(BIO *bio)
358 {
359     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
360
361     sk_MEMPACKET_pop_free(ctx->pkts, mempacket_free);
362     OPENSSL_free(ctx);
363     BIO_set_data(bio, NULL);
364     BIO_set_init(bio, 0);
365     return 1;
366 }
367
368 /* Record Header values */
369 #define EPOCH_HI        3
370 #define EPOCH_LO        4
371 #define RECORD_SEQUENCE 10
372 #define RECORD_LEN_HI   11
373 #define RECORD_LEN_LO   12
374
375 #define STANDARD_PACKET                 0
376
377 static int mempacket_test_read(BIO *bio, char *out, int outl)
378 {
379     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
380     MEMPACKET *thispkt;
381     unsigned char *rec;
382     int rem;
383     unsigned int seq, offset, len, epoch;
384
385     BIO_clear_retry_flags(bio);
386     thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
387     if (thispkt == NULL || thispkt->num != ctx->currpkt) {
388         /* Probably run out of data */
389         BIO_set_retry_read(bio);
390         return -1;
391     }
392     (void)sk_MEMPACKET_shift(ctx->pkts);
393     ctx->currpkt++;
394
395     if (outl > thispkt->len)
396         outl = thispkt->len;
397
398     if (thispkt->type != INJECT_PACKET_IGNORE_REC_SEQ
399             && (ctx->injected || ctx->droprec >= 0)) {
400         /*
401          * Overwrite the record sequence number. We strictly number them in
402          * the order received. Since we are actually a reliable transport
403          * we know that there won't be any re-ordering. We overwrite to deal
404          * with any packets that have been injected
405          */
406         for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len) {
407             if (rem < DTLS1_RT_HEADER_LENGTH)
408                 return -1;
409             epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO];
410             if (epoch != ctx->epoch) {
411                 ctx->epoch = epoch;
412                 ctx->currrec = 0;
413             }
414             seq = ctx->currrec;
415             offset = 0;
416             do {
417                 rec[RECORD_SEQUENCE - offset] = seq & 0xFF;
418                 seq >>= 8;
419                 offset++;
420             } while (seq > 0);
421
422             len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO])
423                   + DTLS1_RT_HEADER_LENGTH;
424             if (rem < (int)len)
425                 return -1;
426             if (ctx->droprec == (int)ctx->currrec && ctx->dropepoch == epoch) {
427                 if (rem > (int)len)
428                     memmove(rec, rec + len, rem - len);
429                 outl -= len;
430                 ctx->droprec = -1;
431                 if (outl == 0)
432                     BIO_set_retry_read(bio);
433             } else {
434                 rec += len;
435             }
436
437             ctx->currrec++;
438         }
439     }
440
441     memcpy(out, thispkt->data, outl);
442     mempacket_free(thispkt);
443     return outl;
444 }
445
446 int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum,
447                           int type)
448 {
449     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
450     MEMPACKET *thispkt = NULL, *looppkt, *nextpkt, *allpkts[3];
451     int i, duprec;
452     const unsigned char *inu = (const unsigned char *)in;
453     size_t len = ((inu[RECORD_LEN_HI] << 8) | inu[RECORD_LEN_LO])
454                  + DTLS1_RT_HEADER_LENGTH;
455
456     if (ctx == NULL)
457         return -1;
458
459     if ((size_t)inl < len)
460         return -1;
461
462     if ((size_t)inl == len)
463         duprec = 0;
464     else
465         duprec = ctx->duprec > 0;
466
467     /* We don't support arbitrary injection when duplicating records */
468     if (duprec && pktnum != -1)
469         return -1;
470
471     /* We only allow injection before we've started writing any data */
472     if (pktnum >= 0) {
473         if (ctx->noinject)
474             return -1;
475         ctx->injected  = 1;
476     } else {
477         ctx->noinject = 1;
478     }
479
480     for (i = 0; i < (duprec ? 3 : 1); i++) {
481         if (!TEST_ptr(allpkts[i] = OPENSSL_malloc(sizeof(*thispkt))))
482             goto err;
483         thispkt = allpkts[i];
484
485         if (!TEST_ptr(thispkt->data = OPENSSL_malloc(inl)))
486             goto err;
487         /*
488          * If we are duplicating the packet, we duplicate it three times. The
489          * first two times we drop the first record if there are more than one.
490          * In this way we know that libssl will not be able to make progress
491          * until it receives the last packet, and hence will be forced to
492          * buffer these records.
493          */
494         if (duprec && i != 2) {
495             memcpy(thispkt->data, in + len, inl - len);
496             thispkt->len = inl - len;
497         } else {
498             memcpy(thispkt->data, in, inl);
499             thispkt->len = inl;
500         }
501         thispkt->num = (pktnum >= 0) ? (unsigned int)pktnum : ctx->lastpkt + i;
502         thispkt->type = type;
503     }
504
505     for(i = 0; (looppkt = sk_MEMPACKET_value(ctx->pkts, i)) != NULL; i++) {
506         /* Check if we found the right place to insert this packet */
507         if (looppkt->num > thispkt->num) {
508             if (sk_MEMPACKET_insert(ctx->pkts, thispkt, i) == 0)
509                 goto err;
510             /* If we're doing up front injection then we're done */
511             if (pktnum >= 0)
512                 return inl;
513             /*
514              * We need to do some accounting on lastpkt. We increment it first,
515              * but it might now equal the value of injected packets, so we need
516              * to skip over those
517              */
518             ctx->lastpkt++;
519             do {
520                 i++;
521                 nextpkt = sk_MEMPACKET_value(ctx->pkts, i);
522                 if (nextpkt != NULL && nextpkt->num == ctx->lastpkt)
523                     ctx->lastpkt++;
524                 else
525                     return inl;
526             } while(1);
527         } else if (looppkt->num == thispkt->num) {
528             if (!ctx->noinject) {
529                 /* We injected two packets with the same packet number! */
530                 goto err;
531             }
532             ctx->lastpkt++;
533             thispkt->num++;
534         }
535     }
536     /*
537      * We didn't find any packets with a packet number equal to or greater than
538      * this one, so we just add it onto the end
539      */
540     for (i = 0; i < (duprec ? 3 : 1); i++) {
541         thispkt = allpkts[i];
542         if (!sk_MEMPACKET_push(ctx->pkts, thispkt))
543             goto err;
544
545         if (pktnum < 0)
546             ctx->lastpkt++;
547     }
548
549     return inl;
550
551  err:
552     for (i = 0; i < (ctx->duprec > 0 ? 3 : 1); i++)
553         mempacket_free(allpkts[i]);
554     return -1;
555 }
556
557 static int mempacket_test_write(BIO *bio, const char *in, int inl)
558 {
559     return mempacket_test_inject(bio, in, inl, -1, STANDARD_PACKET);
560 }
561
562 static long mempacket_test_ctrl(BIO *bio, int cmd, long num, void *ptr)
563 {
564     long ret = 1;
565     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
566     MEMPACKET *thispkt;
567
568     switch (cmd) {
569     case BIO_CTRL_EOF:
570         ret = (long)(sk_MEMPACKET_num(ctx->pkts) == 0);
571         break;
572     case BIO_CTRL_GET_CLOSE:
573         ret = BIO_get_shutdown(bio);
574         break;
575     case BIO_CTRL_SET_CLOSE:
576         BIO_set_shutdown(bio, (int)num);
577         break;
578     case BIO_CTRL_WPENDING:
579         ret = 0L;
580         break;
581     case BIO_CTRL_PENDING:
582         thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
583         if (thispkt == NULL)
584             ret = 0;
585         else
586             ret = thispkt->len;
587         break;
588     case BIO_CTRL_FLUSH:
589         ret = 1;
590         break;
591     case MEMPACKET_CTRL_SET_DROP_EPOCH:
592         ctx->dropepoch = (unsigned int)num;
593         break;
594     case MEMPACKET_CTRL_SET_DROP_REC:
595         ctx->droprec = (int)num;
596         break;
597     case MEMPACKET_CTRL_GET_DROP_REC:
598         ret = ctx->droprec;
599         break;
600     case MEMPACKET_CTRL_SET_DUPLICATE_REC:
601         ctx->duprec = (int)num;
602         break;
603     case BIO_CTRL_RESET:
604     case BIO_CTRL_DUP:
605     case BIO_CTRL_PUSH:
606     case BIO_CTRL_POP:
607     default:
608         ret = 0;
609         break;
610     }
611     return ret;
612 }
613
614 static int mempacket_test_gets(BIO *bio, char *buf, int size)
615 {
616     /* We don't support this - not needed anyway */
617     return -1;
618 }
619
620 static int mempacket_test_puts(BIO *bio, const char *str)
621 {
622     return mempacket_test_write(bio, str, strlen(str));
623 }
624
625 static int always_retry_new(BIO *bi);
626 static int always_retry_free(BIO *a);
627 static int always_retry_read(BIO *b, char *out, int outl);
628 static int always_retry_write(BIO *b, const char *in, int inl);
629 static long always_retry_ctrl(BIO *b, int cmd, long num, void *ptr);
630 static int always_retry_gets(BIO *bp, char *buf, int size);
631 static int always_retry_puts(BIO *bp, const char *str);
632
633 const BIO_METHOD *bio_s_always_retry(void)
634 {
635     if (meth_always_retry == NULL) {
636         if (!TEST_ptr(meth_always_retry = BIO_meth_new(BIO_TYPE_ALWAYS_RETRY,
637                                                        "Always Retry"))
638             || !TEST_true(BIO_meth_set_write(meth_always_retry,
639                                              always_retry_write))
640             || !TEST_true(BIO_meth_set_read(meth_always_retry,
641                                             always_retry_read))
642             || !TEST_true(BIO_meth_set_puts(meth_always_retry,
643                                             always_retry_puts))
644             || !TEST_true(BIO_meth_set_gets(meth_always_retry,
645                                             always_retry_gets))
646             || !TEST_true(BIO_meth_set_ctrl(meth_always_retry,
647                                             always_retry_ctrl))
648             || !TEST_true(BIO_meth_set_create(meth_always_retry,
649                                               always_retry_new))
650             || !TEST_true(BIO_meth_set_destroy(meth_always_retry,
651                                                always_retry_free)))
652             return NULL;
653     }
654     return meth_always_retry;
655 }
656
657 void bio_s_always_retry_free(void)
658 {
659     BIO_meth_free(meth_always_retry);
660 }
661
662 static int always_retry_new(BIO *bio)
663 {
664     BIO_set_init(bio, 1);
665     return 1;
666 }
667
668 static int always_retry_free(BIO *bio)
669 {
670     BIO_set_data(bio, NULL);
671     BIO_set_init(bio, 0);
672     return 1;
673 }
674
675 static int always_retry_read(BIO *bio, char *out, int outl)
676 {
677     BIO_set_retry_read(bio);
678     return -1;
679 }
680
681 static int always_retry_write(BIO *bio, const char *in, int inl)
682 {
683     BIO_set_retry_write(bio);
684     return -1;
685 }
686
687 static long always_retry_ctrl(BIO *bio, int cmd, long num, void *ptr)
688 {
689     long ret = 1;
690
691     switch (cmd) {
692     case BIO_CTRL_FLUSH:
693         BIO_set_retry_write(bio);
694         /* fall through */
695     case BIO_CTRL_EOF:
696     case BIO_CTRL_RESET:
697     case BIO_CTRL_DUP:
698     case BIO_CTRL_PUSH:
699     case BIO_CTRL_POP:
700     default:
701         ret = 0;
702         break;
703     }
704     return ret;
705 }
706
707 static int always_retry_gets(BIO *bio, char *buf, int size)
708 {
709     BIO_set_retry_read(bio);
710     return -1;
711 }
712
713 static int always_retry_puts(BIO *bio, const char *str)
714 {
715     BIO_set_retry_write(bio);
716     return -1;
717 }
718
719 int create_ssl_ctx_pair(const SSL_METHOD *sm, const SSL_METHOD *cm,
720                         int min_proto_version, int max_proto_version,
721                         SSL_CTX **sctx, SSL_CTX **cctx, char *certfile,
722                         char *privkeyfile)
723 {
724     SSL_CTX *serverctx = NULL;
725     SSL_CTX *clientctx = NULL;
726
727     if (!TEST_ptr(serverctx = SSL_CTX_new(sm))
728             || (cctx != NULL && !TEST_ptr(clientctx = SSL_CTX_new(cm))))
729         goto err;
730
731     if ((min_proto_version > 0
732          && !TEST_true(SSL_CTX_set_min_proto_version(serverctx,
733                                                      min_proto_version)))
734         || (max_proto_version > 0
735             && !TEST_true(SSL_CTX_set_max_proto_version(serverctx,
736                                                         max_proto_version))))
737         goto err;
738     if (clientctx != NULL
739         && ((min_proto_version > 0
740              && !TEST_true(SSL_CTX_set_min_proto_version(clientctx,
741                                                          min_proto_version)))
742             || (max_proto_version > 0
743                 && !TEST_true(SSL_CTX_set_max_proto_version(clientctx,
744                                                             max_proto_version)))))
745         goto err;
746
747     if (certfile != NULL && privkeyfile != NULL) {
748         if (!TEST_int_eq(SSL_CTX_use_certificate_file(serverctx, certfile,
749                                                       SSL_FILETYPE_PEM), 1)
750                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(serverctx,
751                                                             privkeyfile,
752                                                             SSL_FILETYPE_PEM), 1)
753                 || !TEST_int_eq(SSL_CTX_check_private_key(serverctx), 1))
754             goto err;
755     }
756
757 #ifndef OPENSSL_NO_DH
758     SSL_CTX_set_dh_auto(serverctx, 1);
759 #endif
760
761     *sctx = serverctx;
762     if (cctx != NULL)
763         *cctx = clientctx;
764     return 1;
765
766  err:
767     SSL_CTX_free(serverctx);
768     SSL_CTX_free(clientctx);
769     return 0;
770 }
771
772 #define MAXLOOPS    1000000
773
774 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
775 static int set_nb(int fd)
776 {
777     int flags;
778
779     flags = fcntl(fd,F_GETFL,0);
780     if (flags == -1)
781         return flags;
782     flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
783     return flags;
784 }
785
786 int create_test_sockets(int *cfd, int *sfd)
787 {
788     struct sockaddr_in sin;
789     const char *host = "127.0.0.1";
790     int cfd_connected = 0, ret = 0;
791     socklen_t slen = sizeof(sin);
792     int afd = -1;
793
794     *cfd = -1;
795     *sfd = -1;
796
797     memset ((char *) &sin, 0, sizeof(sin));
798     sin.sin_family = AF_INET;
799     sin.sin_addr.s_addr = inet_addr(host);
800
801     afd = socket(AF_INET, SOCK_STREAM, 0);
802     if (afd < 0)
803         return 0;
804
805     if (bind(afd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
806         goto out;
807
808     if (getsockname(afd, (struct sockaddr*)&sin, &slen) < 0)
809         goto out;
810
811     if (listen(afd, 1) < 0)
812         goto out;
813
814     *cfd = socket(AF_INET, SOCK_STREAM, 0);
815     if (*cfd < 0)
816         goto out;
817
818     if (set_nb(afd) == -1)
819         goto out;
820
821     while (*sfd == -1 || !cfd_connected ) {
822         *sfd = accept(afd, NULL, 0);
823         if (*sfd == -1 && errno != EAGAIN)
824             goto out;
825
826         if (!cfd_connected && connect(*cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
827             goto out;
828         else
829             cfd_connected = 1;
830     }
831
832     if (set_nb(*cfd) == -1 || set_nb(*sfd) == -1)
833         goto out;
834     ret = 1;
835     goto success;
836
837 out:
838         if (*cfd != -1)
839             close(*cfd);
840         if (*sfd != -1)
841             close(*sfd);
842 success:
843         if (afd != -1)
844             close(afd);
845     return ret;
846 }
847
848 int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
849                           SSL **cssl, int sfd, int cfd)
850 {
851     SSL *serverssl = NULL, *clientssl = NULL;
852     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
853
854     if (*sssl != NULL)
855         serverssl = *sssl;
856     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
857         goto error;
858     if (*cssl != NULL)
859         clientssl = *cssl;
860     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
861         goto error;
862
863     if (!TEST_ptr(s_to_c_bio = BIO_new_socket(sfd, BIO_NOCLOSE))
864             || !TEST_ptr(c_to_s_bio = BIO_new_socket(cfd, BIO_NOCLOSE)))
865         goto error;
866
867     SSL_set_bio(clientssl, c_to_s_bio, c_to_s_bio);
868     SSL_set_bio(serverssl, s_to_c_bio, s_to_c_bio);
869     *sssl = serverssl;
870     *cssl = clientssl;
871     return 1;
872
873  error:
874     SSL_free(serverssl);
875     SSL_free(clientssl);
876     BIO_free(s_to_c_bio);
877     BIO_free(c_to_s_bio);
878     return 0;
879 }
880 #endif
881
882 /*
883  * NOTE: Transfers control of the BIOs - this function will free them on error
884  */
885 int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
886                           SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio)
887 {
888     SSL *serverssl = NULL, *clientssl = NULL;
889     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
890
891     if (*sssl != NULL)
892         serverssl = *sssl;
893     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
894         goto error;
895     if (*cssl != NULL)
896         clientssl = *cssl;
897     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
898         goto error;
899
900     if (SSL_is_dtls(clientssl)) {
901         if (!TEST_ptr(s_to_c_bio = BIO_new(bio_s_mempacket_test()))
902                 || !TEST_ptr(c_to_s_bio = BIO_new(bio_s_mempacket_test())))
903             goto error;
904     } else {
905         if (!TEST_ptr(s_to_c_bio = BIO_new(BIO_s_mem()))
906                 || !TEST_ptr(c_to_s_bio = BIO_new(BIO_s_mem())))
907             goto error;
908     }
909
910     if (s_to_c_fbio != NULL
911             && !TEST_ptr(s_to_c_bio = BIO_push(s_to_c_fbio, s_to_c_bio)))
912         goto error;
913     if (c_to_s_fbio != NULL
914             && !TEST_ptr(c_to_s_bio = BIO_push(c_to_s_fbio, c_to_s_bio)))
915         goto error;
916
917     /* Set Non-blocking IO behaviour */
918     BIO_set_mem_eof_return(s_to_c_bio, -1);
919     BIO_set_mem_eof_return(c_to_s_bio, -1);
920
921     /* Up ref these as we are passing them to two SSL objects */
922     SSL_set_bio(serverssl, c_to_s_bio, s_to_c_bio);
923     BIO_up_ref(s_to_c_bio);
924     BIO_up_ref(c_to_s_bio);
925     SSL_set_bio(clientssl, s_to_c_bio, c_to_s_bio);
926     *sssl = serverssl;
927     *cssl = clientssl;
928     return 1;
929
930  error:
931     SSL_free(serverssl);
932     SSL_free(clientssl);
933     BIO_free(s_to_c_bio);
934     BIO_free(c_to_s_bio);
935     BIO_free(s_to_c_fbio);
936     BIO_free(c_to_s_fbio);
937
938     return 0;
939 }
940
941 /*
942  * Create an SSL connection, but does not ready any post-handshake
943  * NewSessionTicket messages.
944  * If |read| is set and we're using DTLS then we will attempt to SSL_read on
945  * the connection once we've completed one half of it, to ensure any retransmits
946  * get triggered.
947  */
948 int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want,
949                                int read)
950 {
951     int retc = -1, rets = -1, err, abortctr = 0;
952     int clienterr = 0, servererr = 0;
953     int isdtls = SSL_is_dtls(serverssl);
954
955     do {
956         err = SSL_ERROR_WANT_WRITE;
957         while (!clienterr && retc <= 0 && err == SSL_ERROR_WANT_WRITE) {
958             retc = SSL_connect(clientssl);
959             if (retc <= 0)
960                 err = SSL_get_error(clientssl, retc);
961         }
962
963         if (!clienterr && retc <= 0 && err != SSL_ERROR_WANT_READ) {
964             TEST_info("SSL_connect() failed %d, %d", retc, err);
965             clienterr = 1;
966         }
967         if (want != SSL_ERROR_NONE && err == want)
968             return 0;
969
970         err = SSL_ERROR_WANT_WRITE;
971         while (!servererr && rets <= 0 && err == SSL_ERROR_WANT_WRITE) {
972             rets = SSL_accept(serverssl);
973             if (rets <= 0)
974                 err = SSL_get_error(serverssl, rets);
975         }
976
977         if (!servererr && rets <= 0
978                 && err != SSL_ERROR_WANT_READ
979                 && err != SSL_ERROR_WANT_X509_LOOKUP) {
980             TEST_info("SSL_accept() failed %d, %d", rets, err);
981             servererr = 1;
982         }
983         if (want != SSL_ERROR_NONE && err == want)
984             return 0;
985         if (clienterr && servererr)
986             return 0;
987         if (isdtls && read) {
988             unsigned char buf[20];
989
990             /* Trigger any retransmits that may be appropriate */
991             if (rets > 0 && retc <= 0) {
992                 if (SSL_read(serverssl, buf, sizeof(buf)) > 0) {
993                     /* We don't expect this to succeed! */
994                     TEST_info("Unexpected SSL_read() success!");
995                     return 0;
996                 }
997             }
998             if (retc > 0 && rets <= 0) {
999                 if (SSL_read(clientssl, buf, sizeof(buf)) > 0) {
1000                     /* We don't expect this to succeed! */
1001                     TEST_info("Unexpected SSL_read() success!");
1002                     return 0;
1003                 }
1004             }
1005         }
1006         if (++abortctr == MAXLOOPS) {
1007             TEST_info("No progress made");
1008             return 0;
1009         }
1010         if (isdtls && abortctr <= 50 && (abortctr % 10) == 0) {
1011             /*
1012              * It looks like we're just spinning. Pause for a short period to
1013              * give the DTLS timer a chance to do something. We only do this for
1014              * the first few times to prevent hangs.
1015              */
1016             ossl_sleep(50);
1017         }
1018     } while (retc <=0 || rets <= 0);
1019
1020     return 1;
1021 }
1022
1023 /*
1024  * Create an SSL connection including any post handshake NewSessionTicket
1025  * messages.
1026  */
1027 int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want)
1028 {
1029     int i;
1030     unsigned char buf;
1031     size_t readbytes;
1032
1033     if (!create_bare_ssl_connection(serverssl, clientssl, want, 1))
1034         return 0;
1035
1036     /*
1037      * We attempt to read some data on the client side which we expect to fail.
1038      * This will ensure we have received the NewSessionTicket in TLSv1.3 where
1039      * appropriate. We do this twice because there are 2 NewSessionTickets.
1040      */
1041     for (i = 0; i < 2; i++) {
1042         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
1043             if (!TEST_ulong_eq(readbytes, 0))
1044                 return 0;
1045         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
1046                                 SSL_ERROR_WANT_READ)) {
1047             return 0;
1048         }
1049     }
1050
1051     return 1;
1052 }
1053
1054 void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl)
1055 {
1056     SSL_shutdown(clientssl);
1057     SSL_shutdown(serverssl);
1058     SSL_free(serverssl);
1059     SSL_free(clientssl);
1060 }