wolfssl-sys 4.0.0

System bindings for WolfSSL
Documentation
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
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
/* internal.h
 *
 * Copyright (C) 2006-2026 wolfSSL Inc.
 *
 * This file is part of wolfSSL.
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
 */



#ifndef WOLFSSL_INT_H
#define WOLFSSL_INT_H

#include <wolfssl/wolfcrypt/types.h>
#include <wolfssl/ssl.h>
#include <wolfssl/wolfio.h>
#ifdef HAVE_CRL
    #include <wolfssl/crl.h>
#endif
#include <wolfssl/wolfcrypt/random.h>
#ifndef NO_DES3
    #include <wolfssl/wolfcrypt/des3.h>
#endif
#ifdef HAVE_CHACHA
    #include <wolfssl/wolfcrypt/chacha.h>
#endif
#ifndef NO_ASN
    #include <wolfssl/wolfcrypt/asn.h>
    #include <wolfssl/wolfcrypt/pkcs12.h>
#endif
#ifndef NO_MD5
    #include <wolfssl/wolfcrypt/md5.h>
#endif
#ifndef NO_SHA
    #include <wolfssl/wolfcrypt/sha.h>
#endif
#ifndef NO_AES
    #include <wolfssl/wolfcrypt/aes.h>
#endif
#ifdef HAVE_POLY1305
    #include <wolfssl/wolfcrypt/poly1305.h>
#endif
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && defined(OPENSSL_EXTRA)
    #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
#endif
#ifdef HAVE_ARIA
    #include <wolfssl/wolfcrypt/port/aria/aria-crypt.h>
#endif
#ifdef HAVE_CAMELLIA
    #include <wolfssl/wolfcrypt/camellia.h>
#endif
#ifdef WOLFSSL_SM4
    #include <wolfssl/wolfcrypt/sm4.h>
#endif
#include <wolfssl/wolfcrypt/logging.h>
#ifndef NO_HMAC
    #include <wolfssl/wolfcrypt/hmac.h>
#endif
#ifndef NO_RC4
    #include <wolfssl/wolfcrypt/arc4.h>
#endif
#ifndef NO_SHA256
    #include <wolfssl/wolfcrypt/sha256.h>
#endif
#if defined(WOLFSSL_SHA384)
    #include <wolfssl/wolfcrypt/sha512.h>
#endif
#ifdef HAVE_OCSP
    #include <wolfssl/ocsp.h>
#endif
#ifdef WOLFSSL_QUIC
    #include <wolfssl/quic.h>
#endif
#ifdef WOLFSSL_SHA384
    #include <wolfssl/wolfcrypt/sha512.h>
#endif
#ifdef WOLFSSL_SHA512
    #include <wolfssl/wolfcrypt/sha512.h>
#endif
#ifdef WOLFSSL_SM3
    #include <wolfssl/wolfcrypt/sm3.h>
#endif
#ifdef HAVE_AESGCM
    #include <wolfssl/wolfcrypt/sha512.h>
#endif
#ifdef WOLFSSL_RIPEMD
    #include <wolfssl/wolfcrypt/ripemd.h>
#endif
#ifndef NO_RSA
    #include <wolfssl/wolfcrypt/rsa.h>
#endif
#ifdef HAVE_ECC
    #include <wolfssl/wolfcrypt/ecc.h>
#endif
#ifdef WOLFSSL_SM2
    #include <wolfssl/wolfcrypt/sm2.h>
#endif
#ifndef NO_DH
    #include <wolfssl/wolfcrypt/dh.h>
#endif
#ifdef HAVE_ED25519
    #include <wolfssl/wolfcrypt/ed25519.h>
#endif
#ifdef HAVE_CURVE25519
    #include <wolfssl/wolfcrypt/curve25519.h>
#endif
#ifdef HAVE_ED448
    #include <wolfssl/wolfcrypt/ed448.h>
#endif
#ifdef HAVE_CURVE448
    #include <wolfssl/wolfcrypt/curve448.h>
#endif
#ifdef HAVE_FALCON
    #include <wolfssl/wolfcrypt/falcon.h>
#endif
#ifdef HAVE_DILITHIUM
    #include <wolfssl/wolfcrypt/dilithium.h>
#endif
#ifdef HAVE_HKDF
    #include <wolfssl/wolfcrypt/kdf.h>
#endif
#ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
        !defined(WOLFSSL_TICKET_ENC_AES128_GCM) && \
        !defined(WOLFSSL_TICKET_ENC_AES256_GCM)
        #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
    #else
        #include <wolfssl/wolfcrypt/aes.h>
    #endif
#endif

#include <wolfssl/wolfcrypt/wc_encrypt.h>
#include <wolfssl/wolfcrypt/hash.h>

#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
    #include <wolfssl/callbacks.h>
#endif
#ifdef WOLFSSL_CALLBACKS
    #include <signal.h>
#endif

#ifdef WOLFSSL_APACHE_MYNEWT
    #if !defined(WOLFSSL_LWIP)
        void mynewt_ctx_clear(void *ctx);
        void* mynewt_ctx_new();
    #endif
#endif

#if !defined(WOLFCRYPT_ONLY) && !defined(INT_MAX)
    /* Needed for TLS/DTLS limit checking (Added in 91aad90c59 Jan 24, 2025) */
    #include <limits.h>
#endif


#ifdef HAVE_LIBZ
    #include "zlib.h"
#endif

#ifdef WOLFSSL_ASYNC_CRYPT
    #include <wolfssl/wolfcrypt/async.h>
#endif

#ifdef OPENSSL_EXTRA
    #ifdef WOLFCRYPT_HAVE_SRP
        #include <wolfssl/wolfcrypt/srp.h>
    #endif
#endif

#ifdef _MSC_VER
    /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
    #pragma warning(disable: 4996)
#endif

#ifdef NO_SHA
    #define WC_SHA_DIGEST_SIZE 20
#endif

#ifdef NO_SHA256
    #define WC_SHA256_DIGEST_SIZE 32
#endif

#ifdef NO_MD5
    #define WC_MD5_DIGEST_SIZE 16
#endif

#ifdef WOLFSSL_IOTSAFE
    #include <wolfssl/wolfcrypt/port/iotsafe/iotsafe.h>
#endif

#if defined(WOLFSSL_RENESAS_TSIP_TLS)
    #include <wolfssl/wolfcrypt/port/Renesas/renesas_tsip_internal.h>
#endif

#include <wolfssl/wolfcrypt/hpke.h>

#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
#include <wolfssl/sniffer.h>
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */

#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION
    #include <CoreFoundation/CoreFoundation.h>
#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */

#ifdef __cplusplus
    extern "C" {
#endif

/* Define or comment out the cipher suites you'd like to be compiled in
   make sure to use at least one BUILD_SSL_xxx or BUILD_TLS_xxx is defined

   When adding cipher suites, add name to cipher_names, idx to cipher_name_idx

   Now that there is a maximum strength crypto build, the following BUILD_XXX
   flags need to be divided into two groups selected by WOLFSSL_MAX_STRENGTH.
   Those that do not use Perfect Forward Security and do not use AEAD ciphers
   need to be switched off. Allowed suites use (EC)DHE, AES-GCM|CCM, or
   CHACHA-POLY.
*/

/* Check that if WOLFSSL_MAX_STRENGTH is set that all the required options are
 * not turned off. */
#if defined(WOLFSSL_MAX_STRENGTH) && \
    ((!defined(HAVE_ECC) && (defined(NO_DH) || defined(NO_RSA))) || \
     (!defined(HAVE_AESGCM) && !defined(HAVE_AESCCM) && \
      (!defined(HAVE_POLY1305) || !defined(HAVE_CHACHA))) || \
     (defined(NO_SHA256) && !defined(WOLFSSL_SHA384)) || \
     !defined(NO_OLD_TLS))

    #error "You are trying to build max strength with requirements disabled."
#endif

#ifndef WOLFSSL_NO_TLS12

#ifndef WOLFSSL_MAX_STRENGTH

#ifdef WOLFSSL_AEAD_ONLY
    /* AES CBC ciphers are not allowed in AEAD only mode */
    #undef HAVE_AES_CBC
#endif

/* When adding new ciphersuites, make sure that they have appropriate
 * guards for WOLFSSL_HARDEN_TLS. */
#if defined(WOLFSSL_HARDEN_TLS) && \
    !defined(WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES)
/* Use a separate define (undef'ed later) to simplify macro logic. */
#define WSSL_HARDEN_TLS WOLFSSL_HARDEN_TLS
#define NO_TLS_DH
#endif

#ifndef WOLFSSL_AEAD_ONLY
    #if !defined(NO_RSA) && !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS)
        /* MUST NOT negotiate RC4 cipher suites
         * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
        #if defined(WOLFSSL_STATIC_RSA)
            #if !defined(NO_SHA)
                #define BUILD_SSL_RSA_WITH_RC4_128_SHA
            #endif
            #if !defined(NO_MD5)
                #define BUILD_SSL_RSA_WITH_RC4_128_MD5
            #endif
        #endif
    #endif

    #if !defined(NO_RSA) && !defined(NO_DES3) && !defined(NO_DES3_TLS_SUITES)
        #if !defined(NO_SHA)
            #if defined(WOLFSSL_STATIC_RSA)
                #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
            #endif
        #endif
    #endif
#endif /* !WOLFSSL_AEAD_ONLY */

    #if !defined(NO_RSA) && !defined(NO_AES) && !defined(NO_TLS)
        #if !defined(NO_SHA) && defined(HAVE_AES_CBC)
            #if defined(WOLFSSL_STATIC_RSA)
                #ifdef WOLFSSL_AES_128
                    #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
                #endif
                #ifdef WOLFSSL_AES_256
                    #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
                #endif
            #endif
        #endif
        #if defined(WOLFSSL_STATIC_RSA)
            #if !defined (NO_SHA256) && defined(HAVE_AES_CBC)
                #ifdef WOLFSSL_AES_128
                    #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
                #endif
                #ifdef WOLFSSL_AES_256
                    #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
                #endif
            #endif
            #if defined (HAVE_AESGCM)
                #ifdef WOLFSSL_AES_128
                    #define BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
                #endif
                #if defined (WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
                    #define BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
                #endif
            #endif
            #if defined (HAVE_AESCCM)
                #ifdef WOLFSSL_AES_128
                    #define BUILD_TLS_RSA_WITH_AES_128_CCM_8
                #endif
                #ifdef WOLFSSL_AES_256
                    #define BUILD_TLS_RSA_WITH_AES_256_CCM_8
                #endif
            #endif
        #endif
    #endif

    #if defined(HAVE_CAMELLIA) && !defined(NO_TLS) && !defined(NO_CAMELLIA_CBC)
        #ifndef NO_RSA
          #if defined(WOLFSSL_STATIC_RSA)
            #if !defined(NO_SHA)
                #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
                #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
            #endif
            #ifndef NO_SHA256
                #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
                #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
            #endif
          #endif
            #if !defined(NO_DH) && !defined(NO_TLS_DH)
              /* SHOULD NOT negotiate cipher suites based on ephemeral
               * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
               * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
              #if !defined(NO_SHA)
                #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
                #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
              #endif
                #ifndef NO_SHA256
                    #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
                    #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
                #endif
            #endif
        #endif
    #endif

#if defined(WOLFSSL_STATIC_PSK)
    #if !defined(NO_PSK) && !defined(NO_AES) && !defined(NO_TLS)
        #if !defined(NO_SHA)
            #ifdef WOLFSSL_AES_128
                #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
            #endif
            #ifdef WOLFSSL_AES_256
                #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
            #endif
        #endif
        #ifndef NO_SHA256
            #ifdef WOLFSSL_AES_128
                #ifdef HAVE_AES_CBC
                    #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
                #endif
                #ifdef HAVE_AESGCM
                    #define BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
                #endif
            #endif /* WOLFSSL_AES_128 */
            #ifdef HAVE_AESCCM
                #ifdef WOLFSSL_AES_128
                    #define BUILD_TLS_PSK_WITH_AES_128_CCM_8
                    #define BUILD_TLS_PSK_WITH_AES_128_CCM
                #endif
                #ifdef WOLFSSL_AES_256
                    #define BUILD_TLS_PSK_WITH_AES_256_CCM_8
                    #define BUILD_TLS_PSK_WITH_AES_256_CCM
                #endif
            #endif
        #endif
        #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
            #ifdef HAVE_AES_CBC
                #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
            #endif
            #ifdef HAVE_AESGCM
                #define BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
            #endif
        #endif
    #endif
#endif

    #if !defined(NO_TLS) && defined(HAVE_NULL_CIPHER)
        #if !defined(NO_RSA)
            #if defined(WOLFSSL_STATIC_RSA)
                #ifndef NO_MD5
                    #define BUILD_TLS_RSA_WITH_NULL_MD5
                #endif
                #if !defined(NO_SHA)
                    #define BUILD_TLS_RSA_WITH_NULL_SHA
                #endif
                #ifndef NO_SHA256
                    #define BUILD_TLS_RSA_WITH_NULL_SHA256
                #endif
            #endif
        #endif
        #if !defined(NO_PSK) && defined(WOLFSSL_STATIC_PSK)
            #if !defined(NO_SHA)
                #define BUILD_TLS_PSK_WITH_NULL_SHA
            #endif
            #ifndef NO_SHA256
                #define BUILD_TLS_PSK_WITH_NULL_SHA256
            #endif
            #ifdef WOLFSSL_SHA384
                #define BUILD_TLS_PSK_WITH_NULL_SHA384
            #endif
        #endif
    #endif

    #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \
        !defined(NO_RSA) && !defined(NO_TLS_DH)
        /* SHOULD NOT negotiate cipher suites based on ephemeral
         * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
         * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */

        #if !defined(NO_SHA)
            #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
                #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
            #endif
            #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
                #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
            #endif
            #if !defined(NO_DES3) && !defined(NO_DES3_TLS_SUITES)
                #define BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
            #endif
        #endif
        #if !defined(NO_SHA256) && defined(HAVE_AES_CBC)
            #ifdef WOLFSSL_AES_128
                #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
            #endif
            #ifdef WOLFSSL_AES_256
                #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
            #endif
        #endif
    #endif

    #if defined(HAVE_ANON) && !defined(NO_TLS) && !defined(NO_DH) && \
        !defined(NO_AES)
        #if !defined(NO_SHA) && defined(HAVE_AES_CBC) && \
                defined(WOLFSSL_AES_128)
            #define BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
        #endif
        #if defined(WOLFSSL_SHA384) && defined(HAVE_AESGCM) && \
                defined(WOLFSSL_AES_256)
            #define BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
        #endif
    #endif

    #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \
        !defined(NO_TLS_DH)
        /* SHOULD NOT negotiate cipher suites based on ephemeral
         * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
         * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
        #ifndef NO_SHA256
            #if !defined(NO_AES) && defined(WOLFSSL_AES_128) && \
                                                           defined(HAVE_AES_CBC)
                #define BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
            #endif
            #ifdef HAVE_NULL_CIPHER
                #define BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
            #endif
        #endif
        #ifdef WOLFSSL_SHA384
            #if !defined(NO_AES) && defined(WOLFSSL_AES_256) && \
                                                           defined(HAVE_AES_CBC)
                #define BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
            #endif
            #ifdef HAVE_NULL_CIPHER
                #define BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
            #endif
        #endif
    #endif

    #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
                                     defined(HAVE_CURVE448)) && !defined(NO_TLS)
        #if !defined(NO_AES)
            #if !defined(NO_SHA) && defined(HAVE_AES_CBC)
                #if !defined(NO_RSA)
                    #ifdef WOLFSSL_AES_128
                        #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
                    #endif
                    #ifdef WOLFSSL_AES_256
                        #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
                    #endif
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                        #ifdef WOLFSSL_AES_128
                            #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
                        #endif
                        #ifdef WOLFSSL_AES_256
                            #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
                        #endif
                    #endif
                #endif

                #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                    #ifdef WOLFSSL_AES_128
                        #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
                    #endif
                    #ifdef WOLFSSL_AES_256
                        #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
                    #endif
                #endif

                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                    #ifdef WOLFSSL_AES_128
                        #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
                    #endif
                    #ifdef WOLFSSL_AES_256
                        #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
                    #endif
                #endif
            #endif /* NO_SHA */
            #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128) && \
                                                           defined(HAVE_AES_CBC)
                #if !defined(NO_RSA)
                    #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                        #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
                    #endif
                #endif
                #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
                #endif
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                    #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
                #endif
            #endif

            #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256) && \
                                                           defined(HAVE_AES_CBC)
                #if !defined(NO_RSA)
                    #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                        #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
                    #endif
                #endif
                #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
                #endif
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                    #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
                #endif
            #endif

            #if defined (HAVE_AESGCM)
                #if !defined(NO_RSA)
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                        #ifdef WOLFSSL_AES_128
                            #define BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
                        #endif
                    #endif
                    #if defined(WOLFSSL_SHA384)
                        #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                            #ifdef WOLFSSL_AES_256
                                #define BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
                            #endif
                        #endif
                    #endif
                #endif

                #if defined(WOLFSSL_STATIC_DH) && defined(WOLFSSL_AES_128) && \
                                                               defined(HAVE_ECC)
                    #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
                #endif

                #if defined(WOLFSSL_SHA384)
                    #if defined(WOLFSSL_STATIC_DH) && \
                                   defined(WOLFSSL_AES_256) && defined(HAVE_ECC)
                        #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
                    #endif
                #endif
            #endif
        #endif /* NO_AES */
        #ifdef HAVE_ARIA
            #define BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256
            #define BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384
        #endif /* HAVE_ARIA */
        #if !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS)
            /* MUST NOT negotiate RC4 cipher suites
             * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
            #if !defined(NO_SHA)
                #if !defined(NO_RSA)
                    #ifndef WOLFSSL_AEAD_ONLY
                        #define BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
                    #endif
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                        #define BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
                    #endif
                #endif

                #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                    #ifndef WOLFSSL_AEAD_ONLY
                        #define BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
                    #endif
                #endif
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                    #define BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
                #endif
            #endif
        #endif
        #if !defined(NO_DES3) && !(defined(WSSL_HARDEN_TLS) && \
                                           WSSL_HARDEN_TLS > 112) && \
            !defined(NO_DES3_TLS_SUITES)
            /* 3DES offers only 112 bits of security.
             * Using guidance from section 5.6.1
             * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
            #ifndef NO_SHA
                #if !defined(NO_RSA)
                    #define BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                        #define BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
                    #endif
                #endif

                #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
                #endif
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
                    #define BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
                #endif
            #endif /* NO_SHA */
        #endif
        #if defined(HAVE_NULL_CIPHER)
            #if !defined(NO_SHA)
                #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
                #endif
            #endif
            #if !defined(NO_PSK) && !defined(NO_SHA256)
                #define BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
            #endif
        #endif
        #if !defined(NO_PSK) && !defined(NO_SHA256) && !defined(NO_AES) && \
            defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
            #define BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
        #endif
        #if !defined(NO_PSK) && !defined(NO_SHA256) && !defined(NO_AES) && \
            defined(WOLFSSL_AES_128) && defined(HAVE_AESGCM)
            #define BUILD_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256
        #endif
    #endif
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && !defined(NO_SHA256)
        #if !defined(NO_OLD_POLY1305)
        #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
            #define BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
        #endif
        #if !defined(NO_RSA) && defined(HAVE_ECC)
            #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
        #endif
        #if !defined(NO_DH) && !defined(NO_RSA) && !defined(NO_TLS_DH)
            /* SHOULD NOT negotiate cipher suites based on ephemeral
             * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
             * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
            #define BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
        #endif
        #endif /* NO_OLD_POLY1305 */
        #if !defined(NO_PSK)
            #define BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
            #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
                                                             defined(HAVE_ED448)
                #define BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
            #endif
            #if !defined(NO_DH) && !defined(NO_TLS_DH)
                /* SHOULD NOT negotiate cipher suites based on ephemeral
                 * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
                 * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
                #define BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
            #endif
        #endif /* !NO_PSK */
    #endif

#endif /* !WOLFSSL_MAX_STRENGTH */

#if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \
    !defined(NO_RSA) && defined(HAVE_AESGCM) && !defined(NO_TLS_DH)
    /* SHOULD NOT negotiate cipher suites based on ephemeral
     * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
     * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */

    #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
        #define BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
    #endif

    #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
        #define BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
    #endif
#endif

#if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \
    !defined(NO_TLS_DH)
    /* SHOULD NOT negotiate cipher suites based on ephemeral
     * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
     * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
    #ifndef NO_SHA256
        #if defined(HAVE_AESGCM) && defined(WOLFSSL_AES_128)
            #define BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
        #endif
        #ifdef HAVE_AESCCM
            #ifdef WOLFSSL_AES_128
                #define BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
            #endif
            #ifdef WOLFSSL_AES_256
                #define BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
            #endif
        #endif
    #endif
    #if defined(WOLFSSL_SHA384) && defined(HAVE_AESGCM) && \
        defined(WOLFSSL_AES_256)
        #define BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
    #endif
#endif

#if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) \
                                         && !defined(NO_TLS) && !defined(NO_AES)
    #ifdef HAVE_AESGCM
        #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
            #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
            #endif
            #ifndef NO_RSA
                #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
            #endif
        #endif
        #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
            #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
            #endif
            #ifndef NO_RSA
                #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
            #endif
        #endif
    #endif
    #if defined(HAVE_AESCCM) && !defined(NO_SHA256)
        #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
            #ifdef WOLFSSL_AES_128
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
            #endif
            #ifdef WOLFSSL_AES_256
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
            #endif
        #endif
    #endif
#endif

#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && !defined(NO_SHA256)
    #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
        #if defined(HAVE_ECC) || \
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
            #define BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
        #endif
        #ifndef NO_RSA
            #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
        #endif
    #endif
    #if !defined(NO_DH) && !defined(NO_RSA) && !defined(NO_TLS_DH)
        /* SHOULD NOT negotiate cipher suites based on ephemeral
         * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
         * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
        #define BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
    #endif
#endif

    #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
        #ifdef WOLFSSL_SM4_CBC
            #define BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
        #endif
        #ifdef WOLFSSL_SM4_GCM
            #define BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
        #endif
        #ifdef WOLFSSL_SM4_CCM
            #define BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
        #endif
    #endif
#endif

#if defined(WOLFSSL_TLS13)
    #ifdef HAVE_AESGCM
        #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
            #define BUILD_TLS_AES_128_GCM_SHA256
        #endif
        #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
            #define BUILD_TLS_AES_256_GCM_SHA384
        #endif
    #endif

    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
        #ifndef NO_SHA256
            #define BUILD_TLS_CHACHA20_POLY1305_SHA256
        #endif
    #endif

    #ifdef HAVE_AESCCM
        #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
            #define BUILD_TLS_AES_128_CCM_SHA256
            #define BUILD_TLS_AES_128_CCM_8_SHA256
        #endif
    #endif
    #ifdef HAVE_NULL_CIPHER
        #ifndef NO_SHA256
            #define BUILD_TLS_SHA256_SHA256
        #endif
        #ifdef WOLFSSL_SHA384
            #define BUILD_TLS_SHA384_SHA384
        #endif
    #endif

    #ifdef WOLFSSL_SM3
        #ifdef WOLFSSL_SM4_GCM
            #define BUILD_TLS_SM4_GCM_SM3
        #endif

        #ifdef WOLFSSL_SM4_CCM
            #define BUILD_TLS_SM4_CCM_SM3
        #endif
    #endif
#endif

#if !defined(WOLFCRYPT_ONLY) && defined(NO_PSK) && \
    (defined(NO_DH) || !defined(HAVE_ANON)) && \
    defined(NO_RSA) && !defined(HAVE_ECC) && \
    !defined(HAVE_ED25519) && !defined(HAVE_ED448)
   #error "No cipher suites available with this build"
#endif

#ifdef WOLFSSL_MULTICAST
    #if defined(HAVE_NULL_CIPHER) && !defined(NO_SHA256)
        #define BUILD_WDM_WITH_NULL_SHA256
    #endif
#endif

#if defined(BUILD_SSL_RSA_WITH_RC4_128_SHA) || \
    defined(BUILD_SSL_RSA_WITH_RC4_128_MD5)
    #define BUILD_ARC4
#endif

#if defined(BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA)
    #define BUILD_DES3
#endif

#if defined(BUILD_TLS_RSA_WITH_AES_128_CBC_SHA) || \
    defined(BUILD_TLS_RSA_WITH_AES_256_CBC_SHA) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256) || \
    defined(BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256)
    #undef  BUILD_AES
    #define BUILD_AES
#endif

#if defined(BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256) || \
    defined(BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) || \
    defined(BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) || \
    defined(BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256) || \
    defined(BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256) || \
    defined(BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384) || \
    defined(BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384) || \
    defined(BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) || \
    defined(BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384) || \
    defined(BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384) || \
    defined(BUILD_TLS_AES_128_GCM_SHA256) || \
    defined(BUILD_TLS_AES_256_GCM_SHA384)
    #define BUILD_AESGCM
#else
    /* No AES-GCM cipher suites available with build */
    #define NO_AESGCM_AEAD
#endif

#if defined(BUILD_TLS_RSA_WITH_AES_128_CCM_8) || \
    defined(BUILD_TLS_RSA_WITH_AES_256_CCM_8) || \
    defined(BUILD_TLS_PSK_WITH_AES_128_CCM_8) || \
    defined(BUILD_TLS_PSK_WITH_AES_128_CCM) || \
    defined(BUILD_TLS_PSK_WITH_AES_256_CCM_8) || \
    defined(BUILD_TLS_PSK_WITH_AES_256_CCM) || \
    defined(BUILD_TLS_DHE_PSK_WITH_AES_128_CCM) || \
    defined(BUILD_TLS_DHE_PSK_WITH_AES_256_CCM) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8) || \
    defined(BUILD_TLS_AES_128_CCM_SHA256) || \
    defined(BUILD_TLS_AES_128_CCM_8_SHA256)
    #define BUILD_AESCCM
#else
    /* No AES-CCM cipher suites available with build */
    #define NO_AESCCM_AEAD
#endif

#if defined(BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384)
    #define BUILD_ARIA
#endif

#if defined(BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256) || \
    defined(BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256) || \
    defined(BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256) || \
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256) || \
    defined(BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256) || \
    defined(BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256) || \
    defined(BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256) || \
    defined(BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256) || \
    defined(BUILD_TLS_CHACHA20_POLY1305_SHA256)
    /* Have an available ChaCha Poly cipher suite */
#else
    /* No ChaCha Poly cipher suites available with build */
    #define NO_CHAPOL_AEAD
#endif

#ifdef NO_DES3
    #define DES_BLOCK_SIZE 8
#else
    #undef  BUILD_DES3
    #define BUILD_DES3
#endif

#if defined(NO_AES) || !defined(HAVE_AES_DECRYPT)
    #undef WC_AES_BLOCK_SIZE
    #define WC_AES_BLOCK_SIZE 16
    #undef  BUILD_AES
#else
    #undef  BUILD_AES
    #define BUILD_AES
#endif

#if !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS)
    /* MUST NOT negotiate RC4 cipher suites
     * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
    #undef  BUILD_ARC4
    #define BUILD_ARC4
#endif

#ifdef HAVE_CHACHA
    #define CHACHA20_BLOCK_SIZE 16
#endif

#if defined(WOLFSSL_MAX_STRENGTH) || \
    (defined(HAVE_AESGCM) && !defined(NO_AESGCM_AEAD)) || \
     defined(HAVE_AESCCM) || \
     defined(HAVE_ARIA) || \
    (defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
     !defined(NO_CHAPOL_AEAD)) || \
    defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) || \
    (defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER))

    #define HAVE_AEAD
#endif

#if defined(WOLFSSL_MAX_STRENGTH) || \
    defined(HAVE_ECC) || !defined(NO_DH)

    #define HAVE_PFS
#endif

#ifdef WSSL_HARDEN_TLS
    #ifdef HAVE_NULL_CIPHER
        #error "NULL ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1"
    #endif
    #ifdef WOLFSSL_STATIC_RSA
        #error "Static RSA ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1"
    #endif
    #ifdef WOLFSSL_STATIC_DH
        #error "Static DH ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1"
    #endif
    #ifdef HAVE_ANON
        #error "At least the server side has to be authenticated"
    #endif
#endif

#undef WSSL_HARDEN_TLS

/* CA Names feature */
#if !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
    #define SSL_CLIENT_CA_NAMES(ssl) ((ssl)->client_ca_names != NULL ? \
        (ssl)->client_ca_names : \
        (ssl)->ctx->client_ca_names)
    #define SSL_CA_NAMES(ssl) ((ssl)->ca_names != NULL ? \
        (ssl)->ca_names : \
        (ssl)->ctx->ca_names)
    /* On the server, client_ca_names has priority over ca_names if both are
     * set. This mimics OpenSSL's API:
     * https://docs.openssl.org/3.6/man3/SSL_CTX_set0_CA_list/ */
    #define SSL_PRIORITY_CA_NAMES(ssl) \
        (((ssl)->options.side == WOLFSSL_SERVER_END && \
        SSL_CLIENT_CA_NAMES(ssl) != NULL) ? \
            SSL_CLIENT_CA_NAMES(ssl) : \
            SSL_CA_NAMES(ssl))
#else
    #undef  WOLFSSL_NO_CA_NAMES
    #define WOLFSSL_NO_CA_NAMES
#endif


/* actual cipher values, 2nd byte */
enum {
    TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x16,
    TLS_DHE_RSA_WITH_AES_256_CBC_SHA  = 0x39,
    TLS_DHE_RSA_WITH_AES_128_CBC_SHA  = 0x33,
    TLS_DH_anon_WITH_AES_128_CBC_SHA  = 0x34,
    TLS_RSA_WITH_AES_256_CBC_SHA      = 0x35,
    TLS_RSA_WITH_AES_128_CBC_SHA      = 0x2F,
    TLS_RSA_WITH_NULL_MD5             = 0x01,
    TLS_RSA_WITH_NULL_SHA             = 0x02,
    TLS_PSK_WITH_AES_256_CBC_SHA      = 0x8d,
    TLS_PSK_WITH_AES_128_CBC_SHA256   = 0xae,
    TLS_PSK_WITH_AES_256_CBC_SHA384   = 0xaf,
    TLS_PSK_WITH_AES_128_CBC_SHA      = 0x8c,
    TLS_PSK_WITH_NULL_SHA256          = 0xb0,
    TLS_PSK_WITH_NULL_SHA384          = 0xb1,
    TLS_PSK_WITH_NULL_SHA             = 0x2c,
    SSL_RSA_WITH_RC4_128_SHA          = 0x05,
    SSL_RSA_WITH_RC4_128_MD5          = 0x04,
    SSL_RSA_WITH_3DES_EDE_CBC_SHA     = 0x0A,

    /* ECC suites, first byte is 0xC0 (ECC_BYTE) */
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA    = 0x14,
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA    = 0x13,
    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA  = 0x0A,
    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA  = 0x09,
    TLS_ECDHE_RSA_WITH_RC4_128_SHA        = 0x11,
    TLS_ECDHE_ECDSA_WITH_RC4_128_SHA      = 0x07,
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA   = 0x12,
    TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x08,
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   = 0x27,
    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0x23,
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   = 0x28,
    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0x24,
    TLS_ECDHE_ECDSA_WITH_NULL_SHA           = 0x06,
    TLS_ECDHE_PSK_WITH_NULL_SHA256          = 0x3a,
    TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256   = 0x37,

    /* static ECDH, first byte is 0xC0 (ECC_BYTE) */
    TLS_ECDH_RSA_WITH_AES_256_CBC_SHA    = 0x0F,
    TLS_ECDH_RSA_WITH_AES_128_CBC_SHA    = 0x0E,
    TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA  = 0x05,
    TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA  = 0x04,
    TLS_ECDH_RSA_WITH_RC4_128_SHA        = 0x0C,
    TLS_ECDH_ECDSA_WITH_RC4_128_SHA      = 0x02,
    TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA   = 0x0D,
    TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x03,
    TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256   = 0x29,
    TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0x25,
    TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384   = 0x2A,
    TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0x26,

    WDM_WITH_NULL_SHA256          = 0xFE, /* wolfSSL DTLS Multicast */

    /* SHA256 */
    TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x6b,
    TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x67,
    TLS_RSA_WITH_AES_256_CBC_SHA256     = 0x3d,
    TLS_RSA_WITH_AES_128_CBC_SHA256     = 0x3c,
    TLS_RSA_WITH_NULL_SHA256            = 0x3b,
    TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = 0xb2,
    TLS_DHE_PSK_WITH_NULL_SHA256        = 0xb4,

    /* SHA384 */
    TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = 0xb3,
    TLS_DHE_PSK_WITH_NULL_SHA384        = 0xb5,

    /* AES-GCM */
    TLS_RSA_WITH_AES_128_GCM_SHA256          = 0x9c,
    TLS_RSA_WITH_AES_256_GCM_SHA384          = 0x9d,
    TLS_DHE_RSA_WITH_AES_128_GCM_SHA256      = 0x9e,
    TLS_DHE_RSA_WITH_AES_256_GCM_SHA384      = 0x9f,
    TLS_DH_anon_WITH_AES_256_GCM_SHA384      = 0xa7,
    TLS_PSK_WITH_AES_128_GCM_SHA256          = 0xa8,
    TLS_PSK_WITH_AES_256_GCM_SHA384          = 0xa9,
    TLS_DHE_PSK_WITH_AES_128_GCM_SHA256      = 0xaa,
    TLS_DHE_PSK_WITH_AES_256_GCM_SHA384      = 0xab,

    /* ECC AES-GCM, first byte is 0xC0 (ECC_BYTE) */
    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256  = 0x2b,
    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384  = 0x2c,
    TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256   = 0x2d,
    TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384   = 0x2e,
    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256    = 0x2f,
    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384    = 0x30,
    TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256     = 0x31,
    TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384     = 0x32,

    /* AES-CCM, first byte is 0xC0 but isn't ECC,
     * also, in some of the other AES-CCM suites
     * there will be second byte number conflicts
     * with non-ECC AES-GCM */
    TLS_RSA_WITH_AES_128_CCM_8         = 0xa0,
    TLS_RSA_WITH_AES_256_CCM_8         = 0xa1,
    TLS_ECDHE_ECDSA_WITH_AES_128_CCM   = 0xac,
    TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xae,
    TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = 0xaf,
    TLS_PSK_WITH_AES_128_CCM           = 0xa4,
    TLS_PSK_WITH_AES_256_CCM           = 0xa5,
    TLS_PSK_WITH_AES_128_CCM_8         = 0xa8,
    TLS_PSK_WITH_AES_256_CCM_8         = 0xa9,
    TLS_DHE_PSK_WITH_AES_128_CCM       = 0xa6,
    TLS_DHE_PSK_WITH_AES_256_CCM       = 0xa7,

    /* Camellia */
    TLS_RSA_WITH_CAMELLIA_128_CBC_SHA        = 0x41,
    TLS_RSA_WITH_CAMELLIA_256_CBC_SHA        = 0x84,
    TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256     = 0xba,
    TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256     = 0xc0,
    TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA    = 0x45,
    TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA    = 0x88,
    TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xbe,
    TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0xc4,

    /* chacha20-poly1305 suites first byte is 0xCC (CHACHA_BYTE) */
    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   = 0xa8,
    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xa9,
    TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     = 0xaa,
    TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256   = 0xac,
    TLS_PSK_WITH_CHACHA20_POLY1305_SHA256         = 0xab,
    TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256     = 0xad,

    /* chacha20-poly1305 earlier version of nonce and padding (CHACHA_BYTE) */
    TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256   = 0x13,
    TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 = 0x14,
    TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256     = 0x15,

    /* ECDHE_PSK RFC8442, first byte is 0xD0 (EDHE_PSK_BYTE) */
    TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256    = 0x01,

    /* TLS v1.3 cipher suites */
    TLS_AES_128_GCM_SHA256       = 0x01,
    TLS_AES_256_GCM_SHA384       = 0x02,
    TLS_CHACHA20_POLY1305_SHA256 = 0x03,
    TLS_AES_128_CCM_SHA256       = 0x04,
    TLS_AES_128_CCM_8_SHA256     = 0x05,

    /* TLS v1.3 Integrity only cipher suites - 0xC0 (ECC) first byte */
    TLS_SHA256_SHA256            = 0xB4,
    TLS_SHA384_SHA384            = 0xB5,

    /* ARIA-GCM, first byte is 0xC0 (ECC_BYTE)
    * See: https://www.rfc-editor.org/rfc/rfc6209.html#section-5
    */
    TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256   = 0x5c,
    TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384   = 0x5d,

    /* TLS v1.3 SM cipher suites - 0x00 (CIPHER_BYTE) is first byte */
    TLS_SM4_GCM_SM3              = 0xC6,
    TLS_SM4_CCM_SM3              = 0xC7,

    /* TLS v1.2 SM cipher suites - 0xE0 (SM_BYTE) is first byte */
    TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 = 0x11,
    TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3 = 0x51,
    TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3 = 0x52,

    /* Fallback SCSV (Signaling Cipher Suite Value) */
    TLS_FALLBACK_SCSV                        = 0x56,
    /* Renegotiation Indication Extension Special Suite */
    TLS_EMPTY_RENEGOTIATION_INFO_SCSV        = 0xff
};


#ifndef WOLFSSL_SESSION_TIMEOUT
    #define WOLFSSL_SESSION_TIMEOUT 500
    /* default session resumption cache timeout in seconds */
#endif


#ifndef WOLFSSL_DTLS_WINDOW_WORDS
    #define WOLFSSL_DTLS_WINDOW_WORDS 2
#endif /* WOLFSSL_DTLS_WINDOW_WORDS */
#define DTLS_WORD_BITS (sizeof(word32) * CHAR_BIT)
#define DTLS_SEQ_BITS  (WOLFSSL_DTLS_WINDOW_WORDS * DTLS_WORD_BITS)
#define DTLS_SEQ_SZ    (sizeof(word32) * WOLFSSL_DTLS_WINDOW_WORDS)

#ifndef WOLFSSL_MULTICAST
    #define WOLFSSL_DTLS_PEERSEQ_SZ 1
#else
    #ifndef WOLFSSL_MULTICAST_PEERS
        /* max allowed multicast group peers */
        #define WOLFSSL_MULTICAST_PEERS 100
    #endif
    #define WOLFSSL_DTLS_PEERSEQ_SZ WOLFSSL_MULTICAST_PEERS
#endif /* WOLFSSL_MULTICAST */

#ifndef WOLFSSL_MAX_MTU
    /* 1500 - 100 bytes to account for UDP and IP headers */
    #define WOLFSSL_MAX_MTU 1400
#endif /* WOLFSSL_MAX_MTU */

#ifndef WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER
    #define WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER 500
#endif /* WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER */

#ifndef WOLFSSL_DTLS_FRAG_POOL_SZ
    #define WOLFSSL_DTLS_FRAG_POOL_SZ 10
#endif

