Welcome to mirror list, hosted at ThFree Co, Russian Federation.

tls_common.c « methods « record « ssl - github.com/openssl/openssl.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 730e4f7d63ea3eb3f8488f86071156b485d31174 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
/*
 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

#include <assert.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/core_names.h>
#include <openssl/comp.h>
#include <openssl/ssl.h>
#include "internal/e_os.h"
#include "internal/packet.h"
#include "../../ssl_local.h"
#include "../record_local.h"
#include "recmethod_local.h"

static void tls_int_free(OSSL_RECORD_LAYER *rl);

void SSL3_BUFFER_release(SSL3_BUFFER *b)
{
    OPENSSL_free(b->buf);
    b->buf = NULL;
}

void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
                       const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
    va_end(args);

    rl->alert = al;
}

int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
                                     EVP_CIPHER_CTX *ctx,
                                     const EVP_CIPHER *ciph,
                                     const EVP_MD *md)
{
    /*
     * Provided cipher, the TLS padding/MAC removal is performed provider
     * side so we need to tell the ctx about our TLS version and mac size
     */
    OSSL_PARAM params[3], *pprm = params;
    size_t macsize = 0;
    int imacsize = -1;

    if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
            && !rl->use_etm)
        imacsize = EVP_MD_get_size(md);
    if (imacsize >= 0)
        macsize = (size_t)imacsize;

    *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
                                       &rl->version);
    *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
                                          &macsize);
    *pprm = OSSL_PARAM_construct_end();

    if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
        ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
        return 0;
    }

    return 1;
}

/*
 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
 * which ssl3_cbc_digest_record supports.
 */
char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
{
    switch (EVP_MD_CTX_get_type(ctx)) {
    case NID_md5:
    case NID_sha1:
    case NID_sha224:
    case NID_sha256:
    case NID_sha384:
    case NID_sha512:
        return 1;
    default:
        return 0;
    }
}

#ifndef OPENSSL_NO_COMP
static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
{
    if (rl->options & SSL_OP_NO_COMPRESSION)
        return 0;

    return rl->security == NULL
           || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
}
#endif

static void tls_release_write_buffer_int(OSSL_RECORD_LAYER *rl, size_t start)
{
    SSL3_BUFFER *wb;
    size_t pipes;

    pipes = rl->numwpipes;

    while (pipes > start) {
        wb = &rl->wbuf[pipes - 1];

        if (SSL3_BUFFER_is_app_buffer(wb))
            SSL3_BUFFER_set_app_buffer(wb, 0);
        else
            OPENSSL_free(wb->buf);
        wb->buf = NULL;
        pipes--;
    }
}

int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
                           size_t firstlen, size_t nextlen)
{
    unsigned char *p;
    size_t align = 0, headerlen;
    SSL3_BUFFER *wb;
    size_t currpipe;
    size_t defltlen = 0;

    if (firstlen == 0 || (numwpipes > 1 && nextlen == 0)) {
        if (rl->isdtls)
            headerlen = DTLS1_RT_HEADER_LENGTH + 1;
        else
            headerlen = SSL3_RT_HEADER_LENGTH;

#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
        align = SSL3_ALIGN_PAYLOAD - 1;
#endif

        defltlen = rl->max_frag_len + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
                   + headerlen + align;
#ifndef OPENSSL_NO_COMP
        if (tls_allow_compression(rl))
            defltlen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
#endif
        if (!(rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
            defltlen += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
    }

    wb = rl->wbuf;
    for (currpipe = 0; currpipe < numwpipes; currpipe++) {
        SSL3_BUFFER *thiswb = &wb[currpipe];
        size_t len = (currpipe == 0) ? firstlen : nextlen;

        if (len == 0)
            len = defltlen;

        if (thiswb->len != len) {
            OPENSSL_free(thiswb->buf);
            thiswb->buf = NULL;         /* force reallocation */
        }

        p = thiswb->buf;
        if (p == NULL) {
            p = OPENSSL_malloc(len);
            if (p == NULL) {
                if (rl->numwpipes < currpipe)
                    rl->numwpipes = currpipe;
                /*
                 * We've got a malloc failure, and we're still initialising
                 * buffers. We assume we're so doomed that we won't even be able
                 * to send an alert.
                 */
                RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
                return 0;
            }
        }
        memset(thiswb, 0, sizeof(SSL3_BUFFER));
        thiswb->buf = p;
        thiswb->len = len;
    }

    /* Free any previously allocated buffers that we are no longer using */
    tls_release_write_buffer_int(rl, currpipe);

    rl->numwpipes = numwpipes;

    return 1;
}

static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
{
    tls_release_write_buffer_int(rl, 0);

    rl->numwpipes = 0;
}

int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
{
    unsigned char *p;
    size_t len, align = 0, headerlen;
    SSL3_BUFFER *b;

    b = &rl->rbuf;

    if (rl->isdtls)
        headerlen = DTLS1_RT_HEADER_LENGTH;
    else
        headerlen = SSL3_RT_HEADER_LENGTH;

#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
    align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
#endif

    if (b->buf == NULL) {
        len = rl->max_frag_len
              + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
#ifndef OPENSSL_NO_COMP
        if (tls_allow_compression(rl))
            len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
#endif

        /* Ensure our buffer is large enough to support all our pipelines */
        if (rl->max_pipelines > 1)
            len *= rl->max_pipelines;

        if (b->default_len > len)
            len = b->default_len;

        if ((p = OPENSSL_malloc(len)) == NULL) {
            /*
             * We've got a malloc failure, and we're still initialising buffers.
             * We assume we're so doomed that we won't even be able to send an
             * alert.
             */
            RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
            return 0;
        }
        b->buf = p;
        b->len = len;
    }

    return 1;
}

static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
{
    SSL3_BUFFER *b;

    b = &rl->rbuf;
    if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
        OPENSSL_cleanse(b->buf, b->len);
    OPENSSL_free(b->buf);
    b->buf = NULL;
    return 1;
}

/*
 * Return values are as per SSL_read()
 */
int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
                       int clearold, size_t *readbytes)
{
    /*
     * If extend == 0, obtain new n-byte packet; if extend == 1, increase
     * packet by another n bytes. The packet will be in the sub-array of
     * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
     * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
     * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
     * packet to the start of the buffer; if clearold == 0 then leave any old
     * packets where they were
     */
    size_t len, left, align = 0;
    unsigned char *pkt;
    SSL3_BUFFER *rb;

    if (n == 0)
        return OSSL_RECORD_RETURN_NON_FATAL_ERR;

    rb = &rl->rbuf;
    left = rb->left;
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
    align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
    align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif

    if (!extend) {
        /* start with empty packet ... */
        if (left == 0)
            rb->offset = align;

        rl->packet = rb->buf + rb->offset;
        rl->packet_length = 0;
        /* ... now we can act as if 'extend' was set */
    }

    len = rl->packet_length;
    pkt = rb->buf + align;
    /*
     * Move any available bytes to front of buffer: 'len' bytes already
     * pointed to by 'packet', 'left' extra ones at the end
     */
    if (rl->packet != pkt && clearold == 1) {
        memmove(pkt, rl->packet, len + left);
        rl->packet = pkt;
        rb->offset = len + align;
    }

    /*
     * For DTLS/UDP reads should not span multiple packets because the read
     * operation returns the whole packet at once (as long as it fits into
     * the buffer).
     */
    if (rl->isdtls) {
        if (left == 0 && extend) {
            /*
             * We received a record with a header but no body data. This will
             * get dumped.
             */
            return OSSL_RECORD_RETURN_NON_FATAL_ERR;
        }
        if (left > 0 && n > left)
            n = left;
    }

    /* if there is enough in the buffer from a previous read, take some */
    if (left >= n) {
        rl->packet_length += n;
        rb->left = left - n;
        rb->offset += n;
        *readbytes = n;
        return OSSL_RECORD_RETURN_SUCCESS;
    }

    /* else we need to read more data */

    if (n > rb->len - rb->offset) {
        /* does not happen */
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return OSSL_RECORD_RETURN_FATAL;
    }

    /* We always act like read_ahead is set for DTLS */
    if (!rl->read_ahead && !rl->isdtls) {
        /* ignore max parameter */
        max = n;
    } else {
        if (max < n)
            max = n;
        if (max > rb->len - rb->offset)
            max = rb->len - rb->offset;
    }

    while (left < n) {
        size_t bioread = 0;
        int ret;
        BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;

        /*
         * Now we have len+left bytes at the front of rl->rbuf.buf and
         * need to read in more until we have len + n (up to len + max if
         * possible)
         */

        clear_sys_error();
        if (bio != NULL) {
            ret = BIO_read(bio, pkt + len + left, max - left);
            if (ret > 0) {
                bioread = ret;
                ret = OSSL_RECORD_RETURN_SUCCESS;
            } else if (BIO_should_retry(bio)) {
                if (rl->prev != NULL) {
                    /*
                     * We were reading from the previous epoch. Now there is no
                     * more data, so swap to the actual transport BIO
                     */
                    BIO_free(rl->prev);
                    rl->prev = NULL;
                    continue;
                }
                ret = OSSL_RECORD_RETURN_RETRY;
            } else if (BIO_eof(bio)) {
                ret = OSSL_RECORD_RETURN_EOF;
            } else {
                ret = OSSL_RECORD_RETURN_FATAL;
            }
        } else {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
            ret = OSSL_RECORD_RETURN_FATAL;
        }

        if (ret <= OSSL_RECORD_RETURN_RETRY) {
            rb->left = left;
            if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
                if (len + left == 0)
                    tls_release_read_buffer(rl);
            return ret;
        }
        left += bioread;
        /*
         * reads should *never* span multiple packets for DTLS because the
         * underlying transport protocol is message oriented as opposed to
         * byte oriented as in the TLS case.
         */
        if (rl->isdtls) {
            if (n > left)
                n = left;       /* makes the while condition false */
        }
    }

    /* done reading, now the book-keeping */
    rb->offset += n;
    rb->left = left - n;
    rl->packet_length += n;
    *readbytes = n;
    return OSSL_RECORD_RETURN_SUCCESS;
}

/*
 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
 * for us in the buffer.
 */
static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
{
    SSL3_BUFFER *rbuf;
    size_t left, len;
    unsigned char *p;

    rbuf = &rl->rbuf;

    p = SSL3_BUFFER_get_buf(rbuf);
    if (p == NULL)
        return 0;

    left = SSL3_BUFFER_get_left(rbuf);

    if (left < SSL3_RT_HEADER_LENGTH)
        return 0;

    p += SSL3_BUFFER_get_offset(rbuf);

    /*
     * We only check the type and record length, we will sanity check version
     * etc later
     */
    if (*p != SSL3_RT_APPLICATION_DATA)
        return 0;

    p += 3;
    n2s(p, len);

    if (left < SSL3_RT_HEADER_LENGTH + len)
        return 0;

    return 1;
}

static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
                                      size_t overhead, int send)
{
    uint32_t max_early_data = rl->max_early_data;

    if (max_early_data == 0) {
        RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
                    SSL_R_TOO_MUCH_EARLY_DATA);
        return 0;
    }

    /* If we are dealing with ciphertext we need to allow for the overhead */
    max_early_data += overhead;

    if (rl->early_data_count + length > max_early_data) {
        RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
                    SSL_R_TOO_MUCH_EARLY_DATA);
        return 0;
    }
    rl->early_data_count += length;

    return 1;
}

/*
 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
 * will be processed per call to tls_get_more_records. Without this limit an
 * attacker could send empty records at a faster rate than we can process and
 * cause tls_get_more_records to loop forever.
 */
#define MAX_EMPTY_RECORDS 32

#define SSL2_RT_HEADER_LENGTH   2

/*-
 * Call this to buffer new input records in rl->rrec.
 * It will return a OSSL_RECORD_RETURN_* value.
 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
 * records have been decoded. For each record 'i':
 * rrec[i].type    - is the type of record
 * rrec[i].data,   - data
 * rrec[i].length, - number of bytes
 * Multiple records will only be returned if the record types are all
 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
 * |max_pipelines|
 */