/* set minimum DH key size allowed */
#ifndef WOLFSSL_MIN_DHKEY_BITS
    #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
        /* Using guidance from section 5.6.1
         * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
        #if WOLFSSL_HARDEN_TLS >= 128
            #define WOLFSSL_MIN_DHKEY_BITS 3072
        #elif WOLFSSL_HARDEN_TLS >= 112
            #define WOLFSSL_MIN_DHKEY_BITS 2048
        #endif
    #elif defined(WOLFSSL_MAX_STRENGTH)
        #define WOLFSSL_MIN_DHKEY_BITS 2048
    #else
        #define WOLFSSL_MIN_DHKEY_BITS 1024
    #endif
#endif
#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_DHKEY_BITS < 2048 && \
    !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
    /* Implementations MUST NOT negotiate cipher suites offering less than
     * 112 bits of security.
     * https://www.rfc-editor.org/rfc/rfc9325#section-4.1
     * Using guidance from section 5.6.1
     * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
    #error "For 112 bits of security DH needs at least 2048 bit keys"
#endif
#if (WOLFSSL_MIN_DHKEY_BITS % 8)
    #error DH minimum bit size must be multiple of 8
#endif
#if (WOLFSSL_MIN_DHKEY_BITS > 16000)
    #error DH minimum bit size must not be greater than 16000
#endif
#define MIN_DHKEY_SZ (WOLFSSL_MIN_DHKEY_BITS / 8)
/* set maximum DH key size allowed */
#ifndef WOLFSSL_MAX_DHKEY_BITS
    #if (defined(USE_FAST_MATH) && defined(FP_MAX_BITS) && FP_MAX_BITS >= 16384)
        #define WOLFSSL_MAX_DHKEY_BITS  (FP_MAX_BITS / 2)
    #elif (defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH)) && \
           defined(SP_INT_BITS)
        /* SP implementation supports numbers of SP_INT_BITS bits. */
        #define WOLFSSL_MAX_DHKEY_BITS  WC_BITS_FULL_BYTES(SP_INT_BITS)
    #else
        #define WOLFSSL_MAX_DHKEY_BITS  4096
    #endif
#endif
#if (WOLFSSL_MAX_DHKEY_BITS % 8)
    #error DH maximum bit size must be multiple of 8
#endif
#if (WOLFSSL_MAX_DHKEY_BITS > 16384)
    #error DH maximum bit size must not be greater than 16384
#endif
#define MAX_DHKEY_SZ (WOLFSSL_MAX_DHKEY_BITS / 8)

#ifndef NO_DH
#if WOLFSSL_MAX_DHKEY_BITS < WOLFSSL_MIN_DHKEY_BITS
#error "WOLFSSL_MAX_DHKEY_BITS has to be greater than WOLFSSL_MIN_DHKEY_BITS"
#endif
#endif /* NO_DH */

#ifndef MAX_PSK_KEY_LEN
    #define MAX_PSK_KEY_LEN 64
#endif

#ifndef MAX_EARLY_DATA_SZ
    /* maximum early data size */
    #define MAX_EARLY_DATA_SZ  4096
#endif


#if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC)
    /* MySQL wants to be able to use 8192-bit numbers. */
    #if defined(USE_FAST_MATH) && defined(FP_MAX_BITS)
        /* Use the FP size up to 8192-bit and down to a min of 1024-bit. */
        #if FP_MAX_BITS >= 16384
            #define ENCRYPT_BASE_BITS  8192
        #elif defined(HAVE_ECC)
            #if FP_MAX_BITS > 2224
                #define ENCRYPT_BASE_BITS  (FP_MAX_BITS / 2)
            #else
                /* 521-bit ASN.1 signature - 3 + 2 * (2 + 66) bytes. */
                #define ENCRYPT_BASE_BITS  1112
            #endif
        #else
            #if FP_MAX_BITS > 2048
                #define ENCRYPT_BASE_BITS  (FP_MAX_BITS / 2)
            #else
                #define ENCRYPT_BASE_BITS  1024
            #endif
        #endif

        /* Check MySQL size requirements met. */
        #if defined(WOLFSSL_MYSQL_COMPATIBLE) && ENCRYPT_BASE_BITS < 8192
            #error "MySQL needs FP_MAX_BITS at least at 16384"
        #endif

        #if !defined(NO_RSA) && defined(WC_MAX_RSA_BITS) && \
            WC_MAX_RSA_BITS > ENCRYPT_BASE_BITS
            #error "FP_MAX_BITS too small for WC_MAX_RSA_BITS"
        #endif
    #elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH)
        /* Use the SP size up to 8192-bit and down to a min of 1024-bit. */
        #if SP_INT_BITS >= 8192
            #define ENCRYPT_BASE_BITS  8192
        #elif defined(HAVE_ECC)
            #if SP_INT_BITS > 1112
                #define ENCRYPT_BASE_BITS  SP_INT_BITS
            #else
                /* 521-bit ASN.1 signature - 3 + 2 * (2 + 66) bytes. */
                #define ENCRYPT_BASE_BITS  1112
            #endif
        #else
            #if SP_INT_BITS > 1024
                #define ENCRYPT_BASE_BITS  SP_INT_BITS
            #else
                #define ENCRYPT_BASE_BITS  1024
            #endif
        #endif

        /* Check MySQL size requirements met. */
        #if defined(WOLFSSL_MYSQL_COMPATIBLE) && ENCRYPT_BASE_BITS < 8192
            #error "MySQL needs SP_INT_BITS at least at 8192"
        #endif

        #if !defined(NO_RSA) && defined(WC_MAX_RSA_BITS) && \
            WC_MAX_RSA_BITS > SP_INT_BITS
            #error "SP_INT_BITS too small for WC_MAX_RSA_BITS"
        #endif
    #else
        /* Integer/heap maths - support 4096-bit. */
        #define ENCRYPT_BASE_BITS  4096
    #endif
#elif defined(HAVE_CURVE448)
    #define ENCRYPT_BASE_BITS    (456 * 2)
#elif defined(HAVE_CURVE25519)
    #define ENCRYPT_BASE_BITS    (256 * 2)
#else
    /* No secret from public key operation but PSK key plus length used. */
    #define ENCRYPT_BASE_BITS  ((MAX_PSK_KEY_LEN + 2) * 8)
#endif

#ifdef WOLFSSL_DTLS_CID
#ifndef DTLS_CID_MAX_SIZE
/* DTLS parsing code copies the record header in a static buffer to decrypt
 * the record. Increasing the CID max size does increase also this buffer,
 * impacting on per-session runtime memory footprint. */
#define DTLS_CID_MAX_SIZE 10
#endif
#else
#undef DTLS_CID_MAX_SIZE
#define DTLS_CID_MAX_SIZE 0
#endif /* WOLFSSL_DTLS_CID */

#if DTLS_CID_MAX_SIZE > 255
#error "Max size for DTLS CID is 255 bytes"
#endif

/* Record Payload Protection Section 5
 *   https://www.rfc-editor.org/rfc/rfc9146.html#section-5 */
#define WOLFSSL_TLS_HMAC_CID_INNER_SZ                               \
           (8 +                 /* seq_num_placeholder */           \
            1 +                 /* tls12_cid */                     \
            1 +                 /* cid_length */                    \
            1 +                 /* tls12_cid */                     \
            2 +                 /* DTLSCiphertext.version */        \
            2 +                 /* epoch */                         \
            6 +                 /* sequence_number */               \
            DTLS_CID_MAX_SIZE + /* cid */                           \
            2)                  /* length_of_DTLSInnerPlaintext */

#define WOLFSSL_TLS_AEAD_CID_AAD_SZ                                 \
           (8 +                 /* seq_num_placeholder */           \
            1 +                 /* tls12_cid */                     \
            1 +                 /* cid_length */                    \
            1 +                 /* tls12_cid */                     \
            2 +                 /* DTLSCiphertext.version */        \
            2 +                 /* epoch */                         \
            6 +                 /* sequence_number */               \
            DTLS_CID_MAX_SIZE + /* cid */                           \
            2)                  /* length_of_DTLSInnerPlaintext */

#ifndef MAX_TICKET_AGE_DIFF
/* maximum ticket age difference in seconds, 10 seconds */
#define MAX_TICKET_AGE_DIFF     10
#endif
#ifndef TLS13_MAX_TICKET_AGE
/* max ticket age in seconds, 7 days */
#define TLS13_MAX_TICKET_AGE    (7*24*60*60)
#endif


/* Limit is 2^24.5
 * https://www.rfc-editor.org/rfc/rfc8446#section-5.5
 * Without the fraction is 23726566 (0x016A09E6) */
#define AEAD_AES_LIMIT                           w64From32(0x016A, 0x09E6)
/* Limit is 2^23
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-integrity-limits */
#define DTLS_AEAD_AES_CCM_LIMIT                  w64From32(0, 1 << 22)

/* Limit is 2^36
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-aead-limits */
#define DTLS_AEAD_AES_GCM_CHACHA_FAIL_LIMIT      w64From32(1 << 3, 0)
#define DTLS_AEAD_AES_GCM_CHACHA_FAIL_KU_LIMIT   w64From32(1 << 2, 0)
/* Limit is 2^7
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-limits-for-aead_aes_128_ccm */
#define DTLS_AEAD_AES_CCM_8_FAIL_LIMIT           w64From32(0, 1 << 6)
#define DTLS_AEAD_AES_CCM_8_FAIL_KU_LIMIT        w64From32(0, 1 << 5)
/* Limit is 2^23.5.
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-integrity-limits
 * Without the fraction is 11863283 (0x00B504F3)
 * Half of this value is    5931641 (0x005A8279) */
#define DTLS_AEAD_AES_CCM_FAIL_LIMIT             w64From32(0x00B5, 0x04F3)
#define DTLS_AEAD_AES_CCM_FAIL_KU_LIMIT          w64From32(0x005A, 0x8279)

/* Limit is (2^22 - 1) full messages [2^36 - 31 octets]
 * https://www.rfc-editor.org/rfc/rfc8998.html#name-aead_sm4_gcm
 */
#define AEAD_SM4_GCM_LIMIT                       w64From32(0, (1 << 22) - 1)
/* Limit is (2^10 - 1) full messages [2^24 - 1 octets]
 * https://www.rfc-editor.org/rfc/rfc8998.html#name-aead_sm4_ccm
 */
#define AEAD_SM4_CCM_LIMIT                       w64From32(0, (1 << 10) - 1)

#if defined(WOLFSSL_TLS13) || !defined(NO_PSK)

#define TLS13_TICKET_NONCE_MAX_SZ 255

#if (defined(HAVE_FIPS) &&                                                     \
    !(defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) &&                    \
    defined(TLS13_TICKET_NONCE_STATIC_SZ)
#error "TLS13_TICKET_NONCE_STATIC_SZ is not supported in this FIPS version"
#endif

#ifndef TLS13_TICKET_NONCE_STATIC_SZ
#define TLS13_TICKET_NONCE_STATIC_SZ 8
#endif

#if TLS13_TICKET_NONCE_STATIC_SZ > TLS13_TICKET_NONCE_MAX_SZ
#error "Max size for ticket nonce is 255 bytes"
#endif

#endif /* WOLFSSL_TLS13 || !NO_PSK */

#ifdef WOLFSSL_TLS13
/* The length of the certificate verification label - client and server. */
#define CERT_VFY_LABEL_SZ    34
/* The number of prefix bytes for signature data. */
#define SIGNING_DATA_PREFIX_SZ     64
/* Maximum length of the signature data. */
#define MAX_SIG_DATA_SZ            (SIGNING_DATA_PREFIX_SZ + \
                                    CERT_VFY_LABEL_SZ      + \
                                    WC_MAX_DIGEST_SIZE)
#endif /* WOLFSSL_TLS13 */

enum Misc {
    CIPHER_BYTE    = 0x00,         /* Default ciphers */
    ECC_BYTE       = 0xC0,         /* ECC first cipher suite byte */
    CHACHA_BYTE    = 0xCC,         /* ChaCha first cipher suite */
    TLS13_BYTE     = 0x13,         /* TLS v1.3 first byte of cipher suite */
    ECDHE_PSK_BYTE = 0xD0,         /* RFC 8442 */
    SM_BYTE        = 0xE0,         /* SM first byte - private range */

    SEND_CERT       = 1,
    SEND_BLANK_CERT = 2,

    DTLS_MAJOR      = 0xfe,     /* DTLS major version number */
    DTLS_MINOR      = 0xff,     /* DTLS minor version number */
    DTLS_BOGUS_MINOR = 0xfe,    /* DTLS 0xfe was skipped, see RFC6347 Sec. 1 */
    DTLSv1_2_MINOR  = 0xfd,     /* DTLS minor version number */
    DTLSv1_3_MINOR  = 0xfc,     /* DTLS minor version number */
    SSLv3_MAJOR     = 3,        /* SSLv3 and TLSv1+  major version number */
    SSLv3_MINOR     = 0,        /* TLSv1   minor version number */
    TLSv1_MINOR     = 1,        /* TLSv1   minor version number */
    TLSv1_1_MINOR   = 2,        /* TLSv1_1 minor version number */
    TLSv1_2_MINOR   = 3,        /* TLSv1_2 minor version number */
    TLSv1_3_MINOR   = 4,        /* TLSv1_3 minor version number */
    TLS_DRAFT_MAJOR = 0x7f,     /* Draft TLS major version number */
    OLD_HELLO_ID    = 0x01,     /* SSLv2 Client Hello Indicator */
    INVALID_BYTE    = 0xff,     /* Used to initialize cipher specs values */
    NO_COMPRESSION  =  0,
    ZLIB_COMPRESSION = 221,     /* wolfSSL zlib compression */
    HELLO_EXT_SIG_ALGO = 13,    /* ID for the sig_algo hello extension */
    HELLO_EXT_EXTMS = 0x0017,   /* ID for the extended master secret ext */
    SECRET_LEN      = WOLFSSL_MAX_MASTER_KEY_LENGTH,
                                /* pre RSA and all master */
#if !defined(WOLFSSL_TLS13) || defined(WOLFSSL_32BIT_MILLI_TIME)
    TIMESTAMP_LEN   = 4,        /* timestamp size in ticket */
#else
    TIMESTAMP_LEN   = 8,        /* timestamp size in ticket */
#endif
#ifdef WOLFSSL_TLS13
    AGEADD_LEN      = 4,        /* ageAdd size in ticket */
    NAMEDGROUP_LEN  = 2,        /* namedGroup size in ticket */
#ifdef WOLFSSL_EARLY_DATA
    MAXEARLYDATASZ_LEN = 4,     /* maxEarlyDataSz size in ticket */
#endif
#endif
#ifndef NO_PSK
    ENCRYPT_LEN     = (ENCRYPT_BASE_BITS / 8) + MAX_PSK_KEY_LEN + 2,
#else
    ENCRYPT_LEN     = (ENCRYPT_BASE_BITS / 8),
#endif
    SIZEOF_SENDER   =  4,       /* clnt or srvr           */
    FINISHED_SZ     = 36,       /* WC_MD5_DIGEST_SIZE + WC_SHA_DIGEST_SIZE */
    MAX_PLAINTEXT_SZ   = (1 << 14),        /* Max plaintext sz   */
    MAX_TLS_CIPHER_SZ  = (1 << 14) + 2048, /* Max TLS encrypted data sz */
#ifdef WOLFSSL_TLS13
    MAX_TLS13_PLAIN_SZ = (1 << 14) + 1,    /* Max unencrypted data sz */
    MAX_TLS13_ENC_SZ   = (1 << 14) + 256,  /* Max encrypted data sz   */
#endif
    MAX_MSG_EXTRA   = 38 + WC_MAX_DIGEST_SIZE,
                                /* max added to msg, mac + pad  from */
                                /* RECORD_HEADER_SZ + BLOCK_SZ (pad) + Max
                                   digest sz + BLOC_SZ (iv) + pad byte (1) */
    MAX_COMP_EXTRA  = 1024,     /* max compression extra */
    MAX_MTU         = WOLFSSL_MAX_MTU,     /* max expected MTU */
    MAX_UDP_SIZE    = 8192 - 100, /* was MAX_MTU - 100 */
    MAX_DH_SZ       = (MAX_DHKEY_SZ * 3) + 12, /* DH_P, DH_G and DH_Pub */
                                /* 4096 p, pub, g + 2 byte size for each */
    MAX_STR_VERSION = 8,        /* string rep of protocol version */

    PAD_MD5        = 48,       /* pad length for finished */
    PAD_SHA        = 40,       /* pad length for finished */
    MAX_PAD_SIZE   = 256,      /* maximum length of padding */

    LENGTH_SZ      =  2,       /* length field for HMAC, data only */
    VERSION_SZ     =  2,       /* length of proctocol version */
    SEQ_SZ         =  8,       /* 64 bit sequence number  */
    ALERT_SIZE     =  2,       /* level + description     */
    VERIFY_HEADER  =  2,       /* always use 2 bytes      */
    EXTS_SZ        =  2,       /* always use 2 bytes      */
    EXT_ID_SZ      =  2,       /* always use 2 bytes      */
    MAX_DH_SIZE    = MAX_DHKEY_SZ+1,
                               /* Max size plus possible leading 0 */
    MIN_FFHDE_GROUP = 0x100,   /* Named group minimum for FFDHE parameters  */
    MAX_FFHDE_GROUP = 0x1FF,   /* Named group maximum for FFDHE parameters  */
    SESSION_HINT_SZ = 4,       /* session timeout hint */
    SESSION_ADD_SZ = 4,        /* session age add */
    TICKET_NONCE_LEN_SZ = 1,   /* Ticket nonce length size */
    DEF_TICKET_NONCE_SZ = 1,   /* Default ticket nonce size */
#if defined(WOLFSSL_TLS13) || !defined(NO_PSK)
    MAX_TICKET_NONCE_STATIC_SZ = TLS13_TICKET_NONCE_STATIC_SZ,
                               /* maximum ticket nonce static size */
#endif /* WOLFSSL_TLS13 || !NO_PSK */
    MAX_LIFETIME   = 604800,   /* maximum ticket lifetime */

    RAN_LEN      = 32,         /* random length           */
    SEED_LEN     = RAN_LEN * 2, /* tls prf seed length    */
    ID_LEN       = 32,         /* session id length       */
    COOKIE_SECRET_SZ = 14,     /* dtls cookie secret size */
    MAX_COOKIE_LEN = 32,       /* max dtls cookie size    */
    COOKIE_SZ    = 20,         /* use a 20 byte cookie    */
    SUITE_LEN    =  2,         /* cipher suite sz length  */
    ENUM_LEN     =  1,         /* always a byte           */
    OPAQUE8_LEN  =  1,         /* 1 byte                  */
    OPAQUE16_LEN =  2,         /* 2 bytes                 */
    OPAQUE24_LEN =  3,         /* 3 bytes                 */
    OPAQUE32_LEN =  4,         /* 4 bytes                 */
    OPAQUE64_LEN =  8,         /* 8 bytes                 */
    COMP_LEN     =  1,         /* compression length      */
    CURVE_LEN    =  2,         /* ecc named curve length  */
    KE_GROUP_LEN =  2,         /* key exchange group length */
#if defined(NO_SHA) && !defined(NO_SHA256)
    SERVER_ID_LEN = WC_SHA256_DIGEST_SIZE,
#else
    SERVER_ID_LEN = WC_SHA_DIGEST_SIZE,
#endif

    HANDSHAKE_HEADER_SZ   = 4,  /* type + length(3)        */
    DTLS13_HANDSHAKE_HEADER_SZ   = 12, /* sizeof(Dtls13HandshakeHeader) */
    RECORD_HEADER_SZ      = 5,  /* type + version + len(2) */
    CERT_HEADER_SZ        = 3,  /* always 3 bytes          */
    REQ_HEADER_SZ         = 2,  /* cert request header sz  */
    HINT_LEN_SZ           = 2,  /* length of hint size field */
    TRUNCATED_HMAC_SZ     = 10, /* length of hmac w/ truncated hmac extension */
    HELLO_EXT_SZ          = 4,  /* base length of a hello extension */
    HELLO_EXT_TYPE_SZ     = 2,  /* length of a hello extension type */
    HELLO_EXT_SZ_SZ       = 2,  /* length of a hello extension size */
    HELLO_EXT_SIGALGO_SZ  = 2,  /* length of number of items in sigalgo list */

    DTLS_HANDSHAKE_HEADER_SZ = 12, /* normal + seq(2) + offset(3) + length(3) */
    DTLS_RECORD_HEADER_SZ    = 13, /* normal + epoch(2) + seq_num(6) */
    DTLS12_CID_OFFSET        = 11,
    DTLS_UNIFIED_HEADER_MIN_SZ = 2,
    /* flags + seq_number(2) + length(2) + CID */
    DTLS_RECVD_RL_HEADER_MAX_SZ = 5 + DTLS_CID_MAX_SIZE,
    DTLS_RECORD_HEADER_MAX_SZ = 13,
    DTLS_HANDSHAKE_EXTRA     = 8,  /* diff from normal */
    DTLS_RECORD_EXTRA        = 8,  /* diff from normal */
    DTLS_HANDSHAKE_SEQ_SZ    = 2,  /* handshake header sequence number */
    DTLS_HANDSHAKE_FRAG_SZ   = 3,  /* fragment offset and length are 24 bit */
    DTLS_POOL_SZ             = 20, /* allowed number of list items in TX and
                                    * RX pool */
    DTLS_FRAG_POOL_SZ        = WOLFSSL_DTLS_FRAG_POOL_SZ,
                                   /* allowed number of fragments per msg */
    DTLS_EXPORT_PRO          = 165,/* wolfSSL protocol for serialized session */
    DTLS_EXPORT_STATE_PRO    = 166,/* wolfSSL protocol for serialized state */
    TLS_EXPORT_PRO           = 167,/* wolfSSL protocol for serialized TLS */
    DTLS_EXPORT_OPT_SZ       = 62, /* amount of bytes used from Options */
    DTLS_EXPORT_OPT_SZ_4     = 61, /* amount of bytes used from Options */
    TLS_EXPORT_OPT_SZ        = 66, /* amount of bytes used from Options */
    TLS_EXPORT_OPT_SZ_4      = 65, /* amount of bytes used from Options */
    DTLS_EXPORT_OPT_SZ_3     = 60, /* amount of bytes used from Options */
    DTLS_EXPORT_KEY_SZ       = 325 + (DTLS_SEQ_SZ * 2),
                                   /* max amount of bytes used from Keys */
    DTLS_EXPORT_MIN_KEY_SZ   = 85 + (DTLS_SEQ_SZ * 2),
                                   /* min amount of bytes used from Keys */
    WOLFSSL_EXPORT_TLS       = 1,
    WOLFSSL_EXPORT_DTLS      = 0,
#ifndef WOLFSSL_EXPORT_SPC_SZ
    WOLFSSL_EXPORT_SPC_SZ    = 16, /* amount of bytes used from CipherSpecs */
#endif
    WOLFSSL_EXPORT_LEN       = 2,  /* 2 bytes for length and protocol */
    WOLFSSL_EXPORT_VERSION   = 5,  /* wolfSSL version for serialized session */

    WOLFSSL_EXPORT_VERSION_4 = 4,  /* 5.6.4 release and before */
    /* older export versions supported */
    WOLFSSL_EXPORT_VERSION_3 = 3,  /* wolfSSL version before TLS 1.3 addition */

    MAX_EXPORT_IP            = 46, /* max ip size IPv4 mapped IPv6 */
    DTLS_MTU_ADDITIONAL_READ_BUFFER = WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER,
                                   /* Additional bytes to read so that
                                    * we can work with a peer that has
                                    * a slightly different MTU than us. */
    MAX_EXPORT_BUFFER        = 514, /* max size of buffer for exporting */
    MAX_EXPORT_STATE_BUFFER  = (DTLS_EXPORT_MIN_KEY_SZ) + (3 * WOLFSSL_EXPORT_LEN),
                                    /* max size of buffer for exporting state */
    FINISHED_LABEL_SZ   = 15,  /* TLS finished label size */
    TLS_FINISHED_SZ     = 12,  /* TLS has a shorter size  */
    TLS_FINISHED_SZ_MAX = WC_MAX_DIGEST_SIZE,
                            /* longest message digest size is SHA512, 64 */
    EXT_MASTER_LABEL_SZ = 22,  /* TLS extended master secret label sz */
    MASTER_LABEL_SZ     = 13,  /* TLS master secret label sz */
    KEY_LABEL_SZ        = 13,  /* TLS key block expansion sz */
    PROTOCOL_LABEL_SZ   = 9,   /* Length of the protocol label */
    MAX_LABEL_SZ        = 34,  /* Maximum length of a label */
    MAX_REQUEST_SZ      = 256, /* Maximum cert req len (no auth yet */
    SESSION_FLUSH_COUNT = 256, /* Flush session cache unless user turns off */
    TLS_MAX_PAD_SZ      = 255, /* Max padding in TLS */
    MAX_EXT_DATA_LEN    = 65535,
                          /* Max extension data length <0..2^16-1> RFC 8446
                           * Section 4.2 */
    MAX_SV_EXT_LEN      = 255,
                          /* Max supported_versions extension length
                           * <2..254> RFC 8446 Section 4.2.1.*/

#if defined(HAVE_NULL_CIPHER) && defined(WOLFSSL_TLS13)
    #if defined(WOLFSSL_SHA384) && WC_MAX_SYM_KEY_SIZE < 48
        MAX_SYM_KEY_SIZE    = WC_SHA384_DIGEST_SIZE,
    #elif !defined(NO_SHA256) && WC_MAX_SYM_KEY_SIZE < 32
        MAX_SYM_KEY_SIZE    = WC_SHA256_DIGEST_SIZE,
    #else
        MAX_SYM_KEY_SIZE    = WC_MAX_SYM_KEY_SIZE,
    #endif
#else
    MAX_SYM_KEY_SIZE    = WC_MAX_SYM_KEY_SIZE,
#endif

#if defined(HAVE_SELFTEST) && \
    (!defined(HAVE_SELFTEST_VERSION) || (HAVE_SELFTEST_VERSION < 2))
    #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
    #define WOLFSSL_AES_KEY_SIZE_ENUM
    AES_IV_SIZE         = 16,
    AES_128_KEY_SIZE    = 16,
    AES_192_KEY_SIZE    = 24,
    AES_256_KEY_SIZE    = 32,
    #endif
#endif

    MAX_IV_SZ           = WC_AES_BLOCK_SIZE,

    AEAD_SEQ_OFFSET     = 4,   /* Auth Data: Sequence number */
    AEAD_TYPE_OFFSET    = 8,   /* Auth Data: Type            */
    AEAD_VMAJ_OFFSET    = 9,   /* Auth Data: Major Version   */
    AEAD_VMIN_OFFSET    = 10,  /* Auth Data: Minor Version   */
    AEAD_LEN_OFFSET     = 11,  /* Auth Data: Length          */
    AEAD_AUTH_DATA_SZ   = 13,  /* Size of the data to authenticate */
    AEAD_NONCE_SZ       = 12,
    AESGCM_IMP_IV_SZ    = 4,   /* Size of GCM AEAD implicit IV */
    AESCCM_IMP_IV_SZ    = 4,   /* Size of CCM AEAD implicit IV */
    AESGCM_EXP_IV_SZ    = 8,   /* Size of GCM/CCM AEAD explicit IV */
    AESGCM_NONCE_SZ     = AESGCM_EXP_IV_SZ + AESGCM_IMP_IV_SZ,
    GCM_IMP_IV_SZ       = 4,   /* Size of GCM AEAD implicit IV */
    CCM_IMP_IV_SZ       = 4,   /* Size of CCM AEAD implicit IV */
    GCM_EXP_IV_SZ       = 8,   /* Size of GCM/CCM AEAD explicit IV */
    GCM_NONCE_SZ        = GCM_EXP_IV_SZ + GCM_IMP_IV_SZ,

    CHACHA20_IMP_IV_SZ  = 12,  /* Size of ChaCha20 AEAD implicit IV */
    CHACHA20_NONCE_SZ   = 12,  /* Size of ChacCha20 nonce           */
    CHACHA20_OLD_OFFSET = 4,   /* Offset for seq # in old poly1305  */
    CHACHA20_OFFSET     = 4,   /* Offset for seq # in poly1305  */

    /* For any new implicit/explicit IV size adjust AEAD_MAX_***_SZ */

    AES_GCM_AUTH_SZ     = 16, /* AES-GCM Auth Tag length    */
    AES_CCM_16_AUTH_SZ  = 16, /* AES-CCM-16 Auth Tag length */
    AES_CCM_8_AUTH_SZ   = 8,  /* AES-CCM-8 Auth Tag Length  */
    AESCCM_NONCE_SZ     = 12,

    SM4_GCM_AUTH_SZ     = 16, /* SM4-GCM Auth Tag length    */
    SM4_GCM_NONCE_SZ    = 12, /* SM4 GCM Nonce length       */
    SM4_CCM_AUTH_SZ     = 16, /* SM4-CCM Auth Tag length    */
    SM4_CCM_NONCE_SZ    = 12, /* SM4 CCM Nonce length       */

    CAMELLIA_128_KEY_SIZE = 16, /* for 128 bit */
    CAMELLIA_192_KEY_SIZE = 24, /* for 192 bit */
    CAMELLIA_256_KEY_SIZE = 32, /* for 256 bit */
    CAMELLIA_IV_SIZE      = 16, /* always block size */

    CHACHA20_256_KEY_SIZE = 32,  /* for 256 bit             */
    CHACHA20_128_KEY_SIZE = 16,  /* for 128 bit             */
    CHACHA20_IV_SIZE      = 12,  /* 96 bits for iv          */

    POLY1305_AUTH_SZ    = 16,  /* 128 bits                */

    HMAC_NONCE_SZ       = 12,  /* Size of HMAC nonce */

    EVP_SALT_SIZE       =  8,  /* evp salt size 64 bits   */

#ifndef ECDHE_SIZE /* allow this to be overridden at compile-time */
    ECDHE_SIZE          = 32,  /* ECDHE server size defaults to 256 bit */
#endif
    MAX_EXPORT_ECC_SZ   = 256, /* Export ANSI X9.62 max future size */
    MAX_CURVE_NAME_SZ   = 20,  /* Maximum size of curve name string */

    NEW_SA_MAJOR        = 8,   /* Most significant byte used with new sig algos */
    RSA_PSS_RSAE_SHA256_MINOR = 0x04,
    RSA_PSS_RSAE_SHA384_MINOR = 0x05,
    RSA_PSS_RSAE_SHA512_MINOR = 0x06,
    RSA_PSS_PSS_SHA256_MINOR = 0x09,
    RSA_PSS_PSS_SHA384_MINOR = 0x0A,
    RSA_PSS_PSS_SHA512_MINOR = 0x0B,
    ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR = 0x1A,
    ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR = 0x1B,
    ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR = 0x1C,

    ED25519_SA_MAJOR    = 8,   /* Most significant byte for ED25519 */
    ED25519_SA_MINOR    = 7,   /* Least significant byte for ED25519 */
    ED448_SA_MAJOR      = 8,   /* Most significant byte for ED448 */
    ED448_SA_MINOR      = 8,   /* Least significant byte for ED448 */
    SM2_SA_MAJOR        = 7,   /* Most significant byte for SM2 with SM3 */
    SM2_SA_MINOR        = 8,   /* Least significant byte for SM2 with SM3 */

    FALCON_SA_MAJOR     = 0xFE,/* Most significant byte used with falcon sig algs */
    DILITHIUM_SA_MAJOR  = 0x09,/* Most significant byte used with dilithium sig algs */

    /* These values for falcon match what OQS has defined. */
    FALCON_LEVEL1_SA_MAJOR = 0xFE,
    FALCON_LEVEL1_SA_MINOR = 0xAE,
    FALCON_LEVEL5_SA_MAJOR = 0xFE,
    FALCON_LEVEL5_SA_MINOR = 0xB1,

    /* these values for MLDSA (Dilithium) correspond to what is proposed in the
     * IETF. */
    DILITHIUM_LEVEL2_SA_MAJOR = 0x09,
    DILITHIUM_LEVEL2_SA_MINOR = 0x04,
    DILITHIUM_LEVEL3_SA_MAJOR = 0x09,
    DILITHIUM_LEVEL3_SA_MINOR = 0x05,
    DILITHIUM_LEVEL5_SA_MAJOR = 0x09,
    DILITHIUM_LEVEL5_SA_MINOR = 0x06,

    MIN_RSA_SHA512_PSS_BITS = 512 * 2 + 8 * 8, /* Min key size */
    MIN_RSA_SHA384_PSS_BITS = 384 * 2 + 8 * 8, /* Min key size */

    CLIENT_HELLO_FIRST =  35,  /* Protocol + RAN_LEN + sizeof(id_len) */
    MAX_SUITE_NAME     =  48,  /* maximum length of cipher suite string */

    DTLS_TIMEOUT_INIT       =  1, /* default timeout init for DTLS receive  */
    DTLS_TIMEOUT_MAX        = 64, /* default max timeout for DTLS receive */
    DTLS_TIMEOUT_MULTIPLIER =  2, /* default timeout multiplier for DTLS recv */

    NULL_TERM_LEN        =   1,  /* length of null '\0' termination character */
    MIN_PSK_ID_LEN       =   6,  /* min length of identities */
    MIN_PSK_BINDERS_LEN  =  33,  /* min length of binders */

#ifndef MAX_WOLFSSL_FILE_SIZE
    MAX_WOLFSSL_FILE_SIZE = 1024UL * 1024UL * 4,  /* 4 mb file size alloc limit */
#endif
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
    MAX_WOLFSSL_CRYPTO_POLICY_SIZE = 1024UL, /* Crypto-policy file is one line.
                                              * It should not be large. */
    MIN_WOLFSSL_SEC_LEVEL = 0,
    MAX_WOLFSSL_SEC_LEVEL = 5,
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */

    CERT_MIN_SIZE      =  256, /* min PEM cert size with header/footer */

    NO_SNIFF           =   0,  /* not sniffing */
    SNIFF              =   1,  /* currently sniffing */

    HASH_SIG_SIZE      =   2,  /* default SHA1 RSA */

    NO_COPY            =   0,  /* should we copy static buffer for write */
    COPY               =   1,  /* should we copy static buffer for write */

    INVALID_PEER_ID    = 0xFFFF, /* Initialize value for peer ID. */

    PREV_ORDER         = -1,   /* Sequence number is in previous epoch. */
    PEER_ORDER         = 1,    /* Peer sequence number for verify. */
    CUR_ORDER          = 0,    /* Current sequence number. */
    WRITE_PROTO        = 1,    /* writing a protocol message */
    READ_PROTO         = 0     /* reading a protocol message */
};


/* Size of the data to authenticate */
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID)
#define AEAD_AUTH_DATA_SZ WOLFSSL_TLS_AEAD_CID_AAD_SZ
#else
#define AEAD_AUTH_DATA_SZ 13
#endif

#define WOLFSSL_NAMED_GROUP_IS_FFDHE(group) \
    (WOLFSSL_FFDHE_START <= (group) && (group) <= WOLFSSL_FFDHE_END)
#ifdef WOLFSSL_HAVE_MLKEM
WOLFSSL_LOCAL int NamedGroupIsPqc(int group);
WOLFSSL_LOCAL int NamedGroupIsPqcHybrid(int group);
#define WOLFSSL_NAMED_GROUP_IS_PQC(group) NamedGroupIsPqc(group)
#define WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group) NamedGroupIsPqcHybrid(group)
#else
#define WOLFSSL_NAMED_GROUP_IS_PQC(group)        ((void)(group), 0)
#define WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group) ((void)(group), 0)
#endif /* WOLFSSL_HAVE_MLKEM */

/* minimum Downgrade Minor version */
#ifndef WOLFSSL_MIN_DOWNGRADE
    #ifndef NO_OLD_TLS
        #define WOLFSSL_MIN_DOWNGRADE TLSv1_MINOR
    #else
        #define WOLFSSL_MIN_DOWNGRADE TLSv1_2_MINOR
    #endif
#endif

/* minimum DTLS Downgrade Minor version */
#ifndef WOLFSSL_MIN_DTLS_DOWNGRADE
#define WOLFSSL_MIN_DTLS_DOWNGRADE DTLS_MINOR;
#endif

/* Set max implicit IV size for AEAD cipher suites */
#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && defined(WOLFSSL_SHA384)
    /* Integrity-only cipher suites use IV size equal to hash output size */
    #define AEAD_MAX_IMP_SZ 48
#elif defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && !defined(NO_SHA256)
    /* Integrity-only cipher suites use IV size equal to hash output size */
    #define AEAD_MAX_IMP_SZ 32
#else
    #define AEAD_MAX_IMP_SZ 12
#endif

/* Set max explicit IV size for AEAD cipher suites */
#define AEAD_MAX_EXP_SZ 8


#ifndef WOLFSSL_MAX_SUITE_SZ
    #define WOLFSSL_MAX_SUITE_SZ 300
    /* 150 suites for now! */
#endif

/* number of items in the signature algo list */
#ifndef WOLFSSL_MAX_SIGALGO
#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)
    /* If we are building with post-quantum algorithms, we likely want to
     * inter-op with OQS's OpenSSL and they send a lot more sigalgs.
     */
    #define WOLFSSL_MAX_SIGALGO 128
#else
    #define WOLFSSL_MAX_SIGALGO 44
#endif
#endif


/* set minimum ECC key size allowed */
#ifndef WOLFSSL_MIN_ECC_BITS
    #ifdef WOLFSSL_MAX_STRENGTH
        #define WOLFSSL_MIN_ECC_BITS  256
    #else
        #define WOLFSSL_MIN_ECC_BITS 224
    #endif
#endif /* WOLFSSL_MIN_ECC_BITS */
#if (WOLFSSL_MIN_ECC_BITS % 8)
    /* Some ECC keys are not divisible by 8 such as prime239v1 or sect131r1.
       In these cases round down to the nearest value divisible by 8. The
       restriction of being divisible by 8 is in place to match wc_ecc_size
       function from wolfSSL.
     */
    #error ECC minimum bit size must be a multiple of 8
#endif
#define MIN_ECCKEY_SZ (WOLFSSL_MIN_ECC_BITS / 8)

#ifdef HAVE_FALCON
#ifndef MIN_FALCONKEY_SZ
    #define MIN_FALCONKEY_SZ    1281
#endif
#endif
#ifdef HAVE_DILITHIUM
#ifndef MIN_DILITHIUMKEY_SZ
    #define MIN_DILITHIUMKEY_SZ    2528
#endif
#endif

/* set minimum RSA key size allowed */
#ifndef WOLFSSL_MIN_RSA_BITS
    #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
        /* Using guidance from section 5.6.1
         * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
        #if WOLFSSL_HARDEN_TLS >= 128
            #define WOLFSSL_MIN_RSA_BITS 3072
        #elif WOLFSSL_HARDEN_TLS >= 112
            #define WOLFSSL_MIN_RSA_BITS 2048
        #endif
    #elif defined(WOLFSSL_MAX_STRENGTH)
        #define WOLFSSL_MIN_RSA_BITS 2048
    #else
        #define WOLFSSL_MIN_RSA_BITS 1024
    #endif
#endif /* WOLFSSL_MIN_RSA_BITS */
#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_RSA_BITS < 2048 && \
    !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
    /* Implementations MUST NOT negotiate cipher suites offering less than
     * 112 bits of security.
     * https://www.rfc-editor.org/rfc/rfc9325#section-4.1
     * Using guidance from section 5.6.1
     * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
    #error "For 112 bits of security RSA needs at least 2048 bit keys"
#endif
#if (WOLFSSL_MIN_RSA_BITS % 8)
    /* This is to account for the example case of a min size of 2050 bits but
       still allows 2049 bit key. So we need the measurement to be in bytes. */
    #error RSA minimum bit size must be a multiple of 8
#endif
#define MIN_RSAKEY_SZ (WOLFSSL_MIN_RSA_BITS / 8)

#ifdef SESSION_INDEX
/* Shift values for making a session index */
#define SESSIDX_ROW_SHIFT 4
#define SESSIDX_IDX_MASK  0x0F
#endif

#ifndef MAX_X509_SIZE
    #if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)
        #define MAX_X509_SIZE   (8*1024) /* max static x509 buffer size; dilithium is big */
    #elif defined(WOLFSSL_HAPROXY)
        #define MAX_X509_SIZE   3072 /* max static x509 buffer size */
    #else
        #define MAX_X509_SIZE   2048 /* max static x509 buffer size */
    #endif
#endif