int tls_get_more_records(OSSL_RECORD_LAYER *rl)
{
    int enc_err, rret;
    int i;
    size_t more, n;
    SSL3_RECORD *rr, *thisrr;
    SSL3_BUFFER *rbuf;
    unsigned char *p;
    unsigned char md[EVP_MAX_MD_SIZE];
    unsigned int version;
    size_t mac_size = 0;
    int imac_size;
    size_t num_recs = 0, max_recs, j;
    PACKET pkt, sslv2pkt;
    SSL_MAC_BUF *macbufs = NULL;
    int ret = OSSL_RECORD_RETURN_FATAL;

    rr = rl->rrec;
    rbuf = &rl->rbuf;
    if (rbuf->buf == NULL) {
        if (!tls_setup_read_buffer(rl)) {
            /* RLAYERfatal() already called */
            return OSSL_RECORD_RETURN_FATAL;
        }
    }

    max_recs = rl->max_pipelines;

    if (max_recs == 0)
        max_recs = 1;

    do {
        thisrr = &rr[num_recs];

        /* check if we have the header */
        if ((rl->rstate != SSL_ST_READ_BODY) ||
            (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
            size_t sslv2len;
            unsigned int type;

            rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
                                     SSL3_BUFFER_get_len(rbuf), 0,
                                     num_recs == 0 ? 1 : 0, &n);

            if (rret < OSSL_RECORD_RETURN_SUCCESS)
                return rret; /* error or non-blocking */

            rl->rstate = SSL_ST_READ_BODY;

            p = rl->packet;
            if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
                RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
                return OSSL_RECORD_RETURN_FATAL;
            }
            sslv2pkt = pkt;
            if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
                    || !PACKET_get_1(&sslv2pkt, &type)) {
                RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
                return OSSL_RECORD_RETURN_FATAL;
            }
            /*
             * The first record received by the server may be a V2ClientHello.
             */
            if (rl->role == OSSL_RECORD_ROLE_SERVER
                    && rl->is_first_record
                    && (sslv2len & 0x8000) != 0
                    && (type == SSL2_MT_CLIENT_HELLO)) {
                /*
                 *  SSLv2 style record
                 *
                 * |num_recs| here will actually always be 0 because
                 * |num_recs > 0| only ever occurs when we are processing
                 * multiple app data records - which we know isn't the case here
                 * because it is an SSLv2ClientHello. We keep it using
                 * |num_recs| for the sake of consistency
                 */
                thisrr->type = SSL3_RT_HANDSHAKE;
                thisrr->rec_version = SSL2_VERSION;

                thisrr->length = sslv2len & 0x7fff;

                if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
                                     - SSL2_RT_HEADER_LENGTH) {
                    RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
                                SSL_R_PACKET_LENGTH_TOO_LONG);
                    return OSSL_RECORD_RETURN_FATAL;
                }
            } else {
                /* SSLv3+ style record */

                /* Pull apart the header into the SSL3_RECORD */
                if (!PACKET_get_1(&pkt, &type)
                        || !PACKET_get_net_2(&pkt, &version)
                        || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
                    if (rl->msg_callback != NULL)
                        rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
                    RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
                    return OSSL_RECORD_RETURN_FATAL;
                }
                thisrr->type = type;
                thisrr->rec_version = version;

                /*
                 * When we call validate_record_header() only records actually
                 * received in SSLv2 format should have the record version set
                 * to SSL2_VERSION. This way validate_record_header() can know
                 * what format the record was in based on the version.
                 */
                if (thisrr->rec_version == SSL2_VERSION) {
                    RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
                                SSL_R_WRONG_VERSION_NUMBER);
                    return OSSL_RECORD_RETURN_FATAL;
                }

                if (rl->msg_callback != NULL)
                    rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);

                if (thisrr->length >
                    SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
                    RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
                                SSL_R_PACKET_LENGTH_TOO_LONG);
                    return OSSL_RECORD_RETURN_FATAL;
                }
            }

            if (!rl->funcs->validate_record_header(rl, thisrr)) {
                /* RLAYERfatal already called */
                return OSSL_RECORD_RETURN_FATAL;
            }

            /* now rl->rstate == SSL_ST_READ_BODY */
        }

        /*
         * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
         * how much more data we need to read for the rest of the record
         */
        if (thisrr->rec_version == SSL2_VERSION) {
            more = thisrr->length + SSL2_RT_HEADER_LENGTH
                   - SSL3_RT_HEADER_LENGTH;
        } else {
            more = thisrr->length;
        }

        if (more > 0) {
            /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */

            rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
            if (rret < OSSL_RECORD_RETURN_SUCCESS)
                return rret;     /* error or non-blocking io */
        }

        /* set state for later operations */
        rl->rstate = SSL_ST_READ_HEADER;

        /*
         * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
         * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
         * + thisrr->length and we have that many bytes in rl->packet
         */
        if (thisrr->rec_version == SSL2_VERSION)
            thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
        else
            thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);

        /*
         * ok, we can now read from 'rl->packet' data into 'thisrr'.
         * thisrr->input points at thisrr->length bytes, which need to be copied
         * into thisrr->data by either the decryption or by the decompression.
         * When the data is 'copied' into the thisrr->data buffer,
         * thisrr->input will be updated to point at the new buffer
         */

        /*
         * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
         * thisrr->length bytes of encrypted compressed stuff.
         */

        /* decrypt in place in 'thisrr->input' */
        thisrr->data = thisrr->input;
        thisrr->orig_len = thisrr->length;

        num_recs++;

        /* we have pulled in a full packet so zero things */
        rl->packet_length = 0;
        rl->is_first_record = 0;
    } while (num_recs < max_recs
             && thisrr->type == SSL3_RT_APPLICATION_DATA
             && RLAYER_USE_EXPLICIT_IV(rl)
             && rl->enc_ctx != NULL
             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
                 & EVP_CIPH_FLAG_PIPELINE) != 0
             && tls_record_app_data_waiting(rl));

    if (num_recs == 1
            && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
               /* The following can happen in tlsany_meth after HRR */
            && rl->version == TLS1_3_VERSION
            && rl->is_first_handshake) {
        /*
         * CCS messages must be exactly 1 byte long, containing the value 0x01
         */
        if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
            RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
                        SSL_R_INVALID_CCS_MESSAGE);
            return OSSL_RECORD_RETURN_FATAL;
        }
        /*
         * CCS messages are ignored in TLSv1.3. We treat it like an empty
         * handshake record
         */
        thisrr->type = SSL3_RT_HANDSHAKE;
        if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
            RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
                        SSL_R_UNEXPECTED_CCS_MESSAGE);
            return OSSL_RECORD_RETURN_FATAL;
        }
        rl->num_recs = 0;
        rl->curr_rec = 0;
        rl->num_released = 0;

        return OSSL_RECORD_RETURN_SUCCESS;
    }

    if (rl->md_ctx != NULL) {
        const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);

        if (tmpmd != NULL) {
            imac_size = EVP_MD_get_size(tmpmd);
            if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
                RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
                return OSSL_RECORD_RETURN_FATAL;
            }
            mac_size = (size_t)imac_size;
        }
    }

    /*
     * If in encrypt-then-mac mode calculate mac from encrypted record. All
     * the details below are public so no timing details can leak.
     */
    if (rl->use_etm && rl->md_ctx != NULL) {
        unsigned char *mac;

        for (j = 0; j < num_recs; j++) {
            thisrr = &rr[j];

            if (thisrr->length < mac_size) {
                RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
                return OSSL_RECORD_RETURN_FATAL;
            }
            thisrr->length -= mac_size;
            mac = thisrr->data + thisrr->length;
            i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
            if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
                RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
                            SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
                return OSSL_RECORD_RETURN_FATAL;
            }
        }
        /*
         * We've handled the mac now - there is no MAC inside the encrypted
         * record
         */
        mac_size = 0;
    }

    if (mac_size > 0) {
        macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
        if (macbufs == NULL) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
            return OSSL_RECORD_RETURN_FATAL;
        }
    }

    enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);

    /*-
     * enc_err is:
     *    0: if the record is publicly invalid, or an internal error, or AEAD
     *       decryption failed, or ETM decryption failed.
     *    1: Success or MTE decryption failed (MAC will be randomised)
     */
    if (enc_err == 0) {
        if (rl->alert != SSL_AD_NO_ALERT) {
            /* RLAYERfatal() already got called */
            goto end;
        }
        if (num_recs == 1
                && rl->skip_early_data != NULL
                && rl->skip_early_data(rl->cbarg)) {
            /*
             * Valid early_data that we cannot decrypt will fail here. We treat
             * it like an empty record.
             */

            thisrr = &rr[0];

            if (!rlayer_early_data_count_ok(rl, thisrr->length,
                                            EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
                /* RLAYERfatal() already called */
                goto end;
            }

            thisrr->length = 0;
            rl->num_recs = 0;
            rl->curr_rec = 0;
            rl->num_released = 0;
            /* Reset the read sequence */
            memset(rl->sequence, 0, sizeof(rl->sequence));
            ret = 1;
            goto end;
        }
        RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
        goto end;
    }
    OSSL_TRACE_BEGIN(TLS) {
        BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
        BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
    } OSSL_TRACE_END(TLS);

    /* r->length is now the compressed data plus mac */
    if (rl->enc_ctx != NULL
            && !rl->use_etm
            && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
        for (j = 0; j < num_recs; j++) {
            SSL_MAC_BUF *thismb = &macbufs[j];

            thisrr = &rr[j];

            i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
            if (i == 0 || thismb == NULL || thismb->mac == NULL
                || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
                enc_err = 0;
            if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
                enc_err = 0;
        }
    }

    if (enc_err == 0) {
        if (rl->alert != SSL_AD_NO_ALERT) {
            /* We already called RLAYERfatal() */
            goto end;
        }
        /*
         * A separate 'decryption_failed' alert was introduced with TLS 1.0,
         * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
         * failure is directly visible from the ciphertext anyway, we should
         * not reveal which kind of error occurred -- this might become
         * visible to an attacker (e.g. via a logfile)
         */
        RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
        goto end;
    }

    for (j = 0; j < num_recs; j++) {
        thisrr = &rr[j];

        if (!rl->funcs->post_process_record(rl, thisrr)) {
            /* RLAYERfatal already called */
            goto end;
        }

        /*
         * Check if the received packet overflows the current
         * Max Fragment Length setting.
         * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
         */
        if (thisrr->length > rl->max_frag_len) {
            RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
            goto end;
        }

        thisrr->off = 0;
        /*-
         * So at this point the following is true
         * thisrr->type   is the type of record
         * thisrr->length == number of bytes in record
         * thisrr->off    == offset to first valid byte
         * thisrr->data   == where to take bytes from, increment after use :-).
         */

        /* just read a 0 length packet */
        if (thisrr->length == 0) {
            if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
                RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
                            SSL_R_RECORD_TOO_SMALL);
                goto end;
            }
        } else {
            rl->empty_record_count = 0;
        }
    }

    if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
        thisrr = &rr[0];
        if (thisrr->type == SSL3_RT_APPLICATION_DATA
                && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
            /* RLAYERfatal already called */
            goto end;
        }
    }

    rl->num_recs = num_recs;
    rl->curr_rec = 0;
    rl->num_released = 0;
    ret = OSSL_RECORD_RETURN_SUCCESS;
 end:
    if (macbufs != NULL) {
        for (j = 0; j < num_recs; j++) {
            if (macbufs[j].alloced)
                OPENSSL_free(macbufs[j].mac);
        }
        OPENSSL_free(macbufs);
    }
    return ret;
}