/* max cert chain peer depth */
#ifndef MAX_CHAIN_DEPTH
    #define MAX_CHAIN_DEPTH 9
#endif

#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
                    defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
    #if !defined(HAVE_OCSP)
        #error OCSP Stapling and Stapling V2 needs OCSP. Please define HAVE_OCSP.
    #endif
#endif

/* Max certificate extensions in TLS1.3 */
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST)
    /* Number of extensions to set each OCSP response */
    #define MAX_CERT_EXTENSIONS (1 + MAX_CHAIN_DEPTH)
#else
    /* Only empty extensions */
    #define MAX_CERT_EXTENSIONS 1
#endif

/* max size of a certificate message payload */
/* assumes MAX_CHAIN_DEPTH number of certificates at 2kb per certificate */
#ifndef MAX_CERTIFICATE_SZ
    #define MAX_CERTIFICATE_SZ \
                (CERT_HEADER_SZ + \
                (MAX_X509_SIZE + CERT_HEADER_SZ) * MAX_CHAIN_DEPTH)
#endif

/* max size of a handshake message, currently set to the certificate */
#ifndef MAX_HANDSHAKE_SZ
    #define MAX_HANDSHAKE_SZ MAX_CERTIFICATE_SZ
#endif

#ifndef PREALLOC_SESSION_TICKET_LEN
    #define PREALLOC_SESSION_TICKET_LEN 512
#endif

#ifndef PREALLOC_SESSION_TICKET_NONCE_LEN
    #define PREALLOC_SESSION_TICKET_NONCE_LEN 32
#endif

#ifndef SESSION_TICKET_HINT_DEFAULT
    #define SESSION_TICKET_HINT_DEFAULT 300
#endif

#if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_WOLFSSL_SERVER)
    /* Check chosen encryption is available. */
    #if !(defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) && \
        defined(WOLFSSL_TICKET_ENC_CHACHA20_POLY1305)
        #error "ChaCha20-Poly1305 not available for default ticket encryption"
    #endif
    #if !defined(HAVE_AESGCM) && (defined(WOLFSSL_TICKET_ENC_AES128_GCM) || \
        defined(WOLFSSL_TICKET_ENC_AES256_GCM))
        #error "AES-GCM not available for default ticket encryption"
    #endif

    #ifndef WOLFSSL_TICKET_KEY_LIFETIME
        /* Default lifetime is 1 hour from issue of first ticket with key. */
        #define WOLFSSL_TICKET_KEY_LIFETIME       (60 * 60)
    #endif
    #if WOLFSSL_TICKET_KEY_LIFETIME <= SESSION_TICKET_HINT_DEFAULT
        #error "Ticket Key lifetime must be longer than ticket life hint."
    #endif
#endif

#define MAX_ENCRYPT_SZ ENCRYPT_LEN

#define WOLFSSL_ASSERT_EQ(x, y) wc_static_assert((x) == (y))
#define WOLFSSL_ASSERT_GE(x, y) wc_static_assert((x) >= (y))

#define WOLFSSL_ASSERT_SIZEOF_GE(x, y) wc_static_assert(sizeof(x) >= sizeof(y))
#define WOLFSSL_ASSERT_SIZEOF_EQ(x, y) wc_static_assert(sizeof(x) == sizeof(y))

/* states. Adding state before HANDSHAKE_DONE will break session importing */
enum states {
    NULL_STATE = 0,

    SERVER_HELLOVERIFYREQUEST_COMPLETE,
    SERVER_HELLO_RETRY_REQUEST_COMPLETE,
    SERVER_HELLO_COMPLETE,
    SERVER_ENCRYPTED_EXTENSIONS_COMPLETE,
    SERVER_CERT_COMPLETE,
    SERVER_CERT_VERIFY_COMPLETE,
    SERVER_KEYEXCHANGE_COMPLETE,
    SERVER_HELLODONE_COMPLETE,
    SERVER_CHANGECIPHERSPEC_COMPLETE,
    SERVER_FINISHED_COMPLETE,

    CLIENT_HELLO_RETRY,
    CLIENT_HELLO_COMPLETE,
    CLIENT_KEYEXCHANGE_COMPLETE,
    CLIENT_CHANGECIPHERSPEC_COMPLETE,
    CLIENT_FINISHED_COMPLETE,

    HANDSHAKE_DONE,

#ifdef WOLFSSL_DTLS13
    SERVER_FINISHED_ACKED,
#endif /* WOLFSSL_DTLS13 */

};

/* SSL Version */
typedef struct ProtocolVersion {
    byte major;
    byte minor;
} WOLFSSL_PACK ProtocolVersion;


WOLFSSL_LOCAL ProtocolVersion MakeSSLv3(void);
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1(void);
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_1(void);
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_2(void);
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_3(void);

#ifdef WOLFSSL_DTLS
    WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1(void);
    WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1_2(void);

#ifdef WOLFSSL_DTLS13
    WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1_3(void);
#endif /* WOLFSSL_DTLS13 */

#endif
#ifdef WOLFSSL_SESSION_EXPORT
WOLFSSL_LOCAL int wolfSSL_session_export_internal(WOLFSSL* ssl, byte* buf,
        word32* sz, int type);
WOLFSSL_LOCAL int wolfSSL_session_import_internal(WOLFSSL* ssl, const byte* buf,
        word32 sz, int type);
#ifdef WOLFSSL_DTLS
    WOLFSSL_LOCAL int wolfSSL_dtls_export_state_internal(WOLFSSL* ssl,
                                                          byte* buf, word32 sz);
    WOLFSSL_LOCAL int wolfSSL_dtls_import_state_internal(WOLFSSL* ssl,
                                                    const byte* buf, word32 sz);
    WOLFSSL_LOCAL int wolfSSL_send_session(WOLFSSL* ssl);
#endif
#endif

struct WOLFSSL_BY_DIR_HASH {
    unsigned long hash_value;
    int last_suffix;
};

struct WOLFSSL_BY_DIR_entry {
    char*   dir_name;
    int     dir_type;
    WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *hashes;
};

struct WOLFSSL_BY_DIR {
    WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *dir_entry;
    wolfSSL_Mutex    lock; /* dir list lock */
};

/* wolfSSL method type */
struct WOLFSSL_METHOD {
    ProtocolVersion version;
    byte            side;         /* connection side, server or client */
    byte            downgrade;    /* whether to downgrade version, default no */
};

/* wolfSSL buffer type - internal uses "buffer" type */
typedef WOLFSSL_BUFFER_INFO buffer;

typedef struct Suites Suites;

/* Declare opaque struct for API to use */
#ifndef WOLFSSL_CLIENT_SESSION_DEFINED
    typedef struct ClientSession ClientSession;
    #define WOLFSSL_CLIENT_SESSION_DEFINED
#endif

/* defaults to client */
WOLFSSL_LOCAL void InitSSL_Method(WOLFSSL_METHOD* method, ProtocolVersion pv);

WOLFSSL_LOCAL void InitSSL_CTX_Suites(WOLFSSL_CTX* ctx);
WOLFSSL_LOCAL int InitSSL_Suites(WOLFSSL* ssl);
WOLFSSL_LOCAL int InitSSL_Side(WOLFSSL* ssl, word16 side);


WOLFSSL_LOCAL int DoHandShakeMsgType(WOLFSSL* ssl, byte* input,
        word32* inOutIdx, byte type, word32 size, word32 totalSz);
/* for sniffer */
WOLFSSL_LOCAL int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
                            word32 size, word32 totalSz, int sniff);
#ifdef WOLFSSL_TLS13
WOLFSSL_LOCAL int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
                           word32 size, word32 totalSz, int sniff);
#endif
#ifdef WOLFSSL_API_PREFIX_MAP
    #define DoApplicationData wolfSSL_DoApplicationData
#endif
WOLFSSL_TEST_VIS int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx,
                                    int sniff);
/* TLS v1.3 needs these */
WOLFSSL_LOCAL int  HandleTlsResumption(WOLFSSL* ssl, Suites* clSuites);
#ifdef WOLFSSL_TLS13
WOLFSSL_LOCAL byte SuiteMac(const byte* suite);
#endif
WOLFSSL_LOCAL int  DoClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
                             word32 helloSz);
#ifdef WOLFSSL_TLS13
WOLFSSL_LOCAL int DoTls13ClientHello(WOLFSSL* ssl, const byte* input,
                                     word32* inOutIdx, word32 helloSz);
#endif
WOLFSSL_LOCAL int  DoServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
                      word32 helloSz);
WOLFSSL_LOCAL int  CompleteServerHello(WOLFSSL *ssl);
WOLFSSL_LOCAL int  CheckVersion(WOLFSSL *ssl, ProtocolVersion pv);
WOLFSSL_LOCAL int  PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo,
                                   word32 hashSigAlgoSz, int matchSuites);
#if defined(WOLF_PRIVATE_KEY_ID) && !defined(NO_CHECK_PRIVATE_KEY)
WOLFSSL_LOCAL int  CreateDevPrivateKey(void** pkey, byte* data, word32 length,
                                       int hsType, int label, int id,
                                       void* heap, int devId);
#endif
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
WOLFSSL_LOCAL int wolfssl_priv_der_blind(WC_RNG* rng, DerBuffer* key,
    DerBuffer** mask);
WOLFSSL_LOCAL void wolfssl_priv_der_blind_toggle(DerBuffer* key,
    const DerBuffer* mask);
WOLFSSL_LOCAL WARN_UNUSED_RESULT DerBuffer *wolfssl_priv_der_unblind(
    const DerBuffer* key, const DerBuffer* mask);
WOLFSSL_LOCAL void wolfssl_priv_der_unblind_free(DerBuffer* key);
#endif
WOLFSSL_LOCAL int  DecodePrivateKey(WOLFSSL *ssl, word32* sigLen);
#ifdef WOLFSSL_DUAL_ALG_CERTS
WOLFSSL_LOCAL int  DecodeAltPrivateKey(WOLFSSL *ssl, word32* sigLen);
#endif
#if defined(WOLF_PRIVATE_KEY_ID) || defined(HAVE_PK_CALLBACKS)
WOLFSSL_LOCAL int GetPrivateKeySigSize(WOLFSSL* ssl);
#ifndef NO_ASN
    WOLFSSL_LOCAL int  InitSigPkCb(WOLFSSL* ssl, SignatureCtx* sigCtx);
#endif
#endif
WOLFSSL_LOCAL int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
                                int check);
WOLFSSL_LOCAL int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
                                      int sigAlgo, int hashAlgo);
#ifdef WOLFSSL_ASYNC_IO
WOLFSSL_LOCAL void FreeAsyncCtx(WOLFSSL* ssl, byte freeAsync);
#endif
WOLFSSL_LOCAL void FreeKeyExchange(WOLFSSL* ssl);
WOLFSSL_LOCAL void FreeSuites(WOLFSSL* ssl);
WOLFSSL_LOCAL int  ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 totalSz);
WOLFSSL_LOCAL int  MatchDomainName(const char* pattern, int len,
                                   const char* str, word32 strLen,
                                   unsigned int flags);
#if !defined(NO_CERTS) && !defined(NO_ASN)
WOLFSSL_LOCAL int  CheckForAltNames(DecodedCert* dCert, const char* domain,
                                    word32 domainLen, int* checkCN,
                                    unsigned int flags, byte isIP);
WOLFSSL_LOCAL int  CheckIPAddr(DecodedCert* dCert, const char* ipasc);
WOLFSSL_LOCAL void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType);
#endif
WOLFSSL_LOCAL int  SetupTicket(WOLFSSL* ssl);
WOLFSSL_LOCAL int  CreateTicket(WOLFSSL* ssl);
WOLFSSL_LOCAL int  HashRaw(WOLFSSL* ssl, const byte* data, int sz);
WOLFSSL_LOCAL int  HashOutput(WOLFSSL* ssl, const byte* output, int sz,
                              int ivSz);
WOLFSSL_LOCAL int  HashInput(WOLFSSL* ssl, const byte* input, int sz);

#ifdef HAVE_SNI
#ifndef NO_WOLFSSL_SERVER
WOLFSSL_LOCAL int SNI_Callback(WOLFSSL* ssl);
#endif
#endif

#ifdef HAVE_ALPN
WOLFSSL_LOCAL int ALPN_Select(WOLFSSL* ssl);
#endif

WOLFSSL_LOCAL int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input,
                              word16 sz, byte type); /* needed by sniffer */
WOLFSSL_LOCAL int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input,
                              word16 sz); /* needed by sniffer */

#ifdef WOLFSSL_TLS13
WOLFSSL_LOCAL int  DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
                                word16 sz, const byte* aad, word16 aadSz);
WOLFSSL_LOCAL int  DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input,
                                           word32* inOutIdx, byte type,
                                           word32 size, word32 totalSz);
WOLFSSL_LOCAL int  DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input,
                                       word32* inOutIdx, word32 totalSz);
WOLFSSL_LOCAL int DoTls13ServerHello(WOLFSSL* ssl, const byte* input,
                                     word32* inOutIdx, word32 helloSz,
                                     byte* extMsgType);
WOLFSSL_LOCAL int RestartHandshakeHash(WOLFSSL* ssl);

WOLFSSL_LOCAL int Tls13DeriveKey(WOLFSSL *ssl, byte *output, int outputLen,
    const byte *secret, const byte *label, word32 labelLen, int hashAlgo,
    int includeMsgs, int side);
#endif
int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz,
                    int pLen, int content);


enum {
    FORCED_FREE = 1,
    NO_FORCED_FREE = 0
};


/* only use compression extra if using compression */
#ifdef HAVE_LIBZ
    #define COMP_EXTRA MAX_COMP_EXTRA
#else
    #define COMP_EXTRA 0
#endif

/* only the sniffer needs space in the buffer for extra MTU record(s) */
#ifdef WOLFSSL_SNIFFER
    #define MTU_EXTRA MAX_MTU * 3
#else
    #define MTU_EXTRA 0
#endif


/* embedded callbacks require large static buffers, make sure on */
#ifdef WOLFSSL_CALLBACKS
    #undef  LARGE_STATIC_BUFFERS
    #define LARGE_STATIC_BUFFERS
#endif


/* determine maximum record size */
#define MAX_RECORD_SIZE 16384  /* 2^14, max size by standard */

#ifdef RECORD_SIZE
    /* user supplied value */
    #if RECORD_SIZE < 128 || RECORD_SIZE > MAX_RECORD_SIZE
        #error Invalid record size
    #endif
#else
    /* give user option to use 16K static buffers */
    #if defined(LARGE_STATIC_BUFFERS)
        #define RECORD_SIZE     MAX_RECORD_SIZE
    #else
        #ifdef WOLFSSL_DTLS
            #define RECORD_SIZE MAX_MTU
        #else
            #define RECORD_SIZE 128
        #endif
    #endif
#endif


/* user option to turn off 16K output option */
/* if using small static buffers (default) and SSL_write tries to write data
   larger than the record we have, dynamically get it, unless user says only
   write in static buffer chunks  */
#ifndef STATIC_CHUNKS_ONLY
    #define OUTPUT_RECORD_SIZE MAX_RECORD_SIZE
#else
    #define OUTPUT_RECORD_SIZE RECORD_SIZE
#endif

/* wolfSSL input buffer

   RFC 2246:

   length
       The length (in bytes) of the following TLSPlaintext.fragment.
       The length should not exceed 2^14.
*/
#ifdef STATIC_BUFFER_LEN
    /* user supplied option */
    #if STATIC_BUFFER_LEN < 5 || STATIC_BUFFER_LEN > (RECORD_HEADER_SZ + \
                          RECORD_SIZE + COMP_EXTRA + MTU_EXTRA + MAX_MSG_EXTRA))
        #error Invalid static buffer length
    #endif
#elif defined(LARGE_STATIC_BUFFERS)
    #define STATIC_BUFFER_LEN (RECORD_HEADER_SZ + RECORD_SIZE + COMP_EXTRA + \
             MTU_EXTRA + MAX_MSG_EXTRA)
#else
    /* don't fragment memory from the record header */
    #define STATIC_BUFFER_LEN RECORD_HEADER_SZ
#endif

typedef struct {
    ALIGN16 byte staticBuffer[STATIC_BUFFER_LEN];
    byte*  buffer;       /* place holder for static or dynamic buffer */
    word32 length;       /* total buffer length used */
    word32 idx;          /* idx to part of length already consumed */
    word32 bufferSize;   /* current buffer size */
    byte   dynamicFlag;  /* dynamic memory currently in use */
    byte   offset;       /* alignment offset attempt */
} bufferStatic;

/* Cipher Suites holder */
struct Suites {
    word16 suiteSz;                 /* suite length in bytes        */
    word16 hashSigAlgoSz;           /* SigAlgo extension length in bytes */
    byte   suites[WOLFSSL_MAX_SUITE_SZ];
    byte   hashSigAlgo[WOLFSSL_MAX_SIGALGO]; /* sig/algo to offer */
    byte   setSuites:1;             /* user set suites from default */
};

typedef struct CipherSuite {
    byte   cipherSuite0;
    byte   cipherSuite;
    word32 ecdhCurveOID;
    struct KeyShareEntry* clientKSE;
#if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
    int    doHelloRetry;
#endif
} CipherSuite;

#ifdef WOLFSSL_API_PREFIX_MAP
    #define InitSuitesHashSigAlgo wolfSSL_InitSuitesHashSigAlgo
#endif
WOLFSSL_TEST_VIS void InitSuitesHashSigAlgo(byte* hashSigAlgo, int have,
                                       int tls1_2, int tls1_3, int keySz,
                                       word16* len);
WOLFSSL_LOCAL int AllocateCtxSuites(WOLFSSL_CTX* ctx);
WOLFSSL_LOCAL int AllocateSuites(WOLFSSL* ssl);
WOLFSSL_LOCAL void InitSuites(Suites* suites, ProtocolVersion pv, int keySz,
                              word16 haveRSA, word16 havePSK, word16 haveDH,
                              word16 haveECDSAsig, word16 haveECC,
                              word16 haveStaticRSA, word16 haveStaticECC,
                              word16 haveAnon, word16 haveNull,
                              word16 haveAES128, word16 haveSHA1,
                              word16 haveRC4, int side);

void refineSuites(const Suites* sslSuites, const Suites* peerSuites,
        Suites* outSuites, byte useClientOrder);
void sslRefineSuites(WOLFSSL* ssl, Suites* peerSuites);

typedef struct TLSX TLSX;
WOLFSSL_LOCAL int MatchSuite_ex(const WOLFSSL* ssl, Suites* peerSuites,
                                CipherSuite* cs, TLSX* extensions);
WOLFSSL_LOCAL int  MatchSuite(WOLFSSL* ssl, Suites* peerSuites);
WOLFSSL_LOCAL int  SetCipherList_ex(const WOLFSSL_CTX* ctx, const WOLFSSL* ssl,
        Suites* suites, const char* list);
WOLFSSL_LOCAL int  SetCipherList(const WOLFSSL_CTX* ctx, Suites* suites,
                                 const char* list);
WOLFSSL_LOCAL int  SetCipherListFromBytes(WOLFSSL_CTX* ctx, Suites* suites,
                                          const byte* list, const int listSz);
WOLFSSL_LOCAL int  SetSuitesHashSigAlgo(Suites* suites, const char* list);

#ifndef PSK_TYPES_DEFINED
    typedef unsigned int (*wc_psk_client_callback)(WOLFSSL*, const char*, char*,
                          unsigned int, unsigned char*, unsigned int);
    typedef unsigned int (*wc_psk_server_callback)(WOLFSSL*, const char*,
                          unsigned char*, unsigned int);
#ifdef WOLFSSL_TLS13
    typedef unsigned int (*wc_psk_client_cs_callback)(WOLFSSL*, const char*,
                          char*, unsigned int, unsigned char*, unsigned int,
                          const char* cipherName);
    typedef unsigned int (*wc_psk_client_tls13_callback)(WOLFSSL*, const char*,
                          char*, unsigned int, unsigned char*, unsigned int,
                          const char** cipherName);
    typedef unsigned int (*wc_psk_server_tls13_callback)(WOLFSSL*, const char*,
                          unsigned char*, unsigned int,
                          const char** cipherName);
#endif
#endif /* PSK_TYPES_DEFINED */
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_SESSION_EXPORT) && \
   !defined(WOLFSSL_DTLS_EXPORT_TYPES)
    typedef int (*wc_dtls_export)(WOLFSSL* ssl,

#define WOLFSSL_DTLS_EXPORT_TYPES
#endif /* WOLFSSL_DTLS_EXPORT_TYPES */


#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
#define MAX_DESCRIPTION_SZ 255
#endif
struct WOLFSSL_CIPHER {
    byte cipherSuite0;
    byte cipherSuite;
    const WOLFSSL* ssl;
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
    char description[MAX_DESCRIPTION_SZ];
    unsigned long offset;
    unsigned int in_stack; /* TRUE if added to stack in wolfSSL_get_ciphers_compat */
    int bits;
#endif
};


#ifdef NO_ASN
    /* no_asn won't have */
    typedef struct CertStatus CertStatus;
#endif

#ifndef HAVE_OCSP
    typedef struct WOLFSSL_OCSP WOLFSSL_OCSP;
#endif

/* wolfSSL OCSP controller */
#ifdef HAVE_OCSP
struct WOLFSSL_OCSP {
    WOLFSSL_CERT_MANAGER* cm;            /* pointer back to cert manager */
    OcspEntry*            ocspList;      /* OCSP response list */
    wolfSSL_Mutex         ocspLock;      /* OCSP list lock */
    int                   error;
    int(*statusCb)(WOLFSSL*, void*);
    void*                 statusCbArg;
};
#endif

typedef struct CRL_Entry CRL_Entry;

#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
    #define CRL_DIGEST_SIZE WC_SM3_DIGEST_SIZE
#elif defined(NO_SHA)
    #define CRL_DIGEST_SIZE WC_SHA256_DIGEST_SIZE
#else
    #define CRL_DIGEST_SIZE WC_SHA_DIGEST_SIZE
#endif

#ifdef NO_ASN
    typedef struct RevokedCert RevokedCert;
#endif
#ifdef CRL_STATIC_REVOKED_LIST
    #ifndef CRL_MAX_REVOKED_CERTS
        #define CRL_MAX_REVOKED_CERTS 4
    #elif CRL_MAX_REVOKED_CERTS > 22000
        #error CRL_MAX_REVOKED_CERTS too big, max is 22000
    #endif
#endif

#ifdef HAVE_CRL
/* Complete CRL */
struct CRL_Entry {
    byte*   toBeSigned;
    byte*   signature;
#if defined(OPENSSL_EXTRA)
    WOLFSSL_X509_NAME*    issuer;     /* X509_NAME type issuer */
#endif
    CRL_Entry* next;                      /* next entry */
    wolfSSL_Mutex verifyMutex;
    /* DupCRL_Entry copies data after the `verifyMutex` member. Using the mutex
     * as the marker because clang-tidy doesn't like taking the sizeof a
     * pointer. */
    char    crlNumber[CRL_MAX_NUM_HEX_STR_SZ];    /* CRL number extension */
    byte    issuerHash[CRL_DIGEST_SIZE];  /* issuer hash                 */
    /* byte    crlHash[CRL_DIGEST_SIZE];      raw crl data hash           */
    /* restore the hash here if needed for optimized comparisons */
    byte    lastDate[MAX_DATE_SIZE]; /* last date updated  */
    byte    nextDate[MAX_DATE_SIZE]; /* next update date   */
    byte    lastDateFormat;          /* last date format */
    byte    nextDateFormat;          /* next date format */
#if defined(OPENSSL_EXTRA)
    WOLFSSL_ASN1_TIME lastDateAsn1;  /* last date updated  */
    WOLFSSL_ASN1_TIME nextDateAsn1;  /* next update date   */
#endif
#ifdef CRL_STATIC_REVOKED_LIST
    RevokedCert certs[CRL_MAX_REVOKED_CERTS];
#else
    RevokedCert* certs;             /* revoked cert list  */
#endif
    int     totalCerts;             /* number on list     */
    int     version;                /* version of certificate */
    int     verified;
    word32  tbsSz;
    word32  signatureSz;
    word32  signatureOID;
#ifdef WC_RSA_PSS
    word32  sigParamsSz; /* length of signature parameters   */
    byte*   sigParams;   /* buffer with signature parameters */
#endif
#if !defined(NO_SKID) && !defined(NO_ASN)
    byte    extAuthKeyId[KEYID_SIZE];
    byte    extAuthKeyIdSet:1;  /* Auth key identifier set indicator */
#endif
    byte    crlNumberSet:1;     /* CRL number set indicator */
};


#ifdef HAVE_CRL_MONITOR
typedef struct CRL_Monitor CRL_Monitor;

/* CRL directory monitor */
struct CRL_Monitor {
    char* path;      /* full dir path, if valid pointer we're using */
    int   type;      /* PEM or ASN1 type */
};


#if defined(HAVE_CRL) && defined(NO_FILESYSTEM)
    #undef HAVE_CRL_MONITOR
#endif

/* PEM and DER possible */
#define WOLFSSL_CRL_MONITORS_LEN (2)

#if defined(__MACH__) || defined(__FreeBSD__) || defined(__linux__)
typedef int    wolfSSL_CRL_mfd_t; /* monitor fd, -1 if no init yet */
/* mfd for bsd is kqueue fd, eventfd for linux */
#define WOLFSSL_CRL_MFD_INIT_VAL (-1)
#elif defined(_MSC_VER)
typedef HANDLE wolfSSL_CRL_mfd_t; /* monitor fd, INVALID_HANDLE_VALUE if
                                   * no init yet */
#define WOLFSSL_CRL_MFD_INIT_VAL (INVALID_HANDLE_VALUE)
#endif
#endif

/* wolfSSL CRL controller */
struct WOLFSSL_CRL {
    WOLFSSL_CERT_MANAGER* cm;            /* pointer back to cert manager */
    CRL_Entry*            currentEntry;  /* Current CRL entry being processed */
    CRL_Entry*            crlList;       /* our CRL list */
#ifdef HAVE_CRL_IO
    CbCrlIO               crlIOCb;
#endif
    wolfSSL_RwLock        crlLock;       /* CRL list lock */
#ifdef HAVE_CRL_MONITOR
    CRL_Monitor           monitors[WOLFSSL_CRL_MONITORS_LEN];
    COND_TYPE             cond;          /* condition to signal setup */
    THREAD_TYPE           tid;           /* monitoring thread */
    wolfSSL_CRL_mfd_t     mfd;
    int                   setup;         /* thread is setup predicate */
#endif
#ifdef OPENSSL_ALL
    wolfSSL_Ref           ref;
#endif
#if defined(OPENSSL_EXTRA)
    WOLFSSL_STACK*        revokedStack;  /* cached STACK_OF(X509_REVOKED) */
#endif
    void*                 heap;          /* heap hint for dynamic memory */
};
#endif


#ifdef NO_ASN
    typedef struct Signer Signer;
#ifdef WOLFSSL_TRUST_PEER_CERT
    typedef struct TrustedPeerCert TrustedPeerCert;
#endif
#endif


#ifndef CA_TABLE_SIZE
    #define CA_TABLE_SIZE 11
#endif
#ifdef WOLFSSL_TRUST_PEER_CERT
    #define TP_TABLE_SIZE 11
#endif

/* wolfSSL Certificate Manager */
struct WOLFSSL_CERT_MANAGER {
    Signer*         caTable[CA_TABLE_SIZE]; /* the CA signer table */
    void*           heap;                /* heap helper */
#ifdef WOLFSSL_TRUST_PEER_CERT
    TrustedPeerCert* tpTable[TP_TABLE_SIZE]; /* table of trusted peer certs */
    wolfSSL_Mutex   tpLock;                  /* trusted peer list lock */
#endif
    WOLFSSL_CRL*    crl;                 /* CRL checker */
    WOLFSSL_OCSP*   ocsp;                /* OCSP checker */
#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
                               ||  defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
    WOLFSSL_OCSP*   ocsp_stapling;       /* OCSP checker for OCSP stapling */
#endif
    char*           ocspOverrideURL;     /* use this responder */
    void*           ocspIOCtx;           /* I/O callback CTX */
#ifndef NO_WOLFSSL_CM_VERIFY
    VerifyCallback  verifyCallback;      /* Verify callback */
#endif
    CallbackCACache caCacheCallback;       /* CA cache addition callback */
    CbMissingCRL    cbMissingCRL;          /* notify thru cb of missing crl */
    crlErrorCb      crlCb;                 /* Allow user to override error */
    void*           crlCbCtx;
    CbOCSPIO        ocspIOCb;              /* I/O callback for OCSP lookup */
    CbOCSPRespFree  ocspRespFreeCb;        /* Frees OCSP Response from IO Cb */
    wolfSSL_Mutex   caLock;                /* CA list lock */
    byte            crlEnabled:1;          /* is CRL on ? */
    byte            crlCheckAll:1;         /* always leaf, but all ? */
    byte            ocspEnabled:1;         /* is OCSP on ? */
    byte            ocspCheckAll:1;        /* always leaf, but all ? */
    byte            ocspSendNonce:1;       /* send the OCSP nonce ? */
    byte            ocspUseOverrideURL:1;  /* ignore cert responder, override */
    byte            ocspStaplingEnabled:1; /* is OCSP Stapling on ? */
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
||  defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
    byte            ocspMustStaple:1;      /* server must respond with staple */
#endif

#ifndef NO_RSA
    short           minRsaKeySz;         /* minimum allowed RSA key size */
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
    short           minEccKeySz;         /* minimum allowed ECC key size */
#endif
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
    WOLFSSL_X509_STORE  *x509_store_p;  /* a pointer back to CTX x509 store  */
                                        /* CTX has ownership and free this   */
                                        /* with CTX free.                    */
#endif
    wolfSSL_Ref     ref;
#ifdef HAVE_FALCON
    short           minFalconKeySz;     /* minimum allowed Falcon key size */
#endif
#ifdef HAVE_DILITHIUM
    short           minDilithiumKeySz;  /* minimum allowed Dilithium key size */
#endif
#ifdef WC_ASN_UNKNOWN_EXT_CB
    wc_UnknownExtCallback unknownExtCallback;
#endif
#ifdef HAVE_CRL_UPDATE_CB
    CbUpdateCRL    cbUpdateCRL; /* notify thru cb that crl has updated */
#endif
};

WOLFSSL_LOCAL int CM_SaveCertCache(WOLFSSL_CERT_MANAGER* cm,
                                   const char* fname);
WOLFSSL_LOCAL int CM_RestoreCertCache(WOLFSSL_CERT_MANAGER* cm,
                                      const char* fname);
WOLFSSL_LOCAL int CM_MemSaveCertCache(WOLFSSL_CERT_MANAGER* cm, void* mem,
                                      int sz, int* used);
WOLFSSL_LOCAL int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm,
                                         const void* mem, int sz);
WOLFSSL_LOCAL int CM_GetCertCacheMemSize(WOLFSSL_CERT_MANAGER* cm);
WOLFSSL_LOCAL int CM_VerifyBuffer_ex(WOLFSSL_CERT_MANAGER* cm, const byte* buff,
                                     long sz, int format, int prev_err);


#ifndef NO_CERTS
#if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
typedef struct ProcPeerCertArgs {
    buffer*      certs;
#ifdef WOLFSSL_TLS13
    buffer*      exts; /* extensions */
#endif
#ifndef NO_ASN
    DecodedCert* dCert;
#endif
    word32 idx;
    word32 begin;
    int    totalCerts; /* number of certs in certs buffer */
    int    count;
    int    certIdx;
    int    lastErr;
    int    leafVerifyErr;
#ifdef WOLFSSL_TLS13
    byte   ctxSz;
#endif
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    char   untrustedDepth;
#endif
    word16 fatal:1;
    word16 verifyErr:1;
    word16 dCertInit:1;
#ifdef WOLFSSL_TRUST_PEER_CERT
    word16 haveTrustPeer:1; /* was cert verified by loaded trusted peer cert */
#endif
} ProcPeerCertArgs;
WOLFSSL_LOCAL int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl,
        int cert_err, ProcPeerCertArgs* args);
WOLFSSL_LOCAL void DoCrlCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl,
        ProcPeerCertArgs* args, int* outRet);

WOLFSSL_LOCAL int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt,
        WOLFSSL* ssl, WOLFSSL_CERT_MANAGER* cm, ProcPeerCertArgs* args,
        int cert_err, void* heap, int* x509Free);
WOLFSSL_LOCAL void CleanupStoreCtxCallback(WOLFSSL_X509_STORE_CTX* store,
        WOLFSSL* ssl, void* heap, int x509Free);
#endif /* !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) */
WOLFSSL_LOCAL int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str,
                                        byte *buf, word32 bufLen, int type);
#endif /* !defined NO_CERTS */

/* wolfSSL Sock Addr */
struct WOLFSSL_SOCKADDR {
    unsigned int sz; /* sockaddr size */
    unsigned int bufSz; /* size of allocated buffer */
    void*        sa; /* pointer to the sockaddr_in or sockaddr_in6 */
};

#ifdef WOLFSSL_DTLS
typedef struct WOLFSSL_DTLS_CTX {
#ifdef WOLFSSL_RW_THREADED
    /* Protect peer access after the handshake */
    wolfSSL_RwLock peerLock;
#endif
    WOLFSSL_SOCKADDR peer;
#ifdef WOLFSSL_DTLS_CID
    WOLFSSL_SOCKADDR pendingPeer; /* When using CID's, we don't want to update
                                   * the peer's address until we successfully
                                   * de-protect the record. */
#endif
    int rfd;
    int wfd;
    WolfSSLRecvFrom recvfrom;
    WolfSSLSento sendto;
    byte userSet:1;
    byte connected:1; /* When set indicates rfd and wfd sockets are
                       * connected (connect() and bind() both called).
                       * This means that sendto and recvfrom do not need to
                       * specify and store the peer address. */
#ifdef WOLFSSL_DTLS_CID
    byte processingPendingRecord:1;
#endif
} WOLFSSL_DTLS_CTX;
#endif


typedef struct WOLFSSL_DTLS_PEERSEQ {
    word32 window[WOLFSSL_DTLS_WINDOW_WORDS];
                        /* Sliding window for current epoch    */
    word16 nextEpoch;   /* Expected epoch in next record       */
    word16 nextSeq_hi;  /* Expected sequence in next record    */
    word32 nextSeq_lo;

    word32 prevWindow[WOLFSSL_DTLS_WINDOW_WORDS];
                        /* Sliding window for old epoch        */
    word32 prevSeq_lo;
    word16 prevSeq_hi;  /* Next sequence in allowed old epoch  */

#ifdef WOLFSSL_MULTICAST
    word16 peerId;
    word32 highwaterMark;
#endif
} WOLFSSL_DTLS_PEERSEQ;

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
struct WOLFSSL_BIO {
    WOLFSSL_BUF_MEM* mem_buf;
    WOLFSSL_BIO_METHOD* method;
    WOLFSSL_BIO* prev;          /* previous in chain */
    WOLFSSL_BIO* next;          /* next in chain */
    WOLFSSL_BIO* pair;          /* BIO paired with */
    void*        heap;          /* user heap hint */
    union {
        byte*    mem_buf_data;
#ifndef WOLFCRYPT_ONLY
        WOLFSSL* ssl;
        WOLFSSL_EVP_MD_CTX* md_ctx;
#endif
#ifndef NO_FILESYSTEM
        XFILE    fh;
#endif
    } ptr;
    void*        usrCtx;        /* user set pointer */
    char*        ip;            /* IP address for wolfIO_TcpConnect */
    word16       port;          /* Port for wolfIO_TcpConnect */
    char*        infoArg;       /* BIO callback argument */
    wolf_bio_info_cb infoCb;    /* BIO callback */
    int          wrSz;          /* write buffer size (mem) */
    int          wrSzReset;     /* First buffer size (mem) - read ONLY data */
    int          wrIdx;         /* current index for write buffer */
    int          rdIdx;         /* current read index */
    int          readRq;        /* read request */
    union {
        SOCKET_T fd;
        size_t   length;
    } num;
    int          eof;           /* eof flag */
    int          flags;
    byte         type;          /* method type */
    byte         init:1;        /* bio has been initialized */
    byte         shutdown:1;    /* close flag */
    byte         connected:1;   /* connected state, for datagram BIOs -- as for
                                 * struct WOLFSSL_DTLS_CTX, when set, sendto and
                                 * recvfrom leave the peer_addr unchanged. */
#ifdef WOLFSSL_HAVE_BIO_ADDR
    union WOLFSSL_BIO_ADDR peer_addr; /* for datagram BIOs, the socket address stored
                                       * with BIO_CTRL_DGRAM_CONNECT,
                                       * BIO_CTRL_DGRAM_SET_CONNECTED, or
                                       * BIO_CTRL_DGRAM_SET_PEER, or stored when a
                                       * packet was received on an unconnected BIO. */
#endif

#if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_BIO_NO_FLOW_STATS)
    #define WOLFSSL_BIO_HAVE_FLOW_STATS
    word64       bytes_read;
    word64       bytes_written;
#endif

#ifdef HAVE_EX_DATA
    WOLFSSL_CRYPTO_EX_DATA ex_data;
#endif
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
    wolfSSL_Ref  ref;
#endif
};
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */

#if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(OPENSSL_EXTRA)
WOLFSSL_LOCAL socklen_t wolfSSL_BIO_ADDR_size(const WOLFSSL_BIO_ADDR *addr);
#endif

#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && defined(WOLFSSL_SHA384)
    /* Integrity-only cipher suites use IV size equal to hash output size */
    #define MAX_WRITE_IV_SZ 48
#elif defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && !defined(NO_SHA256)
    /* Integrity-only cipher suites use IV size equal to hash output size */
    #define MAX_WRITE_IV_SZ 32
#else
    #define MAX_WRITE_IV_SZ 16 /* max size of client/server write_IV */
#endif

/* keys and secrets
 * keep as a constant size (no additional ifdefs) for session export */
typedef struct Keys {
#if !defined(WOLFSSL_AEAD_ONLY) || defined(WOLFSSL_TLS13)
    byte client_write_MAC_secret[WC_MAX_DIGEST_SIZE];   /* max sizes */
    byte server_write_MAC_secret[WC_MAX_DIGEST_SIZE];
#endif
    byte client_write_key[MAX_SYM_KEY_SIZE];         /* max sizes */
    byte server_write_key[MAX_SYM_KEY_SIZE];
    byte client_write_IV[MAX_WRITE_IV_SZ];               /* max sizes */
    byte server_write_IV[MAX_WRITE_IV_SZ];
#if defined(HAVE_AEAD) || defined(WOLFSSL_SESSION_EXPORT)
    byte aead_exp_IV[AEAD_MAX_EXP_SZ];
    byte aead_enc_imp_IV[AEAD_MAX_IMP_SZ];
    byte aead_dec_imp_IV[AEAD_MAX_IMP_SZ];
#endif

#ifdef WOLFSSL_DTLS13
    byte client_sn_key[MAX_SYM_KEY_SIZE];
    byte server_sn_key[MAX_SYM_KEY_SIZE];
#endif /* WOLFSSL_DTLS13 */

    word32 peer_sequence_number_hi;
    word32 peer_sequence_number_lo;
    word32 sequence_number_hi;
    word32 sequence_number_lo;

#ifdef WOLFSSL_DTLS
    word16 curEpoch;    /* Received epoch in current record    */
    word16 curSeq_hi;   /* Received sequence in current record */
    word32 curSeq_lo;

#ifdef WOLFSSL_DTLS13
    w64wrapper curEpoch64;    /* Received epoch in current record    */
    w64wrapper curSeq;
#endif /* WOLFSSL_DTLS13 */

#ifdef WOLFSSL_MULTICAST
    byte   curPeerId;   /* Received peer group ID in current record */
#endif
    WOLFSSL_DTLS_PEERSEQ peerSeq[WOLFSSL_DTLS_PEERSEQ_SZ];

    word16 dtls_peer_handshake_number;
    word16 dtls_expected_peer_handshake_number;

    word16 dtls_epoch;                          /* Current epoch    */
    word16 dtls_sequence_number_hi;             /* Current epoch */
    word32 dtls_sequence_number_lo;
    word16 dtls_prev_sequence_number_hi;        /* Previous epoch */
    word32 dtls_prev_sequence_number_lo;
    word16 dtls_handshake_number;               /* Current tx handshake seq */
#endif

    word32 encryptSz;             /* last size of encrypted data   */
    word32 padSz;                 /* how much to advance after decrypt part */
    byte   encryptionOn;          /* true after change cipher spec */
    byte   decryptedCur;          /* only decrypt current record once */
#ifdef WOLFSSL_TLS13
    byte   updateResponseReq;     /* KeyUpdate response from peer required. */
    byte   keyUpdateRespond;      /* KeyUpdate is to be responded to. */
#endif
#ifdef WOLFSSL_RENESAS_TSIP_TLS

    tsip_hmac_sha_key_index_t tsip_client_write_MAC_secret;
    tsip_hmac_sha_key_index_t tsip_server_write_MAC_secret;

#endif
#ifdef WOLFSSL_RENESAS_FSPSM_TLS
    FSPSM_HMAC_WKEY fspsm_client_write_MAC_secret;
    FSPSM_HMAC_WKEY fspsm_server_write_MAC_secret;
#endif
} Keys;