/* Shared by ssl3_meth and tls1_meth */
int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
{
    size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;

    if (rec->rec_version != rl->version) {
        RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
        return 0;
    }

#ifndef OPENSSL_NO_COMP
    /*
     * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
     * does not include the compression overhead anyway.
     */
    if (rl->compctx == NULL)
        len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
#endif

    if (rec->length > len) {
        RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
                    SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
        return 0;
    }

    return 1;
}

int tls_do_compress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *wr)
{
#ifndef OPENSSL_NO_COMP
    int i;

    i = COMP_compress_block(rl->compctx, wr->data,
                            (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
                            wr->input, (int)wr->length);
    if (i < 0)
        return 0;

    wr->length = i;
    wr->input = wr->data;
    return 1;
#else
    return 0;
#endif
}

int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
{
#ifndef OPENSSL_NO_COMP
    int i;

    if (rec->comp == NULL) {
        rec->comp = (unsigned char *)
            OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
    }
    if (rec->comp == NULL)
        return 0;

    i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
                          rec->data, (int)rec->length);
    if (i < 0)
        return 0;
    else
        rec->length = i;
    rec->data = rec->comp;
    return 1;
#else
    return 0;
#endif
}

/* Shared by tlsany_meth, ssl3_meth and tls1_meth */
int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
{
    if (rl->compctx != NULL) {
        if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
            RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
                        SSL_R_COMPRESSED_LENGTH_TOO_LONG);
            return 0;
        }
        if (!tls_do_uncompress(rl, rec)) {
            RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
                        SSL_R_BAD_DECOMPRESSION);
            return 0;
        }
    }

    if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
        RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
        return 0;
    }

    return 1;
}