/* Forward declare opaque pointer to make available for func def */
typedef struct Options Options;


/** TLS Extensions - RFC 6066 */
#ifdef HAVE_TLS_EXTENSIONS

#define TLSXT_SERVER_NAME                0x0000 /* a.k.a. SNI  */
#define TLSXT_MAX_FRAGMENT_LENGTH        0x0001
#define TLSXT_TRUSTED_CA_KEYS            0x0003
#define TLSXT_TRUNCATED_HMAC             0x0004
#define TLSXT_STATUS_REQUEST             0x0005 /* a.k.a. OCSP stapling   */
#define TLSXT_SUPPORTED_GROUPS           0x000a /* a.k.a. Supported Curves */
#define TLSXT_EC_POINT_FORMATS           0x000b
#define TLSXT_SIGNATURE_ALGORITHMS       0x000d /* HELLO_EXT_SIG_ALGO */
#define TLSXT_USE_SRTP                   0x000e /* 14 */
#define TLSXT_APPLICATION_LAYER_PROTOCOL 0x0010 /* a.k.a. ALPN */
#define TLSXT_STATUS_REQUEST_V2          0x0011 /* a.k.a. OCSP stapling v2 */
#define TLSXT_CLIENT_CERTIFICATE         0x0013 /* RFC8446 */
#define TLSXT_SERVER_CERTIFICATE         0x0014 /* RFC8446 */
#define TLSXT_ENCRYPT_THEN_MAC           0x0016 /* RFC 7366 */
#define TLSXT_EXTENDED_MASTER_SECRET     0x0017 /* HELLO_EXT_EXTMS */
#define TLSXT_SESSION_TICKET             0x0023
#define TLSXT_PRE_SHARED_KEY             0x0029
#define TLSXT_EARLY_DATA                 0x002a
#define TLSXT_SUPPORTED_VERSIONS         0x002b
#define TLSXT_COOKIE                     0x002c
#define TLSXT_PSK_KEY_EXCHANGE_MODES     0x002d
#define TLSXT_CERTIFICATE_AUTHORITIES    0x002f
#define TLSXT_POST_HANDSHAKE_AUTH        0x0031
#define TLSXT_SIGNATURE_ALGORITHMS_CERT  0x0032
#define TLSXT_KEY_SHARE                  0x0033
#define TLSXT_CONNECTION_ID              0x0036
#define TLSXT_KEY_QUIC_TP_PARAMS         0x0039 /* RFC 9001, ch. 8.2 */
#define TLSXT_ECH                        0xfe0d /* RFC 9849 */
#define TLSXT_ECH_OUTER_EXTENSIONS       0xfd00 /* RFC 9849 */
/* The 0xFF section is experimental/custom/personal use */
#define TLSXT_CKS                        0xff92 /* X9.146 */
#define TLSXT_RENEGOTIATION_INFO         0xff01
#define TLSXT_KEY_QUIC_TP_PARAMS_DRAFT   0xffa5 /* from */
                                                /* draft-ietf-quic-tls-27 */

typedef enum {
#ifdef HAVE_SNI
    TLSX_SERVER_NAME                = TLSXT_SERVER_NAME,
#endif
    TLSX_MAX_FRAGMENT_LENGTH        = TLSXT_MAX_FRAGMENT_LENGTH,
    TLSX_TRUSTED_CA_KEYS            = TLSXT_TRUSTED_CA_KEYS,
    TLSX_TRUNCATED_HMAC             = TLSXT_TRUNCATED_HMAC,
    TLSX_STATUS_REQUEST             = TLSXT_STATUS_REQUEST,
    TLSX_SUPPORTED_GROUPS           = TLSXT_SUPPORTED_GROUPS,
    TLSX_EC_POINT_FORMATS           = TLSXT_EC_POINT_FORMATS,
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
    TLSX_SIGNATURE_ALGORITHMS       = TLSXT_SIGNATURE_ALGORITHMS,
#endif
#ifdef WOLFSSL_SRTP
    TLSX_USE_SRTP                   = TLSXT_USE_SRTP,
#endif
    TLSX_APPLICATION_LAYER_PROTOCOL = TLSXT_APPLICATION_LAYER_PROTOCOL,
    TLSX_STATUS_REQUEST_V2          = TLSXT_STATUS_REQUEST_V2,
#ifdef HAVE_RPK
    TLSX_CLIENT_CERTIFICATE_TYPE    = TLSXT_CLIENT_CERTIFICATE,
    TLSX_SERVER_CERTIFICATE_TYPE    = TLSXT_SERVER_CERTIFICATE,
#endif
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
    TLSX_ENCRYPT_THEN_MAC           = TLSXT_ENCRYPT_THEN_MAC,
#endif
    TLSX_EXTENDED_MASTER_SECRET     = TLSXT_EXTENDED_MASTER_SECRET,
    TLSX_SESSION_TICKET             = TLSXT_SESSION_TICKET,
#ifdef WOLFSSL_TLS13
    #ifdef WOLFSSL_EARLY_DATA
    TLSX_EARLY_DATA                 = TLSXT_EARLY_DATA,
    #endif
    TLSX_SUPPORTED_VERSIONS         = TLSXT_SUPPORTED_VERSIONS,
    #ifdef WOLFSSL_SEND_HRR_COOKIE
    TLSX_COOKIE                     = TLSXT_COOKIE,
    #endif
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    TLSX_PSK_KEY_EXCHANGE_MODES     = TLSXT_PSK_KEY_EXCHANGE_MODES,
    #endif
    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
    TLSX_CERTIFICATE_AUTHORITIES    = TLSXT_CERTIFICATE_AUTHORITIES,
    #endif
    #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
    TLSX_POST_HANDSHAKE_AUTH        = TLSXT_POST_HANDSHAKE_AUTH,
    #endif
    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
    TLSX_SIGNATURE_ALGORITHMS_CERT  = TLSXT_SIGNATURE_ALGORITHMS_CERT,
    #endif
    #ifdef WOLFSSL_QUIC
    TLSX_KEY_QUIC_TP_PARAMS         = TLSXT_KEY_QUIC_TP_PARAMS,
    #endif
    #ifdef HAVE_ECH
    TLSX_ECH                        = TLSXT_ECH,
    #endif
#endif
#if defined(WOLFSSL_DTLS_CID)
    TLSX_CONNECTION_ID              = TLSXT_CONNECTION_ID,
#endif /* defined(WOLFSSL_DTLS_CID) */
#if defined(WOLFSSL_TLS13) || !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    TLSX_PRE_SHARED_KEY             = TLSXT_PRE_SHARED_KEY,
    #endif
    TLSX_KEY_SHARE                  = TLSXT_KEY_SHARE,
#endif
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_DUAL_ALG_CERTS)
    TLSX_CKS                        = TLSXT_CKS,
#endif
    TLSX_RENEGOTIATION_INFO         = TLSXT_RENEGOTIATION_INFO,
#ifdef WOLFSSL_QUIC
    TLSX_KEY_QUIC_TP_PARAMS_DRAFT   = TLSXT_KEY_QUIC_TP_PARAMS_DRAFT,
#endif
} TLSX_Type;

/* TLS Certificate type defined RFC7250
 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#tls-extensiontype-values-3
 */
#if defined(HAVE_RPK)
typedef struct RpkConfig {
    /* user's preference */
    byte preferred_ClientCertTypeCnt;
    byte preferred_ClientCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
    byte preferred_ServerCertTypeCnt;
    byte preferred_ServerCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
    /* reflect to client_certificate_type extension in xxxHello */
} RpkConfig;

typedef struct RpkState {
    byte sending_ClientCertTypeCnt;
    byte sending_ClientCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
    /* reflect to server_certificate_type extension in xxxHello */
    byte sending_ServerCertTypeCnt;
    byte sending_ServerCertTypes[MAX_SERVER_CERT_TYPE_CNT];
    /* client_certificate_type extension in received yyyHello  */
    byte received_ClientCertTypeCnt;
    byte received_ClientCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
    /* server_certificate_type extension in received yyyHello  */
    byte received_ServerCertTypeCnt;
    byte received_ServerCertTypes[MAX_SERVER_CERT_TYPE_CNT];
    /* set if Raw-public-key cert is loaded as own certificate */
    int  isRPKLoaded;
} RpkState;
#endif /* HAVE_RPK */

#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
#define ECH_ACCEPT_CONFIRMATION_SZ 8

typedef enum {
    ECH_TYPE_OUTER = 0,
    ECH_TYPE_INNER = 1
} EchType;

typedef enum {
    ECH_WRITE_GREASE,
    ECH_WRITE_REAL,
    ECH_WRITE_RETRY_CONFIGS,
    ECH_WRITE_NONE,
    ECH_PARSED_INTERNAL,
} EchState;

typedef enum {
    ECH_OUTER_SNI,
    ECH_INNER_SNI,
    ECH_INNER_SNI_ATTEMPT,
    ECH_SNI_DONE,
} EchStateSNI;

typedef struct EchCipherSuite {
    word16 kdfId;
    word16 aeadId;
} EchCipherSuite;

typedef struct WOLFSSL_EchConfig {
    byte* raw;
    char* publicName;
    void* receiverPrivkey;
    struct WOLFSSL_EchConfig* next;
    EchCipherSuite* cipherSuites;
    word32 rawLen;
    word16 kemId;
    byte configId;
    byte numCipherSuites;
    byte receiverPubkey[HPKE_Npk_MAX];
} WOLFSSL_EchConfig;

typedef struct WOLFSSL_ECH {
    Hpke* hpke;
    HpkeBaseContext* hpkeContext;
    const byte* aad;
    const char* privateName;
    void* ephemeralKey;
    WOLFSSL_EchConfig* echConfig;
    byte* innerClientHello;
    byte* outerClientPayload;
    byte* confBuf;
    EchCipherSuite cipherSuite;
    word16 aadLen;
    word16 paddingLen;
    word16 innerClientHelloLen;
    word16 kemId;
    word16 encLen;
    EchState state;
    EchStateSNI sniState;
    byte type;
    byte configId;
    byte enc[HPKE_Npk_MAX];
    byte innerCount;
} WOLFSSL_ECH;

WOLFSSL_LOCAL int EchConfigGetSupportedCipherSuite(WOLFSSL_EchConfig* config);

WOLFSSL_LOCAL int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen);


WOLFSSL_LOCAL int SetEchConfigsEx(WOLFSSL_EchConfig** outputConfigs, void* heap,
    const byte* echConfigs, word32 echConfigsLen);

WOLFSSL_LOCAL int GetEchConfig(WOLFSSL_EchConfig* config, byte* output,
    word32* outputLen);

WOLFSSL_LOCAL int GetEchConfigsEx(WOLFSSL_EchConfig* configs,
    byte* output, word32* outputLen);

WOLFSSL_LOCAL void FreeEchConfigs(WOLFSSL_EchConfig* configs, void* heap);
#endif

struct TLSX {
    TLSX_Type    type; /* Extension Type  */
    void*        data; /* Extension Data  */
    word32       val;  /* Extension Value */
    byte         resp; /* IsResponse Flag */
    struct TLSX* next; /* List Behavior   */
};

#ifdef WOLFSSL_API_PREFIX_MAP
    #define TLSX_Find wolfSSL_TLSX_Find
#endif
WOLFSSL_TEST_VIS TLSX* TLSX_Find(TLSX* list, TLSX_Type type);
WOLFSSL_LOCAL void  TLSX_Remove(TLSX** list, TLSX_Type type, void* heap);
WOLFSSL_LOCAL void  TLSX_FreeAll(TLSX* list, void* heap);
WOLFSSL_LOCAL int   TLSX_SupportExtensions(WOLFSSL* ssl);
WOLFSSL_LOCAL int   TLSX_PopulateExtensions(WOLFSSL* ssl, byte isRequest);

#if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
WOLFSSL_LOCAL int   TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType,
                                         word32* pLength);
WOLFSSL_LOCAL int   TLSX_WriteRequest(WOLFSSL* ssl, byte* output,
                                       byte msgType, word32* pOffset);
#endif

#if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
/* TLS 1.3 Certificate messages have extensions. */
WOLFSSL_LOCAL int   TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType,
                                          word16* pLength);
WOLFSSL_LOCAL int   TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType,
                                        word16* pOffset);
#endif

WOLFSSL_LOCAL int   TLSX_ParseVersion(WOLFSSL* ssl, const byte* input,
                                      word16 length, byte msgType, int* found);
WOLFSSL_LOCAL int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl,
        const byte* input, word16 length, byte msgType, ProtocolVersion* pv,
        Options* opts, TLSX** exts);
WOLFSSL_LOCAL int   TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length,
                               byte msgType, Suites *suites);
WOLFSSL_LOCAL int TLSX_Push(TLSX** list, TLSX_Type type,
                            const void* data, void* heap);
WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type,
                            const void* data, void* heap);

#elif defined(HAVE_SNI)                           \
   || defined(HAVE_MAX_FRAGMENT)                  \
   || defined(HAVE_TRUSTED_CA)                    \
   || defined(HAVE_TRUNCATED_HMAC)                \
   || defined(HAVE_CERTIFICATE_STATUS_REQUEST)    \
   || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) \
   || defined(HAVE_SUPPORTED_CURVES)              \
   || defined(HAVE_ALPN)                          \
   || defined(HAVE_SESSION_TICKET)                \
   || defined(HAVE_SECURE_RENEGOTIATION)          \
   || defined(HAVE_SERVER_RENEGOTIATION_INFO)

#ifndef NO_TLS
#error Using TLS extensions requires HAVE_TLS_EXTENSIONS to be defined.
#endif
#endif /* HAVE_TLS_EXTENSIONS */

/** Server Name Indication - RFC 6066 (session 3) */
#ifdef HAVE_SNI

typedef struct SNI {
    byte                       type;    /* SNI Type         */
    union { char* host_name; } data;    /* SNI Data         */
    struct SNI*                next;    /* List Behavior    */
    byte                       status;  /* Matching result  */
#ifndef NO_WOLFSSL_SERVER
    byte                       options; /* Behavior options */
#endif
} SNI;

WOLFSSL_LOCAL int TLSX_UseSNI(TLSX** extensions, byte type, const void* data,
                                                       word16 size, void* heap);
WOLFSSL_LOCAL byte TLSX_SNI_Status(TLSX* extensions, byte type);
WOLFSSL_LOCAL word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type,
                                                void** data, byte ignoreStatus);
#ifdef WOLFSSL_API_PREFIX_MAP
    #define TLSX_SNI_GetSize wolfSSL_TLSX_SNI_GetSize
#endif
WOLFSSL_TEST_VIS word16 TLSX_SNI_GetSize(SNI* list);

#ifndef NO_WOLFSSL_SERVER
WOLFSSL_LOCAL void   TLSX_SNI_SetOptions(TLSX* extensions, byte type,
                                                                  byte options);
WOLFSSL_LOCAL int    TLSX_SNI_GetFromBuffer(const byte* clientHello,
                         word32 helloSz, byte type, byte* sni, word32* inOutSz);
#endif

#endif /* HAVE_SNI */

/* Trusted CA Key Indication - RFC 6066 (section 6) */
#ifdef HAVE_TRUSTED_CA

typedef struct TCA {
    byte                       type;    /* TCA Type            */
    byte*                      id;      /* TCA identifier      */
    word16                     idSz;    /* TCA identifier size */
    struct TCA*                next;    /* List Behavior       */
} TCA;

WOLFSSL_LOCAL int TLSX_UseTrustedCA(TLSX** extensions, byte type,
                    const byte* id, word16 idSz, void* heap);

#endif /* HAVE_TRUSTED_CA */

/* Application-Layer Protocol Negotiation - RFC 7301 */
#ifdef HAVE_ALPN
typedef struct ALPN {
    char*        protocol_name; /* ALPN protocol name */
    struct ALPN* next;          /* List Behavior      */
    byte         options;       /* Behavior options */
    byte         negotiated;    /* ALPN protocol negotiated or not */
} ALPN;

WOLFSSL_LOCAL int TLSX_ALPN_GetRequest(TLSX* extensions,
                                       void** data, word16 *dataSz);

WOLFSSL_LOCAL int TLSX_UseALPN(TLSX** extensions, const void* data,
                               word16 size, byte options, void* heap);

WOLFSSL_LOCAL int TLSX_ALPN_SetOptions(TLSX** extensions, byte option);

#endif /* HAVE_ALPN */

/** Maximum Fragment Length Negotiation - RFC 6066 (session 4) */
#ifdef HAVE_MAX_FRAGMENT

WOLFSSL_LOCAL int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap);

#endif /* HAVE_MAX_FRAGMENT */

/** Truncated HMAC - RFC 6066 (session 7) */
#ifdef HAVE_TRUNCATED_HMAC

WOLFSSL_LOCAL int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap);

#endif /* HAVE_TRUNCATED_HMAC */

/** Certificate Status Request - RFC 6066 (session 8) */
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST

typedef struct {
    byte status_type;
    byte options;
    WOLFSSL* ssl;
    union {
        OcspRequest ocsp[MAX_CERT_EXTENSIONS];
    } request;
    word16 requests;
#ifdef WOLFSSL_TLS13
    buffer responses[MAX_CERT_EXTENSIONS];
#endif
} CertificateStatusRequest;

WOLFSSL_LOCAL int   TLSX_UseCertificateStatusRequest(TLSX** extensions,
           byte status_type, byte options, WOLFSSL* ssl, void* heap, int devId);
#ifndef NO_CERTS
WOLFSSL_LOCAL int   TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert,
                                                                    void* heap);
WOLFSSL_LOCAL int   TLSX_CSR_InitRequest_ex(TLSX* extensions, DecodedCert* cert,
                                            void* heap, int idx);
#endif
WOLFSSL_LOCAL void* TLSX_CSR_GetRequest(TLSX* extensions);
WOLFSSL_LOCAL int   TLSX_CSR_ForceRequest(WOLFSSL* ssl);
WOLFSSL_LOCAL word16 TLSX_CSR_GetSize_ex(CertificateStatusRequest* csr,
                                        byte isRequest,
                                        int idx);
WOLFSSL_LOCAL int TLSX_CSR_Write_ex(CertificateStatusRequest* csr, byte* output,
                          byte isRequest, int idx);
WOLFSSL_LOCAL void* TLSX_CSR_GetRequest_ex(TLSX* extensions, int idx);

WOLFSSL_LOCAL int TLSX_CSR_SetResponseWithStatusCB(WOLFSSL *ssl);
WOLFSSL_LOCAL int ProcessChainOCSPRequest(WOLFSSL* ssl);

#endif
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
    defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
WOLFSSL_LOCAL int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request,
                             DecodedCert* cert, byte* certData, word32 length,
                             byte *ctxOwnsRequest);
#endif
/** Certificate Status Request v2 - RFC 6961 */
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2

typedef struct CSRIv2 {
    byte status_type;
    byte options;
    word16 requests;
    union {
        OcspRequest ocsp[1 + MAX_CHAIN_DEPTH];
    } request;
    struct CSRIv2* next;
    Signer *pendingSigners;
} CertificateStatusRequestItemV2;

WOLFSSL_LOCAL int   TLSX_UseCertificateStatusRequestV2(TLSX** extensions,
                         byte status_type, byte options, void* heap, int devId);
#ifndef NO_CERTS
WOLFSSL_LOCAL int TLSX_CSR2_IsMulti(TLSX *extensions);
WOLFSSL_LOCAL int TLSX_CSR2_AddPendingSigner(TLSX *extensions, Signer *s);
WOLFSSL_LOCAL Signer* TLSX_CSR2_GetPendingSigners(TLSX *extensions);
WOLFSSL_LOCAL int TLSX_CSR2_ClearPendingCA(WOLFSSL *ssl);
WOLFSSL_LOCAL int TLSX_CSR2_MergePendingCA(WOLFSSL* ssl);
WOLFSSL_LOCAL int   TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert,
                                                       byte isPeer, void* heap);
#endif
WOLFSSL_LOCAL void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type,
                                                                    byte idx);
WOLFSSL_LOCAL int   TLSX_CSR2_ForceRequest(WOLFSSL* ssl);

#endif

#if defined(WOLFSSL_PUBLIC_ASN) && defined(HAVE_PK_CALLBACKS)
/* Internal callback guarded by WOLFSSL_TEST_VIS because of DecodedCert. */
typedef int (*CallbackProcessPeerCert)(WOLFSSL* ssl, DecodedCert* p_cert);
WOLFSSL_TEST_VIS void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
       CallbackProcessPeerCert cb);
#endif /* DecodedCert && HAVE_PK_CALLBACKS */

#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
typedef struct SignatureAlgorithms {
    /* Not const since it is modified in TLSX_SignatureAlgorithms_MapPss */
    WOLFSSL*    ssl;
    word16      hashSigAlgoSz; /* SigAlgo extension length in bytes */
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
     * MSVC warning */
    #ifdef _MSC_VER
    #pragma warning(disable: 4200)
    #endif
    byte        hashSigAlgo[]; /* sig/algo to offer */
} SignatureAlgorithms;

WOLFSSL_LOCAL SignatureAlgorithms* TLSX_SignatureAlgorithms_New(
        WOLFSSL* ssl, word16 hashSigAlgoSz, void* heap);
WOLFSSL_LOCAL void TLSX_SignatureAlgorithms_FreeAll(SignatureAlgorithms* sa,
                                                    void* heap);
#endif

/** Supported Elliptic Curves - RFC 4492 (session 4) */
#ifdef HAVE_SUPPORTED_CURVES

typedef struct SupportedCurve {
    word16 name;                 /* Curve Names */
    struct SupportedCurve* next; /* List Behavior */
} SupportedCurve;

typedef struct PointFormat {
    byte format;                /* PointFormat */
    struct PointFormat* next;   /* List Behavior */
} PointFormat;

WOLFSSL_LOCAL int TLSX_SupportedCurve_Copy(TLSX* src, TLSX** dst, void* heap);
WOLFSSL_LOCAL int TLSX_UseSupportedCurve(TLSX** extensions, word16 name,
                                                                    void* heap);

WOLFSSL_LOCAL int TLSX_UsePointFormat(TLSX** extensions, byte point,
                                                                    void* heap);
WOLFSSL_LOCAL int TLSX_IsGroupSupported(int namedGroup);

#ifndef NO_WOLFSSL_SERVER
WOLFSSL_LOCAL int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first,
                                               byte second, word32* ecdhCurveOID);
WOLFSSL_LOCAL int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl);
WOLFSSL_LOCAL int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl);
#endif
WOLFSSL_LOCAL int TLSX_SupportedCurve_IsSupported(WOLFSSL* ssl, word16 name);
WOLFSSL_LOCAL int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl,
                                                            int checkSupported);
WOLFSSL_LOCAL int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl,
        const byte* input, word16 length, byte isRequest, TLSX** extensions);

#endif /* HAVE_SUPPORTED_CURVES */

/** Renegotiation Indication - RFC 5746 */
#if defined(HAVE_SECURE_RENEGOTIATION) \
 || defined(HAVE_SERVER_RENEGOTIATION_INFO)

enum key_cache_state {
    SCR_CACHE_NULL   = 0,       /* empty / begin state */
    SCR_CACHE_NEEDED,           /* need to cache keys */
    SCR_CACHE_COPY,             /* we have a cached copy */
    SCR_CACHE_PARTIAL,          /* partial restore to real keys */
    SCR_CACHE_COMPLETE          /* complete restore to real keys */
};

/* Additional Connection State according to rfc5746 section 3.1 */
typedef struct SecureRenegotiation {
   byte                 enabled;  /* secure_renegotiation flag in rfc */
   byte                 verifySet;
   byte                 startScr; /* server requested client to start scr */
   enum key_cache_state cache_status;  /* track key cache state */
   byte                 client_verify_data[TLS_FINISHED_SZ];  /* cached */
   byte                 server_verify_data[TLS_FINISHED_SZ];  /* cached */
   byte                 subject_hash_set; /* if peer cert hash is set */
   byte                 subject_hash[KEYID_SIZE];  /* peer cert hash */
   Keys                 tmp_keys;  /* can't overwrite real keys yet */
} SecureRenegotiation;

WOLFSSL_LOCAL int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap);

#ifdef HAVE_SERVER_RENEGOTIATION_INFO
WOLFSSL_LOCAL int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap);
#endif

#endif /* HAVE_SECURE_RENEGOTIATION */

#ifdef HAVE_SESSION_TICKET
/* Max peer cert size for ticket: 2KB is reasonable for most RSA/ECC certs */
#ifndef MAX_TICKET_PEER_CERT_SZ
#define MAX_TICKET_PEER_CERT_SZ 2048
#endif

/* Our ticket format. All members need to be a byte or array of byte to
 * avoid alignment issues */
typedef struct InternalTicket {
    ProtocolVersion pv;                    /* version when ticket created */
    byte            suite[SUITE_LEN];      /* cipher suite when created */
    byte            msecret[SECRET_LEN];   /* master secret */
    byte            timestamp[TIMESTAMP_LEN];          /* born on */
    byte            haveEMS;               /* have extended master secret */
#ifdef WOLFSSL_TLS13
    byte            ageAdd[AGEADD_LEN];    /* Obfuscation of age */
    byte            namedGroup[NAMEDGROUP_LEN]; /* Named group used */
    byte            ticketNonceLen;
    byte            ticketNonce[MAX_TICKET_NONCE_STATIC_SZ];
#ifdef WOLFSSL_EARLY_DATA
    byte            maxEarlyDataSz[MAXEARLYDATASZ_LEN]; /* Max size of
                                                         * early data */
#endif
#endif
#ifdef WOLFSSL_TICKET_HAVE_ID
    byte            id[ID_LEN];
#endif
#ifdef OPENSSL_EXTRA
    byte            sessionCtxSz;          /* sessionCtx length        */
    byte            sessionCtx[ID_LEN];    /* app specific context id */
#endif /* OPENSSL_EXTRA */
#if defined(OPENSSL_ALL) && defined(KEEP_PEER_CERT) && \
    !defined(NO_CERT_IN_TICKET)
    byte            peerCertLen[OPAQUE16_LEN]; /* peer cert length */
    byte            peerCert[]; /* peer certificate DER - variable length */
#endif
} InternalTicket;

/* Base size of InternalTicket without the variable-length peerCert field */
#define WOLFSSL_INTERNAL_TICKET_BASE_SZ  (sizeof(InternalTicket))

/* Minimum internal ticket length (no peer cert) */
#ifndef WOLFSSL_TICKET_ENC_CBC_HMAC
    #define WOLFSSL_INTERNAL_TICKET_LEN     WOLFSSL_INTERNAL_TICKET_BASE_SZ
#else
    #define WOLFSSL_INTERNAL_TICKET_LEN     \
        (((WOLFSSL_INTERNAL_TICKET_BASE_SZ + 15) / 16) * 16)
#endif

/* Maximum internal ticket length (with max peer cert) */
#if defined(OPENSSL_ALL) && defined(KEEP_PEER_CERT) && \
    !defined(NO_CERT_IN_TICKET)
    #define WOLFSSL_INTERNAL_TICKET_MAX_SZ  \
        (WOLFSSL_INTERNAL_TICKET_BASE_SZ + MAX_TICKET_PEER_CERT_SZ)
#else
    #define WOLFSSL_INTERNAL_TICKET_MAX_SZ  WOLFSSL_INTERNAL_TICKET_BASE_SZ
#endif

#ifndef WOLFSSL_TICKET_EXTRA_PADDING_SZ
#define WOLFSSL_TICKET_EXTRA_PADDING_SZ 32
#endif

/* Maximum encrypted ticket size */
#define WOLFSSL_TICKET_ENC_SZ \
    (WOLFSSL_INTERNAL_TICKET_MAX_SZ + WOLFSSL_TICKET_EXTRA_PADDING_SZ)

/* RFC 5077 defines this for session tickets. All members need to be a byte or
 * array of byte to avoid alignment issues */
typedef struct ExternalTicket {
    byte key_name[WOLFSSL_TICKET_NAME_SZ];  /* key context name - 16 */
    byte iv[WOLFSSL_TICKET_IV_SZ];          /* this ticket's iv - 16 */
    byte enc_len[OPAQUE16_LEN];             /* encrypted length - 2 */
    byte enc_ticket[];                      /* encrypted ticket - var length
                                             *   + total mac - 32 */
} ExternalTicket;

/* Fixed portion of external ticket (key_name + iv + enc_len) */
#define WOLFSSL_TICKET_FIXED_SZ  \
    (WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + OPAQUE16_LEN + \
        WOLFSSL_TICKET_MAC_SZ)

/* Maximum session ticket length */
#define SESSION_TICKET_LEN  \
    ((int)(WOLFSSL_TICKET_FIXED_SZ + WOLFSSL_TICKET_ENC_SZ))

typedef struct SessionTicket {
    word32 lifetime;
#ifdef WOLFSSL_TLS13
    word64 seen;
    word32 ageAdd;
#endif
    byte*  data;
    word16 size;
} SessionTicket;

#if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_WOLFSSL_SERVER)

/* Data passed to default SessionTicket enc/dec callback. */
typedef struct TicketEncCbCtx {
    /* Name for this context. */
    byte name[WOLFSSL_TICKET_NAME_SZ];
    /* Current keys - current and next. */
    byte key[2][WOLFSSL_TICKET_KEY_SZ];
    /* Expirary date of keys. */
    word32 expirary[2];
    /* Random number generator to use for generating name, keys and IV. */
    WC_RNG rng;
#ifndef SINGLE_THREADED
    /* Mutex for access to changing keys. */
    wolfSSL_Mutex mutex;
#endif
    /* Pointer back to SSL_CTX. */
    WOLFSSL_CTX* ctx;
} TicketEncCbCtx;

#endif /* !WOLFSSL_NO_DEF_TICKET_ENC_CB && !NO_WOLFSSL_SERVER */

WOLFSSL_LOCAL int  TLSX_UseSessionTicket(TLSX** extensions,
                                             SessionTicket* ticket, void* heap);
WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
                                           byte* data, word16 size, void* heap);
WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap);

#endif /* HAVE_SESSION_TICKET */

#ifndef MAX_PSK_ID_LEN
    /* max psk identity/hint supported */
    #if defined(WOLFSSL_TLS13)
        #ifdef SESSION_TICKET_LEN
            #define MAX_PSK_ID_LEN SESSION_TICKET_LEN
        #else
            /* Previous value. Use as fallback for when tickets are disabled. */
            #define MAX_PSK_ID_LEN 1536
        #endif
    #else
        #define MAX_PSK_ID_LEN 128
    #endif
#endif

#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl);
#endif

#ifdef WOLFSSL_TLS13
/* Cookie extension information - cookie data. */
typedef struct Cookie {
    word16 len;
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
     * MSVC warning */
    #ifdef _MSC_VER
    #pragma warning(disable: 4200)
    #endif
    byte   data[];
} Cookie;

WOLFSSL_LOCAL int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data,
        word16 len, byte* mac, byte macSz, int resp, TLSX** exts);
WOLFSSL_LOCAL int TlsCheckCookie(const WOLFSSL* ssl, const byte* cookie,
                                 word16 cookieSz);


/* Key Share - TLS v1.3 Specification */

/* The KeyShare extension information - entry in a linked list. */
typedef struct KeyShareEntry {
    word16                group;     /* NamedGroup                        */
    byte*                 ke;        /* Key exchange data                 */
    word32                keLen;     /* Key exchange data length          */
    void*                 key;       /* Key struct                        */
    word32                keyLen;    /* Key size (bytes)                  */
    byte*                 pubKey;    /* Public key                        */
    word32                pubKeyLen; /* Public key length                 */
#if !defined(NO_DH) || defined(WOLFSSL_HAVE_MLKEM)
    byte*                 privKey;   /* Private key                       */
    word32                privKeyLen;/* Private key length - PQC only     */
#endif
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    word16                session;   /* NamedGroup that was in session    */
    word16                derived;   /* preMaster has been derived        */
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
    int                   lastRet;
#endif
    struct KeyShareEntry* next;      /* List pointer             */
} KeyShareEntry;

WOLFSSL_LOCAL int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group,
        word16 len, byte* data, KeyShareEntry **kse, TLSX** extensions);
WOLFSSL_LOCAL int TLSX_KeyShare_Empty(WOLFSSL* ssl);
WOLFSSL_LOCAL int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl,
        TLSX** extensions);
WOLFSSL_LOCAL int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse);
WOLFSSL_LOCAL int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
        byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse,
        byte* searched);
WOLFSSL_LOCAL int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE);
WOLFSSL_LOCAL int TLSX_KeyShare_Establish(WOLFSSL* ssl, int* doHelloRetry);
WOLFSSL_LOCAL int TLSX_KeyShare_DeriveSecret(WOLFSSL* sclientKSEclientKSEsl);
WOLFSSL_LOCAL int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input,
        word16 length, byte msgType);
WOLFSSL_LOCAL int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
        const byte* input, word16 length, TLSX** extensions);
WOLFSSL_LOCAL int TLSX_KeyShare_HandlePqcHybridKeyServer(WOLFSSL* ssl,
        KeyShareEntry* keyShareEntry, byte* data, word16 len);
#ifdef WOLFSSL_DUAL_ALG_CERTS
WOLFSSL_LOCAL int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input,
                                 word16 length, TLSX** extensions);
WOLFSSL_LOCAL int TLSX_CKS_Set(WOLFSSL* ssl, TLSX** extensions);
#endif
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)

enum PskDecryptReturn {
    PSK_DECRYPT_NONE = 0,
    PSK_DECRYPT_OK,
    PSK_DECRYPT_CREATE,
    PSK_DECRYPT_FAIL,
};

#ifdef HAVE_SESSION_TICKET
typedef struct psk_sess_free_cb_ctx {
    word32 row;
#ifdef HAVE_EXT_CACHE
    int extCache;
    int freeSess;
#endif
} psk_sess_free_cb_ctx;
typedef void (psk_sess_free_cb)(const WOLFSSL* ssl, const WOLFSSL_SESSION* sess,
        psk_sess_free_cb_ctx* freeCtx);
#endif

/* The PreSharedKey extension information - entry in a linked list. */
typedef struct PreSharedKey {
    word16               identityLen;             /* Length of identity */
    byte*                identity;                /* PSK identity       */
    word32               ticketAge;               /* Age of the ticket  */
    byte                 cipherSuite0;            /* Cipher Suite       */
    byte                 cipherSuite;             /* Cipher Suite       */
    word32               binderLen;               /* Length of HMAC     */
    byte                 binder[WC_MAX_DIGEST_SIZE]; /* HMAC of handshake */
    byte                 hmac;                    /* HMAC algorithm     */
#ifdef HAVE_SESSION_TICKET
    InternalTicket*      it;                      /* ptr to ticket      */
    const WOLFSSL_SESSION* sess; /* ptr to session either from external cache or
                                  * into SessionCache. Work around so that we
                                  * don't call into the cache more than once */
    psk_sess_free_cb* sess_free_cb;               /* callback to free sess */
    psk_sess_free_cb_ctx sess_free_cb_ctx;        /* info for sess_free_cb */
#endif
    byte                 resumption:1;            /* Resumption PSK     */
    byte                 chosen:1;                /* Server's choice    */
    byte                 decryptRet:3;            /* Ticket decrypt return */
    struct PreSharedKey* next;                    /* List pointer       */
} PreSharedKey;

WOLFSSL_LOCAL int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list,
                                                 byte* output, byte msgType,
                                                 word16* pSz);
WOLFSSL_LOCAL int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list,
                                                   byte msgType, word16* pSz);
WOLFSSL_LOCAL int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity,
                                        word16 len, word32 age, byte hmac,
                                        byte cipherSuite0, byte cipherSuite,
                                        byte resumption,
                                        PreSharedKey **preSharedKey,
                                        void* heap);
WOLFSSL_LOCAL int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions,
                                  const byte* input, word16 length, void* heap);

/* The possible Pre-Shared Key key exchange modes. */
enum PskKeyExchangeMode {
    PSK_KE,
    PSK_DHE_KE
};

/* User can define this. */
#ifndef WOLFSSL_DEF_PSK_CIPHER
#define WOLFSSL_DEF_PSK_CIPHER    TLS_AES_128_GCM_SHA256
#endif

WOLFSSL_LOCAL int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes);
WOLFSSL_LOCAL int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length,
                                              byte msgType, byte* modes);

#ifdef WOLFSSL_EARLY_DATA
WOLFSSL_LOCAL int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 max, int is_response);
#endif
#endif /* HAVE_SESSION_TICKET || !NO_PSK */


/* The types of keys to derive for. */
enum DeriveKeyType {
    no_key,
    early_data_key,
    handshake_key,
    traffic_key,
    update_traffic_key
};

WOLFSSL_LOCAL int DeriveEarlySecret(WOLFSSL* ssl);
WOLFSSL_LOCAL int DeriveHandshakeSecret(WOLFSSL* ssl);
#ifdef WOLFSSL_API_PREFIX_MAP
    #define DeriveTls13Keys wolfSSL_DeriveTls13Keys
#endif
WOLFSSL_TEST_VIS int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store);
WOLFSSL_LOCAL int DeriveMasterSecret(WOLFSSL* ssl);
WOLFSSL_LOCAL int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret);
WOLFSSL_LOCAL int DeriveResumptionSecret(WOLFSSL* ssl, byte* key);

WOLFSSL_LOCAL int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen,
        const char *label, size_t labelLen,
        const unsigned char *context, size_t contextLen);

/* The key update request values for KeyUpdate message. */
enum KeyUpdateRequest {
    update_not_requested,
    update_requested
};
#endif /* WOLFSSL_TLS13 */

#ifdef WOLFSSL_DTLS_CID
WOLFSSL_LOCAL void TLSX_ConnectionID_Free(byte* ext, void* heap);
WOLFSSL_LOCAL word16 TLSX_ConnectionID_Write(byte* ext, byte* output);
WOLFSSL_LOCAL word16 TLSX_ConnectionID_GetSize(byte* ext);
WOLFSSL_LOCAL int TLSX_ConnectionID_Use(WOLFSSL* ssl);
WOLFSSL_LOCAL int TLSX_ConnectionID_Parse(WOLFSSL* ssl, const byte* input,
    word16 length, byte isRequest);