/* Shared by tls13_meth and ktls_meth */
int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
{
    if (rec->type != SSL3_RT_APPLICATION_DATA
            && rec->type != SSL3_RT_ALERT
            && rec->type != SSL3_RT_HANDSHAKE) {
        RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
        return 0;
    }

    if (rl->msg_callback != NULL)
        rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
                        1, rl->cbarg);

    /*
     * TLSv1.3 alert and handshake records are required to be non-zero in
     * length.
     */
    if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
            && rec->length == 0) {
        RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
        return 0;
    }

    return 1;
}

int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
                    int *type, unsigned char **data, size_t *datalen,
                    uint16_t *epoch, unsigned char *seq_num)
{
    SSL3_RECORD *rec;

    /*
     * tls_get_more_records() can return success without actually reading
     * anything useful (i.e. if empty records are read). We loop here until
     * we have something useful. tls_get_more_records() will eventually fail if
     * too many sequential empty records are read.
     */
    while (rl->curr_rec >= rl->num_recs) {
        int ret;

        if (rl->num_released != rl->num_recs) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
            return OSSL_RECORD_RETURN_FATAL;
        }

        ret = rl->funcs->get_more_records(rl);

        if (ret != OSSL_RECORD_RETURN_SUCCESS)
            return ret;
    }

    /*
     * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
     * points to the next one to read.
     */
    rec = &rl->rrec[rl->curr_rec++];

    *rechandle = rec;
    *rversion = rec->rec_version;
    *type = rec->type;
    *data = rec->data + rec->off;
    *datalen = rec->length;
    if (rl->isdtls) {
        *epoch = rec->epoch;
        memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
    }

    return OSSL_RECORD_RETURN_SUCCESS;
}

int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
{
    if (!ossl_assert(rl->num_released < rl->curr_rec)
            || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
        /* Should not happen */
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
        return OSSL_RECORD_RETURN_FATAL;
    }

    rl->num_released++;

    if (rl->curr_rec == rl->num_released
            && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
            && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
        tls_release_read_buffer(rl);

    return OSSL_RECORD_RETURN_SUCCESS;
}

int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
{
    const OSSL_PARAM *p;

    p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
    if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
        ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
        return 0;
    }

    p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
    if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
        ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
        return 0;
    }

    if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
        p = OSSL_PARAM_locate_const(options,
                                    OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
        if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
            ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
    } else {
        p = OSSL_PARAM_locate_const(options,
                                    OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
        if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
            ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
    }

    if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
        /*
         * We ignore any read_ahead setting prior to the application protection
         * level. Otherwise we may read ahead data in a lower protection level
         * that is destined for a higher protection level. To simplify the logic
         * we don't support that at this stage.
         */
        p = OSSL_PARAM_locate_const(options,
                                    OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
        if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
            ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
    }

    return 1;
}

int
tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
                         int role, int direction, int level, unsigned char *key,
                         size_t keylen, unsigned char *iv, size_t ivlen,
                         unsigned char *mackey, size_t mackeylen,
                         const EVP_CIPHER *ciph, size_t taglen,
                         int mactype,
                         const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
                         BIO *transport, BIO *next, BIO_ADDR *local,
                         BIO_ADDR *peer, const OSSL_PARAM *settings,
                         const OSSL_PARAM *options,
                         const OSSL_DISPATCH *fns, void *cbarg,
                         OSSL_RECORD_LAYER **retrl)
{
    OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
    const OSSL_PARAM *p;

    *retrl = NULL;

    if (rl == NULL)
        return OSSL_RECORD_RETURN_FATAL;

    /*
     * Default the value for max_frag_len. This may be overridden by the
     * settings
     */
    rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH;

    /* Loop through all the settings since they must all be understood */
    if (settings != NULL) {
        for (p = settings; p->key != NULL; p++) {
            if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
                if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
                    ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
                    goto err;
                }
            } else if (strcmp(p->key,
                              OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
                if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
                    ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
                    goto err;
                }
            } else if (strcmp(p->key,
                              OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
                if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
                    ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
                    goto err;
                }
            } else if (strcmp(p->key,
                              OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
                if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
                    ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
                    goto err;
                }
            } else if (strcmp(p->key,
                              OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
                if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
                    ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
                    goto err;
                }
            } else {
                ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
                goto err;
            }
        }
    }

    rl->libctx = libctx;
    rl->propq = propq;

    rl->version = vers;
    rl->role = role;
    rl->direction = direction;
    rl->level = level;
    rl->taglen = taglen;
    rl->md = md;

    rl->alert = SSL_AD_NO_ALERT;

    if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
        rl->is_first_record = 1;

    if (!tls_set1_bio(rl, transport))
        goto err;

    if (prev != NULL && !BIO_up_ref(prev))
        goto err;
    rl->prev = prev;

    if (next != NULL && !BIO_up_ref(next))
        goto err;
    rl->next = next;

    rl->cbarg = cbarg;
    if (fns != NULL) {
        for (; fns->function_id != 0; fns++) {
            switch (fns->function_id) {
            case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
                rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
                break;
            case OSSL_FUNC_RLAYER_MSG_CALLBACK:
                rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
                break;
            case OSSL_FUNC_RLAYER_SECURITY:
                rl->security = OSSL_FUNC_rlayer_security(fns);
                break;
            case OSSL_FUNC_RLAYER_PADDING:
                rl->padding = OSSL_FUNC_rlayer_padding(fns);
            default:
                /* Just ignore anything we don't understand */
                break;
            }
        }
    }

    if (!tls_set_options(rl, options)) {
        ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
        goto err;
    }

    if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
            && rl->version <= TLS1_VERSION
            && !EVP_CIPHER_is_a(ciph, "NULL")
            && !EVP_CIPHER_is_a(ciph, "RC4")) {
        /*
         * Enable vulnerability countermeasure for CBC ciphers with known-IV
         * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
         */
        rl->need_empty_fragments = 1;
    }

    *retrl = rl;
    return OSSL_RECORD_RETURN_SUCCESS;
 err:
    tls_int_free(rl);
    return OSSL_RECORD_RETURN_FATAL;
}

static int
tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
                     int role, int direction, int level, uint16_t epoch,
                     unsigned char *key, size_t keylen, unsigned char *iv,
                     size_t ivlen, unsigned char *mackey, size_t mackeylen,
                     const EVP_CIPHER *ciph, size_t taglen,
                     int mactype,
                     const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
                     BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
                     const OSSL_PARAM *settings, const OSSL_PARAM *options,
                     const OSSL_DISPATCH *fns, void *cbarg,
                     OSSL_RECORD_LAYER **retrl)
{
    int ret;

    ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
                                   key, keylen, iv, ivlen, mackey, mackeylen,
                                   ciph, taglen, mactype, md, comp, prev,
                                   transport, next, local, peer, settings,
                                   options, fns, cbarg, retrl);

    if (ret != OSSL_RECORD_RETURN_SUCCESS)
        return ret;

    switch (vers) {
    case TLS_ANY_VERSION:
        (*retrl)->funcs = &tls_any_funcs;
        break;
    case TLS1_3_VERSION:
        (*retrl)->funcs = &tls_1_3_funcs;
        break;
    case TLS1_2_VERSION:
    case TLS1_1_VERSION:
    case TLS1_VERSION:
        (*retrl)->funcs = &tls_1_funcs;
        break;
    case SSL3_VERSION:
        (*retrl)->funcs = &ssl_3_0_funcs;
        break;
    default:
        /* Should not happen */
        ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
        ret = OSSL_RECORD_RETURN_FATAL;
        goto err;
    }

    ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
                                            ivlen, mackey, mackeylen, ciph,
                                            taglen, mactype, md, comp);

 err:
    if (ret != OSSL_RECORD_RETURN_SUCCESS) {
        OPENSSL_free(*retrl);
        *retrl = NULL;
    }
    return ret;
}

static void tls_int_free(OSSL_RECORD_LAYER *rl)
{
    BIO_free(rl->prev);
    BIO_free(rl->bio);
    BIO_free(rl->next);
    SSL3_BUFFER_release(&rl->rbuf);

    tls_release_write_buffer(rl);

    EVP_CIPHER_CTX_free(rl->enc_ctx);
    EVP_MD_CTX_free(rl->md_ctx);
#ifndef OPENSSL_NO_COMP
    COMP_CTX_free(rl->compctx);
#endif

    if (rl->version == SSL3_VERSION)
        OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));

    SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);

    OPENSSL_free(rl);
}

int tls_free(OSSL_RECORD_LAYER *rl)
{
    SSL3_BUFFER *rbuf;
    size_t left, written;
    int ret = 1;

    if (rl == NULL)
        return 1;

    rbuf = &rl->rbuf;

    left = SSL3_BUFFER_get_left(rbuf);
    if (left > 0) {
        /*
         * This record layer is closing but we still have data left in our
         * buffer. It must be destined for the next epoch - so push it there.
         */
        ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
    }
    tls_int_free(rl);

    return ret;
}

int tls_reset(OSSL_RECORD_LAYER *rl)
{
    memset(rl, 0, sizeof(*rl));
    return 1;
}

int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
{
    return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
}

int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
{
    return rl->curr_rec < rl->num_recs;
}

size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
{
    size_t i;
    size_t num = 0;

    for (i = rl->curr_rec; i < rl->num_recs; i++) {
        if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
            return num;
        num += rl->rrec[i].length;
    }
    return num;
}

size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, int type, size_t len,
                                   size_t maxfrag, size_t *preffrag)
{
    /*
     * If we have a pipeline capable cipher, and we have been configured to use
     * it, then return the preferred number of pipelines.
     */
    if (rl->max_pipelines > 0
            && rl->enc_ctx != NULL
            && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
                & EVP_CIPH_FLAG_PIPELINE) != 0
            && RLAYER_USE_EXPLICIT_IV(rl)) {
        size_t pipes;

        if (len == 0)
            return 1;
        pipes = ((len - 1) / *preffrag) + 1;

        return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
    }

    return 1;
}

size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
                           size_t maxfrag, size_t *preffrag)
{
    return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
}

int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
                                         OSSL_RECORD_TEMPLATE *templates,
                                         size_t numtempl,
                                         size_t *prefix)
{
    if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
        /* RLAYERfatal() already called */
        return 0;
    }

    return 1;
}

int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
                                         OSSL_RECORD_TEMPLATE *templates,
                                         size_t numtempl,
                                         OSSL_RECORD_TEMPLATE *prefixtempl,
                                         WPACKET *pkt,
                                         SSL3_BUFFER *bufs,
                                         size_t *wpinited)
{
    WPACKET *thispkt;
    size_t j, align;
    SSL3_BUFFER *wb;

    for (j = 0; j < numtempl; j++) {
        thispkt = &pkt[j];
        wb = &bufs[j];

        wb->type = templates[j].type;

#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
        align = (size_t)SSL3_BUFFER_get_buf(wb);
        align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
        align = SSL3_ALIGN_PAYLOAD - 1
                - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
        SSL3_BUFFER_set_offset(wb, align);

        if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
                                     SSL3_BUFFER_get_len(wb), 0)) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
            return 0;
        }
        (*wpinited)++;
        if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
            return 0;
        }
    }

    return 1;
}

int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
                                      WPACKET *thispkt,
                                      OSSL_RECORD_TEMPLATE *templ,
                                      unsigned int rectype,
                                      unsigned char **recdata)
{
    size_t maxcomplen;

    *recdata = NULL;

    maxcomplen = templ->buflen;
    if (rl->compctx != NULL)
        maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;

    if (!WPACKET_put_bytes_u8(thispkt, rectype)
            || !WPACKET_put_bytes_u16(thispkt, templ->version)
            || !WPACKET_start_sub_packet_u16(thispkt)
            || (rl->eivlen > 0
                && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
            || (maxcomplen > 0
                && !WPACKET_reserve_bytes(thispkt, maxcomplen,
                                          recdata))) {
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return 0;
    }

    return 1;
}

int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
                                       size_t mac_size,
                                       WPACKET *thispkt,
                                       SSL3_RECORD *thiswr)
{
    size_t len;
    unsigned char *recordstart;

    /*
     * we should still have the output to thiswr->data and the input from
     * wr->input. Length should be thiswr->length. thiswr->data still points
     * in the wb->buf
     */

    if (!rl->use_etm && mac_size != 0) {
        unsigned char *mac;

        if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
                || !rl->funcs->mac(rl, thiswr, mac, 1)) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
            return 0;
        }
    }

    /*
     * Reserve some bytes for any growth that may occur during encryption. If
     * we are adding the MAC independently of the cipher algorithm, then the
     * max encrypted overhead does not need to include an allocation for that
     * MAC
     */
    if (!WPACKET_reserve_bytes(thispkt, SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
                               - mac_size, NULL)
            /*
             * We also need next the amount of bytes written to this
             * sub-packet
             */
            || !WPACKET_get_length(thispkt, &len)) {
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return 0;
    }

    /* Get a pointer to the start of this record excluding header */
    recordstart = WPACKET_get_curr(thispkt) - len;
    SSL3_RECORD_set_data(thiswr, recordstart);
    SSL3_RECORD_reset_input(thiswr);
    SSL3_RECORD_set_length(thiswr, len);

    return 1;
}