WOLFSSL_LOCAL void DtlsCIDOnExtensionsParsed(WOLFSSL* ssl);
WOLFSSL_LOCAL byte DtlsCIDCheck(WOLFSSL* ssl, const byte* input,
    word16 inputSize);
WOLFSSL_LOCAL int Dtls13UnifiedHeaderCIDPresent(byte flags);
#endif /* WOLFSSL_DTLS_CID */
WOLFSSL_LOCAL byte DtlsGetCidTxSize(WOLFSSL* ssl);
WOLFSSL_LOCAL byte DtlsGetCidRxSize(WOLFSSL* ssl);

#ifdef OPENSSL_EXTRA
enum SetCBIO {
    WOLFSSL_CBIO_NONE = 0,
    WOLFSSL_CBIO_RECV = 0x1,
    WOLFSSL_CBIO_SEND = 0x2,
};
#endif

#ifdef WOLFSSL_STATIC_EPHEMERAL
/* contains static ephemeral keys */
typedef struct {
#ifndef NO_DH
    DerBuffer* dhKey;
#endif
#ifdef HAVE_ECC
    DerBuffer* ecKey;
#endif
#ifdef HAVE_CURVE25519
    DerBuffer* x25519Key;
#endif
#ifdef HAVE_CURVE448
    DerBuffer* x448Key;
#endif
} StaticKeyExchangeInfo_t;
#endif /* WOLFSSL_STATIC_EPHEMERAL */


/* wolfSSL context type */
struct WOLFSSL_CTX {
    WOLFSSL_METHOD* method;
#ifdef SINGLE_THREADED
    WC_RNG*         rng;          /* to be shared with WOLFSSL w/o locking */
#endif
    wolfSSL_RefWithMutex ref;
    int         err;              /* error code in case of mutex not created */
#ifndef NO_DH
    buffer      serverDH_P;
    buffer      serverDH_G;
#endif
#ifndef NO_CERTS
    DerBuffer*  certificate;
    DerBuffer*  certChain;
    int         certChainCnt;
                 /* chain after self, in DER, with leading size for each cert */
    #ifndef WOLFSSL_NO_CA_NAMES
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* client_ca_names;
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* ca_names;
    #endif
    #ifdef OPENSSL_EXTRA
    WOLF_STACK_OF(WOLFSSL_X509)* x509Chain;
    #endif
#ifdef WOLFSSL_CERT_SETUP_CB
#ifdef OPENSSL_EXTRA
    client_cert_cb CBClientCert;  /* client certificate callback */
#endif
    CertSetupCallback  certSetupCb;
    void*              certSetupCbArg;
#endif
    DerBuffer*  privateKey;
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
    DerBuffer*  privateKeyMask;             /* Mask of private key DER. */
#endif
    byte        privateKeyType;
    byte        privateKeyId:1;
    byte        privateKeyLabel:1;
    int         privateKeySz;
    int         privateKeyDevId;

#ifdef WOLFSSL_DUAL_ALG_CERTS
    DerBuffer*  altPrivateKey;
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
    DerBuffer*  altPrivateKeyMask;          /* Mask of alt private key DER. */
#endif
    byte        altPrivateKeyType;
    byte        altPrivateKeyId:1;
    byte        altPrivateKeyLabel:1;
    int         altPrivateKeySz;
    int         altPrivateKeyDevId;
#endif /* WOLFSSL_DUAL_ALG_CERTS */
#ifdef OPENSSL_ALL
    /* note it is the privateKeyPKey pointer that is volatile, not the object it
     * points to:
     */
    WOLFSSL_EVP_PKEY* volatile privateKeyPKey;
#endif
    WOLFSSL_CERT_MANAGER* cm;      /* our cert manager, ctx owns SSL will use */
#endif
#ifdef KEEP_OUR_CERT
    WOLFSSL_X509*    ourCert;     /* keep alive a X509 struct of cert */
    int              ownOurCert;  /* Dispose of certificate if we own */
#endif
    Suites*     suites;           /* make dynamic, user may not need/set */
    void*       heap;             /* for user memory overrides */
    byte        verifyDepth;
    byte        verifyPeer:1;
    byte        verifyNone:1;
    byte        failNoCert:1;
    byte        failNoCertxPSK:1; /* fail if no cert with the exception of PSK*/
    byte        sessionCacheOff:1;
    byte        sessionCacheFlushOff:1;
#ifdef HAVE_EXT_CACHE
    byte        internalCacheOff:1;
    byte        internalCacheLookupOff:1;
#endif
    byte        sendVerify:2;     /* for client side (can not be single bit) */
    byte        haveRSA:1;        /* RSA available */
    byte        haveECC:1;        /* ECC available */
    byte        haveDH:1;         /* server DH params set by user */
    byte        haveECDSAsig:1;   /* server cert signed w/ ECDSA */
    byte        haveFalconSig:1;  /* server cert signed w/ Falcon */
    byte        haveDilithiumSig:1;/* server cert signed w/ Dilithium */
    byte        haveStaticECC:1;  /* static server ECC private key */
    byte        partialWrite:1;   /* only one msg per write call */
    byte        autoRetry:1;      /* retry read/write on a WANT_{READ|WRITE} */
    byte        quietShutdown:1;  /* don't send close notify */
    byte        groupMessages:1;  /* group handshake messages before sending */
    byte        minDowngrade;     /* minimum downgrade version */
    byte        haveEMS:1;        /* have extended master secret extension */
    byte        useClientOrder:1; /* Use client's cipher preference order */
#if defined(HAVE_SESSION_TICKET)
    byte        noTicketTls12:1;  /* TLS 1.2 server won't send ticket */
#endif
#ifdef WOLFSSL_TLS13
    #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
    unsigned int maxTicketTls13;  /* maximum number of tickets to send */
    #endif
    byte        noTicketTls13:1;  /* TLS 1.3 Server won't create new Ticket */
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    byte        noPskDheKe:1;     /* Don't use (EC)DHE with PSK */
#ifdef HAVE_SUPPORTED_CURVES
    byte        onlyPskDheKe:1;   /* Only use (EC)DHE with PSK */
#endif
#endif
#endif /* WOLFSSL_TLS13 */
    byte        mutualAuth:1;     /* Mutual authentication required */
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
    byte        postHandshakeAuth:1;  /* Post-handshake auth supported. */
    byte        verifyPostHandshake:1; /* Only send client cert req post
                                        * handshake, not also during */
#endif
#ifndef NO_DH
    #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
        !defined(HAVE_SELFTEST)
    byte        dhKeyTested:1;   /* Set when key has been tested. */
    #endif
#endif
#if defined(HAVE_SECURE_RENEGOTIATION) || defined(HAVE_SERVER_RENEGOTIATION_INFO)
    byte        useSecureReneg:1; /* when set will set WOLFSSL objects generated to enable */
#endif
#ifdef HAVE_ENCRYPT_THEN_MAC
    byte        disallowEncThenMac:1;  /* Don't do Encrypt-Then-MAC */
#endif
#ifdef WOLFSSL_STATIC_MEMORY
    byte        onHeapHint:1; /* whether the ctx/method is put on heap hint */
#endif
#if defined(WOLFSSL_STATIC_EPHEMERAL) && !defined(SINGLE_THREADED)
    byte        staticKELockInit:1;
#endif
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_SCTP)
    byte        dtlsSctp:1;         /* DTLS-over-SCTP mode */
#endif
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
    byte        disableECH:1;
#endif
    word16      minProto:1; /* sets min to min available */
    word16      maxProto:1; /* sets max to max available */
#if defined(HAVE_RPK)
    RpkConfig   rpkConfig;
    RpkState    rpkState;
#endif /* HAVE_RPK */
#ifdef WOLFSSL_SRTP
    word16      dtlsSrtpProfiles;  /* DTLS-with-SRTP mode
                                    * (list of selected profiles - up to 16) */
#endif
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_MULTICAST)
    byte        haveMcast;        /* multicast requested */
    byte        mcastID;          /* multicast group ID */
#endif
#if defined(WOLFSSL_DTLS) && \
    (defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU))
    word16      dtlsMtuSz;        /* DTLS MTU size */
#endif
#ifndef NO_DH
    word16      minDhKeySz;       /* minimum DH key size */
    word16      maxDhKeySz;       /* maximum DH key size */
#endif
#ifndef NO_RSA
    short       minRsaKeySz;      /* minimum RSA key size */
#ifdef WC_RSA_PSS
    word8       useRsaPss;        /* cert supports RSA-PSS */
#endif
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
    short       minEccKeySz;      /* minimum ECC key size */
#endif
#ifdef HAVE_FALCON
    short       minFalconKeySz;   /* minimum Falcon key size */
#endif
#ifdef HAVE_DILITHIUM
    short       minDilithiumKeySz;/* minimum Dilithium key size */
#endif
    unsigned long     mask;             /* store SSL_OP_ flags */
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
    word32            disabledCurves;   /* curves disabled by user */
#endif
#ifdef WOLFSSL_SESSION_ID_CTX
    byte              sessionCtx[ID_LEN]; /* app session context ID */
    byte              sessionCtxSz;
#endif
#ifdef OPENSSL_EXTRA
    const unsigned char *alpn_cli_protos;/* ALPN client protocol list */
    unsigned int         alpn_cli_protos_len;
    byte              cbioFlag;  /* WOLFSSL_CBIO_RECV/SEND: CBIORecv/Send is set */
    CallbackInfoState* CBIS;      /* used to get info about SSL state */
    WOLFSSL_X509_VERIFY_PARAM* param;    /* verification parameters*/
#endif
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
    NetworkFilterCallback_t AcceptFilter;
    void *AcceptFilter_arg;
    NetworkFilterCallback_t ConnectFilter;
    void *ConnectFilter_arg;
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
    CallbackIORecv CBIORecv;
    CallbackIOSend CBIOSend;
#ifdef WOLFSSL_DTLS
    CallbackGenCookie CBIOCookie;       /* gen cookie callback */
#endif /* WOLFSSL_DTLS */
#ifdef WOLFSSL_SESSION_EXPORT
#ifdef WOLFSSL_DTLS
    wc_dtls_export  dtls_export;        /* export function for DTLS session */
#endif
    CallbackGetPeer CBGetPeer;
    CallbackSetPeer CBSetPeer;
#endif
    VerifyCallback  verifyCallback;     /* cert verification callback */
    void*           verifyCbCtx;        /* cert verify callback user ctx*/
#ifdef OPENSSL_ALL
    CertVerifyCallback verifyCertCb;
    void*              verifyCertCbArg;
#endif /* OPENSSL_ALL */
#ifdef OPENSSL_EXTRA
    SSL_Msg_Cb      protoMsgCb;         /* inspect protocol message callback */
    void*           protoMsgCtx;        /* user set context with msg callback */
#endif
    word32          timeout;            /* session timeout */
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_CURVE25519) || \
    defined(HAVE_ED448)
    word32          ecdhCurveOID;       /* curve Ecc_Sum */
#endif
#ifdef HAVE_ECC
    word16          eccTempKeySz;       /* in octets 20 - 66 */
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
    word32          pkCurveOID;         /* curve Ecc_Sum */
#endif
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    byte        havePSK;                /* psk key set by user */
    wc_psk_client_callback client_psk_cb;  /* client callback */
    wc_psk_server_callback server_psk_cb;  /* server callback */
#ifdef WOLFSSL_TLS13
    wc_psk_client_cs_callback    client_psk_cs_cb;     /* client callback */
    wc_psk_client_tls13_callback client_psk_tls13_cb;  /* client callback */
    wc_psk_server_tls13_callback server_psk_tls13_cb;  /* server callback */
#endif
    void*       psk_ctx;
    char        server_hint[MAX_PSK_ID_LEN + NULL_TERM_LEN];
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
#ifdef WOLFSSL_TLS13
    word16          group[WOLFSSL_MAX_GROUP_COUNT];
    byte            numGroups;
#endif
#ifdef WOLFSSL_EARLY_DATA
    word32          maxEarlyDataSz;
#endif
#ifdef HAVE_ANON
    byte        useAnon;               /* User wants to allow Anon suites */
#endif /* HAVE_ANON */
#ifdef WOLFSSL_ENCRYPTED_KEYS
    wc_pem_password_cb* passwd_cb;
    void*               passwd_userdata;
#endif
#ifdef WOLFSSL_LOCAL_X509_STORE
    WOLFSSL_X509_STORE x509_store; /* points to ctx->cm */
    WOLFSSL_X509_STORE* x509_store_pt; /* take ownership of external store */
#endif
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)
    byte            readAhead;
    void*           userPRFArg; /* passed to prf callback */
#endif
#ifdef HAVE_EX_DATA
    WOLFSSL_CRYPTO_EX_DATA ex_data;
#endif
#if defined(HAVE_ALPN) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
    defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || defined(WOLFSSL_QUIC))
    CallbackALPNSelect alpnSelect;
    void*              alpnSelectArg;
#endif
#ifdef HAVE_SNI
    CallbackSniRecv sniRecvCb;
    void*           sniRecvCbArg;
#endif
#if defined(WOLFSSL_MULTICAST) && defined(WOLFSSL_DTLS)
    CallbackMcastHighwater mcastHwCb; /* Sequence number highwater callback */
    word32      mcastFirstSeq;    /* first trigger level */
    word32      mcastSecondSeq;   /* second trigger level */
    word32      mcastMaxSeq;      /* max level */
#endif
#ifdef HAVE_OCSP
    WOLFSSL_OCSP      ocsp;
#endif
    int             devId;              /* async device id to use */
#ifdef HAVE_TLS_EXTENSIONS
    TLSX* extensions;                  /* RFC 6066 TLS Extensions data */
    #ifndef NO_WOLFSSL_SERVER
        #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
         || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
            OcspRequest* certOcspRequest;
            ocspVerifyStatusCb ocspStatusVerifyCb;
            void* ocspStatusVerifyCbArg;
        #endif
        #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
            OcspRequest* chainOcspRequest[MAX_CHAIN_DEPTH];
        #endif
    #endif
    #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
        SessionTicketEncCb ticketEncCb;   /* enc/dec session ticket Cb */
        void*              ticketEncCtx;  /* session encrypt context */
        #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
          || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
        ticketCompatCb     ticketEncWrapCb; /* callback for OpenSSL ticket key callback */
        #endif
        int                ticketHint;    /* ticket hint in seconds */
        #ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB
            TicketEncCbCtx ticketKeyCtx;
        #endif
    #endif
    #endif
    #ifdef HAVE_SUPPORTED_CURVES
        byte userCurves;                  /* indicates user called wolfSSL_CTX_UseSupportedCurve */
    #endif
#ifdef ATOMIC_USER
    CallbackMacEncrypt    MacEncryptCb;    /* Atomic User Mac/Encrypt Cb */
    CallbackDecryptVerify DecryptVerifyCb; /* Atomic User Decrypt/Verify Cb */
    #ifdef HAVE_ENCRYPT_THEN_MAC
        CallbackEncryptMac    EncryptMacCb;    /* Atomic User Mac/Enc Cb */
        CallbackVerifyDecrypt VerifyDecryptCb; /* Atomic User Dec/Verify Cb */
    #endif
#endif
#ifdef HAVE_PK_CALLBACKS
    #ifdef HAVE_ECC
        CallbackEccKeyGen EccKeyGenCb;  /* User EccKeyGen Callback Handler */
        CallbackEccSign   EccSignCb;    /* User EccSign   Callback handler */
        void*             EccSignCtx;   /* Ecc Sign       Callback Context */
        CallbackEccVerify EccVerifyCb;  /* User EccVerify Callback handler */
        CallbackEccSharedSecret EccSharedSecretCb; /* User EccVerify Callback handler */
    #endif /* HAVE_ECC */
    #ifdef HAVE_HKDF
        CallbackHKDFExtract HkdfExtractCb; /* User hkdf Extract Callback handler */
    #endif
    #ifdef HAVE_ED25519
        /* User Ed25519Sign   Callback handler */
        CallbackEd25519Sign   Ed25519SignCb;
        /* User Ed25519Verify Callback handler */
        CallbackEd25519Verify Ed25519VerifyCb;
    #endif
    #ifdef HAVE_CURVE25519
        /* User X25519 KeyGen Callback Handler */
        CallbackX25519KeyGen X25519KeyGenCb;
        /* User X25519 SharedSecret Callback handler */
        CallbackX25519SharedSecret X25519SharedSecretCb;
    #endif
    #ifdef HAVE_ED448
        /* User Ed448Sign   Callback handler */
        CallbackEd448Sign   Ed448SignCb;
        /* User Ed448Verify Callback handler */
        CallbackEd448Verify Ed448VerifyCb;
    #endif
    #ifdef HAVE_CURVE448
        /* User X448 KeyGen Callback Handler */
        CallbackX448KeyGen X448KeyGenCb;
        /* User X448 SharedSecret Callback handler */
        CallbackX448SharedSecret X448SharedSecretCb;
    #endif
    #ifndef NO_DH
        /* User DH KeyGen Callback handler*/
        CallbackDhGenerateKeyPair DhGenerateKeyPairCb;
        /* User DH Agree Callback handler */
        CallbackDhAgree DhAgreeCb;
    #endif
    #ifndef NO_RSA
        /* User RsaSign Callback handler (priv key) */
        CallbackRsaSign   RsaSignCb;
        /* User RsaVerify Callback handler (pub key) */
        CallbackRsaVerify RsaVerifyCb;
        /* User VerifyRsaSign Callback handler (priv key) */
        CallbackRsaVerify RsaSignCheckCb;
        #ifdef WC_RSA_PSS
            /* User RsaSign (priv key) */
            CallbackRsaPssSign   RsaPssSignCb;
            /* User RsaVerify (pub key) */
            CallbackRsaPssVerify RsaPssVerifyCb;
            /* User VerifyRsaSign (priv key) */
            CallbackRsaPssVerify RsaPssSignCheckCb;
        #endif
        CallbackRsaEnc    RsaEncCb;     /* User Rsa Public Encrypt  handler */
        CallbackRsaDec    RsaDecCb;     /* User Rsa Private Decrypt handler */
    #endif /* NO_RSA */

    /* User generate pre-master handler */
    CallbackGenPreMaster        GenPreMasterCb;
    /* User generate master secret handler */
    CallbackGenMasterSecret     GenMasterCb;
    /* User generate Extended master secret handler */
    CallbackGenExtMasterSecret  GenExtMasterCb;
    /* User generate session key handler */
    CallbackGenSessionKey       GenSessionKeyCb;
    /* User setting encrypt keys handler */
    CallbackEncryptKeys         EncryptKeysCb;
    /* User Tls finished handler */
    CallbackTlsFinished         TlsFinishedCb;
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
    /* User Verify mac handler */
    CallbackVerifyMac           VerifyMacCb;
#endif
#if defined(WOLFSSL_PUBLIC_ASN)
    /* User handler to process a certificate */
    CallbackProcessPeerCert ProcessPeerCertCb;
#endif
    /* User handler to process the server's key exchange public key */
    CallbackProcessServerSigKex ProcessServerSigKexCb;
    /* User handler to process the TLS record */
    CallbackPerformTlsRecordProcessing PerformTlsRecordProcessingCb;
    /* User handler to do HKDF expansions */
    CallbackHKDFExpandLabel HKDFExpandLabelCb;

#endif /* HAVE_PK_CALLBACKS */
#ifdef HAVE_WOLF_EVENT
    WOLF_EVENT_QUEUE event_queue;
#endif /* HAVE_WOLF_EVENT */
#ifdef HAVE_EXT_CACHE
    WOLFSSL_SESSION*(*get_sess_cb)(WOLFSSL*, const unsigned char*, int, int*);
    int (*new_sess_cb)(WOLFSSL*, WOLFSSL_SESSION*);
#endif
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
    Rem_Sess_Cb rem_sess_cb;
#endif
#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256)
    Srp*  srp;  /* TLS Secure Remote Password Protocol*/
    byte* srp_password;
#endif
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
    wolfSSL_CTX_keylog_cb_func keyLogCb;
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
#ifdef WOLFSSL_STATIC_EPHEMERAL
    StaticKeyExchangeInfo_t staticKE;
    #ifndef SINGLE_THREADED
    wolfSSL_Mutex staticKELock;
    #endif
#endif
#ifdef WOLFSSL_QUIC
    struct {
        const WOLFSSL_QUIC_METHOD *method;
    } quic;
#endif
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
    WOLFSSL_EchConfig* echConfigs;
#endif
#if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
    byte doAppleNativeCertValidationFlag:1;
#endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */
#ifdef WOLFSSL_DUAL_ALG_CERTS
    byte *sigSpec;
    word16 sigSpecSz;
#endif
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
    int secLevel; /* The security level of system-wide crypto policy. */
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */

#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION
    CFMutableArrayRef testTrustedCAs;
#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */
};

WOLFSSL_LOCAL
int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap);
WOLFSSL_LOCAL
void FreeSSL_Ctx(WOLFSSL_CTX* ctx);
WOLFSSL_LOCAL
void SSL_CtxResourceFree(WOLFSSL_CTX* ctx);

#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
    #ifndef HAVE_EX_DATA
        #error "HAVE_EX_DATA_CLEANUP_HOOKS requires HAVE_EX_DATA to be defined"
    #endif
void wolfSSL_CRYPTO_cleanup_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data);
#endif

WOLFSSL_LOCAL
int DeriveTlsKeys(WOLFSSL* ssl);
WOLFSSL_LOCAL
int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
                          word32 inSz, word16 sz);

#ifndef NO_CERTS
    WOLFSSL_LOCAL int AddSigner(WOLFSSL_CERT_MANAGER* cm, Signer *s);
    WOLFSSL_LOCAL
    int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify);
    WOLFSSL_LOCAL int RemoveCA(WOLFSSL_CERT_MANAGER* cm, byte* hash, int type);
    WOLFSSL_LOCAL int SetCAType(WOLFSSL_CERT_MANAGER* cm, byte* hash, int type);
    WOLFSSL_LOCAL
    int AlreadySigner(WOLFSSL_CERT_MANAGER* cm, byte* hash);
#ifdef WOLFSSL_TRUST_PEER_CERT
    WOLFSSL_LOCAL
    int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify);
    WOLFSSL_LOCAL
    int AlreadyTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DecodedCert* cert);
#endif
#endif

#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION
    WOLFSSL_API
    int wolfSSL_TestAppleNativeCertValidation_AppendCA(WOLFSSL_CTX* ctx,
                                                    const byte* derCert,
                                                    int derLen);
#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */

/* All cipher suite related info
 * Keep as a constant size (no ifdefs) for session export */
typedef struct CipherSpecs {
    word16 key_size;
    word16 iv_size;
    word16 block_size;
    word16 aead_mac_size;
    byte bulk_cipher_algorithm;
    byte cipher_type;               /* block, stream, or aead */
    byte mac_algorithm;
    byte kea;                       /* key exchange algo */
    byte sig_algo;
    byte hash_size;
    byte pad_size;
    byte static_ecdh;
} CipherSpecs;


void InitCipherSpecs(CipherSpecs* cs);


/* Supported Key Exchange Protocols */
enum KeyExchangeAlgorithm {
    no_kea,
    rsa_kea,
    diffie_hellman_kea,
    fortezza_kea,
    psk_kea,
    dhe_psk_kea,
    ecdhe_psk_kea,
    ecc_diffie_hellman_kea,
    ecc_static_diffie_hellman_kea,      /* for verify suite only */
    any_kea
};

/* Used with InitSuitesHashSigAlgo */
#define SIG_ECDSA       0x01
#define SIG_RSA         0x02
#define SIG_SM2         0x04
#define SIG_FALCON      0x08
#define SIG_DILITHIUM   0x10
#define SIG_ANON        0x20
/* SIG_ANON is omitted by default */
#define SIG_ALL         (SIG_ECDSA | SIG_RSA | SIG_SM2 | SIG_FALCON | \
                         SIG_DILITHIUM)

/* Supported Authentication Schemes */
enum SignatureAlgorithm {
    anonymous_sa_algo            = 0,
    rsa_sa_algo                  = 1,
    dsa_sa_algo                  = 2,
    ecc_dsa_sa_algo              = 3,
    rsa_pss_sa_algo              = 8,
    ed25519_sa_algo              = 9,
    rsa_pss_pss_algo             = 10,
    ed448_sa_algo                = 11,
    falcon_level1_sa_algo        = 12,
    falcon_level5_sa_algo        = 13,
    dilithium_level2_sa_algo     = 14,
    dilithium_level3_sa_algo     = 15,
    dilithium_level5_sa_algo     = 16,
    sm2_sa_algo                  = 17,
    any_sa_algo                  = 18,
    ecc_brainpool_sa_algo        = 19,
    invalid_sa_algo              = 255
};

#define PSS_RSAE_TO_PSS_PSS(macAlgo) \
    ((macAlgo) + (pss_sha256 - sha256_mac))

#define PSS_PSS_HASH_TO_MAC(macAlgo) \
    ((macAlgo) - (pss_sha256 - sha256_mac))

enum SigAlgRsaPss {
    pss_sha256  = 0x09,
    pss_sha384  = 0x0a,
    pss_sha512  = 0x0b,
};

#ifdef WOLFSSL_SM2
    /* Default SM2 signature ID. */
    #define TLS12_SM2_SIG_ID        ((byte*)"1234567812345678")
    /* Length of default SM2 signature ID. */
    #define TLS12_SM2_SIG_ID_SZ     16

    /* https://www.rfc-editor.org/rfc/rfc8998.html#name-sm2-signature-scheme */
    /* ID to use when signing/verifying TLS v1.3 data. */
    #define TLS13_SM2_SIG_ID        ((byte*)"TLSv1.3+GM+Cipher+Suite")
    /* Length of ID to use when signing/verifying TLS v1.3 data. */
    #define TLS13_SM2_SIG_ID_SZ     23
#endif

/* Supported ECC Curve Types */
enum EccCurves {
    named_curve = 3
};


/* Valid client certificate request types from page 27 */
enum ClientCertificateType {
    rsa_sign            = 1,
    dss_sign            = 2,
    rsa_fixed_dh        = 3,
    dss_fixed_dh        = 4,
    rsa_ephemeral_dh    = 5,
    dss_ephemeral_dh    = 6,
    fortezza_kea_cert   = 20,
    ecdsa_sign          = 64,
    rsa_fixed_ecdh      = 65,
    ecdsa_fixed_ecdh    = 66,
    falcon_sign         = 67,
    dilithium_sign      = 68,
};


#ifndef WOLFSSL_AEAD_ONLY
enum CipherType { stream, block, aead };
#else
enum CipherType { aead };
#endif


#if defined(BUILD_AES) || defined(BUILD_AESGCM) || defined(HAVE_ARIA) || \
        (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) || defined(WOLFSSL_TLS13)
    #define CIPHER_NONCE
#endif

#if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
enum CipherSrc {
    KEYS_NOT_SET = 0,
    KEYS,     /* keys from ssl->keys are loaded */
    SCR       /* keys from ssl->secure_renegotiation->tmp_keys are loaded */
};
#endif

#ifdef WOLFSSL_CIPHER_TEXT_CHECK
    #ifndef WOLFSSL_CIPHER_CHECK_SZ
        /* 64-bits to confirm encrypt operation worked */
        #define WOLFSSL_CIPHER_CHECK_SZ 8
    #endif
#endif

/* cipher for now */
typedef struct Ciphers {
#ifdef BUILD_ARC4
    Arc4*   arc4;
#endif
#ifdef BUILD_DES3
    Des3*   des3;
#endif
#if defined(BUILD_AES) || defined(BUILD_AESGCM)
    Aes*    aes;
#endif
#if (defined(BUILD_AESGCM) || defined(HAVE_AESCCM)) && !defined(WOLFSSL_NO_TLS12)
    byte* additional;
#endif
#ifdef HAVE_ARIA
    wc_Aria* aria;
#endif
#ifdef CIPHER_NONCE
    byte* nonce;
#endif
#ifdef HAVE_CAMELLIA
    wc_Camellia* cam;
#endif
#ifdef HAVE_CHACHA
    ChaCha*   chacha;
#endif
#ifdef WOLFSSL_SM4
    wc_Sm4*   sm4;
#endif
#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && !defined(NO_HMAC)
    Hmac* hmac;
#endif
#ifdef WOLFSSL_CIPHER_TEXT_CHECK
    word32 sanityCheck[WOLFSSL_CIPHER_CHECK_SZ/sizeof(word32)];
#endif
    byte    state;
    byte    setup;       /* have we set it up flag for detection */
#if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
    enum CipherSrc src;  /* DTLS uses this to determine which keys
                          * are currently loaded */
#endif
} Ciphers;

#ifdef WOLFSSL_DTLS13
typedef struct RecordNumberCiphers {
#if defined(BUILD_AES) || defined(BUILD_AESGCM)
        Aes *aes;
#endif /*  BUILD_AES || BUILD_AESGCM */
#ifdef HAVE_CHACHA
        ChaCha *chacha;
#endif
} RecordNumberCiphers;
#endif /* WOLFSSL_DTLS13 */

#ifdef HAVE_ONE_TIME_AUTH
/* Ciphers for one time authentication such as poly1305 */
typedef struct OneTimeAuth {
#ifdef HAVE_POLY1305
    Poly1305* poly1305;
#endif
    byte    setup;      /* flag for if a cipher has been set */

} OneTimeAuth;
#endif


WOLFSSL_LOCAL void InitCiphers(WOLFSSL* ssl);
WOLFSSL_LOCAL void FreeCiphers(WOLFSSL* ssl);


/* hashes type */
typedef struct Hashes {
    #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
        byte md5[WC_MD5_DIGEST_SIZE];
    #endif
    #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
                              defined(WOLFSSL_ALLOW_TLS_SHA1))
        byte sha[WC_SHA_DIGEST_SIZE];
    #endif
    #ifndef NO_SHA256
        byte sha256[WC_SHA256_DIGEST_SIZE];
    #endif
    #ifdef WOLFSSL_SHA384
        byte sha384[WC_SHA384_DIGEST_SIZE];
    #endif
    #ifdef WOLFSSL_SHA512
        byte sha512[WC_SHA512_DIGEST_SIZE];
    #endif
    #ifdef WOLFSSL_SM3
        byte sm3[WC_SM3_DIGEST_SIZE];
    #endif
} Hashes;

WOLFSSL_LOCAL int BuildCertHashes(const WOLFSSL* ssl, Hashes* hashes);

#ifdef WOLFSSL_TLS13
typedef union Digest {
#ifndef NO_SHA256
    wc_Sha256 sha256;
#endif
#ifdef WOLFSSL_SHA384
    wc_Sha384 sha384;
#endif
#ifdef WOLFSSL_SHA512
    wc_Sha512 sha512;
#endif
#ifdef WOLFSSL_SM3
    wc_Sm3    sm3;
#endif
} Digest;
#endif

/* Static x509 buffer */
typedef struct x509_buffer {
    int  length;                  /* actual size */
    byte buffer[MAX_X509_SIZE];   /* max static cert size */
} x509_buffer;


/* wolfSSL X509_CHAIN, for no dynamic memory SESSION_CACHE */
struct WOLFSSL_X509_CHAIN {
    int         count;                    /* total number in chain */
    x509_buffer certs[MAX_CHAIN_DEPTH];   /* only allow max depth 4 for now */
};

typedef enum WOLFSSL_SESSION_TYPE {
    WOLFSSL_SESSION_TYPE_UNKNOWN,
    WOLFSSL_SESSION_TYPE_SSL,    /* in ssl->session */
    WOLFSSL_SESSION_TYPE_CACHE,  /* pointer to internal cache */
    WOLFSSL_SESSION_TYPE_HEAP    /* allocated from heap SESSION_new */
} WOLFSSL_SESSION_TYPE;

#ifdef WOLFSSL_QUIC
typedef struct QuicRecord QuicRecord;
typedef struct QuicRecord {
    struct QuicRecord *next;
    uint8_t *data;
    word32 capacity;
    word32 len;
    word32 start;
    word32 end;
    WOLFSSL_ENCRYPTION_LEVEL level;
    word32 rec_hdr_remain;
} QuicEncData;

typedef struct QuicTransportParam QuicTransportParam;
struct QuicTransportParam {
    const uint8_t *data;
    word16 len;
};

WOLFSSL_LOCAL const QuicTransportParam *QuicTransportParam_new(const uint8_t *data, size_t len, void *heap);
WOLFSSL_LOCAL const QuicTransportParam *QuicTransportParam_dup(const QuicTransportParam *tp, void *heap);
WOLFSSL_LOCAL void QuicTransportParam_free(const QuicTransportParam *tp, void *heap);
WOLFSSL_LOCAL int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response);
WOLFSSL_LOCAL int wolfSSL_quic_add_transport_extensions(WOLFSSL *ssl, int msg_type);

#define QTP_FREE     QuicTransportParam_free

#endif /* WOLFSSL_QUIC */

/** Session Ticket - RFC 5077 (session 3.2) */
#if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
/* Ticket nonce - for deriving PSK.
   Length allowed to be: 1..255. Only support
 * TLS13_TICKET_NONCE_STATIC_SZ length bytes.
 */
typedef struct TicketNonce {
    byte len;
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
    byte *data;
    byte dataStatic[MAX_TICKET_NONCE_STATIC_SZ];
#else
    byte data[MAX_TICKET_NONCE_STATIC_SZ];
#endif /* WOLFSSL_TICKET_NONCE_MALLOC  && FIPS_VERSION_GE(5,3) */
} TicketNonce;
#endif

/* wolfSSL session type */
struct WOLFSSL_SESSION {
    /* WARNING Do not add fields here. They will be ignored in
     *         wolfSSL_DupSession. */
    WOLFSSL_SESSION_TYPE type;
#ifndef NO_SESSION_CACHE
    int                cacheRow;          /* row in session cache     */
#endif
    wolfSSL_Ref        ref;
    byte               altSessionID[ID_LEN];
    byte               haveAltSessionID:1;
#ifdef HAVE_EX_DATA
    byte               ownExData:1;
#endif
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
    Rem_Sess_Cb        rem_sess_cb;
#endif
    void*              heap;
    /* WARNING The above fields (up to and including the heap) are not copied
     *         in wolfSSL_DupSession. Place new fields after the heap
     *         member */

    byte               side;              /* Either WOLFSSL_CLIENT_END or
                                                    WOLFSSL_SERVER_END */

    word32             bornOn;            /* create time in seconds   */
    word32             timeout;           /* timeout in seconds       */

    byte               sessionID[ID_LEN]; /* id for protocol or bogus
                                           * ID for TLS 1.3           */
    byte               sessionIDSz;

    byte               masterSecret[SECRET_LEN]; /* stored secret     */
    word16             haveEMS;           /* ext master secret flag   */
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
    WOLFSSL_X509*      peer;              /* peer cert */
#endif
    ProtocolVersion    version;           /* which version was used   */
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
                        (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
    byte               cipherSuite0;      /* first byte, normally 0   */
    byte               cipherSuite;       /* 2nd byte, actual suite   */
#endif
#ifndef NO_CLIENT_CACHE
    word16             idLen;             /* serverID length          */
    byte               serverID[SERVER_ID_LEN]; /* for easier client lookup */
#endif
#ifdef WOLFSSL_SESSION_ID_CTX
    byte               sessionCtxSz;      /* sessionCtx length        */
    byte               sessionCtx[ID_LEN]; /* app specific context id */
#endif /* WOLFSSL_SESSION_ID_CTX */
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    byte               peerVerifyRet;     /* cert verify error */
#endif
#ifdef WOLFSSL_TLS13
    word16             namedGroup;
#endif
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
#ifdef WOLFSSL_TLS13
#ifdef WOLFSSL_32BIT_MILLI_TIME
    word32             ticketSeen;        /* Time ticket seen (ms) */
#else
    sword64            ticketSeen;        /* Time ticket seen (ms) */
#endif
    word32             ticketAdd;         /* Added by client */
    TicketNonce        ticketNonce;       /* Nonce used to derive PSK */
#endif
#ifdef WOLFSSL_EARLY_DATA
    word32             maxEarlyDataSz;
#endif
#endif
#ifdef HAVE_SESSION_TICKET
    byte               staticTicket[SESSION_TICKET_LEN];
    byte*              ticket;
    word16             ticketLen;
    word16             ticketLenAlloc;    /* is dynamic */
#endif

#ifdef SESSION_CERTS
    WOLFSSL_X509_CHAIN chain;             /* peer cert chain, static  */
    #ifdef WOLFSSL_ALT_CERT_CHAINS
    WOLFSSL_X509_CHAIN altChain;          /* peer alt cert chain, static */
    #endif
#endif
#ifdef HAVE_EX_DATA
    WOLFSSL_CRYPTO_EX_DATA ex_data;
#endif
#ifdef HAVE_MAX_FRAGMENT
    byte               mfl; /* max fragment length negotiated i.e.
                             * WOLFSSL_MFL_2_8  (6) */
#endif
    byte               isSetup:1;
};

#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) &&                  \
        defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                \
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
WOLFSSL_LOCAL int SessionTicketNoncePopulate(WOLFSSL_SESSION *session,
    const byte* nonce, byte len);
#endif /* WOLFSSL_TLS13 &&  */

WOLFSSL_LOCAL int wolfSSL_RAND_Init(void);

WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_NewSession(void* heap);
WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_GetSession(
    WOLFSSL* ssl, byte* masterSecret, byte restoreSessionCerts);
WOLFSSL_LOCAL void SetupSession(WOLFSSL* ssl);
WOLFSSL_LOCAL void AddSession(WOLFSSL* ssl);
#ifdef WOLFSSL_API_PREFIX_MAP
    #define AddSessionToCache wolfSSL_AddSessionToCache
#endif
WOLFSSL_TEST_VIS int AddSessionToCache(WOLFSSL_CTX* ctx,
    WOLFSSL_SESSION* addSession, const byte* id, byte idSz, int* sessionIndex,
    int side, word16 useTicket, ClientSession** clientCacheEntry);
#ifndef NO_CLIENT_CACHE
WOLFSSL_LOCAL ClientSession* AddSessionToClientCache(int side, int row, int idx,
                      byte* serverID, word16 idLen, const byte* sessionID,
                      word16 useTicket);
#endif
WOLFSSL_LOCAL
WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session);
WOLFSSL_LOCAL void TlsSessionCacheUnlockRow(word32 row);
WOLFSSL_LOCAL int TlsSessionCacheGetAndRdLock(const byte *id,
    const WOLFSSL_SESSION **sess, word32 *lockedRow, byte side);
WOLFSSL_LOCAL int TlsSessionCacheGetAndWrLock(const byte *id,
    WOLFSSL_SESSION **sess, word32 *lockedRow, byte side);
WOLFSSL_LOCAL void EvictSessionFromCache(WOLFSSL_SESSION* session);
WOLFSSL_TEST_VIS int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output);
WOLFSSL_LOCAL int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session);
WOLFSSL_LOCAL void wolfSSL_FreeSession(WOLFSSL_CTX* ctx,
        WOLFSSL_SESSION* session);
WOLFSSL_LOCAL int wolfSSL_DupSession(const WOLFSSL_SESSION* input,
        WOLFSSL_SESSION* output, int avoidSysCalls);


typedef int (*hmacfp) (WOLFSSL*, byte*, const byte*, word32, int, int, int, int);

#ifndef NO_CLIENT_CACHE
    WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_GetSessionClient(
        WOLFSSL* ssl, const byte* id, int len);
#endif

/* client connect state for nonblocking restart */
enum ConnectState {
    CONNECT_BEGIN = 0,
    CLIENT_HELLO_SENT,
    HELLO_AGAIN,               /* HELLO_AGAIN s for DTLS case */
    HELLO_AGAIN_REPLY,
    FIRST_REPLY_DONE,
    FIRST_REPLY_FIRST,
    FIRST_REPLY_SECOND,
    FIRST_REPLY_THIRD,
    FIRST_REPLY_FOURTH,
    FINISHED_DONE,
    SECOND_REPLY_DONE,

#ifdef WOLFSSL_DTLS13
    WAIT_FINISHED_ACK
#endif /* WOLFSSL_DTLS13 */

};


/* server accept state for nonblocking restart */
enum AcceptState {
    ACCEPT_BEGIN = 0,
    ACCEPT_BEGIN_RENEG,
    ACCEPT_CLIENT_HELLO_DONE,
    ACCEPT_HELLO_RETRY_REQUEST_DONE,
    ACCEPT_FIRST_REPLY_DONE,
    SERVER_HELLO_SENT,
    CERT_SENT,
    CERT_VERIFY_SENT,
    CERT_STATUS_SENT,
    KEY_EXCHANGE_SENT,
    CERT_REQ_SENT,
    SERVER_HELLO_DONE,
    ACCEPT_SECOND_REPLY_DONE,
    TICKET_SENT,
    CHANGE_CIPHER_SENT,
    ACCEPT_FINISHED_DONE,
    ACCEPT_THIRD_REPLY_DONE
};

/* TLS 1.3 server accept state for nonblocking restart */
enum AcceptStateTls13 {
    TLS13_ACCEPT_BEGIN = 0,
    TLS13_ACCEPT_BEGIN_RENEG,
    TLS13_ACCEPT_CLIENT_HELLO_DONE,
    TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE,
    TLS13_ACCEPT_FIRST_REPLY_DONE,
    TLS13_ACCEPT_SECOND_REPLY_DONE,
    TLS13_SERVER_HELLO_SENT,
    TLS13_ACCEPT_THIRD_REPLY_DONE,
    TLS13_SERVER_EXTENSIONS_SENT,
    TLS13_CERT_REQ_SENT,
    TLS13_CERT_SENT,
    TLS13_CERT_VERIFY_SENT,
    TLS13_ACCEPT_FINISHED_SENT,
    TLS13_PRE_TICKET_SENT,
    TLS13_ACCEPT_FINISHED_DONE,
    TLS13_TICKET_SENT
};

#ifdef WOLFSSL_THREADED_CRYPT

#include <pthread.h>

typedef struct ThreadCrypt {
    Ciphers encrypt;
    bufferStatic buffer;
    unsigned char nonce[AESGCM_NONCE_SZ];
    unsigned char additional[AEAD_AUTH_DATA_SZ];
    int init;
    int offset;
    int cryptLen;
    int done;
    int avail;
    int stop;
    WOLFSSL_THREAD_SIGNAL signal;
    void*                 signalCtx;
} ThreadCrypt;

#endif

/* buffers for struct WOLFSSL */
typedef struct Buffers {
    bufferStatic    inputBuffer;
    bufferStatic    outputBuffer;
#ifdef WOLFSSL_THREADED_CRYPT
    ThreadCrypt     encrypt[WOLFSSL_THREADED_CRYPT_CNT];
#endif
    buffer          domainName;            /* for client check */
    buffer          ipasc;                 /* for client IP SAN check */
    buffer          clearOutputBuffer;
    buffer          sig;                   /* signature data */
    buffer          digest;                /* digest data */
    word32          prevSent;              /* previous plain text bytes sent
                                              when got WANT_WRITE            */
    word32          plainSz;               /* plain text bytes in buffer to send
                                              when got WANT_WRITE            */
    byte            weOwnCert;             /* SSL own cert flag */
    byte            weOwnCertChain;        /* SSL own cert chain flag */
    byte            weOwnKey;              /* SSL own key flag */
#ifdef WOLFSSL_DUAL_ALG_CERTS
    byte            weOwnAltKey;           /* SSL own alt key flag */
#endif
    byte            weOwnDH;               /* SSL own dh (p,g)  flag */
#ifndef NO_DH
    buffer          serverDH_P;            /* WOLFSSL_CTX owns, unless we own */
    buffer          serverDH_G;            /* WOLFSSL_CTX owns, unless we own */
    buffer          serverDH_Pub;
    buffer          serverDH_Priv;
    DhKey*          serverDH_Key;
#endif
#ifndef NO_CERTS
    DerBuffer*      certificate;           /* WOLFSSL_CTX owns, unless we own */
    DerBuffer*      key;                   /* WOLFSSL_CTX owns, unless we own */
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
    DerBuffer*      keyMask;               /* Mask of private key DER. */
#endif
    byte            keyType;               /* Type of key */
    byte            keyId:1;               /* Key data is an id not data */
    byte            keyLabel:1;            /* Key data is a label not data */
    int             keySz;                 /* Size of RSA key */
    int             keyDevId;              /* Device Id for key */
#ifdef WOLFSSL_DUAL_ALG_CERTS
    DerBuffer*      altKey;                /* WOLFSSL_CTX owns, unless we own */
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
    DerBuffer*      altKeyMask;            /* Mask of alt private key DER. */
#endif
    byte            altKeyType;            /* Type of alt key */
    byte            altKeyId:1;            /* Key data is an id not data */
    byte            altKeyLabel:1;         /* Key data is a label not data */
    int             altKeySz;              /* Size of alt key */
    int             altKeyDevId;           /* Device Id for alt key */
#endif
    DerBuffer*      certChain;             /* WOLFSSL_CTX owns, unless we own */
                 /* chain after self, in DER, with leading size for each cert */
    int             certChainCnt;
#ifdef WOLFSSL_TLS13
    DerBuffer*      certExts[MAX_CERT_EXTENSIONS];
#endif
#endif
#ifdef WOLFSSL_SEND_HRR_COOKIE
    buffer          tls13CookieSecret;     /* HRR cookie secret */
#endif
#ifdef WOLFSSL_DTLS
    WOLFSSL_DTLS_CTX dtlsCtx;              /* DTLS connection context */
    #ifndef NO_WOLFSSL_SERVER
        buffer       dtlsCookieSecret;     /* DTLS cookie secret */
    #endif /* NO_WOLFSSL_SERVER */
#endif
#ifdef HAVE_PK_CALLBACKS
    #ifdef HAVE_ECC
        buffer peerEccDsaKey;              /* we own for Ecc Verify Callbacks */
    #endif /* HAVE_ECC */
    #ifdef HAVE_ED25519
        buffer peerEd25519Key;             /* for Ed25519 Verify Callbacks */
    #endif /* HAVE_ED25519 */
    #ifdef HAVE_ED448
        buffer peerEd448Key;             /* for Ed448 Verify Callbacks */
    #endif /* HAVE_ED448 */
    #ifndef NO_RSA
        buffer peerRsaKey;                 /* we own for Rsa Verify Callbacks */
    #endif /* NO_RSA */
#endif /* HAVE_PK_CALLBACKS */
} Buffers;

/* sub-states for send/do key share (key exchange) */
enum asyncState {
    TLS_ASYNC_BEGIN = 0,
    TLS_ASYNC_BUILD,
    TLS_ASYNC_DO,
    TLS_ASYNC_VERIFY,
    TLS_ASYNC_FINALIZE,
    TLS_ASYNC_END
};

/* sub-states for build message */
enum buildMsgState {
    BUILD_MSG_BEGIN = 0,
    BUILD_MSG_SIZE,
    BUILD_MSG_HASH,
    BUILD_MSG_VERIFY_MAC,
    BUILD_MSG_ENCRYPT,
    BUILD_MSG_ENCRYPTED_VERIFY_MAC,
};

/* sub-states for cipher operations */
enum cipherState {
    CIPHER_STATE_BEGIN = 0,
    CIPHER_STATE_DO,
    CIPHER_STATE_END,
};

struct Options {
#ifndef NO_PSK
    wc_psk_client_callback client_psk_cb;
    wc_psk_server_callback server_psk_cb;
#ifdef OPENSSL_EXTRA
    wc_psk_use_session_cb_func session_psk_cb;
#endif
#ifdef WOLFSSL_TLS13
    wc_psk_client_cs_callback    client_psk_cs_cb;     /* client callback */
    wc_psk_client_tls13_callback client_psk_tls13_cb;  /* client callback */
    wc_psk_server_tls13_callback server_psk_tls13_cb;  /* server callback */
#endif
    void*             psk_ctx;
#endif /* NO_PSK */
    unsigned long     mask; /* store SSL_OP_ flags */
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)
    word16            minProto:1; /* sets min to min available */
    word16            maxProto:1; /* sets max to max available */
#endif
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13)
    unsigned int      maxTicketTls13;  /* maximum number of tickets to send */
    unsigned int      ticketsSent;     /* keep track of the total sent */
#endif

    /* on/off or small bit flags, optimize layout */
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    word16            havePSK:1;            /* psk key set by user */
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
    word16            sendVerify:2;     /* false = 0, true = 1, sendBlank = 2 */
    word16            sessionCacheOff:1;
    word16            sessionCacheFlushOff:1;
#ifdef HAVE_EXT_CACHE
    word16            internalCacheOff:1;
    word16            internalCacheLookupOff:1;
#endif
    word16            side:2;             /* client, server or neither end */
    word16            verifyPeer:1;
    word16            verifyNone:1;
    word16            failNoCert:1;
    word16            failNoCertxPSK:1;   /* fail for no cert except with PSK */
    word16            downgrade:1;        /* allow downgrade of versions */
    word16            resuming:1;
#ifdef HAVE_SECURE_RENEGOTIATION
    word16            resumed:1;          /* resuming may be reset on SCR */
#endif
    word16            isPSK:1;
    word16            haveSessionId:1;    /* server may not send */
    word16            tls:1;              /* using TLS ? */
    word16            tls1_1:1;           /* using TLSv1.1+ ? */
    word16            tls1_3:1;           /* using TLSv1.3+ ? */
    word16            dtls:1;             /* using datagrams ? */
#ifdef WOLFSSL_DTLS
    word16            dtlsStateful:1;     /* allow stateful processing ? */
#endif
    word16            connReset:1;        /* has the peer reset */
    word16            isClosed:1;         /* if we consider conn closed */
    word16            closeNotify:1;      /* we've received a close notify */
    word16            sentNotify:1;       /* we've sent a close notify */
    word16            usingCompression:1; /* are we using compression */
    word16            haveRSA:1;          /* RSA available */
    word16            haveECC:1;          /* ECC available */
    word16            haveDH:1;           /* server DH params set by user */
    word16            haveECDSAsig:1;     /* server ECDSA signed cert */
    word16            haveStaticECC:1;    /* static server ECC private key */
    word16            haveFalconSig:1;    /* server Falcon signed cert */
    word16            haveDilithiumSig:1; /* server Dilithium signed cert */
    word16            havePeerCert:1;     /* do we have peer's cert */
    word16            havePeerVerify:1;   /* and peer's cert verify */
    word16            usingPSK_cipher:1;  /* are using psk as cipher */
    word16            usingAnon_cipher:1; /* are we using an anon cipher */
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    word16            noPskDheKe:1;       /* Don't use (EC)DHE with PSK */
#ifdef HAVE_SUPPORTED_CURVES
    word16            onlyPskDheKe:1;     /* Only use (EC)DHE with PSK */
#endif
#endif
    word16            partialWrite:1;     /* only one msg per write call */
    word16            quietShutdown:1;    /* don't send close notify */
    word16            certOnly:1;         /* stop once we get cert */
    word16            groupMessages:1;    /* group handshake messages */
    word16            saveArrays:1;       /* save array Memory for user get keys
                                           or psk */
    word16            weOwnRng:1;         /* will be true unless CTX owns */
    word16            dontFreeDigest:1;   /* when true, we used SetDigest */
    word16            haveEMS:1;          /* using extended master secret */
#ifdef HAVE_POLY1305
    word16            oldPoly:1;        /* set when to use old rfc way of poly*/
#endif
    word16            useAnon:1;       /* User wants to allow Anon suites */
#ifdef HAVE_SESSION_TICKET
    word16            createTicket:1;     /* Server to create new Ticket */
    word16            useTicket:1;        /* Use Ticket not session cache */
    word16            rejectTicket:1;     /* Callback rejected ticket */
    word16            noTicketTls12:1;    /* TLS 1.2 server won't send ticket */
#ifdef WOLFSSL_TLS13
    word16            noTicketTls13:1;    /* Server won't create new Ticket */
#endif
#endif
#ifdef WOLFSSL_DTLS
#ifdef HAVE_SECURE_RENEGOTIATION
    word16            dtlsDoSCR:1;        /* Enough packets were dropped. We
                                           * need to re-key. */
#endif
    word16            dtlsUseNonblock:1;  /* are we using nonblocking socket */
    word16            dtlsHsRetain:1;     /* DTLS retaining HS data */
#ifdef WOLFSSL_SCTP
    word16            dtlsSctp:1;         /* DTLS-over-SCTP mode */
#endif
#endif /* WOLFSSL_DTLS */
#if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_SUPPORTED_CURVES)
    word16            userCurves:1;       /* indicates user called wolfSSL_UseSupportedCurve */
#endif
    word16            keepResources:1;    /* Keep resources after handshake */
    word16            useClientOrder:1;   /* Use client's cipher order */
    word16            mutualAuth:1;       /* Mutual authentication is required */
    word16            peerAuthGood:1;     /* Any required peer auth done */
#if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
    word16            pskNegotiated:1;    /* Session Ticket/PSK negotiated. */
#endif
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
    word16            postHandshakeAuth:1;/* Client send post_handshake_auth
                                           * extension */
    word16            verifyPostHandshake:1; /* Only send client cert req post
                                              * handshake, not also during */
#endif
#if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
    word16            sendCookie:1;       /* Server creates a Cookie in HRR */
#endif
#ifdef WOLFSSL_ALT_CERT_CHAINS
    word16            usingAltCertChain:1;/* Alternate cert chain was used */
#endif
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
    word16            sentChangeCipher:1; /* Change Cipher Spec sent */
#endif
#if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
               ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
                (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
                (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
    word16            cacheMessages:1;    /* Cache messages for sign/verify */
#endif
#ifndef NO_DH
    #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
        !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
        word16        dhDoKeyTest:1;      /* Need to do the DH Key prime test */
        word16        dhKeyTested:1;      /* Set when key has been tested. */
    #endif
#endif
#ifdef HAVE_ENCRYPT_THEN_MAC
    word16            disallowEncThenMac:1;   /* Don't do Encrypt-Then-MAC */
    word16            encThenMac:1;           /* Doing Encrypt-Then-MAC */
    word16            startedETMRead:1;       /* Doing Encrypt-Then-MAC read */
    word16            startedETMWrite:1;      /* Doing Encrypt-Then-MAC write */
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
    word16            buildArgsSet:1;         /* buildArgs are set and need to
                                               * be free'd */
#endif
#ifdef WOLFSSL_DTLS13
    word16            dtls13SendMoreAcks:1;  /* Send more acks during the
                                              * handshake process */
#ifdef WOLFSSL_DTLS13_NO_HRR_ON_RESUME
    word16            dtls13NoHrrOnResume:1;
#endif
#ifdef WOLFSSL_DTLS_CH_FRAG
    word16            dtls13ChFrag:1;
#endif
#endif
#ifdef WOLFSSL_TLS13
    word16            tls13MiddleBoxCompat:1; /* TLSv1.3 middlebox compatibility */
#endif
#ifdef WOLFSSL_DTLS_CID
    word16            useDtlsCID:1;
#endif /* WOLFSSL_DTLS_CID */
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
    word16            echAccepted:1;
    byte              disableECH:1;           /* Did the user disable ech */
#endif
#ifdef WOLFSSL_SEND_HRR_COOKIE
    word16            cookieGood:1;
#endif
#if defined(HAVE_DANE)
    word16            useDANE:1;
#endif /* HAVE_DANE */
#ifdef WOLFSSL_TLS13
#ifdef WOLFSSL_SEND_HRR_COOKIE
    word16            hrrSentCookie:1;    /* HRR sent with cookie */
#endif
    word16            hrrSentKeyShare:1;  /* HRR sent with key share */
    word16            shSentKeyShare:1;   /* SH sent with key share */
#endif
    word16            returnOnGoodCh:1;
    word16            disableRead:1;

#ifdef WOLFSSL_EARLY_DATA
    word16            clientInEarlyData:1; /* Client is in wolfSSL_read_early_data */
#endif
#ifdef WOLFSSL_DTLS
    byte              haveMcast;          /* using multicast ? */
#endif
    byte              buildingMsg;        /* If set then we need to re-enter the
                                           * handshake logic. */
    byte              seenUnifiedHdr;     /* received msg with unified header */
    byte              shutdownDone;       /* we've completed a shutdown */
    byte              sendKeyUpdate;      /* Key Update to write */
#if defined(HAVE_RPK)
    RpkConfig         rpkConfig;
    RpkState          rpkState;
#endif /* HAVE_RPK */

    /* need full byte values for this section */
    byte            processReply;           /* nonblocking resume */
    byte            cipherSuite0;           /* first byte, normally 0 */
    byte            cipherSuite;            /* second byte, actual suite */
#ifdef WOLFSSL_TLS13
    byte            hrrCipherSuite0;        /* first byte, normally 0 */
    byte            hrrCipherSuite;         /* second byte, actual suite */
#endif
    byte            hashAlgo;               /* selected hash algorithm */
    byte            sigAlgo;                /* selected sig algorithm */
    byte            peerHashAlgo;           /* peer's chosen hash algo */
    byte            peerSigAlgo;            /* peer's chosen sig algo */
    byte            serverState;
    byte            clientState;
    byte            handShakeState;
    byte            handShakeDone;      /* at least one handshake complete */
    byte            minDowngrade;       /* minimum downgrade version */
    byte            connectState;       /* nonblocking resume */
    byte            acceptState;        /* nonblocking resume */
    byte            asyncState;         /* sub-state for enum asyncState */
    byte            buildMsgState;      /* sub-state for enum buildMsgState */
    byte            alertCount;         /* detect warning dos attempt */
#ifdef WOLFSSL_MULTICAST
    word16          mcastID;            /* Multicast group ID */
#endif
#ifndef NO_DH
    word16          minDhKeySz;         /* minimum DH key size */
    word16          maxDhKeySz;         /* minimum DH key size */
    word16          dhKeySz;            /* actual DH key size */
#endif
#ifndef NO_RSA
    short           minRsaKeySz;      /* minimum RSA key size */
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
    short           minEccKeySz;      /* minimum ECC key size */
#endif
#if defined(HAVE_FALCON)
    short           minFalconKeySz;   /* minimum Falcon key size */
#endif
#if defined(HAVE_DILITHIUM)
    short           minDilithiumKeySz;/* minimum Dilithium key size */
#endif
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    byte            verifyDepth;      /* maximum verification depth */
#endif
#ifdef WOLFSSL_EARLY_DATA
    word16          pskIdIndex;
    word32          maxEarlyDataSz;
#endif
#ifdef WOLFSSL_TLS13
    byte            oldMinor;          /* client preferred version < TLS 1.3 */
#endif
};

typedef struct Arrays {
    byte*           pendingMsg;         /* defrag buffer */
    byte*           preMasterSecret;
    word32          preMasterSz;        /* differs for DH, actual size */
    word32          pendingMsgSz;       /* defrag buffer size */
    word32          pendingMsgOffset;   /* current offset into defrag buffer */
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    word32          psk_keySz;          /* actual size */
    char            client_identity[MAX_PSK_ID_LEN + NULL_TERM_LEN];
    char            server_hint[MAX_PSK_ID_LEN + NULL_TERM_LEN];
    byte            psk_key[MAX_PSK_KEY_LEN];
#endif
    byte            clientRandom[RAN_LEN];
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
    byte            clientRandomInner[RAN_LEN];
#endif
    byte            serverRandom[RAN_LEN];
    byte            sessionID[ID_LEN];
    byte            sessionIDSz;
#ifdef WOLFSSL_TLS13
    byte            secret[SECRET_LEN];
#endif
#ifdef HAVE_KEYING_MATERIAL
    byte            exporterSecret[WC_MAX_DIGEST_SIZE];
#endif
    byte            masterSecret[SECRET_LEN];
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
   !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
    byte            tsip_masterSecret[TSIP_TLS_MASTERSECRET_SIZE];
#endif
#if defined(WOLFSSL_RENESAS_FSPSM_TLS)
    byte            fspsm_masterSecret[FSPSM_TLS_MASTERSECRET_SIZE];
#endif
#ifdef WOLFSSL_DTLS
    byte            cookie[MAX_COOKIE_LEN];
    byte            cookieSz;
#endif
    byte            pendingMsgType;    /* defrag buffer message type */
} Arrays;

#ifndef ASN_NAME_MAX
    #ifndef NO_ASN
        /* use value from asn.h */
        #define ASN_NAME_MAX WC_ASN_NAME_MAX
    #else
        /* calculate for WOLFSSL_X509 */
        #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
            defined(WOLFSSL_CERT_EXT)
            #define ASN_NAME_MAX 330
        #else
            #define ASN_NAME_MAX 256
        #endif
    #endif
#endif

typedef enum {
    STACK_TYPE_X509               = 0,
    STACK_TYPE_GEN_NAME           = 1,
    STACK_TYPE_BIO                = 2,
    STACK_TYPE_OBJ                = 3,
    STACK_TYPE_STRING             = 4,
    STACK_TYPE_CIPHER             = 5,
    STACK_TYPE_ACCESS_DESCRIPTION = 6,
    STACK_TYPE_X509_EXT           = 7,
    STACK_TYPE_NULL               = 8,
    STACK_TYPE_X509_NAME          = 9,
    STACK_TYPE_CONF_VALUE         = 10,
    STACK_TYPE_X509_INFO          = 11,
    STACK_TYPE_BY_DIR_entry       = 12,
    STACK_TYPE_BY_DIR_hash        = 13,
    STACK_TYPE_X509_OBJ           = 14,
    STACK_TYPE_DIST_POINT         = 15,
    STACK_TYPE_X509_CRL           = 16,
    STACK_TYPE_X509_NAME_ENTRY    = 17,
    STACK_TYPE_X509_REQ_ATTR      = 18,
    STACK_TYPE_GENERAL_SUBTREE    = 19,
    STACK_TYPE_X509_REVOKED       = 20,
} WOLF_STACK_TYPE;

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)

struct WOLFSSL_STACK {
    unsigned long num; /* number of nodes in stack
                        * (safety measure for freeing and shortcut for count) */
    #if defined(OPENSSL_ALL)
    wolf_sk_hash_cb hash_fn;
    unsigned long hash;
    #endif

    union {
        WOLFSSL_X509*          x509;
        WOLFSSL_X509_NAME*     name;
        WOLFSSL_X509_NAME_ENTRY* name_entry;
        WOLFSSL_X509_INFO*     info;
        WOLFSSL_BIO*           bio;
        WOLFSSL_ASN1_OBJECT*   obj;
        WOLFSSL_CIPHER         cipher;
        WOLFSSL_ACCESS_DESCRIPTION* access;
        WOLFSSL_X509_EXTENSION* ext;
#ifdef OPENSSL_EXTRA
        WOLFSSL_CONF_VALUE*    conf;
#endif
        void*                  generic;
        char*                  string;
        WOLFSSL_GENERAL_NAME*  gn;
        WOLFSSL_GENERAL_SUBTREE* subtree;
        WOLFSSL_BY_DIR_entry*  dir_entry;
        WOLFSSL_BY_DIR_HASH*   dir_hash;
        WOLFSSL_X509_OBJECT*   x509_obj;
        WOLFSSL_DIST_POINT*    dp;
        WOLFSSL_X509_CRL*      crl;
        WOLFSSL_X509_REVOKED*  revoked;
    } data;
    void* heap; /* memory heap hint */
    WOLFSSL_STACK* next;
    WOLF_STACK_TYPE type;     /* Identifies type of stack. */
};

#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */

struct WOLFSSL_X509_NAME {
    char  *name;
    int   dynamicName;
    int   sz;
    char  staticName[ASN_NAME_MAX];
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
    !defined(NO_ASN)
    DecodedName fullName;
    int   entrySz; /* number of entries */
    WOLFSSL_X509_NAME_ENTRY entry[MAX_NAME_ENTRIES]; /* all entries i.e. CN */
    WOLFSSL_X509*           x509;   /* x509 that struct belongs to */
#endif /* OPENSSL_EXTRA */
#ifndef WOLFSSL_NO_CA_NAMES
    byte  raw[ASN_NAME_MAX];
    int   rawLen;

    WOLF_STACK_OF(WOLFSSL_X509_NAME_ENTRY)* entries;
#endif
    void* heap;
};

#ifndef EXTERNAL_SERIAL_SIZE
    #define EXTERNAL_SERIAL_SIZE 32
#endif

#ifdef NO_ASN
    typedef struct DNS_entry DNS_entry;
    #ifndef IGNORE_NAME_CONSTRAINTS
        typedef struct Base_entry Base_entry;
    #endif
#endif

#ifndef WOLFSSL_AIA_ENTRY_DEFINED
#ifndef WOLFSSL_MAX_AIA_ENTRIES
    #define WOLFSSL_MAX_AIA_ENTRIES 8
#endif

#define WOLFSSL_AIA_ENTRY_DEFINED
typedef struct WOLFSSL_AIA_ENTRY {
    word32      method; /* AIA method OID sum (e.g., AIA_OCSP_OID). */
    const byte* uri;    /* Pointer into cert DER for the URI. */
    word32      uriSz;  /* Length of URI data. */
} WOLFSSL_AIA_ENTRY;
#endif /* WOLFSSL_AIA_ENTRY_DEFINED */

struct WOLFSSL_X509 {
    int              version;
    int              serialSz;
#ifdef WOLFSSL_SEP
    int              deviceTypeSz;
    int              hwTypeSz;
    byte             deviceType[EXTERNAL_SERIAL_SIZE];
    byte             hwType[EXTERNAL_SERIAL_SIZE];
    int              hwSerialNumSz;
    byte             hwSerialNum[EXTERNAL_SERIAL_SIZE];
    byte             certPolicySet;
    byte             certPolicyCrit;
#endif /* WOLFSSL_SEP */
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
    WOLFSSL_STACK* ext_sk; /* Store X509_EXTENSIONS from wolfSSL_X509_get_ext */
    WOLFSSL_STACK* ext_sk_full; /* Store X509_EXTENSIONS from wolfSSL_X509_get0_extensions */
    WOLFSSL_STACK* ext_d2i;/* Store d2i extensions from wolfSSL_X509_get_ext_d2i */
#endif /* WOLFSSL_QT || OPENSSL_ALL */
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
    WOLFSSL_ASN1_INTEGER* serialNumber; /* Stores SN from wolfSSL_X509_get_serialNumber */
#endif
    WOLFSSL_ASN1_TIME notBefore;
    WOLFSSL_ASN1_TIME notAfter;
    buffer           sig;
    int              sigOID;
    DNS_entry*       altNames;                       /* alt names list */
#ifndef IGNORE_NAME_CONSTRAINTS
    Base_entry*      permittedNames;                 /* name constraints */
    Base_entry*      excludedNames;
    byte             nameConstraintCrit:1;
#endif
    buffer           pubKey;
    int              pubKeyOID;
    DNS_entry*       altNamesNext;                   /* hint for retrieval */
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
    defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)
    word32       pkCurveOID;
#endif
#ifndef NO_CERTS
    DerBuffer*   derCert;                            /* may need  */
#endif
    void*            heap;                           /* heap hint */
    byte             dynamicMemory;                  /* dynamic memory flag */
    byte             isCa:1;
#ifdef WOLFSSL_CERT_EXT
    char             certPolicies[MAX_CERTPOL_NB][MAX_CERTPOL_SZ];
    int              certPoliciesNb;
#endif /* WOLFSSL_CERT_EXT */
#if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA)
    wolfSSL_Ref      ref;
#endif
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
#ifdef HAVE_EX_DATA
    WOLFSSL_CRYPTO_EX_DATA ex_data;
#endif
    byte*            authKeyId; /* Points into authKeyIdSrc */
    byte*            authKeyIdSrc;
    byte*            subjKeyId;
    WOLFSSL_ASN1_STRING* subjKeyIdStr;
    byte*            extKeyUsageSrc;
#ifdef OPENSSL_ALL
    byte*            subjAltNameSrc;
#endif
    byte*            rawCRLInfo;
    byte*            CRLInfo;
    byte*            authInfo;
#ifdef WOLFSSL_ASN_CA_ISSUER
    byte*            authInfoCaIssuer;
    int              authInfoCaIssuerSz;
#endif
    WOLFSSL_AIA_ENTRY authInfoList[WOLFSSL_MAX_AIA_ENTRIES];
    byte             authInfoListSz:7;
    byte             authInfoListOverflow:1;
    word32           pathLength;
    word16           keyUsage;
    int              rawCRLInfoSz;
    int              CRLInfoSz;
    int              authInfoSz;
    word32           authKeyIdSz;
    word32           authKeyIdSrcSz;
    word32           subjKeyIdSz;
    byte             extKeyUsage;
    word32           extKeyUsageSz;
    word32           extKeyUsageCount;
#ifndef IGNORE_NETSCAPE_CERT_TYPE
    byte             nsCertType;
#endif
#ifdef OPENSSL_ALL
    word32           subjAltNameSz;
#endif

    byte             CRLdistSet:1;
    byte             CRLdistCrit:1;
    byte             authInfoSet:1;
    byte             authInfoCrit:1;
    byte             keyUsageSet:1;
    byte             keyUsageCrit:1;
    byte             extKeyUsageCrit:1;
    byte             subjKeyIdSet:1;
    byte             pathLengthSet:1;

    byte             subjKeyIdCrit:1;
    byte             basicConstSet:1;
    byte             basicConstCrit:1;
    byte             basicConstPlSet:1;
    byte             subjAltNameSet:1;
    byte             subjAltNameCrit:1;
    byte             authKeyIdSet:1;
    byte             authKeyIdCrit:1;
    byte             issuerSet:1;
#ifdef WOLFSSL_CUSTOM_OID
    CertExtension    custom_exts[NUM_CUSTOM_EXT];
    int              customExtCount;
#endif /* WOLFSSL_CUSTOM_OID */
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
#ifdef WOLFSSL_CERT_REQ
    byte             isCSR:1;
#endif
    byte             serial[EXTERNAL_SERIAL_SIZE];
    char             subjectCN[ASN_NAME_MAX];        /* common name short cut */
#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN)
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
    /* stack of CSR attributes */
    WOLF_STACK_OF(WOLFSSL_X509_ATRIBUTE)* reqAttributes;
#endif
    #if defined(WOLFSSL_CERT_REQ)
    char             challengePw[CTC_NAME_SIZE]; /* for REQ certs */
    char             contentType[CTC_NAME_SIZE];
    #endif
#endif /* WOLFSSL_CERT_REQ || WOLFSSL_CERT_GEN */
    WOLFSSL_X509_NAME issuer;
    WOLFSSL_X509_NAME subject;
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
    defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_APACHE_HTTPD) || \
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS)
    WOLFSSL_X509_ALGOR algor;
    WOLFSSL_X509_PUBKEY key;
#endif
#if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA) || \
    defined(OPENSSL_ALL) || defined(KEEP_OUR_CERT) || \
    defined(KEEP_PEER_CERT) || defined(SESSION_CERTS)
    byte            notBeforeData[CTC_DATE_SIZE];
    byte            notAfterData[CTC_DATE_SIZE];
#endif
#ifdef WOLFSSL_DUAL_ALG_CERTS
    /* Subject Alternative Public Key Info */
    byte *sapkiDer;
    int sapkiLen;
    /* Alternative Signature Algorithm */
    byte *altSigAlgDer;
    int altSigAlgLen;
    /* Alternative Signature Value */
    byte *altSigValDer;
    int altSigValLen;

    byte sapkiCrit:1;
    byte altSigAlgCrit:1;
    byte altSigValCrit:1;
#endif /* WOLFSSL_DUAL_ALG_CERTS */
};

#if defined(WOLFSSL_ACERT)
struct WOLFSSL_X509_ACERT {
    int               version;
    int               serialSz;
    byte              serial[EXTERNAL_SERIAL_SIZE];
    WOLFSSL_ASN1_TIME notBefore;
    WOLFSSL_ASN1_TIME notAfter;
    buffer            sig;
    int               sigOID;
#ifndef NO_CERTS
    DerBuffer *       derCert;
#endif
    void *            heap;
    int               dynamic; /* whether struct was dynamically allocated */
    /* copy of raw Attributes field from */
    byte              holderSerial[EXTERNAL_SERIAL_SIZE];
    int               holderSerialSz;
    DNS_entry *       holderEntityName;  /* Holder entityName from ACERT */
    DNS_entry *       holderIssuerName;  /* issuerName from ACERT */
    DNS_entry *       AttCertIssuerName; /* AttCertIssuer name from ACERT */
    byte *            rawAttr;
    word32            rawAttrLen;
};
#endif /* WOLFSSL_ACERT */

/* record layer header for PlainText, Compressed, and CipherText */
typedef struct RecordLayerHeader {
    byte            type;
    byte            pvMajor;
    byte            pvMinor;
    byte            length[2];
} RecordLayerHeader;


/* record layer header for DTLS PlainText, Compressed, and CipherText */
typedef struct DtlsRecordLayerHeader {
    byte            type;
    byte            pvMajor;
    byte            pvMinor;
    byte            sequence_number[8];   /* per record */
    byte            length[2];
} DtlsRecordLayerHeader;

typedef struct DtlsFragBucket {
    /* m stands for meta */
    union {
        struct {
            struct DtlsFragBucket* next;
            word32 offset;
            word32 sz;
        } m;
        /* Make sure we have at least DTLS_HANDSHAKE_HEADER_SZ bytes before the
         * buf so that we can reconstruct the header in the allocated
         * DtlsFragBucket buffer. */
        byte padding[DTLS_HANDSHAKE_HEADER_SZ];
    } m;
/* Ignore "nonstandard extension used : zero-sized array in struct/union"
 * MSVC warning */
#ifdef _MSC_VER
#pragma warning(disable: 4200)
#endif
    byte buf[];
} DtlsFragBucket;

typedef struct DtlsMsg {
    struct DtlsMsg* next;
    byte*           raw;
    byte*           fullMsg;   /* for TX fullMsg == raw. For RX this points to
                                * the start of the message after headers. */
    DtlsFragBucket* fragBucketList;
    word32          bytesReceived;
    word16          epoch;     /* Epoch that this message belongs to */
    word32          seq;       /* Handshake sequence number    */
    word32          sz;        /* Length of whole message      */
    byte            type;
    byte            fragBucketListCount;
    byte            ready:1;
    byte            encrypted:1;
} DtlsMsg;


#ifdef HAVE_NETX

    /* NETX I/O Callback default */
    typedef struct NetX_Ctx {
        NX_TCP_SOCKET* nxSocket;    /* send/recv socket handle */
        NX_PACKET*     nxPacket;    /* incoming packet handle for short reads */
        ULONG          nxOffset;    /* offset already read from nxPacket */
        ULONG          nxWait;      /* wait option flag */
    } NetX_Ctx;

#endif

/* Handshake messages received from peer (plus change cipher */
typedef struct MsgsReceived {
    word16 got_hello_request:1;
    word16 got_client_hello:2;
    word16 got_server_hello:1;
    word16 got_hello_verify_request:1;
    word16 got_session_ticket:1;
    word16 got_end_of_early_data:1;
    word16 got_hello_retry_request:1;
    word16 got_encrypted_extensions:1;
    word16 got_certificate:1;
    word16 got_certificate_status:1;
    word16 got_server_key_exchange:1;
    word16 got_certificate_request:1;
    word16 got_server_hello_done:1;
    word16 got_certificate_verify:1;
    word16 got_client_key_exchange:1;
    word16 got_finished:1;
    word16 got_key_update:1;
    word16 got_change_cipher:1;
} MsgsReceived;


/* Handshake hashes */
typedef struct HS_Hashes {
    Hashes          verifyHashes;
    Hashes          certHashes;         /* for cert verify */
#if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
                          defined(WOLFSSL_ALLOW_TLS_SHA1))
    wc_Sha          hashSha;            /* sha hash of handshake msgs */
#endif
#if !defined(NO_MD5) && !defined(NO_OLD_TLS)
    wc_Md5          hashMd5;            /* md5 hash of handshake msgs */
#endif
#ifndef NO_SHA256
    wc_Sha256       hashSha256;         /* sha256 hash of handshake msgs */
#endif
#ifdef WOLFSSL_SHA384
    wc_Sha384       hashSha384;         /* sha384 hash of handshake msgs */
#endif
#ifdef WOLFSSL_SHA512
    wc_Sha512       hashSha512;         /* sha512 hash of handshake msgs */
#endif
#ifdef WOLFSSL_SM3
    wc_Sm3          hashSm3;            /* sm3 hash of handshake msgs */
#endif
#if (defined(HAVE_ED25519) || defined(HAVE_ED448) || \
     (defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3))) && \
    !defined(WOLFSSL_NO_CLIENT_AUTH)
    byte*           messages;           /* handshake messages */
    int             length;             /* length of handshake messages' data */
    int             prevLen;            /* length of messages but last */
#endif
} HS_Hashes;


#ifndef WOLFSSL_NO_TLS12
/* Persistable BuildMessage arguments */
typedef struct BuildMsgArgs {
    word32 digestSz;
    word32 sz;
    word32 pad;
    word32 idx;
    word32 headerSz;
    word16 size;
    word32 ivSz;      /* TLSv1.1  IV */
    byte   type;
    byte*  iv;
    ALIGN16 byte staticIvBuffer[MAX_IV_SZ];
} BuildMsgArgs;
#endif

#ifdef WOLFSSL_ASYNC_IO
    #define MAX_ASYNC_ARGS 18
    typedef void (*FreeArgsCb)(struct WOLFSSL* ssl, void* pArgs);

    struct WOLFSSL_ASYNC {
#if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WOLFSSL_NO_TLS12)
        BuildMsgArgs  buildArgs; /* holder for current BuildMessage args */
#endif
        FreeArgsCb    freeArgs; /* function pointer to cleanup args */
        word32        args[MAX_ASYNC_ARGS]; /* holder for current args */
    };
#endif

#ifdef HAVE_WRITE_DUP

    #define WRITE_DUP_SIDE 1
    #define READ_DUP_SIDE 2

    typedef struct WriteDup {
        wolfSSL_Mutex   dupMutex;       /* field access mutex */
        int             dupCount;       /* reference count */
        int             dupErr;         /* under dupMutex, pass to other side */
#ifdef WOLFSSL_DTLS13
        struct Dtls13RecordNumber* sendAckList; /* ownership transferred */
        /* Key update ACK tracking: write side stores the (epoch, seq) of its
         * in-flight KeyUpdate; read side sets keyUpdateAcked when the ACK for
         * that exact record arrives.  Both epoch and seq are checked to avoid
         * false positives from data records in the same epoch. */
        w64wrapper keyUpdateEpoch;     /* epoch of the KeyUpdate */
        w64wrapper keyUpdateSeq;       /* seq num of the KeyUpdate */
#endif /* WOLFSSL_DTLS13 */
#ifdef WOLFSSL_TLS13
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
        /* Post-handshake certificate request delegation: the read side received
         * a CertificateRequest but cannot write; it saves state here and the
         * write side sends Certificate+CertificateVerify+Finished. */
        struct HS_Hashes* postHandshakeHashState;    /* transcript at CR time */
        struct CertReqCtx* postHandshakeCertReqCtx; /* context from CR */
        byte postHandshakeSendVerify;    /* ssl->options.sendVerify */
        byte postHandshakeSigAlgo;       /* ssl->options.sigAlgo */
        byte postHandshakeHashAlgo;      /* ssl->options.hashAlgo */
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
#endif /* WOLFSSL_TLS13 */

        /* Flags */
#ifdef WOLFSSL_DTLS13
        WC_BITFIELD keyUpdateWaiting:1; /* write side has an unACKed KeyUpdate */
        WC_BITFIELD keyUpdateAcked:1;   /* read side confirmed the ACK arrived */
        /* DTLS 1.3: read side cannot write, so it passes ACK work to the
         * write side. */
        WC_BITFIELD sendAcks:1;
#endif /* WOLFSSL_DTLS13 */
#ifdef WOLFSSL_TLS13
        /* TLS 1.3 (and DTLS 1.3): read side received a KeyUpdate(update_requested)
         * but cannot send the response; write side handles it. */
        WC_BITFIELD keyUpdateRespond:1; /* write side must send a KeyUpdate response */
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
        WC_BITFIELD postHandshakeAuthPending:1; /* write side must respond */
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
#endif /* WOLFSSL_TLS13 */
    } WriteDup;

    WOLFSSL_LOCAL void FreeWriteDup(WOLFSSL* ssl);
    WOLFSSL_LOCAL int  NotifyWriteSide(WOLFSSL* ssl, int err);