int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
                                           size_t mac_size,
                                           OSSL_RECORD_TEMPLATE *thistempl,
                                           WPACKET *thispkt,
                                           SSL3_RECORD *thiswr)
{
    size_t origlen, len;
    size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
                                  : SSL3_RT_HEADER_LENGTH;

    /* Allocate bytes for the encryption overhead */
    if (!WPACKET_get_length(thispkt, &origlen)
               /* Check we allowed enough room for the encryption growth */
            || !ossl_assert(origlen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
                            - mac_size >= thiswr->length)
            /* Encryption should never shrink the data! */
            || origlen > thiswr->length
            || (thiswr->length > origlen
                && !WPACKET_allocate_bytes(thispkt,
                                           thiswr->length - origlen,
                                           NULL))) {
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return 0;
    }
    if (rl->use_etm && mac_size != 0) {
        unsigned char *mac;

        if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
                || !rl->funcs->mac(rl, thiswr, mac, 1)) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
            return 0;
        }

        SSL3_RECORD_add_length(thiswr, mac_size);
    }

    if (!WPACKET_get_length(thispkt, &len)
            || !WPACKET_close(thispkt)) {
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return 0;
    }

    if (rl->msg_callback != NULL) {
        unsigned char *recordstart;

        recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
        rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
                         headerlen, rl->cbarg);

        if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
            unsigned char ctype = thistempl->type;

            rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
                             &ctype, 1, rl->cbarg);
        }
    }

    if (!WPACKET_finish(thispkt)) {
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return 0;
    }

    SSL3_RECORD_add_length(thiswr, headerlen);

    return 1;
}

int tls_write_records_default(OSSL_RECORD_LAYER *rl,
                              OSSL_RECORD_TEMPLATE *templates,
                              size_t numtempl)
{
    WPACKET pkt[SSL_MAX_PIPELINES + 1];
    SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
    WPACKET *thispkt;
    SSL3_RECORD *thiswr;
    int mac_size = 0, ret = 0;
    size_t wpinited = 0;
    size_t j, prefix = 0;
    OSSL_RECORD_TEMPLATE prefixtempl;
    OSSL_RECORD_TEMPLATE *thistempl;

    if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
        mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
        if (mac_size < 0) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
            goto err;
        }
    }

    if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
        /* RLAYERfatal() already called */
        goto err;
    }

    if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
                                             &prefixtempl, pkt, rl->wbuf,
                                             &wpinited)) {
        /* RLAYERfatal() already called */
        goto err;
    }

    /* Clear our SSL3_RECORD structures */
    memset(wr, 0, sizeof(wr));
    for (j = 0; j < numtempl + prefix; j++) {
        unsigned char *compressdata = NULL;
        unsigned int rectype;

        thispkt = &pkt[j];
        thiswr = &wr[j];
        thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];

        /*
         * Default to the record type as specified in the template unless the
         * protocol implementation says differently.
         */
        if (rl->funcs->get_record_type != NULL)
            rectype = rl->funcs->get_record_type(rl, thistempl);
        else
            rectype = thistempl->type;

        SSL3_RECORD_set_type(thiswr, rectype);
        SSL3_RECORD_set_rec_version(thiswr, thistempl->version);

        if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
                                              &compressdata)) {
            /* RLAYERfatal() already called */
            goto err;
        }

        /* lets setup the record stuff. */
        SSL3_RECORD_set_data(thiswr, compressdata);
        SSL3_RECORD_set_length(thiswr, thistempl->buflen);

        SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);

        /*
         * we now 'read' from thiswr->input, thiswr->length bytes into
         * thiswr->data
         */

        /* first we compress */
        if (rl->compctx != NULL) {
            if (!tls_do_compress(rl, thiswr)
                    || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
                RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
                goto err;
            }
        } else if (compressdata != NULL) {
            if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
                RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
                goto err;
            }
            SSL3_RECORD_reset_input(&wr[j]);
        }

        if (rl->funcs->add_record_padding != NULL
                && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
                                                  thiswr)) {
            /* RLAYERfatal() already called */
            goto err;
        }

        if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
            /* RLAYERfatal() already called */
            goto err;
        }
    }

    if (prefix) {
        if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
            if (rl->alert == SSL_AD_NO_ALERT) {
                RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
            }
            goto err;
        }
    }

    if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
        if (rl->alert == SSL_AD_NO_ALERT) {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        }
        goto err;
    }

    for (j = 0; j < numtempl + prefix; j++) {
        thispkt = &pkt[j];
        thiswr = &wr[j];
        thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];

        if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
                                                   thispkt, thiswr)) {
            /* RLAYERfatal() already called */
            goto err;
        }

        /* now let's set up wb */
        SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
    }

    ret = 1;
 err:
    for (j = 0; j < wpinited; j++)
        WPACKET_cleanup(&pkt[j]);
    return ret;
}

int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
                      size_t numtempl)
{
    /* Check we don't have pending data waiting to write */
    if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
                     || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
        return OSSL_RECORD_RETURN_FATAL;
    }

    if (!rl->funcs->write_records(rl, templates, numtempl)) {
        /* RLAYERfatal already called */
        return OSSL_RECORD_RETURN_FATAL;
    }

    rl->nextwbuf = 0;
    /* we now just need to write the buffers */
    return tls_retry_write_records(rl);
}