#endif /* HAVE_WRITE_DUP */

#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
typedef struct CertReqCtx CertReqCtx;

struct CertReqCtx {
    CertReqCtx* next;
    byte        len;
    byte        ctx;
};
#endif

#ifdef WOLFSSL_EARLY_DATA
typedef enum EarlyDataState {
    no_early_data,
    early_data_ext,
    expecting_early_data,
    process_early_data,
    done_early_data
} EarlyDataState;
#endif

#ifdef WOLFSSL_DTLS13

/* size of the mask used to encrypt/decrypt Record Number  */
#define DTLS13_RN_MASK_SIZE 16

typedef struct Dtls13UnifiedHdrInfo {
    word16 recordLength;
    byte seqLo;
    byte seqHi;
    byte seqHiPresent:1;
    byte epochBits;
} Dtls13UnifiedHdrInfo;

enum  {
    DTLS13_EPOCH_EARLYDATA = 1,
    DTLS13_EPOCH_HANDSHAKE = 2,
    DTLS13_EPOCH_TRAFFIC0 = 3
};

/* 64-bit epoch + 64-bit sequence number */
#define DTLS13_RN_SIZE (OPAQUE64_LEN + OPAQUE64_LEN)
/* Maximum number of ACK records allowed in an ACK message */
#ifndef DTLS13_ACK_MAX_RECORDS
#define DTLS13_ACK_MAX_RECORDS 128
#endif
/* WOLFSSL_MAX_16BIT / DTLS13_RN_SIZE (0xffff / (OPAQUE64_LEN + OPAQUE64_LEN))
 * Literals are used because OPAQUE64_LEN is an enum value, invisible to the
 * preprocessor. */
#if DTLS13_ACK_MAX_RECORDS > 0xffff / 16
#error "DTLS13_ACK_MAX_RECORDS exceeds the maximum encodable in the word16 length field"
#endif


typedef struct Dtls13Epoch {
    w64wrapper epochNumber;

    w64wrapper nextSeqNumber;
    w64wrapper nextPeerSeqNumber;

#ifndef WOLFSSL_TLS13_IGNORE_AEAD_LIMITS
    w64wrapper dropCount; /* Amount of records that failed decryption */
#endif

    word32 window[WOLFSSL_DTLS_WINDOW_WORDS];

    /* key material for the epoch */
    byte client_write_key[MAX_SYM_KEY_SIZE];
    byte server_write_key[MAX_SYM_KEY_SIZE];
    byte client_write_IV[MAX_WRITE_IV_SZ];
    byte server_write_IV[MAX_WRITE_IV_SZ];

    byte aead_exp_IV[AEAD_MAX_EXP_SZ];
    byte aead_enc_imp_IV[AEAD_MAX_IMP_SZ];
    byte aead_dec_imp_IV[AEAD_MAX_IMP_SZ];

    byte client_sn_key[MAX_SYM_KEY_SIZE];
    byte server_sn_key[MAX_SYM_KEY_SIZE];

    byte isValid;
    byte side;
} Dtls13Epoch;

#ifndef DTLS13_EPOCH_SIZE
#define DTLS13_EPOCH_SIZE 4
#endif

#ifndef DTLS13_RETRANS_RN_SIZE
#define DTLS13_RETRANS_RN_SIZE 3
#endif

enum Dtls13RtxFsmState {
    DTLS13_RTX_FSM_PREPARING = 0,
    DTLS13_RTX_FSM_SENDING,
    DTLS13_RTX_FSM_WAITING,
    DTLS13_RTX_FSM_FINISHED
};

typedef struct Dtls13RtxRecord {
    struct Dtls13RtxRecord *next;
    word16 length;
    byte *data;
    w64wrapper epoch;
    w64wrapper seq[DTLS13_RETRANS_RN_SIZE];
    byte rnIdx;
    byte handshakeType;
} Dtls13RtxRecord;

typedef struct Dtls13RecordNumber {
    struct Dtls13RecordNumber *next;
    w64wrapper epoch;
    w64wrapper seq;
} Dtls13RecordNumber;

typedef struct Dtls13Rtx {
#ifdef WOLFSSL_RW_THREADED
    wolfSSL_Mutex mutex;
#endif
    enum Dtls13RtxFsmState state; /* Unused? */
    Dtls13RtxRecord *rtxRecords;
    Dtls13RtxRecord **rtxRecordTailPtr;
    Dtls13RecordNumber *seenRecords;
    word16 seenRecordsCount;
#ifdef WOLFSSL_32BIT_MILLI_TIME
    word32 lastRtx;
#else
    sword64 lastRtx;
#endif
    byte triggeredRtxs; /* Unused? */
    byte sendAcks;
    byte retransmit;
} Dtls13Rtx;

#endif /* WOLFSSL_DTLS13 */

#ifdef WOLFSSL_DTLS_CID
typedef struct ConnectionID {
    byte length;
/* Ignore "nonstandard extension used : zero-sized array in struct/union"
 * MSVC warning */
#ifdef _MSC_VER
#pragma warning(disable: 4200)
#endif
    byte id[];
} ConnectionID;

typedef struct CIDInfo {
    ConnectionID* tx;
    ConnectionID* rx;
    byte negotiated : 1;
} CIDInfo;
#endif /* WOLFSSL_DTLS_CID */

/* The idea is to reuse the context suites object whenever possible to save
 * space. */
#define WOLFSSL_SUITES(ssl) \
    ((const Suites*) ((ssl)->suites != NULL ? \
        (ssl)->suites : \
        (ssl)->ctx->suites))

/* wolfSSL ssl type */
struct WOLFSSL {
    WOLFSSL_CTX*    ctx;
#if defined(WOLFSSL_HAPROXY)
    WOLFSSL_CTX*    initial_ctx; /* preserve session key materials */
#endif
    Suites*         suites; /* Only need during handshake. Can be NULL when
                             * reusing the context's object. When WOLFSSL
                             * object needs separate instance of suites use
                             * AllocateSuites(). */
    Suites*         clSuites;
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
    WOLF_STACK_OF(WOLFSSL_CIPHER)* suitesStack; /* stack of available cipher
                                                 * suites */
    WOLF_STACK_OF(WOLFSSL_CIPHER)* clSuitesStack; /* stack of client cipher
                                                   * suites */
#endif
    Arrays*         arrays;
#ifdef WOLFSSL_TLS13
    byte            clientSecret[SECRET_LEN];
    byte            serverSecret[SECRET_LEN];
#endif
    HS_Hashes*      hsHashes;
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
    HS_Hashes*      hsHashesEch;
#endif
    void*           IOCB_ReadCtx;
    void*           IOCB_WriteCtx;
    WC_RNG*         rng;
    void*           verifyCbCtx;        /* cert verify callback user ctx*/
    VerifyCallback  verifyCallback;     /* cert verification callback */
    void*           heap;               /* for user overrides */
#ifdef HAVE_WRITE_DUP
    WriteDup*       dupWrite;           /* valid pointer indicates ON */
             /* side that decrements dupCount to zero frees overall structure */
    byte            dupSide;            /* write side or read side */
#endif
#ifdef OPENSSL_EXTRA
    byte              cbioFlag;         /* WOLFSSL_CBIO_RECV/SEND:
                                         * CBIORecv/Send is set */
#endif
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
    NetworkFilterCallback_t AcceptFilter;
    void *AcceptFilter_arg;
    NetworkFilterCallback_t ConnectFilter;
    void *ConnectFilter_arg;
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
    CallbackIORecv  CBIORecv;
    CallbackIOSend  CBIOSend;
#ifdef WOLFSSL_STATIC_MEMORY
    WOLFSSL_HEAP_HINT heap_hint;
#endif
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
    ClientHelloGoodCb chGoodCb;        /* notify user we parsed a verified
                                        * ClientHello that passed basic tests */
    void*             chGoodCtx;       /* user ClientHello cb context  */
#endif
#ifndef NO_HANDSHAKE_DONE_CB
    HandShakeDoneCb hsDoneCb;          /* notify user handshake done */
    void*           hsDoneCtx;         /* user handshake cb context  */
#endif
#ifdef WOLFSSL_ASYNC_IO
#ifdef WOLFSSL_ASYNC_CRYPT
    WC_ASYNC_DEV* asyncDev;
#endif
    /* Message building context should be stored here for functions that expect
     * to encounter encryption blocking or fragment the message. */
    struct WOLFSSL_ASYNC* async;
#endif
    void*           hsKey;              /* Handshake key (RsaKey or ecc_key)
                                         * allocated from heap */
    word32          hsType;             /* Type of Handshake key (hsKey) */
    WOLFSSL_CIPHER  cipher;
#ifdef WOLFSSL_DUAL_ALG_CERTS
    void*           hsAltKey;           /* Handshake key (dilithium, falcon)
                                         * allocated from heap */
    word32          hsAltType;          /* Type of Handshake key (hsAltKey) */
#endif
#ifndef WOLFSSL_AEAD_ONLY
    hmacfp          hmac;
#endif
    Ciphers         encrypt;
    Ciphers         decrypt;
    Buffers         buffers;
    WOLFSSL_SESSION* session;
#ifndef NO_CLIENT_CACHE
    ClientSession*  clientSession;
#endif
    WOLFSSL_ALERT_HISTORY alert_history;
    WOLFSSL_ALERT   pendingAlert;
    int             error;
    int             rfd;                /* read  file descriptor */
    int             wfd;                /* write file descriptor */
    int             rflags;             /* user read  flags */
    int             wflags;             /* user write flags */
    word32          timeout;            /* session timeout */
    word32          fragOffset;         /* fragment offset */
    word16          curSize;
    word32          curStartIdx;
    byte            verifyDepth;
    RecordLayerHeader curRL;
    MsgsReceived    msgsReceived;       /* peer messages received */
    ProtocolVersion version;            /* negotiated version */
    ProtocolVersion chVersion;          /* client hello version */
    CipherSpecs     specs;
    Keys            keys;
    Options         options;
#ifdef WOLFSSL_SESSION_ID_CTX
    byte             sessionCtx[ID_LEN]; /* app session context ID */
    byte             sessionCtxSz;       /* size of sessionCtx stored */
#endif
#ifdef OPENSSL_EXTRA
    CallbackInfoState* CBIS;             /* used to get info about SSL state */
    int              cbmode;             /* read or write on info callback */
    int              cbtype;             /* event type in info callback */
    WOLFSSL_BIO*     biord;              /* socket bio read  to free/close */
    WOLFSSL_BIO*     biowr;              /* socket bio write to free/close */
    WOLFSSL_X509_VERIFY_PARAM* param;    /* verification parameters*/
#endif
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
    word32            disabledCurves;   /* curves disabled by user */
#endif
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
    defined(OPENSSL_ALL)
    unsigned long    peerVerifyRet;
#endif
#ifdef OPENSSL_EXTRA
    byte             readAhead;
#ifdef HAVE_PK_CALLBACKS
    void*            loggingCtx;         /* logging callback argument */
#endif
#endif /* OPENSSL_EXTRA */
#ifndef NO_RSA
    RsaKey*         peerRsaKey;
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
    void*           RenesasUserCtx;
    byte*           peerSceTsipEncRsaKeyIndex;
#endif
    byte            peerRsaKeyPresent;
#ifdef WC_RSA_PSS
    word8           useRsaPss;           /* cert supports RSA-PSS */
#endif
#endif
#if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
    word16          namedGroup;
#endif
#ifdef WOLFSSL_TLS13
    word16          group[WOLFSSL_MAX_GROUP_COUNT];
    byte            numGroups;
#endif
    word16          pssAlgo;
#ifdef WOLFSSL_TLS13
    word16          certHashSigAlgoSz;  /* SigAlgoCert ext length in bytes */
    byte            certHashSigAlgo[WOLFSSL_MAX_SIGALGO]; /* cert sig/algo to
                                                           * offer */
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
    int             eccVerifyRes;
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_CURVE25519) || \
    defined(HAVE_ED448) || defined(HAVE_CURVE448)
    word32          ecdhCurveOID;            /* curve Ecc_Sum     */
    ecc_key*        eccTempKey;              /* private ECDHE key */
    byte            eccTempKeyPresent;       /* also holds type */
    byte            peerEccKeyPresent;
#endif
#ifdef HAVE_ECC
    ecc_key*        peerEccKey;              /* peer's  ECDHE key */
    ecc_key*        peerEccDsaKey;           /* peer's  ECDSA key */
    word16          eccTempKeySz;            /* in octets 20 - 66 */
    byte            peerEccDsaKeyPresent;
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
    defined(HAVE_CURVE448) || defined(HAVE_ED448)
    word32          pkCurveOID;              /* curve Ecc_Sum     */
#endif
#ifdef HAVE_ED25519
    ed25519_key*    peerEd25519Key;
    byte            peerEd25519KeyPresent;
#endif
#ifdef HAVE_CURVE25519
    curve25519_key* peerX25519Key;
    byte            peerX25519KeyPresent;
#endif
#ifdef HAVE_ED448
    ed448_key*      peerEd448Key;
    byte            peerEd448KeyPresent;
#endif
#ifdef HAVE_CURVE448
    curve448_key*   peerX448Key;
    byte            peerX448KeyPresent;
#endif
#ifdef HAVE_FALCON
    falcon_key*     peerFalconKey;
    byte            peerFalconKeyPresent;
#endif
#ifdef HAVE_DILITHIUM
    dilithium_key*  peerDilithiumKey;
    byte            peerDilithiumKeyPresent;
#endif
#ifdef HAVE_LIBZ
    z_stream        c_stream;           /* compression   stream */
    z_stream        d_stream;           /* decompression stream */
    byte            didStreamInit;      /* for stream init and end */
#endif
#ifdef WOLFSSL_DTLS
    int             dtls_timeout_init;  /* starting timeout value */
    int             dtls_timeout_max;   /* maximum timeout value */
    int             dtls_timeout;       /* current timeout value, changes */
#ifndef NO_ASN_TIME
    word32          dtls_start_timeout;
#endif /* !NO_ASN_TIME */
    word32          dtls_tx_msg_list_sz;
    word32          dtls_rx_msg_list_sz;
    DtlsMsg*        dtls_tx_msg_list;
    DtlsMsg*        dtls_tx_msg;
    DtlsMsg*        dtls_rx_msg_list;
    void*           IOCB_CookieCtx;     /* gen cookie ctx */
#ifdef WOLFSSL_SESSION_EXPORT
    wc_dtls_export  dtls_export;        /* export function for session */
#endif
#if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
    word16          dtlsMtuSz;
#endif /* WOLFSSL_SCTP || WOLFSSL_DTLS_MTU */
#ifdef WOLFSSL_MULTICAST
    void*           mcastHwCbCtx;       /* Multicast highwater callback ctx */
#endif /* WOLFSSL_MULTICAST */
#ifdef WOLFSSL_DTLS_DROP_STATS
    word32 macDropCount;
    word32 replayDropCount;
#endif /* WOLFSSL_DTLS_DROP_STATS */
#ifdef WOLFSSL_SRTP
    word16         dtlsSrtpProfiles;   /* DTLS-with-SRTP profiles list
                                        * (selected profiles - up to 16) */
    word16         dtlsSrtpId;         /* DTLS-with-SRTP profile ID selected */
#endif
#ifdef WOLFSSL_DTLS13
    RecordNumberCiphers dtlsRecordNumberEncrypt;
    RecordNumberCiphers dtlsRecordNumberDecrypt;
    Dtls13Epoch dtls13Epochs[DTLS13_EPOCH_SIZE];
    Dtls13Epoch *dtls13EncryptEpoch;
    Dtls13Epoch *dtls13DecryptEpoch;
    w64wrapper dtls13Epoch;
    w64wrapper dtls13PeerEpoch;
    w64wrapper dtls13InvalidateBefore;
    byte dtls13CurRL[DTLS_RECVD_RL_HEADER_MAX_SZ];
    word16 dtls13CurRlLength;

    /* used to store the message if it needs to be fragmented */
    buffer dtls13FragmentsBuffer;
    byte dtls13SendingFragments:1;
    byte dtls13SendingAckOrRtx;
    byte dtls13FastTimeout:1;
#ifdef HAVE_WRITE_DUP
    byte dtls13KeyUpdateAcked:1;
#endif
    byte dtls13WaitKeyUpdateAck;
    byte dtls13DoKeyUpdate;
    word32 dtls13MessageLength;
    word32 dtls13FragOffset;
    byte dtls13FragHandshakeType;
    Dtls13Rtx dtls13Rtx;
    byte *dtls13ClientHello;
    word16 dtls13ClientHelloSz;

#endif /* WOLFSSL_DTLS13 */
#ifdef WOLFSSL_DTLS_CID
    CIDInfo *dtlsCidInfo;
#endif /* WOLFSSL_DTLS_CID */

#endif /* WOLFSSL_DTLS */
#ifdef WOLFSSL_CALLBACKS
    TimeoutInfo     timeoutInfo;        /* info saved during handshake */
    HandShakeInfo   handShakeInfo;      /* info saved during handshake */
#endif
#ifdef OPENSSL_EXTRA
    SSL_Msg_Cb      protoMsgCb;         /* inspect protocol message callback */
    void*           protoMsgCtx;        /* user set context with msg callback */
#endif
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
    byte            hsInfoOn;           /* track handshake info        */
    byte            toInfoOn;           /* track timeout   info        */
#endif
#ifdef HAVE_FUZZER
    CallbackFuzzer  fuzzerCb;           /* for testing with using fuzzer */
    void*           fuzzerCtx;          /* user defined pointer */
#endif
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
    CertReqCtx*     certReqCtx;
#endif
#ifdef WOLFSSL_LOCAL_X509_STORE
    WOLFSSL_X509_STORE* x509_store_pt; /* take ownership of external store */
#endif
#ifdef KEEP_PEER_CERT
    /* TODO put this on the heap so we can properly use the
     * reference counter and not have to duplicate it. */
    WOLFSSL_X509     peerCert;           /* X509 peer cert */
#endif
#ifdef KEEP_OUR_CERT
    WOLFSSL_X509*    ourCert;            /* keep alive a X509 struct of cert.
                                            points to ctx if not owned (owned
                                            flag found in buffers.weOwnCert) */
#endif
    byte             keepCert;           /* keep certificate after handshake */
#ifdef HAVE_EX_DATA
    WOLFSSL_CRYPTO_EX_DATA ex_data; /* external data, for Fortress */
#endif
    int              devId;             /* async device id to use */
#ifdef HAVE_ONE_TIME_AUTH
    OneTimeAuth     auth;
#endif
#ifdef HAVE_TLS_EXTENSIONS
    TLSX* extensions;                  /* RFC 6066 TLS Extensions data */
    #ifdef HAVE_MAX_FRAGMENT
        word16 max_fragment;
    #endif
    #ifdef HAVE_TRUNCATED_HMAC
        byte truncated_hmac;
    #endif
    #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
        byte status_request;
    #endif
    #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
        byte status_request_v2;
    #endif
    #if defined(HAVE_SECURE_RENEGOTIATION) \
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
        int                  secure_rene_count;    /* how many times */
        SecureRenegotiation* secure_renegotiation; /* valid pointer indicates */
    #endif                                         /* user turned on */
    #ifdef HAVE_ALPN
        byte *alpn_peer_requested; /* the ALPN bytes requested by peer, sequence
                                    * of length byte + chars */
        word16 alpn_peer_requested_length; /* number of bytes total */
        #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)  || \
            defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_QUIC)
            CallbackALPNSelect alpnSelect;
            void*              alpnSelectArg;
        #endif
    #endif                         /* of accepted protocols */
    #if !defined(NO_WOLFSSL_CLIENT) && defined(HAVE_SESSION_TICKET)
        CallbackSessionTicket session_ticket_cb;
        void*                 session_ticket_ctx;
        byte                  expect_session_ticket;
    #endif
        word16 hrr_keyshare_group;
#endif /* HAVE_TLS_EXTENSIONS */
#ifdef HAVE_OCSP
        void*       ocspIOCtx;
        byte ocspProducedDate[MAX_DATE_SIZE];
        int ocspProducedDateFormat;
        buffer      ocspCsrResp[1 + MAX_CHAIN_DEPTH];
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
        char*   url;
    #endif
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
            word32 response_idx;
#endif
#endif
#ifdef HAVE_NETX
    NetX_Ctx        nxCtx;             /* NetX IO Context */
#endif
#if defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
    void*           mnCtx;             /* mynewt mn_socket IO Context */
#endif /* defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP) */
#ifdef WOLFSSL_GNRC
    struct gnrc_wolfssl_ctx *gnrcCtx;  /* Riot-OS GNRC UDP/IP context */
#endif
#ifdef SESSION_INDEX
    int sessionIndex;                  /* Session's location in the cache. */
#endif
#ifdef ATOMIC_USER
    void*    MacEncryptCtx;    /* Atomic User Mac/Encrypt Callback Context */
    void*    DecryptVerifyCtx; /* Atomic User Decrypt/Verify Callback Context */
    #ifdef HAVE_ENCRYPT_THEN_MAC
        void*    EncryptMacCtx;    /* Atomic User Encrypt/Mac Callback Ctx */
        void*    VerifyDecryptCtx; /* Atomic User Verify/Decrypt Callback Ctx */
    #endif
#endif
#ifdef HAVE_PK_CALLBACKS
    #ifdef HAVE_ECC
        void* EccKeyGenCtx;          /* EccKeyGen  Callback Context */
        void* EccSignCtx;            /* Ecc Sign   Callback Context */
        void* EccVerifyCtx;          /* Ecc Verify Callback Context */
        void* EccSharedSecretCtx;    /* Ecc Pms    Callback Context */
    #endif /* HAVE_ECC */
    #ifdef HAVE_HKDF
        void* HkdfExtractCtx;       /* Hkdf extract callback context */
    #endif
    #ifdef HAVE_ED25519
        void* Ed25519SignCtx;        /* ED25519 Sign   Callback Context */
        void* Ed25519VerifyCtx;      /* ED25519 Verify Callback Context */
    #endif
    #ifdef HAVE_CURVE25519
        void* X25519KeyGenCtx;       /* X25519 KeyGen Callback Context */
        void* X25519SharedSecretCtx; /* X25519 Pms    Callback Context */
    #endif
    #ifdef HAVE_ED448
        void* Ed448SignCtx;          /* ED448 Sign   Callback Context */
        void* Ed448VerifyCtx;        /* ED448 Verify Callback Context */
    #endif
    #ifdef HAVE_CURVE448
        void* X448KeyGenCtx;         /* X448 KeyGen Callback Context */
        void* X448SharedSecretCtx;   /* X448 Pms    Callback Context */
    #endif
    #ifndef NO_DH
        void* DhAgreeCtx; /* DH Pms Callback Context */
    #endif /* !NO_DH */
    #ifndef NO_RSA
        void* RsaSignCtx;     /* Rsa Sign   Callback Context */
        void* RsaVerifyCtx;   /* Rsa Verify Callback Context */
        #ifdef WC_RSA_PSS
            void* RsaPssSignCtx;     /* Rsa PSS Sign   Callback Context */
            void* RsaPssVerifyCtx;   /* Rsa PSS Verify Callback Context */
        #endif
        void* RsaEncCtx;      /* Rsa Public  Encrypt   Callback Context */
        void* RsaDecCtx;      /* Rsa Private Decrypt   Callback Context */
    #endif /* NO_RSA */
    void* GenPreMasterCtx;   /* Generate Premaster Callback Context */
    void* GenMasterCtx;      /* Generate Master Callback Context */
    void* GenExtMasterCtx;   /* Generate Extended Master Callback Context */
    void* GenSessionKeyCtx;  /* Generate Session Key Callback Context */
    void* EncryptKeysCtx;    /* Set Encrypt keys Callback Context */
    void* TlsFinishedCtx;    /* Generate Tls Finished Callback Context */
    void* VerifyMacCtx;      /* Verify mac Callback Context */
#endif /* HAVE_PK_CALLBACKS */
#ifdef HAVE_SECRET_CALLBACK
        SessionSecretCb sessionSecretCb;
        void*           sessionSecretCtx;
        TicketParseCb   ticketParseCb;
        void*           ticketParseCtx;
        TlsSecretCb     tlsSecretCb;
        void*           tlsSecretCtx;
    #ifdef WOLFSSL_TLS13
        Tls13SecretCb   tls13SecretCb;
        void*           tls13SecretCtx;
    #endif
    #ifdef OPENSSL_EXTRA
        SessionSecretCb keyLogCb;
    #ifdef WOLFSSL_TLS13
        Tls13SecretCb   tls13KeyLogCb;
    #endif
    #endif
#endif /* HAVE_SECRET_CALLBACK */
#ifdef WOLFSSL_JNI
        void* jObjectRef;     /* reference to WolfSSLSession in JNI wrapper */
#endif /* WOLFSSL_JNI */
#ifdef WOLFSSL_EARLY_DATA
    EarlyDataState earlyData;
    word32 earlyDataSz;
    byte earlyDataStatus;
#endif
#if defined(OPENSSL_EXTRA)
    WOLFSSL_STACK* supportedCiphers; /* Used in wolfSSL_get_ciphers_compat */
    WOLFSSL_STACK* peerCertChain;    /* Used in wolfSSL_get_peer_cert_chain */
    WOLFSSL_STACK* verifiedChain;    /* peer cert chain to CA */
#ifdef KEEP_OUR_CERT
    WOLFSSL_STACK* ourCertChain;    /* Used in wolfSSL_add1_chain_cert */
#endif
#endif
#ifdef WOLFSSL_STATIC_EPHEMERAL
    StaticKeyExchangeInfo_t staticKE;
#endif
#ifdef WOLFSSL_MAXQ10XX_TLS
    maxq_ssl_t maxq_ctx;
#endif
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
    /* Added in libest port: allow applications to get the 'tls-unique' Channel
     * Binding Type (https://tools.ietf.org/html/rfc5929#section-3). This is
     * used in the EST protocol to bind an enrollment to a TLS session through
     * 'proof-of-possession' (https://tools.ietf.org/html/rfc7030#section-3.4
     * and https://tools.ietf.org/html/rfc7030#section-3.5). */
    byte clientFinished[TLS_FINISHED_SZ_MAX];
    byte serverFinished[TLS_FINISHED_SZ_MAX];
    byte clientFinished_len;
    byte serverFinished_len;
#endif
#ifndef WOLFSSL_NO_CA_NAMES
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* client_ca_names; /* Used in *_set/get_client_CA_list
                                                          (server only) */
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* ca_names;        /* Used in *_set0/get0_CA_list */
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* peer_ca_names;   /* Used in *_get0_peer_CA_list
                                                          and (client only)
                                                          wolfSSL_get_client_CA_list */
#endif
#if defined(WOLFSSL_IOTSAFE) && defined(HAVE_PK_CALLBACKS)
    IOTSAFE iotsafe;
#endif
#ifdef WOLFSSL_LWIP_NATIVE
    WOLFSSL_LWIP_NATIVE_STATE      lwipCtx; /* LwIP native socket IO Context */
#endif
#ifdef WOLFSSL_QUIC
    struct {
        const WOLFSSL_QUIC_METHOD* method;
        WOLFSSL_ENCRYPTION_LEVEL enc_level_read;
        WOLFSSL_ENCRYPTION_LEVEL enc_level_read_next;
        WOLFSSL_ENCRYPTION_LEVEL enc_level_latest_recvd;
        WOLFSSL_ENCRYPTION_LEVEL enc_level_write;
        WOLFSSL_ENCRYPTION_LEVEL enc_level_write_next;
        int transport_version;
        const QuicTransportParam* transport_local;
        const QuicTransportParam* transport_peer;
        const QuicTransportParam* transport_peer_draft;
        QuicRecord* input_head;          /* we own, data for handshake */
        QuicRecord* input_tail;          /* points to last element for append */
        QuicRecord* scratch;             /* we own, record construction */
        enum wolfssl_encryption_level_t output_rec_level;
                                         /* encryption level of current output record */
        word32 output_rec_remain;        /* how many bytes of output TLS record
                                          * content have not been handled yet by quic */
    } quic;
#endif /* WOLFSSL_QUIC */
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
    WOLFSSL_EchConfig* echConfigs;
#endif

#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
    SSLSnifferSecretCb snifferSecretCb;
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
#ifdef WOLFSSL_DUAL_ALG_CERTS
    byte *sigSpec;         /* This pointer never owns the memory. */
    word16 sigSpecSz;
    byte *peerSigSpec;     /* This pointer always owns the memory. */
    word16 peerSigSpecSz;
#endif
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
    int secLevel; /* The security level of system-wide crypto policy. */
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
#if !defined(NO_WOLFSSL_CLIENT) && !defined(WOLFSSL_NO_TLS12) && \
    defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK)
    WC_BITFIELD          scr_check_enabled:1;  /* enable/disable SCR check */
#endif
#ifdef HAVE_WRITE_DUP
#ifdef WOLFSSL_TLS13
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
    WC_BITFIELD postHandshakeAuthPending:1;
#endif
#endif
#endif
};

#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
#define WOLFSSL_SECLEVEL_STR "@SECLEVEL="
struct SystemCryptoPolicy {
    int    enabled;
    int    secLevel;
    char   str[MAX_WOLFSSL_CRYPTO_POLICY_SIZE + 1]; /* + 1 for null term */
};
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */

/*
 * wolfSSL_PEM_read_bio_X509 pushes an ASN_NO_PEM_HEADER error
 * to the error queue on file end. This should not be left
 * for the caller to find so we clear the last error.
 */
#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_HAVE_ERROR_QUEUE)
#define CLEAR_ASN_NO_PEM_HEADER_ERROR(err)                                     \
do {                                                                           \
    (err) = wolfSSL_ERR_peek_last_error();                                     \
    if (wolfSSL_ERR_GET_LIB(err) == WOLFSSL_ERR_LIB_PEM &&                     \
        wolfSSL_ERR_GET_REASON(err) == -WOLFSSL_PEM_R_NO_START_LINE_E) {       \
        unsigned long peekErr;                                                 \
        do {                                                                   \
            wc_RemoveErrorNode(-1);                                            \
            peekErr = wolfSSL_ERR_peek_last_error();                           \
        } while (wolfSSL_ERR_GET_LIB(peekErr) == WOLFSSL_ERR_LIB_PEM &&        \
                 wolfSSL_ERR_GET_REASON(peekErr) ==                            \
                                              -WOLFSSL_PEM_R_NO_START_LINE_E); \
    }                                                                          \
} while(0)
#else
#define CLEAR_ASN_NO_PEM_HEADER_ERROR(err) (void)(err);
#endif

/*
 * The SSL object may have its own certificate store. The below macros simplify
 * logic for choosing which WOLFSSL_CERT_MANAGER and WOLFSSL_X509_STORE to use.
 * Always use SSL specific objects when available and revert to CTX otherwise.
 */
#ifdef WOLFSSL_LOCAL_X509_STORE
#define SSL_CM(ssl) ((ssl)->x509_store_pt ? (ssl)->x509_store_pt->cm : \
                     ((ssl)->ctx->x509_store_pt ? (ssl)->ctx->x509_store_pt->cm : \
                                            (ssl)->ctx->cm))
#define SSL_STORE(ssl) ((ssl)->x509_store_pt ? (ssl)->x509_store_pt : \
                  ((ssl)->ctx->x509_store_pt ? (ssl)->ctx->x509_store_pt : \
                                            &(ssl)->ctx->x509_store))
#define CTX_STORE(ctx) ((ctx)->x509_store_pt ? (ctx)->x509_store_pt : \
                                            &(ctx)->x509_store)
#else
#define SSL_CM(ssl) (ssl)->ctx->cm
#endif
/* Issue warning when we are modifying the overall context CM */
#define SSL_CM_WARNING(ssl) \
    do {                                                             \
        if (SSL_CM( (ssl) ) == (ssl)->ctx->cm) {                     \
            WOLFSSL_MSG("Modifying SSL_CTX CM not SSL specific CM"); \
        }                                                            \
    } while (0)

WOLFSSL_LOCAL int  SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup);
WOLFSSL_LOCAL int  InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup);
WOLFSSL_LOCAL int  ReinitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup);
WOLFSSL_LOCAL void FreeSSL(WOLFSSL* ssl, void* heap);
WOLFSSL_TEST_VIS   void wolfSSL_ResourceFree(WOLFSSL* ssl);   /* Micrium uses */
#ifndef OPENSSL_COEXIST
#define SSL_ResourceFree wolfSSL_ResourceFree
#endif


#ifndef NO_CERTS

    WOLFSSL_LOCAL int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff,
                                    long sz, int format, int type, WOLFSSL* ssl,
                                    long* used, int userChain, int verify,
                                    const char *source_name);
    WOLFSSL_LOCAL int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format,
                                 int type, WOLFSSL* ssl, int userChain,
                                WOLFSSL_CRL* crl, int verify);

    #ifndef NO_ASN
    WOLFSSL_LOCAL int CheckHostName(DecodedCert* dCert, const char *domainName,
                                    size_t domainNameLen, unsigned int flags,
                                    byte isIP);
    #endif
#endif


#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
    WOLFSSL_LOCAL void InitHandShakeInfo(HandShakeInfo* info, WOLFSSL* ssl);
    WOLFSSL_LOCAL void FinishHandShakeInfo(HandShakeInfo* info);
    WOLFSSL_LOCAL void AddPacketName(WOLFSSL* ssl, const char* name);

    WOLFSSL_LOCAL void InitTimeoutInfo(TimeoutInfo* info);
    WOLFSSL_LOCAL void FreeTimeoutInfo(TimeoutInfo* info, void* heap);
    WOLFSSL_LOCAL int AddPacketInfo(WOLFSSL* ssl, const char* name, int type,
                             const byte* data, int sz, int written, int lateRL,
                             void* heap);
    WOLFSSL_LOCAL void AddLateName(const char* name, TimeoutInfo* info);
    WOLFSSL_LOCAL void AddLateRecordHeader(const RecordLayerHeader* rl,
                                           TimeoutInfo* info);
#endif


/* Record Layer Header identifier from page 12 */
enum ContentType {
    no_type            = 0,
    change_cipher_spec = 20,
    alert              = 21,
    handshake          = 22,
    application_data   = 23,
    dtls12_cid         = 25,
#ifdef WOLFSSL_DTLS13
    ack                = 26,
#endif /* WOLFSSL_DTLS13 */
};


/* handshake header, same for each message type, pgs 20/21 */
typedef struct HandShakeHeader {
    byte            type;
    word24          length;
} HandShakeHeader;


/* DTLS handshake header, same for each message type */
typedef struct DtlsHandShakeHeader {
    byte            type;
    word24          length;
    byte            message_seq[2];    /* start at 0, retransmit gets same # */
    word24          fragment_offset;   /* bytes in previous fragments */
    word24          fragment_length;   /* length of this fragment */
} DtlsHandShakeHeader;


enum HandShakeType {
    hello_request        =   0,
    client_hello         =   1,
    server_hello         =   2,
    hello_verify_request =   3,    /* DTLS addition */
    session_ticket       =   4,
    end_of_early_data    =   5,
    hello_retry_request  =   6,
    encrypted_extensions =   8,
    certificate          =  11,
    server_key_exchange  =  12,
    certificate_request  =  13,
    server_hello_done    =  14,
    certificate_verify   =  15,
    client_key_exchange  =  16,
    finished             =  20,
    certificate_status   =  22,
    key_update           =  24,
    change_cipher_hs     =  55,    /* simulate unique handshake type for sanity
                                      checks.  record layer change_cipher
                                      conflicts with handshake finished */
    message_hash         = 254,    /* synthetic message type for TLS v1.3 */
    no_shake             = 255     /* used to initialize the DtlsMsg record */
};

enum ProvisionSide {
    PROVISION_CLIENT = 1,
    PROVISION_SERVER = 2,
    PROVISION_CLIENT_SERVER = 3
};

/* cipher requirements */
enum {
    REQUIRES_RSA,
    REQUIRES_DHE,
    REQUIRES_ECC,
    REQUIRES_ECC_STATIC,
    REQUIRES_PSK,
    REQUIRES_RSA_SIG,
    REQUIRES_AEAD
};

static const byte kTlsClientStr[SIZEOF_SENDER+1] = { 0x43, 0x4C, 0x4E, 0x54, 0x00 }; /* CLNT */
static const byte kTlsServerStr[SIZEOF_SENDER+1] = { 0x53, 0x52, 0x56, 0x52, 0x00 }; /* SRVR */

static const byte kTlsClientFinStr[FINISHED_LABEL_SZ + 1] = "client finished";
static const byte kTlsServerFinStr[FINISHED_LABEL_SZ + 1] = "server finished";

#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || defined(HAVE_CURL)
typedef struct {
    int name_len;
    const char *name;
    int nid;
    word16 curve;
} WOLF_EC_NIST_NAME;
extern const WOLF_EC_NIST_NAME kNistCurves[];
WOLFSSL_LOCAL int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx,
        const char* names, byte curves_only);
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_CURL */

/* internal functions */
WOLFSSL_LOCAL int SendChangeCipher(WOLFSSL* ssl);
WOLFSSL_LOCAL int SendTicket(WOLFSSL* ssl);
#ifdef HAVE_SESSION_TICKET
WOLFSSL_LOCAL int DoDecryptTicket(const WOLFSSL* ssl, const byte* input,
        word32 len, InternalTicket **it);
/* Return 0 when check successful. <0 on failure. */
WOLFSSL_LOCAL void DoClientTicketFinalize(WOLFSSL* ssl, InternalTicket* it,
                                          const WOLFSSL_SESSION* sess);

#ifdef WOLFSSL_TLS13
WOLFSSL_LOCAL int DoClientTicketCheck(const WOLFSSL* ssl,
        const PreSharedKey* psk, sword64 timeout, const byte* suite);
WOLFSSL_LOCAL void CleanupClientTickets(PreSharedKey* psk);
WOLFSSL_LOCAL int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk,
                                    int retainSess);
#endif

WOLFSSL_LOCAL int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len);
#endif /* HAVE_SESSION_TICKET */
WOLFSSL_LOCAL int SendData(WOLFSSL* ssl, const void* data, size_t sz);
#ifdef WOLFSSL_THREADED_CRYPT
WOLFSSL_LOCAL int SendAsyncData(WOLFSSL* ssl);
#endif
#ifdef WOLFSSL_TLS13
WOLFSSL_LOCAL int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType);
#endif
WOLFSSL_LOCAL int SendCertificate(WOLFSSL* ssl);
WOLFSSL_LOCAL int SendCertificateRequest(WOLFSSL* ssl);
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
 || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
WOLFSSL_LOCAL int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest,
                       buffer* response);
#endif
#if defined(HAVE_SECURE_RENEGOTIATION) && \
    !defined(NO_WOLFSSL_SERVER)
WOLFSSL_LOCAL int SendHelloRequest(WOLFSSL* ssl);
#endif
WOLFSSL_LOCAL int SendCertificateStatus(WOLFSSL* ssl);
WOLFSSL_LOCAL int SendServerKeyExchange(WOLFSSL* ssl);
WOLFSSL_LOCAL int SendBuffered(WOLFSSL* ssl);
WOLFSSL_LOCAL int ReceiveData(WOLFSSL* ssl, byte* output, size_t sz, int peek);
WOLFSSL_LOCAL int SendFinished(WOLFSSL* ssl);
WOLFSSL_LOCAL int RetrySendAlert(WOLFSSL* ssl);
WOLFSSL_LOCAL int SendAlert(WOLFSSL* ssl, int severity, int type);
WOLFSSL_LOCAL int SendFatalAlertOnly(WOLFSSL *ssl, int error);
WOLFSSL_LOCAL int ProcessReply(WOLFSSL* ssl);
WOLFSSL_LOCAL int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr);

WOLFSSL_LOCAL const char* AlertTypeToString(int type);

WOLFSSL_LOCAL int SetCipherSpecs(WOLFSSL* ssl);
WOLFSSL_LOCAL int GetCipherSpec(word16 side, byte cipherSuite0,
        byte cipherSuite, CipherSpecs* specs, Options* opts);
WOLFSSL_LOCAL int MakeMasterSecret(WOLFSSL* ssl);

WOLFSSL_LOCAL int DeriveKeys(WOLFSSL* ssl);
WOLFSSL_LOCAL int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side);

WOLFSSL_LOCAL int IsTLS(const WOLFSSL* ssl);
WOLFSSL_LOCAL int IsTLS_ex(const ProtocolVersion pv);
WOLFSSL_LOCAL int IsAtLeastTLSv1_2(const WOLFSSL* ssl);
WOLFSSL_LOCAL int IsAtLeastTLSv1_3(ProtocolVersion pv);
WOLFSSL_LOCAL int IsEncryptionOn(const WOLFSSL* ssl, int isSend);
WOLFSSL_LOCAL int TLSv1_3_Capable(WOLFSSL* ssl);

WOLFSSL_LOCAL void FreeHandshakeResources(WOLFSSL* ssl);
WOLFSSL_LOCAL void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree);
WOLFSSL_LOCAL void ShrinkOutputBuffer(WOLFSSL* ssl);
WOLFSSL_LOCAL byte* GetOutputBuffer(WOLFSSL* ssl);

WOLFSSL_LOCAL int CipherRequires(byte first, byte second, int requirement);
WOLFSSL_LOCAL int VerifyClientSuite(word16 havePSK, byte cipherSuite0,
                                    byte cipherSuite);

WOLFSSL_LOCAL int SetTicket(WOLFSSL* ssl, const byte* ticket, word32 length);
WOLFSSL_LOCAL int wolfssl_local_GetRecordSize(WOLFSSL *ssl, int payloadSz,
        int isEncrypted);
WOLFSSL_LOCAL int wolfssl_local_GetMaxPlaintextSize(WOLFSSL *ssl);
WOLFSSL_LOCAL int wolfSSL_GetMaxFragSize(WOLFSSL* ssl);

#if defined(WOLFSSL_IOTSAFE) && defined(HAVE_PK_CALLBACKS)
WOLFSSL_LOCAL IOTSAFE *wolfSSL_get_iotsafe_ctx(WOLFSSL *ssl);
WOLFSSL_LOCAL int wolfSSL_set_iotsafe_ctx(WOLFSSL *ssl, IOTSAFE *iotsafe);
#endif

#if (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) && defined(HAVE_ECC)
WOLFSSL_LOCAL int SetECKeyInternal(WOLFSSL_EC_KEY* eckey);
WOLFSSL_LOCAL int SetECKeyExternal(WOLFSSL_EC_KEY* eckey);
#endif

#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
WOLFSSL_LOCAL int wolfSSL_curve_is_disabled(const WOLFSSL* ssl,
                                            word16 curve_id);
#else
static WC_INLINE int wolfSSL_curve_is_disabled(const WOLFSSL* ssl,
                                               word16 curve_id)
{
    (void)ssl;
    (void)curve_id;
    return 0;
}
#endif

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
WOLFSSL_LOCAL WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA *rsa, WC_RNG **tmpRNG,
                                         int *initTmpRng);
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */

#ifndef NO_CERTS
    #ifndef NO_RSA
        #ifdef WC_RSA_PSS
            WOLFSSL_LOCAL int CheckRsaPssPadding(const byte* plain, word32 plainSz,
                byte* out, word32 sigSz, enum wc_HashType hashType);
            WOLFSSL_LOCAL int ConvertHashPss(int hashAlgo,
                enum wc_HashType* hashType, int* mgf);
        #endif
        WOLFSSL_LOCAL int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig,
            word32 sigSz, const byte* plain, word32 plainSz, int sigAlgo,
            int hashAlgo, RsaKey* key, DerBuffer* keyBufInfo);
        WOLFSSL_LOCAL int RsaSign(WOLFSSL* ssl, const byte* in, word32 inSz,
            byte* out, word32* outSz, int sigAlgo, int hashAlgo, RsaKey* key,
            DerBuffer* keyBufInfo);
        WOLFSSL_LOCAL int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz,
            byte** out, int sigAlgo, int hashAlgo, RsaKey* key,
            buffer* keyBufInfo);
        WOLFSSL_LOCAL int RsaDec(WOLFSSL* ssl, byte* in, word32 inSz, byte** out,
            word32* outSz, RsaKey* key, DerBuffer* keyBufInfo);
        WOLFSSL_LOCAL int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
            word32* outSz, RsaKey* key, buffer* keyBufInfo);
    #endif /* !NO_RSA */

    #ifdef HAVE_ECC
        WOLFSSL_LOCAL int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz,
            byte* out, word32* outSz, ecc_key* key, DerBuffer* keyBufInfo);
        WOLFSSL_LOCAL int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz,
            const byte* out, word32 outSz, ecc_key* key, buffer* keyBufInfo);
        WOLFSSL_LOCAL int EccSharedSecret(WOLFSSL* ssl, ecc_key* priv_key,
            ecc_key* pub_key, byte* pubKeyDer, word32* pubKeySz, byte* out,
            word32* outlen, int side);
    #endif /* HAVE_ECC */
    #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
        WOLFSSL_LOCAL int Sm2wSm3Sign(WOLFSSL* ssl, const byte* id, word32 idSz,
            const byte* in, word32 inSz, byte* out, word32* outSz, ecc_key* key,
            DerBuffer* keyBufInfo);
        WOLFSSL_LOCAL int Sm2wSm3Verify(WOLFSSL* ssl, const byte* id,
            word32 idSz, const byte* in, word32 inSz, const byte* out,
            word32 outSz, ecc_key* key, buffer* keyBufInfo);
    #endif /* WOLFSSL_SM2 && WOLFSSL_SM3 */
    #ifdef HAVE_ED25519
        WOLFSSL_LOCAL int Ed25519CheckPubKey(WOLFSSL* ssl);
        WOLFSSL_LOCAL int Ed25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
            byte* out, word32* outSz, ed25519_key* key, DerBuffer* keyBufInfo);
        WOLFSSL_LOCAL int Ed25519Verify(WOLFSSL* ssl, const byte* in,
            word32 inSz, const byte* msg, word32 msgSz, ed25519_key* key,
            buffer* keyBufInfo);
    #endif /* HAVE_ED25519 */
    #ifdef HAVE_ED448
        WOLFSSL_LOCAL int Ed448CheckPubKey(WOLFSSL* ssl);
        WOLFSSL_LOCAL int Ed448Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
            byte* out, word32* outSz, ed448_key* key, DerBuffer* keyBufInfo);
        WOLFSSL_LOCAL int Ed448Verify(WOLFSSL* ssl, const byte* in,
            word32 inSz, const byte* msg, word32 msgSz, ed448_key* key,
            buffer* keyBufInfo);
    #endif /* HAVE_ED448 */


    #ifdef WOLFSSL_TRUST_PEER_CERT

        /* options for searching hash table for a matching trusted peer cert */
        #define WC_MATCH_SKID 0
        #define WC_MATCH_NAME 1

        WOLFSSL_LOCAL TrustedPeerCert* GetTrustedPeer(void* vp, DecodedCert* cert);
        WOLFSSL_LOCAL int MatchTrustedPeer(TrustedPeerCert* tp,
                                                             DecodedCert* cert);
    #endif


    #ifndef GetCA
        WOLFSSL_LOCAL Signer* GetCA(void* vp, byte* hash);
    #endif
    #if defined(WOLFSSL_AKID_NAME) && !defined(WC_SYM_RELOC_TABLES)
        /* note WOLFSSL_API_PREFIX_MAPping is in asn.h, and if
         * WC_SYM_RELOC_TABLES, the prototype is in the port layer
         * (e.g. linuxkm_wc_port.h), to allow shimming.
         */
        WOLFSSL_TEST_VIS Signer* GetCAByAKID(void* vp, const byte* issuer,
                word32 issuerSz, const byte* serial, word32 serialSz);
    #endif
    #if defined(HAVE_OCSP) && !defined(GetCAByKeyHash)
        WOLFSSL_LOCAL Signer* GetCAByKeyHash(void* vp, const byte* keyHash);
    #endif
    #if !defined(NO_SKID) && !defined(GetCAByName)
        WOLFSSL_LOCAL Signer* GetCAByName(void* vp, byte* hash);
    #endif
#endif /* !NO_CERTS */
WOLFSSL_LOCAL int  BuildTlsHandshakeHash(WOLFSSL* ssl, byte* hash,
                                   word32* hashLen);
WOLFSSL_LOCAL int  BuildTlsFinished(WOLFSSL* ssl, Hashes* hashes,
                                   const byte* sender);
WOLFSSL_LOCAL void FreeArrays(WOLFSSL* ssl, int keep);
WOLFSSL_LOCAL  int CheckAvailableSize(WOLFSSL *ssl, int size);
WOLFSSL_LOCAL  int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength);
WOLFSSL_LOCAL  int MsgCheckEncryption(WOLFSSL* ssl, byte type, byte encrypted);
WOLFSSL_LOCAL  int EarlySanityCheckMsgReceived(WOLFSSL* ssl, byte type,
        word32 msgSz);
WOLFSSL_LOCAL int GetHandshakeHeader(WOLFSSL* ssl, const byte* input,
        word32* inOutIdx, byte* type, word32* size, word32 totalSz);
#if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
WOLFSSL_LOCAL void DoCertFatalAlert(WOLFSSL* ssl, int ret);
#endif
#ifndef NO_TLS
    WOLFSSL_LOCAL int  MakeTlsMasterSecret(WOLFSSL* ssl);
#ifndef WOLFSSL_AEAD_ONLY
    WOLFSSL_LOCAL int  TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in,
                                word32 sz, int padSz, int content, int verify, int epochOrder);
#endif
#endif

WOLFSSL_LOCAL int cipherExtraData(WOLFSSL* ssl);
WOLFSSL_LOCAL word32 MacSize(const WOLFSSL* ssl);

#ifndef NO_WOLFSSL_CLIENT
    WOLFSSL_LOCAL int HaveUniqueSessionObj(WOLFSSL* ssl);
    WOLFSSL_LOCAL int SendClientHello(WOLFSSL* ssl);
    WOLFSSL_LOCAL int DoHelloVerifyRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
        word32 size);
    #ifdef WOLFSSL_TLS13
    WOLFSSL_LOCAL int SendTls13ClientHello(WOLFSSL* ssl);
    #endif
    WOLFSSL_LOCAL int SendClientKeyExchange(WOLFSSL* ssl);
    WOLFSSL_LOCAL int SendCertificateVerify(WOLFSSL* ssl);
#endif /* NO_WOLFSSL_CLIENT */

#ifndef NO_WOLFSSL_SERVER
    WOLFSSL_LOCAL int SendServerHello(WOLFSSL* ssl);
    WOLFSSL_LOCAL int SendServerHelloDone(WOLFSSL* ssl);
#endif /* NO_WOLFSSL_SERVER */

#ifdef WOLFSSL_TLS13
    WOLFSSL_LOCAL int SendTls13KeyUpdate(WOLFSSL* ssl);
#endif

#ifdef WOLFSSL_DTLS
    #ifdef WOLFSSL_API_PREFIX_MAP
        #define DtlsMsgListDelete wolfSSL_DtlsMsgListDelete
        #define DtlsMsgFind wolfSSL_DtlsMsgFind
        #define DtlsMsgStore wolfSSL_DtlsMsgStore
    #endif /* WOLFSSL_API_PREFIX_MAP */
    WOLFSSL_LOCAL DtlsMsg* DtlsMsgNew(word32 sz, byte tx, void* heap);
    WOLFSSL_LOCAL void DtlsMsgDelete(DtlsMsg* item, void* heap);
    WOLFSSL_TEST_VIS void DtlsMsgListDelete(DtlsMsg* head, void* heap);
    WOLFSSL_LOCAL void DtlsTxMsgListClean(WOLFSSL* ssl);
    WOLFSSL_LOCAL int  DtlsMsgSet(DtlsMsg* msg, word32 seq, word16 epoch,
                                  const byte* data, byte type,
                                  word32 fragOffset, word32 fragSz, void* heap,
                                  word32 totalLen, byte encrypted);
    WOLFSSL_TEST_VIS DtlsMsg* DtlsMsgFind(DtlsMsg* head, word16 epoch, word32 seq);

    WOLFSSL_TEST_VIS void DtlsMsgStore(WOLFSSL* ssl, word16 epoch, word32 seq,
                                    const byte* data, word32 dataSz, byte type,
                                    word32 fragOffset, word32 fragSz,
                                    void* heap);
    WOLFSSL_LOCAL DtlsMsg* DtlsMsgInsert(DtlsMsg* head, DtlsMsg* item);

    WOLFSSL_LOCAL int  DtlsMsgPoolSave(WOLFSSL* ssl, const byte* data,
                                       word32 dataSz, enum HandShakeType type);
    WOLFSSL_LOCAL int  DtlsMsgPoolTimeout(WOLFSSL* ssl);
    WOLFSSL_LOCAL int  VerifyForDtlsMsgPoolSend(WOLFSSL* ssl, byte type,
                                                word32 fragOffset);
    WOLFSSL_LOCAL int  VerifyForTxDtlsMsgDelete(WOLFSSL* ssl, DtlsMsg* item);
    WOLFSSL_LOCAL void DtlsMsgPoolReset(WOLFSSL* ssl);
    WOLFSSL_LOCAL int  DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket);
    WOLFSSL_LOCAL void DtlsMsgDestroyFragBucket(DtlsFragBucket* fragBucket, void* heap);
    WOLFSSL_LOCAL int GetDtlsHandShakeHeader(WOLFSSL *ssl, const byte *input,
        word32 *inOutIdx, byte *type, word32 *size, word32 *fragOffset,
        word32 *fragSz, word32 totalSz);
    WOLFSSL_LOCAL int DtlsMsgDrain(WOLFSSL *ssl);
    WOLFSSL_LOCAL int SendHelloVerifyRequest(WOLFSSL* ssl,
        const byte* cookie, byte cookieSz);

#if !defined(NO_WOLFSSL_SERVER)
    WOLFSSL_LOCAL int DoClientHelloStateless(WOLFSSL* ssl,
            const byte* input, word32 helloSz, byte isFirstCHFrag, byte* tls13);
#endif /* !defined(NO_WOLFSSL_SERVER) */
#if !defined(WOLFCRYPT_ONLY) && !defined(WOLFSSL_NO_SOCK) && \
    (defined(USE_WOLFSSL_IO) || defined(WOLFSSL_USER_IO))
    WOLFSSL_LOCAL int sockAddrEqual(SOCKADDR_S *a, XSOCKLENT aLen,
                                    SOCKADDR_S *b, XSOCKLENT bLen);
#endif
#endif /* WOLFSSL_DTLS */

#if defined(HAVE_SECURE_RENEGOTIATION) && defined(WOLFSSL_DTLS)
    WOLFSSL_LOCAL int DtlsSCRKeysSet(WOLFSSL* ssl);
    WOLFSSL_LOCAL int IsDtlsMsgSCRKeys(WOLFSSL* ssl);
    WOLFSSL_LOCAL int DtlsUseSCRKeys(WOLFSSL* ssl);
    WOLFSSL_LOCAL int DtlsCheckOrder(WOLFSSL* ssl, int order);
#endif
    WOLFSSL_LOCAL int IsSCR(WOLFSSL* ssl);
    WOLFSSL_LOCAL int IsDtlsNotSctpMode(WOLFSSL* ssl);
    WOLFSSL_LOCAL int IsDtlsNotSrtpMode(WOLFSSL* ssl);

    WOLFSSL_LOCAL void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out);

#if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || \
        !defined(NO_PSK) || defined(WOLFSSL_DTLS13))
#ifdef WOLFSSL_32BIT_MILLI_TIME
    WOLFSSL_LOCAL word32 TimeNowInMilliseconds(void);
#else
    WOLFSSL_LOCAL sword64 TimeNowInMilliseconds(void);
#endif

#endif
WOLFSSL_LOCAL word32  LowResTimer(void);

WOLFSSL_LOCAL int FindSuiteSSL(const WOLFSSL* ssl, byte* suite);
WOLFSSL_LOCAL int FindSuite(const Suites* suites, byte first, byte second);

WOLFSSL_LOCAL void DecodeSigAlg(const byte* input, byte* hashAlgo,
        byte* hsType);
WOLFSSL_LOCAL enum wc_HashType HashAlgoToType(int hashAlgo);

#ifndef NO_CERTS
    WOLFSSL_LOCAL void InitX509Name(WOLFSSL_X509_NAME* name, int dynamicFlag,
                                    void* heap);
    WOLFSSL_LOCAL void FreeX509Name(WOLFSSL_X509_NAME* name);
    WOLFSSL_LOCAL void InitX509(WOLFSSL_X509* x509, int dynamicFlag,
                                void* heap);
    WOLFSSL_LOCAL void FreeX509(WOLFSSL_X509* x509);
    #ifndef NO_ASN
    WOLFSSL_LOCAL int  CopyDecodedToX509(WOLFSSL_X509* x509,
                                         DecodedCert* dCert);
    #endif
#endif

#if defined(WOLFSSL_ACERT)
    WOLFSSL_LOCAL int  CopyDecodedAcertToX509(WOLFSSL_X509_ACERT* x509,
                                              DecodedAcert* dAcert);
#endif /* WOLFSSL_ACERT */


#ifndef MAX_CIPHER_NAME
#define MAX_CIPHER_NAME 50
#endif

#ifdef WOLFSSL_NAMES_STATIC
typedef char cipher_name[MAX_CIPHER_NAME];
#else
typedef const char* cipher_name;
#endif

typedef struct CipherSuiteInfo {
    cipher_name name;
#ifndef NO_ERROR_STRINGS
    cipher_name name_iana;
#endif
    byte cipherSuite0;
    byte cipherSuite;
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) || \
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX)
    byte minor;
    byte major;
#endif
    byte flags;
} CipherSuiteInfo;

WOLFSSL_LOCAL const CipherSuiteInfo* GetCipherNames(void);
WOLFSSL_LOCAL int GetCipherNamesSize(void);
WOLFSSL_LOCAL const char* GetCipherNameInternal(byte cipherSuite0, byte cipherSuite);
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
/* used in wolfSSL_sk_CIPHER_description */
#define MAX_SEGMENTS    5
#define MAX_SEGMENT_SZ 20
WOLFSSL_LOCAL int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher);
WOLFSSL_LOCAL const char* GetCipherSegment(const WOLFSSL_CIPHER* cipher,
                                           char n[][MAX_SEGMENT_SZ]);
WOLFSSL_LOCAL const char* GetCipherProtocol(byte minor);
WOLFSSL_LOCAL const char* GetCipherKeaStr(char n[][MAX_SEGMENT_SZ]);
WOLFSSL_LOCAL const char* GetCipherAuthStr(char n[][MAX_SEGMENT_SZ]);
WOLFSSL_LOCAL const char* GetCipherEncStr(char n[][MAX_SEGMENT_SZ]);
WOLFSSL_LOCAL const char* GetCipherMacStr(char n[][MAX_SEGMENT_SZ]);
WOLFSSL_LOCAL int SetCipherBits(const char* enc);
WOLFSSL_LOCAL int IsCipherAEAD(char n[][MAX_SEGMENT_SZ]);
#endif
WOLFSSL_LOCAL const char* GetCipherNameIana(byte cipherSuite0, byte cipherSuite);
WOLFSSL_LOCAL const char* wolfSSL_get_cipher_name_internal(WOLFSSL* ssl);
WOLFSSL_LOCAL const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl);
WOLFSSL_LOCAL int GetCipherSuiteFromName(const char* name, byte* cipherSuite0,
                       byte* cipherSuite, byte* major, byte* minor, int* flags);


enum encrypt_side {
    ENCRYPT_SIDE_ONLY = 1,
    DECRYPT_SIDE_ONLY,
    ENCRYPT_AND_DECRYPT_SIDE
};

WOLFSSL_LOCAL int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys,
    CipherSpecs* specs, int side, void* heap, int devId, WC_RNG* rng,
    int tls13);
WOLFSSL_LOCAL int SetKeysSide(WOLFSSL* ssl, enum encrypt_side side);

/* Set*Internal and Set*External functions */
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
WOLFSSL_LOCAL int SetDsaInternal(WOLFSSL_DSA* dsa);
WOLFSSL_LOCAL int SetDsaExternal(WOLFSSL_DSA* dsa);
WOLFSSL_LOCAL int SetRsaExternal(WOLFSSL_RSA* rsa);
WOLFSSL_LOCAL int SetRsaInternal(WOLFSSL_RSA* rsa);

typedef enum elem_set {
    ELEMENT_P   = 0x01,
    ELEMENT_Q   = 0x02,
    ELEMENT_G   = 0x04,
    ELEMENT_PUB = 0x08,
    ELEMENT_PRV = 0x10,
} Element_Set;
WOLFSSL_LOCAL int SetDhExternal_ex(WOLFSSL_DH *dh, int elm );
WOLFSSL_LOCAL int SetDhInternal(WOLFSSL_DH* dh);
WOLFSSL_LOCAL int SetDhExternal(WOLFSSL_DH *dh);
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */

#if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
    WOLFSSL_LOCAL int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey,
        byte* priv, word32* privSz,
        byte* pub, word32* pubSz);
    WOLFSSL_LOCAL int DhAgree(WOLFSSL* ssl, DhKey* dhKey,
        const byte* priv, word32 privSz,
        const byte* otherPub, word32 otherPubSz,
        byte* agree, word32* agreeSz,
        const byte* prime, word32 primeSz);
#endif /* !NO_DH */

#ifdef HAVE_ECC
    WOLFSSL_LOCAL int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer);
    WOLFSSL_LOCAL word16 GetCurveByOID(int oidSum);
#endif

WOLFSSL_LOCAL int InitHandshakeHashes(WOLFSSL* ssl);
WOLFSSL_LOCAL void Free_HS_Hashes(HS_Hashes* hsHashes, void* heap);
WOLFSSL_LOCAL void FreeHandshakeHashes(WOLFSSL* ssl);
WOLFSSL_LOCAL int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source,
    HS_Hashes** destination);


#ifndef WOLFSSL_NO_TLS12
WOLFSSL_LOCAL void FreeBuildMsgArgs(WOLFSSL* ssl, BuildMsgArgs* args);
#endif
WOLFSSL_LOCAL int BuildMessage(WOLFSSL* ssl, byte* output, int outSz,
                        const byte* input, int inSz, int type, int hashOutput,
                        int sizeOnly, int asyncOkay, int epochOrder);

#ifdef WOLFSSL_TLS13
#ifdef WOLFSSL_API_PREFIX_MAP
    #define BuildTls13Message wolfSSL_BuildTls13Message
#endif
WOLFSSL_TEST_VIS int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
               int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay);
WOLFSSL_LOCAL int Tls13UpdateKeys(WOLFSSL* ssl);
#endif

WOLFSSL_LOCAL int AllocKey(WOLFSSL* ssl, int type, void** pKey);
WOLFSSL_LOCAL void FreeKey(WOLFSSL* ssl, int type, void** pKey);

#ifdef WOLFSSL_ASYNC_CRYPT
    WOLFSSL_LOCAL int wolfSSL_AsyncInit(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev, word32 flags);
    WOLFSSL_LOCAL int wolfSSL_AsyncPop(WOLFSSL* ssl, byte* state);
    WOLFSSL_LOCAL int wolfSSL_AsyncPush(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev);
#endif

#if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) && \
    (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \
    !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
WOLFSSL_LOCAL int LoadCertByIssuer(WOLFSSL_X509_STORE* store,
                                           X509_NAME* issuer, int Type);
#endif
#if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
WOLFSSL_LOCAL WOLFSSL_BY_DIR_HASH* wolfSSL_BY_DIR_HASH_new(void);
WOLFSSL_LOCAL void wolfSSL_BY_DIR_HASH_free(WOLFSSL_BY_DIR_HASH* dir_hash);
WOLFSSL_LOCAL WOLFSSL_STACK* wolfSSL_sk_BY_DIR_HASH_new_null(void);
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_HASH_find(
   WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk, const WOLFSSL_BY_DIR_HASH* toFind);
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_HASH_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk);
WOLFSSL_LOCAL WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_value(
                        const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk, int i);
WOLFSSL_LOCAL WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_pop(
                                WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk);
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_HASH_pop_free(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk,
    void (*f) (WOLFSSL_BY_DIR_HASH*));
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_HASH_free(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk);
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_HASH_push(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk,
                                               WOLFSSL_BY_DIR_HASH* in);
/* WOLFSSL_BY_DIR_entry stuff */
WOLFSSL_LOCAL WOLFSSL_BY_DIR_entry* wolfSSL_BY_DIR_entry_new(void);
WOLFSSL_LOCAL void wolfSSL_BY_DIR_entry_free(WOLFSSL_BY_DIR_entry* entry);
WOLFSSL_LOCAL WOLFSSL_STACK* wolfSSL_sk_BY_DIR_entry_new_null(void);
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_entry_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *sk);
WOLFSSL_LOCAL WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_value(
                        const WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *sk, int i);
WOLFSSL_LOCAL WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_pop(
                                WOLF_STACK_OF(WOLFSSL_BY_DIR_entry)* sk);
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_entry_pop_free(WOLF_STACK_OF(wolfSSL_BY_DIR_entry)* sk,
    void (*f) (WOLFSSL_BY_DIR_entry*));
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_entry_free(WOLF_STACK_OF(wolfSSL_BY_DIR_entry) *sk);
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_entry_push(WOLF_STACK_OF(wolfSSL_BY_DIR_entry)* sk,
                                               WOLFSSL_BY_DIR_entry* in);
#endif /* OPENSSL_ALL && !NO_FILESYSTEM && !NO_WOLFSSL_DIR */
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
WOLFSSL_LOCAL int oid2nid(word32 oid, int grp);
WOLFSSL_LOCAL word32 nid2oid(int nid, int grp);
#endif

#ifdef WOLFSSL_DTLS
WOLFSSL_TEST_VIS int wolfSSL_DtlsUpdateWindow(word16 cur_hi, word32 cur_lo,
        word16* next_hi, word32* next_lo, word32 *window);
WOLFSSL_LOCAL int DtlsUpdateWindow(WOLFSSL* ssl);
WOLFSSL_LOCAL void DtlsResetState(WOLFSSL *ssl);
WOLFSSL_LOCAL int DtlsIgnoreError(int err);
WOLFSSL_LOCAL void DtlsSetSeqNumForReply(WOLFSSL* ssl);
#endif

#ifdef WOLFSSL_DTLS13
    #ifdef WOLFSSL_API_PREFIX_MAP
        #define Dtls13GetEpoch wolfSSL_Dtls13GetEpoch
        #define Dtls13CheckEpoch wolfSSL_Dtls13CheckEpoch
        #define Dtls13WriteAckMessage wolfSSL_Dtls13WriteAckMessage
        #define Dtls13RtxAddAck wolfSSL_Dtls13RtxAddAck
        #define Dtls13DoScheduledWork wolfSSL_Dtls13DoScheduledWork
    #endif

WOLFSSL_TEST_VIS struct Dtls13Epoch* Dtls13GetEpoch(WOLFSSL* ssl,
    w64wrapper epochNumber);
WOLFSSL_LOCAL void Dtls13SetOlderEpochSide(WOLFSSL* ssl, w64wrapper epochNumber,
    int side);
WOLFSSL_LOCAL int Dtls13NewEpoch(WOLFSSL* ssl, w64wrapper epochNumber,
    int side);
WOLFSSL_LOCAL int Dtls13SetEpochKeys(WOLFSSL* ssl, w64wrapper epochNumber,
    enum encrypt_side side);
WOLFSSL_LOCAL int Dtls13GetSeq(WOLFSSL* ssl, int order, word32* seq,
    byte increment);
WOLFSSL_LOCAL void Dtls13RtxRemoveRecord(WOLFSSL* ssl, w64wrapper epoch,
    w64wrapper seq);
WOLFSSL_TEST_VIS int Dtls13DoScheduledWork(WOLFSSL* ssl);
WOLFSSL_LOCAL int Dtls13DeriveSnKeys(WOLFSSL* ssl, int provision);
WOLFSSL_LOCAL int Dtls13SetRecordNumberKeys(WOLFSSL* ssl,
    enum encrypt_side side);

WOLFSSL_LOCAL int Dtls13AddHeaders(byte* output, word32 length,
    enum HandShakeType hs_type, WOLFSSL* ssl);
WOLFSSL_LOCAL word16 Dtls13GetHeadersLength(WOLFSSL *ssl,
    enum HandShakeType type);
WOLFSSL_LOCAL word16 Dtls13GetRlHeaderLength(WOLFSSL *ssl, byte is_encrypted);
WOLFSSL_LOCAL int Dtls13RlAddCiphertextHeader(WOLFSSL* ssl, byte* out,
    word16 length);
WOLFSSL_LOCAL int Dtls13RlAddPlaintextHeader(WOLFSSL* ssl, byte* out,
    enum ContentType content_type, word16 length);
WOLFSSL_LOCAL int Dtls13MinimumRecordLength(WOLFSSL* ssl);
WOLFSSL_LOCAL int Dtls13EncryptRecordNumber(WOLFSSL* ssl, byte* hdr,
    word16 recordLength);
WOLFSSL_LOCAL int Dtls13IsUnifiedHeader(byte header_flags);
WOLFSSL_LOCAL int Dtls13GetUnifiedHeaderSize(WOLFSSL* ssl, const byte input,
    word16* size);
WOLFSSL_LOCAL int Dtls13ParseUnifiedRecordLayer(WOLFSSL* ssl, const byte* input,
    word16 input_size, Dtls13UnifiedHdrInfo* hdrInfo);
WOLFSSL_LOCAL int Dtls13HandshakeSend(WOLFSSL* ssl, byte* output,
    word16 output_size, word16 length, enum HandShakeType handshake_type,
    int hash_output);
WOLFSSL_LOCAL int Dtls13RecordRecvd(WOLFSSL* ssl);
WOLFSSL_TEST_VIS int Dtls13CheckEpoch(WOLFSSL* ssl, enum HandShakeType type);
WOLFSSL_LOCAL int Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input,
    word32* inOutIdx, word32 totalSz);
WOLFSSL_LOCAL int Dtls13HandshakeAddHeader(WOLFSSL* ssl, byte* output,
    enum HandShakeType msg_type, word32 length);
#define EE_MASK (0x3)
WOLFSSL_LOCAL int Dtls13FragmentsContinue(WOLFSSL* ssl);
WOLFSSL_LOCAL int DoDtls13KeyUpdateAck(WOLFSSL* ssl);
WOLFSSL_LOCAL int DoDtls13Ack(WOLFSSL* ssl, const byte* input, word32 inputSize,
    word32* processedSize);
WOLFSSL_LOCAL int Dtls13ReconstructEpochNumber(WOLFSSL* ssl, byte epochBits,
    w64wrapper* epoch);
WOLFSSL_LOCAL int Dtls13ReconstructSeqNumber(WOLFSSL* ssl,
    Dtls13UnifiedHdrInfo* hdrInfo, w64wrapper* out);
WOLFSSL_TEST_VIS int Dtls13WriteAckMessage(WOLFSSL* ssl,
    Dtls13RecordNumber* recordNumberList, word16 recordsCount, word32* length);
WOLFSSL_LOCAL int SendDtls13Ack(WOLFSSL* ssl);
WOLFSSL_TEST_VIS int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq);
WOLFSSL_LOCAL int Dtls13RtxProcessingCertificate(WOLFSSL* ssl, byte* input,
    word32 inputSize);
WOLFSSL_LOCAL int Dtls13HashHandshake(WOLFSSL* ssl, const byte* input,
    word16 length);
WOLFSSL_LOCAL int Dtls13HashClientHello(const WOLFSSL* ssl, byte* hash,
        int* hashSz, const byte* body, word32 length, CipherSpecs* specs);
WOLFSSL_LOCAL void Dtls13FreeFsmResources(WOLFSSL* ssl);
WOLFSSL_LOCAL void Dtls13RtxFlushBuffered(WOLFSSL* ssl,
        byte keepNewSessionTicket);
WOLFSSL_LOCAL int Dtls13RtxTimeout(WOLFSSL* ssl);
WOLFSSL_LOCAL int Dtls13ProcessBufferedMessages(WOLFSSL* ssl);
WOLFSSL_LOCAL int Dtls13CheckAEADFailLimit(WOLFSSL* ssl);
WOLFSSL_LOCAL int Dtls13UpdateWindowRecordRecvd(WOLFSSL* ssl);
#endif /* WOLFSSL_DTLS13 */

#ifdef WOLFSSL_STATIC_EPHEMERAL
WOLFSSL_LOCAL int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr);
#endif

#ifndef NO_CERTS
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
    defined(OPENSSL_EXTRA_X509_SMALL)
WOLFSSL_LOCAL int wolfSSL_ASN1_STRING_canon(WOLFSSL_ASN1_STRING* asn_out,
    const WOLFSSL_ASN1_STRING* asn_in);
#endif
#ifdef OPENSSL_EXTRA
WOLFSSL_LOCAL int GetX509Error(int e);
#endif
#endif

#ifdef HAVE_EX_DATA_CRYPTO
typedef struct CRYPTO_EX_cb_ctx {
    long ctx_l;
    void *ctx_ptr;
    WOLFSSL_CRYPTO_EX_new* new_func;
    WOLFSSL_CRYPTO_EX_free* free_func;
    WOLFSSL_CRYPTO_EX_dup* dup_func;
    struct CRYPTO_EX_cb_ctx* next;
} CRYPTO_EX_cb_ctx;

WOLFSSL_TEST_VIS extern CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session;
#ifdef WOLFSSL_API_PREFIX_MAP
    #define crypto_ex_cb_free wolfSSL_crypto_ex_cb_free
#endif
WOLFSSL_TEST_VIS void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx);
WOLFSSL_LOCAL void crypto_ex_cb_setup_new_data(void *new_obj,
        CRYPTO_EX_cb_ctx* cb_ctx, WOLFSSL_CRYPTO_EX_DATA* ex_data);
WOLFSSL_LOCAL void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
        WOLFSSL_CRYPTO_EX_DATA* ex_data);
WOLFSSL_LOCAL int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx);
WOLFSSL_LOCAL int wolfssl_get_ex_new_index(int class_index, long ctx_l,
        void* ctx_ptr, WOLFSSL_CRYPTO_EX_new* new_func,
        WOLFSSL_CRYPTO_EX_dup* dup_func, WOLFSSL_CRYPTO_EX_free* free_func);
#endif /* HAVE_EX_DATA_CRYPTO */

WOLFSSL_LOCAL WC_RNG* wolfssl_get_global_rng(void);
WOLFSSL_LOCAL WC_RNG* wolfssl_make_global_rng(void);

#if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
#if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER)
WOLFSSL_LOCAL int EncryptDerKey(byte *der, int *derSz,
    const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
    byte **cipherInfo, int maxDerSz, int hashType);
#endif
#endif

#if !defined(NO_RSA) && defined(OPENSSL_EXTRA)
WOLFSSL_LOCAL int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf,
    int publicKey, void* heap);
#endif

#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || defined(HAVE_SECRET_CALLBACK)
WOLFSSL_LOCAL int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s);
#endif

#ifdef WOLFSSL_QUIC
#define WOLFSSL_IS_QUIC(s)  (((s) != NULL) && ((s)->quic.method != NULL))
WOLFSSL_LOCAL int wolfSSL_quic_receive(WOLFSSL* ssl, byte* buf, word32 sz);
WOLFSSL_LOCAL int wolfSSL_quic_send(WOLFSSL* ssl);
WOLFSSL_LOCAL void wolfSSL_quic_clear(WOLFSSL* ssl);
WOLFSSL_LOCAL void wolfSSL_quic_free(WOLFSSL* ssl);
WOLFSSL_LOCAL int wolfSSL_quic_forward_secrets(WOLFSSL *ssl,
                                               int ktype, int side);
WOLFSSL_LOCAL int wolfSSL_quic_keys_active(WOLFSSL* ssl, enum encrypt_side side);

#else
#define WOLFSSL_IS_QUIC(s) 0
#endif /* WOLFSSL_QUIC (else) */

#if defined(SHOW_SECRETS) && defined(WOLFSSL_SSLKEYLOGFILE)
WOLFSSL_LOCAL int tls13ShowSecrets(WOLFSSL* ssl, int id, const unsigned char* secret,
    int secretSz, void* ctx);
#endif

#if defined(SHOW_SECRETS)
WOLFSSL_LOCAL int tlsShowSecrets(WOLFSSL* ssl, void* secret,
        int secretSz, void* ctx);
#endif

/* Optional Pre-Master-Secret logging for Wireshark */
#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
#ifndef WOLFSSL_SSLKEYLOGFILE_OUTPUT
    #define WOLFSSL_SSLKEYLOGFILE_OUTPUT "sslkeylog.log"
#endif
#endif

#if defined(WOLFSSL_TLS13) && !defined(NO_PSK)
WOLFSSL_LOCAL int FindPskSuite(const WOLFSSL* ssl, PreSharedKey* psk,
        byte* psk_key, word32* psk_keySz, const byte* suite, int* found,
        byte* foundSuite);
#endif

WOLFSSL_LOCAL int wolfSSL_GetHmacType_ex(CipherSpecs* specs);

#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
WOLFSSL_LOCAL int CreateCookieExt(const WOLFSSL* ssl, byte* hash,
                                  word16 hashSz, TLSX** exts,
                                  byte cipherSuite0, byte cipherSuite);
#endif

WOLFSSL_LOCAL int TranslateErrorToAlert(int err);

#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
WOLFSSL_LOCAL void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk,
                                        WOLF_STACK_TYPE type);
WOLFSSL_LOCAL void* wolfSSL_sk_pop_node(WOLFSSL_STACK* sk, int idx);
WOLFSSL_LOCAL WOLFSSL_STACK* wolfssl_sk_new_type(WOLF_STACK_TYPE type);
WOLFSSL_LOCAL WOLFSSL_STACK* wolfssl_sk_new_type_ex(WOLF_STACK_TYPE type,
        void* heap);

WOLFSSL_LOCAL int wolfssl_asn1_obj_set(WOLFSSL_ASN1_OBJECT* obj,
        const byte* der, word32 len, int addHdr);
#endif

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
WOLFSSL_LOCAL int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key,
        word32* keySz);
WOLFSSL_LOCAL int pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey,
        const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key,
        word32* keySz);
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */

WOLFSSL_LOCAL void wolfssl_local_MaybeCheckAlertOnErr(WOLFSSL* ssl, int err);

#ifdef __cplusplus
    }  /* extern "C" */
#endif

#endif /* wolfSSL_INT_H */