int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
{
    int i, ret;
    SSL3_BUFFER *thiswb;
    size_t tmpwrit = 0;

    if (rl->nextwbuf >= rl->numwpipes)
        return OSSL_RECORD_RETURN_SUCCESS;

    for (;;) {
        thiswb = &rl->wbuf[rl->nextwbuf];

        clear_sys_error();
        if (rl->bio != NULL) {
            if (rl->funcs->prepare_write_bio != NULL) {
                ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
                if (ret != OSSL_RECORD_RETURN_SUCCESS)
                    return ret;
            }
            i = BIO_write(rl->bio, (char *)
                          &(SSL3_BUFFER_get_buf(thiswb)
                            [SSL3_BUFFER_get_offset(thiswb)]),
                          (unsigned int)SSL3_BUFFER_get_left(thiswb));
            if (i >= 0) {
                tmpwrit = i;
                if (i == 0 && BIO_should_retry(rl->bio))
                    ret = OSSL_RECORD_RETURN_RETRY;
                else
                    ret = OSSL_RECORD_RETURN_SUCCESS;
            } else {
                if (BIO_should_retry(rl->bio))
                    ret = OSSL_RECORD_RETURN_RETRY;
                else
                    ret = OSSL_RECORD_RETURN_FATAL;
            }
        } else {
            RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
            ret = OSSL_RECORD_RETURN_FATAL;
            i = -1;
        }

        /*
         * When an empty fragment is sent on a connection using KTLS,
         * it is sent as a write of zero bytes.  If this zero byte
         * write succeeds, i will be 0 rather than a non-zero value.
         * Treat i == 0 as success rather than an error for zero byte
         * writes to permit this case.
         */
        if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
            SSL3_BUFFER_set_left(thiswb, 0);
            SSL3_BUFFER_add_offset(thiswb, tmpwrit);
            if (++(rl->nextwbuf) < rl->numwpipes)
                continue;

            if (rl->nextwbuf == rl->numwpipes
                    && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
                tls_release_write_buffer(rl);
            return OSSL_RECORD_RETURN_SUCCESS;
        } else if (i <= 0) {
            if (rl->isdtls) {
                /*
                 * For DTLS, just drop it. That's kind of the whole point in
                 * using a datagram service
                 */
                SSL3_BUFFER_set_left(thiswb, 0);
                if (++(rl->nextwbuf) == rl->numwpipes
                        && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
                    tls_release_write_buffer(rl);

            }
            return ret;
        }
        SSL3_BUFFER_add_offset(thiswb, tmpwrit);
        SSL3_BUFFER_sub_left(thiswb, tmpwrit);
    }
}

int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
{
    return rl->alert;
}

int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
{
    if (bio != NULL && !BIO_up_ref(bio))
        return 0;
    BIO_free(rl->bio);
    rl->bio = bio;

    return 1;
}

/* Shared by most methods except tlsany_meth */
int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
{
    if (rl->version != version)
        return 0;

    return 1;
}

int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
{
    return rl->funcs->set_protocol_version(rl, version);
}

void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
{
    rl->allow_plain_alerts = allow;
}

void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
{
    rl->is_first_handshake = first;
}

void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
{
    rl->max_pipelines = max_pipelines;
    if (max_pipelines > 1)
        rl->read_ahead = 1;
}

void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
                   const char **longstr)
{
    const char *shrt, *lng;

    switch (rl->rstate) {
    case SSL_ST_READ_HEADER:
        shrt = "RH";
        lng = "read header";
        break;
    case SSL_ST_READ_BODY:
        shrt = "RB";
        lng = "read body";
        break;
    default:
        shrt = lng = "unknown";
        break;
    }
    if (shortstr != NULL)
        *shortstr = shrt;
    if (longstr != NULL)
        *longstr = lng;
}

const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
{
#ifndef OPENSSL_NO_COMP
    return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
#else
    return NULL;
#endif
}

void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
{
    rl->max_frag_len = max_frag_len;
    /*
     * We don't need to adjust buffer sizes. Write buffer sizes are
     * automatically checked anyway. We should only be changing the read buffer
     * size during the handshake, so we will create a new buffer when we create
     * the new record layer. We can't change the existing buffer because it may
     * already have data in it.
     */
}

int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
{
    int i;

    /* Increment the sequence counter */
    for (i = SEQ_NUM_SIZE; i > 0; i--) {
        ++(rl->sequence[i - 1]);
        if (rl->sequence[i - 1] != 0)
            break;
    }
    if (i == 0) {
        /* Sequence has wrapped */
        RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
        return 0;
    }
    return 1;
}

int tls_alloc_buffers(OSSL_RECORD_LAYER *rl)
{
    if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
        /* If we have a pending write then buffers are already allocated */
        if (rl->nextwbuf < rl->numwpipes)
            return 1;
        /*
         * We assume 1 pipe with default sized buffer. If what we need ends up
         * being a different size to that then it will be reallocated on demand.
         * If we need more than 1 pipe then that will also be allocated on
         * demand
         */
        if (!tls_setup_write_buffer(rl, 1, 0, 0))
            return 0;

        /*
         * Normally when we allocate write buffers we immediately write
         * something into it. In this case we're not doing that so mark the
         * buffer as empty.
         */
        SSL3_BUFFER_set_left(&rl->wbuf[0], 0);
        return 1;
    }

    /* Read direction */

    /* If we have pending data to be read then buffers are already allocated */
    if (rl->curr_rec < rl->num_recs || SSL3_BUFFER_get_left(&rl->rbuf) != 0)
        return 1;
    return tls_setup_read_buffer(rl);
}

int tls_free_buffers(OSSL_RECORD_LAYER *rl)
{
    if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
        if (rl->nextwbuf < rl->numwpipes) {
            /*
             * We may have pending data. If we've just got one empty buffer
             * allocated then it has probably just been alloc'd via
             * tls_alloc_buffers, and it is fine to free it. Otherwise this
             * looks like real pending data and it is an error.
             */
            if (rl->nextwbuf != 0
                    || rl->numwpipes != 1
                    || SSL3_BUFFER_get_left(&rl->wbuf[0]) != 0)
                return 0;
        }
        tls_release_write_buffer(rl);
        return 1;
    }

    /* Read direction */

    /* If we have pending data to be read then fail */
    if (rl->curr_rec < rl->num_recs || SSL3_BUFFER_get_left(&rl->rbuf) != 0)
        return 0;

    return tls_release_read_buffer(rl);
}

const OSSL_RECORD_METHOD ossl_tls_record_method = {
    tls_new_record_layer,
    tls_free,
    tls_reset,
    tls_unprocessed_read_pending,
    tls_processed_read_pending,
    tls_app_data_pending,
    tls_get_max_records,
    tls_write_records,
    tls_retry_write_records,
    tls_read_record,
    tls_release_record,
    tls_get_alert_code,
    tls_set1_bio,
    tls_set_protocol_version,
    tls_set_plain_alerts,
    tls_set_first_handshake,
    tls_set_max_pipelines,
    NULL,
    tls_get_state,
    tls_set_options,
    tls_get_compression,
    tls_set_max_frag_len,
    NULL,
    tls_increment_sequence_ctr,
    tls_alloc_buffers,
    tls_free_buffers
};