tquic 1.6.0

A high-performance, lightweight, and cross-platform QUIC library
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
// Copyright (c) 2023 The TQUIC Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Note: The API is not stable and may change in future versions.

use std::ffi;
use std::io::Write;
use std::mem;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::net::SocketAddrV4;
use std::net::SocketAddrV6;
use std::ptr;
use std::rc::Rc;
use std::slice;
use std::str::FromStr;
use std::sync::atomic;
use std::sync::Arc;
use std::time::Instant;

#[cfg(unix)]
use std::os::fd::FromRawFd;

use bytes::Bytes;
use libc::c_char;
use libc::c_int;
use libc::c_void;
use libc::size_t;
use libc::sockaddr;
use libc::ssize_t;

#[cfg(not(windows))]
use libc::in_addr;
#[cfg(windows)]
use winapi::shared::inaddr::IN_ADDR as in_addr;

#[cfg(not(windows))]
use libc::in6_addr;
#[cfg(windows)]
use winapi::shared::in6addr::IN6_ADDR as in6_addr;

#[cfg(not(windows))]
use libc::sa_family_t;
#[cfg(windows)]
use winapi::shared::ws2def::ADDRESS_FAMILY as sa_family_t;

#[cfg(not(windows))]
use libc::sockaddr_in;
#[cfg(windows)]
use winapi::shared::ws2def::SOCKADDR_IN as sockaddr_in;

#[cfg(not(windows))]
use libc::sockaddr_in6;
#[cfg(windows)]
use winapi::shared::ws2ipdef::SOCKADDR_IN6_LH as sockaddr_in6;

#[cfg(not(windows))]
use libc::sockaddr_storage;
#[cfg(windows)]
use winapi::shared::ws2def::SOCKADDR_STORAGE_LH as sockaddr_storage;

#[cfg(windows)]
use libc::c_int as socklen_t;
#[cfg(not(windows))]
use libc::socklen_t;

#[cfg(not(windows))]
use libc::AF_INET;
#[cfg(windows)]
use winapi::shared::ws2def::AF_INET;

#[cfg(not(windows))]
use libc::AF_INET6;
#[cfg(windows)]
use winapi::shared::ws2def::AF_INET6;

#[cfg(windows)]
use winapi::shared::in6addr::in6_addr_u;
#[cfg(windows)]
use winapi::shared::inaddr::in_addr_S_un;
#[cfg(windows)]
use winapi::shared::ws2ipdef::SOCKADDR_IN6_LH_u;

#[cfg(not(windows))]
use libc::iovec;

/// cbindgen:ignore
#[cfg(windows)]
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct iovec {
    iov_base: *mut c_void, // starting address
    iov_len: size_t,       // number of bytes to transfer
}

use crate::codec::Decoder;
use crate::connection::ConnectionStats;
use crate::error::Error;
#[cfg(feature = "h3")]
use crate::h3::connection::Http3Connection;
#[cfg(feature = "h3")]
use crate::h3::connection::Http3Priority;
#[cfg(feature = "h3")]
use crate::h3::Http3Config;
#[cfg(feature = "h3")]
use crate::h3::Http3Event;
#[cfg(feature = "h3")]
use crate::h3::Http3Headers;
#[cfg(feature = "h3")]
use crate::h3::NameValue;
#[cfg(feature = "qlog")]
use crate::qlog::events;
use crate::tls::SslCtx;
use crate::tls::TlsConfig;
use crate::Config;
use crate::Connection;
use crate::Endpoint;
use crate::Result;
use crate::Shutdown;
use crate::*;

/// Check whether the protocol version is supported.
#[no_mangle]
pub extern "C" fn quic_version_is_supported(version: u32) -> bool {
    crate::version_is_supported(version)
}

struct LogWriter {
    cb: extern "C" fn(data: *const u8, data_len: size_t, argp: *mut c_void),
    argp: std::sync::atomic::AtomicPtr<c_void>,
}

impl Write for LogWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        (self.cb)(
            buf.as_ptr(),
            buf.len(),
            self.argp.load(atomic::Ordering::Relaxed),
        );
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl log::Log for LogWriter {
    fn enabled(&self, _metadata: &log::Metadata) -> bool {
        true
    }

    fn log(&self, record: &log::Record) {
        let line = format!("{}: {}\n", record.target(), record.args());
        (self.cb)(
            line.as_ptr(),
            line.len(),
            self.argp.load(atomic::Ordering::Relaxed),
        );
    }

    fn flush(&self) {}
}

/// Create default configuration.
/// The caller is responsible for the memory of the Config and should properly
/// destroy it by calling `quic_config_free`.
#[no_mangle]
pub extern "C" fn quic_config_new() -> *mut Config {
    match Config::new() {
        Ok(conf) => Box::into_raw(Box::new(conf)),
        Err(_) => ptr::null_mut(),
    }
}

/// Destroy a Config instance.
#[no_mangle]
pub extern "C" fn quic_config_free(config: *mut Config) {
    unsafe {
        let _ = Box::from_raw(config);
    };
}

/// Set the `max_idle_timeout` transport parameter in milliseconds.
#[no_mangle]
pub extern "C" fn quic_config_set_max_idle_timeout(config: &mut Config, v: u64) {
    config.set_max_idle_timeout(v);
}

/// Set handshake timeout in milliseconds. Zero turns the timeout off.
#[no_mangle]
pub extern "C" fn quic_config_set_max_handshake_timeout(config: &mut Config, v: u64) {
    config.set_max_handshake_timeout(v);
}

/// Set the `max_udp_payload_size` transport parameter in bytes. It limits
/// the size of UDP payloads that the endpoint is willing to receive.
#[no_mangle]
pub extern "C" fn quic_config_set_recv_udp_payload_size(config: &mut Config, v: u16) {
    config.set_recv_udp_payload_size(v);
}

/// Enable the Datagram Packetization Layer Path MTU Discovery
/// default value is true.
#[no_mangle]
pub extern "C" fn enable_dplpmtud(config: &mut Config, v: bool) {
    config.enable_dplpmtud(v);
}

/// Set the maximum outgoing UDP payload size in bytes.
/// It corresponds to the maximum datagram size that DPLPMTUD tries to discovery.
/// The default value is `1200` which means let DPLPMTUD choose a value.
#[no_mangle]
pub extern "C" fn quic_config_set_send_udp_payload_size(config: &mut Config, v: usize) {
    config.set_send_udp_payload_size(v);
}

/// Set the `initial_max_data` transport parameter. It means the initial
/// value for the maximum amount of data that can be sent on the connection.
/// The value is capped by the setting `max_connection_window`.
/// The default value is `10485760`.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_max_data(config: &mut Config, v: u64) {
    config.set_initial_max_data(v);
}

/// Set the `initial_max_stream_data_bidi_local` transport parameter.
/// The value is capped by the setting `max_stream_window`.
/// The default value is `5242880`.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_max_stream_data_bidi_local(config: &mut Config, v: u64) {
    config.set_initial_max_stream_data_bidi_local(v);
}

/// Set the `initial_max_stream_data_bidi_remote` transport parameter.
/// The value is capped by the setting `max_stream_window`.
/// The default value is `2097152`.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_max_stream_data_bidi_remote(config: &mut Config, v: u64) {
    config.set_initial_max_stream_data_bidi_remote(v);
}

/// Set the `initial_max_stream_data_uni` transport parameter.
/// The value is capped by the setting `max_stream_window`.
/// The default value is `1048576`.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_max_stream_data_uni(config: &mut Config, v: u64) {
    config.set_initial_max_stream_data_uni(v);
}

/// Set the `initial_max_streams_bidi` transport parameter.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_max_streams_bidi(config: &mut Config, v: u64) {
    config.set_initial_max_streams_bidi(v);
}

/// Set the `initial_max_streams_uni` transport parameter.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_max_streams_uni(config: &mut Config, v: u64) {
    config.set_initial_max_streams_uni(v);
}

/// Set the `ack_delay_exponent` transport parameter.
#[no_mangle]
pub extern "C" fn quic_config_set_ack_delay_exponent(config: &mut Config, v: u64) {
    config.set_ack_delay_exponent(v);
}

/// Set the `max_ack_delay` transport parameter.
#[no_mangle]
pub extern "C" fn quic_config_set_max_ack_delay(config: &mut Config, v: u64) {
    config.set_max_ack_delay(v);
}

/// Set congestion control algorithm that the connection would use.
#[no_mangle]
pub extern "C" fn quic_config_set_congestion_control_algorithm(
    config: &mut Config,
    v: CongestionControlAlgorithm,
) {
    config.set_congestion_control_algorithm(v);
}

/// Set the initial congestion window in packets.
/// The default value is 10.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_congestion_window(config: &mut Config, v: u64) {
    config.set_initial_congestion_window(v);
}

/// Set the minimal congestion window in packets.
/// The default value is 2.
#[no_mangle]
pub extern "C" fn quic_config_set_min_congestion_window(config: &mut Config, v: u64) {
    config.set_min_congestion_window(v);
}

/// Set the threshold for slow start in packets.
/// The default value is the maximum value of u64.
#[no_mangle]
pub extern "C" fn quic_config_set_slow_start_thresh(config: &mut Config, v: u64) {
    config.set_slow_start_thresh(v);
}

/// Set the minimum duration for BBR ProbeRTT state in milliseconds.
/// The default value is 200 milliseconds.
#[no_mangle]
pub extern "C" fn quic_config_set_bbr_probe_rtt_duration(config: &mut Config, v: u64) {
    config.set_bbr_probe_rtt_duration(v);
}

/// Enable using a cwnd based on bdp during ProbeRTT state.
/// The default value is false.
#[no_mangle]
pub extern "C" fn quic_config_enable_bbr_probe_rtt_based_on_bdp(config: &mut Config, v: bool) {
    config.enable_bbr_probe_rtt_based_on_bdp(v);
}

/// Set the cwnd gain for BBR ProbeRTT state.
/// The default value is 0.75
#[no_mangle]
pub extern "C" fn quic_config_set_bbr_probe_rtt_cwnd_gain(config: &mut Config, v: f64) {
    config.set_bbr_probe_rtt_cwnd_gain(v);
}

/// Set the length of the BBR RTProp min filter window in milliseconds.
/// The default value is 10000 milliseconds.
#[no_mangle]
pub extern "C" fn quic_config_set_bbr_rtprop_filter_len(config: &mut Config, v: u64) {
    config.set_bbr_rtprop_filter_len(v);
}

/// Set the cwnd gain for BBR ProbeBW state.
/// The default value is 2.0
#[no_mangle]
pub extern "C" fn quic_config_set_bbr_probe_bw_cwnd_gain(config: &mut Config, v: f64) {
    config.set_bbr_probe_bw_cwnd_gain(v);
}

/// Set the delta in copa slow start state.
#[no_mangle]
pub extern "C" fn quic_config_set_copa_slow_start_delta(config: &mut Config, v: f64) {
    config.set_copa_slow_start_delta(v);
}

/// Set the delta in coap steady state.
#[no_mangle]
pub extern "C" fn quic_config_set_copa_steady_delta(config: &mut Config, v: f64) {
    config.set_copa_steady_delta(v);
}

/// Enable Using the rtt standing instead of the latest rtt to calculate queueing delay.
#[no_mangle]
pub extern "C" fn quic_config_enable_copa_use_standing_rtt(config: &mut Config, v: bool) {
    config.enable_copa_use_standing_rtt(v);
}

/// Set the initial RTT in milliseconds. The default value is 333ms.
/// The configuration should be changed with caution. Setting a value less than the default
/// will cause retransmission of handshake packets to be more aggressive.
#[no_mangle]
pub extern "C" fn quic_config_set_initial_rtt(config: &mut Config, v: u64) {
    config.set_initial_rtt(v);
}

/// Enable pacing to smooth the flow of packets sent onto the network.
/// The default value is true.
#[no_mangle]
pub extern "C" fn quic_config_enable_pacing(config: &mut Config, v: bool) {
    config.enable_pacing(v);
}

/// Set clock granularity used by the pacer.
/// The default value is 10 milliseconds.
#[no_mangle]
pub extern "C" fn quic_config_set_pacing_granularity(config: &mut Config, v: u64) {
    config.set_pacing_granularity(v);
}

/// Set the linear factor for calculating the probe timeout.
/// The endpoint do not backoff the first `v` consecutive probe timeouts.
/// The default value is `0`.
/// The configuration should be changed with caution. Setting a value greater than the default
/// will cause retransmission to be more aggressive.
#[no_mangle]
pub extern "C" fn quic_config_set_pto_linear_factor(config: &mut Config, v: u64) {
    config.set_pto_linear_factor(v);
}

/// Set the upper limit of probe timeout in milliseconds.
/// A Probe Timeout (PTO) triggers the sending of one or two probe datagrams and enables a
/// connection to recover from loss of tail packets or acknowledgments.
/// See RFC 9002 Section 6.2.
#[no_mangle]
pub extern "C" fn quic_config_set_max_pto(config: &mut Config, v: u64) {
    config.set_max_pto(v);
}

/// Set the `active_connection_id_limit` transport parameter.
#[no_mangle]
pub extern "C" fn quic_config_set_active_connection_id_limit(config: &mut Config, v: u64) {
    config.set_active_connection_id_limit(v);
}

/// Set the `enable_multipath` transport parameter.
/// The default value is false. (Experimental)
#[no_mangle]
pub extern "C" fn quic_config_enable_multipath(config: &mut Config, enabled: bool) {
    config.enable_multipath(enabled);
}

/// Set the multipath scheduling algorithm
/// The default value is MultipathAlgorithm::MinRtt
#[no_mangle]
pub extern "C" fn quic_config_set_multipath_algorithm(config: &mut Config, v: MultipathAlgorithm) {
    config.set_multipath_algorithm(v);
}

/// Set the maximum size of the connection flow control window.
/// The default value is MAX_CONNECTION_WINDOW (15 MB).
#[no_mangle]
pub extern "C" fn quic_config_set_max_connection_window(config: &mut Config, v: u64) {
    config.set_max_connection_window(v);
}

/// Set the maximum size of the stream flow control window.
/// The value should not be greater than the setting `max_connection_window`.
/// The default value is MAX_STREAM_WINDOW (6 MB).
#[no_mangle]
pub extern "C" fn quic_config_set_max_stream_window(config: &mut Config, v: u64) {
    config.set_max_stream_window(v);
}

/// Set the Maximum number of concurrent connections.
#[no_mangle]
pub extern "C" fn quic_config_set_max_concurrent_conns(config: &mut Config, v: u32) {
    config.set_max_concurrent_conns(v);
}

/// Set the key for reset token generation. The token_key_len should be not less
/// than 64.
/// Applicable to Server only.
#[no_mangle]
pub extern "C" fn quic_config_set_reset_token_key(
    config: &mut Config,
    token_key: *const u8,
    token_key_len: size_t,
) -> c_int {
    const RTK_LEN: usize = 64;
    if token_key_len < RTK_LEN {
        let e = Error::InvalidConfig("reset token key".into());
        return e.to_errno() as c_int;
    };

    let token_key = unsafe { slice::from_raw_parts(token_key, RTK_LEN) };
    let mut key = [0; RTK_LEN];
    key.copy_from_slice(token_key);
    config.set_reset_token_key(key);
    0
}

/// Set the lifetime of address token.
/// Applicable to Server only.
#[no_mangle]
pub extern "C" fn quic_config_set_address_token_lifetime(config: &mut Config, seconds: u64) {
    config.set_address_token_lifetime(seconds);
}

/// Set the key for address token generation. It also enables retry.
/// The token_key_len should be a multiple of 16.
/// Applicable to Server only.
#[no_mangle]
pub extern "C" fn quic_config_set_address_token_key(
    config: &mut Config,
    token_keys: *const u8,
    token_keys_len: size_t,
) -> c_int {
    const ATK_LEN: usize = 16;
    if token_keys_len < ATK_LEN || token_keys_len % ATK_LEN != 0 {
        let e = Error::InvalidConfig("address token key".into());
        return e.to_errno() as c_int;
    }

    let mut token_keys = unsafe { slice::from_raw_parts(token_keys, token_keys_len) };
    let mut keys = Vec::new();
    while !token_keys.is_empty() {
        let mut key = [0u8; ATK_LEN];
        key.copy_from_slice(&token_keys[..ATK_LEN]);
        keys.push(key);
        token_keys = &token_keys[ATK_LEN..];
    }

    match config.set_address_token_key(keys) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set whether stateless retry is allowed. Default is not allowed.
/// Applicable to Server only.
#[no_mangle]
pub extern "C" fn quic_config_enable_retry(config: &mut Config, enabled: bool) {
    config.enable_retry(enabled);
}

/// Set whether stateless reset is allowed.
/// Applicable to Endpoint only.
#[no_mangle]
pub extern "C" fn quic_config_enable_stateless_reset(config: &mut Config, enabled: bool) {
    config.enable_stateless_reset(enabled);
}

/// Set the length of source cid. The length should not be greater than 20.
/// Applicable to Endpoint only.
#[no_mangle]
pub extern "C" fn quic_config_set_cid_len(config: &mut Config, v: u8) {
    config.set_cid_len(v as usize);
}

/// Set the anti-amplification factor.
///
/// The server limits the data sent to an unvalidated address to
/// `anti_amplification_factor` times the received data.
#[no_mangle]
pub extern "C" fn quic_config_set_anti_amplification_factor(config: &mut Config, v: u8) {
    config.set_anti_amplification_factor(v as usize);
}

/// Set the batch size for sending packets.
/// Applicable to Endpoint only.
#[no_mangle]
pub extern "C" fn quic_config_set_send_batch_size(config: &mut Config, v: u16) {
    config.set_send_batch_size(v as usize);
}

/// Set the buffer size for disordered zerortt packets on the server.
/// The default value is `1000`. A value of 0 will be treated as default value.
/// Applicable to Server only.
#[no_mangle]
pub extern "C" fn quic_config_set_zerortt_buffer_size(config: &mut Config, v: u16) {
    config.set_zerortt_buffer_size(v as usize);
}

/// Set the maximum number of undecryptable packets that can be stored by one connection.
/// The default value is `10`. A value of 0 will be treated as default value.
#[no_mangle]
pub extern "C" fn quic_config_set_max_undecryptable_packets(config: &mut Config, v: u16) {
    config.set_max_undecryptable_packets(v as usize);
}

/// Enable or disable encryption on 1-RTT packets. (Experimental)
/// The default value is true.
/// WARN: The The disable_1rtt_encryption extension is not meant to be used
/// for any practical application protocol on the open internet.
#[no_mangle]
pub extern "C" fn quic_config_enable_encryption(config: &mut Config, v: bool) {
    config.enable_encryption(v);
}

/// Create a new TlsConfig.
/// The caller is responsible for the memory of the TlsConfig and should properly
/// destroy it by calling `quic_tls_config_free`.
#[no_mangle]
pub extern "C" fn quic_tls_config_new() -> *mut TlsConfig {
    match TlsConfig::new() {
        Ok(tls_config) => Box::into_raw(Box::new(tls_config)),
        Err(_) => ptr::null_mut(),
    }
}

/// Create a new TlsConfig with SSL_CTX.
/// When using raw SSL_CTX, TlsSession::session() and TlsSession::set_keylog() won't take effect.
/// The caller is responsible for the memory of TlsConfig and SSL_CTX when use this function.
#[no_mangle]
pub extern "C" fn quic_tls_config_new_with_ssl_ctx(ssl_ctx: *mut SslCtx) -> *mut TlsConfig {
    Box::into_raw(Box::new(TlsConfig::new_with_ssl_ctx(ssl_ctx)))
}

fn convert_application_protos(protos: *const *const c_char, proto_num: isize) -> Vec<Vec<u8>> {
    let mut application_protos = vec![];
    for i in 0..proto_num {
        let proto = unsafe { (*protos).offset(i) };
        if proto.is_null() {
            continue;
        }

        let proto = unsafe { ffi::CStr::from_ptr(proto).to_bytes().to_vec() };
        application_protos.push(proto);
    }

    application_protos
}

/// Create a new client side TlsConfig.
/// The caller is responsible for the memory of the TlsConfig and should properly
/// destroy it by calling `quic_tls_config_free`.
/// For more information about `protos`, please see `quic_tls_config_set_application_protos`.
#[no_mangle]
pub extern "C" fn quic_tls_config_new_client_config(
    protos: *const *const c_char,
    proto_num: isize,
    enable_early_data: bool,
) -> *mut TlsConfig {
    if protos.is_null() {
        return ptr::null_mut();
    }

    let application_protos = convert_application_protos(protos, proto_num);
    match TlsConfig::new_client_config(application_protos, enable_early_data) {
        Ok(tls_config) => Box::into_raw(Box::new(tls_config)),
        Err(_) => ptr::null_mut(),
    }
}

/// Create a new server side TlsConfig.
/// The caller is responsible for the memory of the TlsConfig and should properly
/// destroy it by calling `quic_tls_config_free`.
/// For more information about `protos`, please see `quic_tls_config_set_application_protos`.
#[no_mangle]
pub extern "C" fn quic_tls_config_new_server_config(
    cert_file: *const c_char,
    key_file: *const c_char,
    protos: *const *const c_char,
    proto_num: isize,
    enable_early_data: bool,
) -> *mut TlsConfig {
    if cert_file.is_null() || key_file.is_null() || protos.is_null() {
        return ptr::null_mut();
    }

    let application_protos = convert_application_protos(protos, proto_num);
    let cert_file = unsafe {
        match ffi::CStr::from_ptr(cert_file).to_str() {
            Ok(cert_file) => cert_file,
            Err(_) => return ptr::null_mut(),
        }
    };
    let key_file = unsafe {
        match ffi::CStr::from_ptr(key_file).to_str() {
            Ok(key_file) => key_file,
            Err(_) => return ptr::null_mut(),
        }
    };
    match TlsConfig::new_server_config(cert_file, key_file, application_protos, enable_early_data) {
        Ok(tls_config) => Box::into_raw(Box::new(tls_config)),
        Err(_) => ptr::null_mut(),
    }
}

/// Destroy a TlsConfig instance.
#[no_mangle]
pub extern "C" fn quic_tls_config_free(tls_config: *mut TlsConfig) {
    unsafe {
        let _ = Box::from_raw(tls_config);
    };
}

/// Set whether early data is allowed.
#[no_mangle]
pub extern "C" fn quic_tls_config_set_early_data_enabled(tls_config: &mut TlsConfig, enable: bool) {
    tls_config.set_early_data_enabled(enable)
}

/// Set the session lifetime in seconds
#[no_mangle]
pub extern "C" fn quic_tls_config_set_session_timeout(tls_config: &mut TlsConfig, timeout: u32) {
    tls_config.set_session_timeout(timeout)
}

/// Set the list of supported application protocols.
/// The `protos` is a pointer that points to an array, where each element of the array is a string
/// pointer representing an application protocol identifier. For example, you can define it as
/// follows: const char* const protos[2] = {"h3", "http/0.9"}.
#[no_mangle]
pub extern "C" fn quic_tls_config_set_application_protos(
    tls_config: &mut TlsConfig,
    protos: *const *const c_char,
    proto_num: isize,
) -> c_int {
    if protos.is_null() {
        return -1;
    }

    let application_protos = convert_application_protos(protos, proto_num);
    match tls_config.set_application_protos(application_protos) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set session ticket key for server.
#[no_mangle]
pub extern "C" fn quic_tls_config_set_ticket_key(
    tls_config: &mut TlsConfig,
    ticket_key: *const u8,
    ticket_key_len: size_t,
) -> c_int {
    let ticket_key = unsafe { slice::from_raw_parts(ticket_key, ticket_key_len) };
    match tls_config.set_ticket_key(ticket_key) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set the certificate verification behavior.
#[no_mangle]
pub extern "C" fn quic_tls_config_set_verify(tls_config: &mut TlsConfig, verify: bool) {
    tls_config.set_verify(verify)
}

/// Set the PEM-encoded certificate file.
#[no_mangle]
pub extern "C" fn quic_tls_config_set_certificate_file(
    tls_config: &mut TlsConfig,
    cert_file: *const c_char,
) -> c_int {
    if cert_file.is_null() {
        return -1;
    }

    let cert_file = unsafe {
        match ffi::CStr::from_ptr(cert_file).to_str() {
            Ok(cert_file) => cert_file,
            Err(_) => return -1,
        }
    };
    match tls_config.set_certificate_file(cert_file) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set the PEM-encoded private key file.
#[no_mangle]
pub extern "C" fn quic_tls_config_set_private_key_file(
    tls_config: &mut TlsConfig,
    key_file: *const c_char,
) -> c_int {
    if key_file.is_null() {
        return -1;
    }

    let key_file = unsafe {
        match ffi::CStr::from_ptr(key_file).to_str() {
            Ok(key_file) => key_file,
            Err(_) => return -1,
        }
    };
    match tls_config.set_private_key_file(key_file) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set CA certificates.
#[no_mangle]
pub extern "C" fn quic_tls_config_set_ca_certs(
    tls_config: &mut TlsConfig,
    ca_path: *const c_char,
) -> c_int {
    if ca_path.is_null() {
        return -1;
    }

    let ca_path = unsafe {
        match ffi::CStr::from_ptr(ca_path).to_str() {
            Ok(ca_path) => ca_path,
            Err(_) => return -1,
        }
    };
    match tls_config.set_ca_certs(ca_path) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set TLS config selector.
#[no_mangle]
pub extern "C" fn quic_config_set_tls_selector(
    config: &mut Config,
    methods: *const TlsConfigSelectMethods,
    context: TlsConfigSelectorContext,
) {
    let selector = TlsConfigSelector { methods, context };
    config.set_tls_config_selector(Arc::new(selector));
}

/// Set TLS config.
///
/// Note: Config doesn't own the TlsConfig when using this function.
/// It is the responsibility of the caller to release it.
#[no_mangle]
pub extern "C" fn quic_config_set_tls_config(config: &mut Config, tls_config: *mut TlsConfig) {
    if tls_config.is_null() {
        return;
    }

    let tls_config = unsafe { tls_config.as_mut().unwrap() };
    let tls_config = TlsConfig::new_with_ssl_ctx(tls_config.ssl_ctx());
    config.set_tls_config(tls_config);
}

/// Create a QUIC endpoint.
///
/// The caller is responsible for the memory of the Endpoint and properly
/// destroy it by calling `quic_endpoint_free`.
///
/// Note: The endpoint doesn't own the underlying resources provided by the C
/// caller. It is the responsibility of the caller to ensure that these
/// resources outlive the endpoint and release them correctly.
#[no_mangle]
pub extern "C" fn quic_endpoint_new(
    config: *mut Config,
    is_server: bool,
    handler_methods: *const TransportMethods,
    handler_ctx: TransportContext,
    sender_methods: *const PacketSendMethods,
    sender_ctx: PacketSendContext,
) -> *mut Endpoint {
    let config = unsafe { Box::from_raw(config) };
    let handler = Box::new(TransportHandler {
        methods: handler_methods,
        context: handler_ctx,
    });
    let sender = Rc::new(PacketSendHandler {
        methods: sender_methods,
        context: sender_ctx,
    });
    let e = Endpoint::new(config.clone(), is_server, handler, sender);
    let _ = Box::into_raw(config);
    Box::into_raw(Box::new(e))
}

/// Destroy a QUIC endpoint.
#[no_mangle]
pub extern "C" fn quic_endpoint_free(endpoint: *mut Endpoint) {
    unsafe {
        let _ = Box::from_raw(endpoint);
    };
}

/// Set the connection id generator for the endpoint.
/// By default, the random connection id generator is used.
#[no_mangle]
pub extern "C" fn quic_endpoint_set_cid_generator(
    endpoint: &mut Endpoint,
    cid_gen_methods: *const ConnectionIdGeneratorMethods,
    cid_gen_ctx: ConnectionIdGeneratorContext,
) {
    let cid_generator = Box::new(ConnectionIdGenerator {
        methods: cid_gen_methods,
        context: cid_gen_ctx,
    });
    endpoint.set_cid_generator(cid_generator);
}

/// Create a client connection.
/// If success, the output parameter `index` carrys the index of the connection.
/// Note: The `config` specific to the endpoint or server is irrelevant and will be disregarded.
#[no_mangle]
pub extern "C" fn quic_endpoint_connect(
    endpoint: &mut Endpoint,
    local: &sockaddr,
    local_len: socklen_t,
    remote: &sockaddr,
    remote_len: socklen_t,
    server_name: *const c_char,
    session: *const u8,
    session_len: size_t,
    token: *const u8,
    token_len: size_t,
    config: *const Config,
    index: *mut u64,
) -> c_int {
    let local = sock_addr_from_c(local, local_len);
    let remote = sock_addr_from_c(remote, remote_len);

    let server_name = if !server_name.is_null() {
        Some(unsafe {
            ffi::CStr::from_ptr(server_name)
                .to_str()
                .unwrap_or_default()
        })
    } else {
        None
    };

    let session = if session_len > 0 {
        Some(unsafe { slice::from_raw_parts(session, session_len) })
    } else {
        None
    };
    let token = if token_len > 0 {
        Some(unsafe { slice::from_raw_parts(token, token_len) })
    } else {
        None
    };
    let config = if !config.is_null() {
        Some(unsafe { &(*config) })
    } else {
        None
    };

    match endpoint.connect(local, remote, server_name, session, token, config) {
        Ok(idx) => {
            if !index.is_null() {
                unsafe {
                    *index = idx;
                }
            }
            0
        }
        Err(e) => e.to_errno() as i32,
    }
}

/// Process an incoming UDP datagram.
#[no_mangle]
pub extern "C" fn quic_endpoint_recv(
    endpoint: &mut Endpoint,
    buf: *mut u8,
    buf_len: size_t,
    info: &PacketInfo,
) -> c_int {
    let buf = unsafe { slice::from_raw_parts_mut(buf, buf_len) };

    let info: crate::PacketInfo = info.into();
    match endpoint.recv(buf, &info) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as i32,
    }
}

/// Return the amount of time until the next timeout event.
#[no_mangle]
pub extern "C" fn quic_endpoint_timeout(endpoint: &Endpoint) -> u64 {
    match endpoint.timeout() {
        Some(v) => v.as_millis() as u64,
        None => u64::MAX,
    }
}

/// Process timeout events on the endpoint.
#[no_mangle]
pub extern "C" fn quic_endpoint_on_timeout(endpoint: &mut Endpoint) {
    let now = Instant::now();
    endpoint.on_timeout(now);
}

/// Process internal events of all tickable connections.
#[no_mangle]
pub extern "C" fn quic_endpoint_process_connections(endpoint: &mut Endpoint) -> c_int {
    match endpoint.process_connections() {
        Ok(_) => 0,
        Err(e) => e.to_errno() as i32,
    }
}

/// Check whether the given connection exists.
#[no_mangle]
pub extern "C" fn quic_endpoint_exist_connection(
    endpoint: &mut Endpoint,
    cid: *const u8,
    cid_len: size_t,
) -> bool {
    let cid = unsafe { slice::from_raw_parts(cid, cid_len) };
    endpoint.conn_exist(ConnectionId::new(cid))
}

/// Get the connection by index
#[no_mangle]
pub extern "C" fn quic_endpoint_get_connection(
    endpoint: &mut Endpoint,
    index: u64,
) -> *mut Connection {
    match endpoint.conn_get_mut(index) {
        Some(v) => v,
        None => ptr::null_mut(),
    }
}

/// Gracefully or forcibly shutdown the endpoint.
/// If `force` is false, cease creating new connections and wait for all
/// active connections to close. Otherwise, forcibly close all the active
/// connections.
#[no_mangle]
pub extern "C" fn quic_endpoint_close(endpoint: &mut Endpoint, force: bool) {
    endpoint.close(force)
}

/// Get index of the connection
#[no_mangle]
pub extern "C" fn quic_conn_index(conn: &mut Connection) -> u64 {
    conn.index().unwrap_or(u64::MAX)
}

/// Check whether the connection is a server connection.
#[no_mangle]
pub extern "C" fn quic_conn_is_server(conn: &mut Connection) -> bool {
    conn.is_server()
}

/// Check whether the connection handshake is complete.
#[no_mangle]
pub extern "C" fn quic_conn_is_established(conn: &mut Connection) -> bool {
    conn.is_established()
}

/// Check whether the connection is created by a resumed handshake.
#[no_mangle]
pub extern "C" fn quic_conn_is_resumed(conn: &mut Connection) -> bool {
    conn.is_resumed()
}

/// Check whether the connection has a pending handshake that has progressed
/// enough to send or receive early data.
#[no_mangle]
pub extern "C" fn quic_conn_is_in_early_data(conn: &mut Connection) -> bool {
    conn.is_in_early_data()
}

/// Check whether the established connection works in multipath mode.
#[no_mangle]
pub extern "C" fn quic_conn_is_multipath(conn: &mut Connection) -> bool {
    conn.is_multipath()
}

/// Return the negotiated application level protocol.
#[no_mangle]
pub extern "C" fn quic_conn_application_proto(
    conn: &mut Connection,
    out: &mut *const u8,
    out_len: &mut size_t,
) {
    let proto = conn.application_proto();
    *out = proto.as_ptr();
    *out_len = proto.len();
}

/// Return the server name in the TLS SNI extension.
#[no_mangle]
pub extern "C" fn quic_conn_server_name(
    conn: &mut Connection,
    out: &mut *const u8,
    out_len: &mut size_t,
) {
    if let Some(name) = conn.server_name() {
        *out = name.as_ptr();
        *out_len = name.len();
    } else {
        *out = ptr::null_mut();
        *out_len = 0;
    }
}

/// Return the session data used by resumption.
#[no_mangle]
pub extern "C" fn quic_conn_session(
    conn: &mut Connection,
    out: &mut *const u8,
    out_len: &mut size_t,
) {
    match conn.session() {
        Some(session) => {
            *out = session.as_ptr();
            *out_len = session.len();
        }
        None => *out_len = 0,
    }
}

/// Return details why 0-RTT was accepted or rejected.
#[no_mangle]
pub extern "C" fn quic_conn_early_data_reason(
    conn: &mut Connection,
    out: &mut *const u8,
    out_len: &mut size_t,
) -> c_int {
    match conn.early_data_reason() {
        Ok(reason) => {
            match reason {
                Some(reason) => {
                    *out = reason.as_ptr();
                    *out_len = reason.len();
                }
                None => *out_len = 0,
            }
            0
        }
        Err(e) => e.to_errno() as i32,
    }
}

/// Send a Ping frame on the active path(s) for keep-alive.
#[no_mangle]
pub extern "C" fn quic_conn_ping(conn: &mut Connection) -> c_int {
    match conn.ping(None) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Send a Ping frame on the specified path for keep-alive.
/// The API is only applicable to multipath quic connections.
#[no_mangle]
pub extern "C" fn quic_conn_ping_path(
    conn: &mut Connection,
    local: &sockaddr,
    local_len: socklen_t,
    remote: &sockaddr,
    remote_len: socklen_t,
) -> c_int {
    let addr = FourTuple {
        local: sock_addr_from_c(local, local_len),
        remote: sock_addr_from_c(remote, remote_len),
    };
    match conn.ping(Some(addr)) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Add a new path on the client connection.
#[no_mangle]
pub extern "C" fn quic_conn_add_path(
    conn: &mut Connection,
    local: &sockaddr,
    local_len: socklen_t,
    remote: &sockaddr,
    remote_len: socklen_t,
    index: *mut u64,
) -> c_int {
    let local = sock_addr_from_c(local, local_len);
    let remote = sock_addr_from_c(remote, remote_len);

    match conn.add_path(local, remote) {
        Ok(idx) => {
            if !index.is_null() {
                unsafe {
                    *index = idx;
                }
            }
            0
        }
        Err(e) => e.to_errno() as i32,
    }
}

/// Remove a path on the client connection.
#[no_mangle]
pub extern "C" fn quic_conn_abandon_path(
    conn: &mut Connection,
    local: &sockaddr,
    local_len: socklen_t,
    remote: &sockaddr,
    remote_len: socklen_t,
) -> c_int {
    let local = sock_addr_from_c(local, local_len);
    let remote = sock_addr_from_c(remote, remote_len);

    match conn.abandon_path(local, remote) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as i32,
    }
}

/// Migrate the client connection to the specified path.
#[no_mangle]
pub extern "C" fn quic_conn_migrate_path(
    conn: &mut Connection,
    local: &sockaddr,
    local_len: socklen_t,
    remote: &sockaddr,
    remote_len: socklen_t,
) -> c_int {
    let local = sock_addr_from_c(local, local_len);
    let remote = sock_addr_from_c(remote, remote_len);

    match conn.migrate_path(local, remote) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as i32,
    }
}

#[repr(C)]
pub struct PathAddress {
    local_addr: sockaddr_storage,
    local_addr_len: socklen_t,
    remote_addr: sockaddr_storage,
    remote_addr_len: socklen_t,
}

/// Return an iterator over path addresses.
/// The caller should properly destroy it by calling `quic_four_tuple_iter_free`.
#[no_mangle]
pub extern "C" fn quic_conn_paths(conn: &mut Connection) -> *mut FourTupleIter {
    let iter = Box::new(conn.paths_iter());
    Box::into_raw(iter)
}

/// Destroy the FourTupleIter
#[no_mangle]
pub extern "C" fn quic_conn_path_iter_free(iter: *mut FourTupleIter) {
    unsafe {
        let _ = Box::from_raw(iter);
    };
}

/// Return the address of the next path.
#[no_mangle]
pub extern "C" fn quic_conn_path_iter_next(iter: &mut FourTupleIter, a: &mut PathAddress) -> bool {
    if let Some(v) = iter.next() {
        a.local_addr_len = sock_addr_to_c(&v.local, &mut a.local_addr);
        a.remote_addr_len = sock_addr_to_c(&v.remote, &mut a.remote_addr);
        return true;
    }
    false
}

/// Return the address of the active path
#[no_mangle]
pub extern "C" fn quic_conn_active_path(conn: &Connection, a: &mut PathAddress) -> bool {
    if let Ok(v) = conn.get_active_path() {
        a.local_addr_len = sock_addr_to_c(&v.local_addr(), &mut a.local_addr);
        a.remote_addr_len = sock_addr_to_c(&v.remote_addr(), &mut a.remote_addr);
        return true;
    }
    false
}

/// Return the latest statistics about the specified path.
#[no_mangle]
pub extern "C" fn quic_conn_path_stats<'a>(
    conn: &'a mut Connection,
    local: &sockaddr,
    local_len: socklen_t,
    remote: &sockaddr,
    remote_len: socklen_t,
) -> Option<&'a PathStats> {
    let local_addr = sock_addr_from_c(local, local_len);
    let remote_addr = sock_addr_from_c(remote, remote_len);
    if let Ok(stats) = conn.get_path_stats(local_addr, remote_addr) {
        return Some(stats);
    }
    None
}

/// Return statistics about the connection.
#[no_mangle]
pub extern "C" fn quic_conn_stats(conn: &mut Connection) -> &ConnectionStats {
    conn.stats()
}

/// Return the trace id of the connection
#[no_mangle]
pub extern "C" fn quic_conn_trace_id(
    conn: &mut Connection,
    out: &mut *const u8,
    out_len: &mut size_t,
) {
    let id = conn.trace_id();
    *out = id.as_ptr();
    *out_len = id.len();
}

/// Check whether the connection is draining.
#[no_mangle]
pub extern "C" fn quic_conn_is_draining(conn: &mut Connection) -> bool {
    conn.is_draining()
}

/// Check whether the connection is closing.
#[no_mangle]
pub extern "C" fn quic_conn_is_closing(conn: &mut Connection) -> bool {
    conn.is_closing()
}

/// Check whether the connection is closed.
#[no_mangle]
pub extern "C" fn quic_conn_is_closed(conn: &mut Connection) -> bool {
    conn.is_closed()
}

/// Check whether the connection was closed due to handshake timeout.
#[no_mangle]
pub extern "C" fn quic_conn_is_handshake_timeout(conn: &mut Connection) -> bool {
    conn.is_handshake_timeout()
}

/// Check whether the connection was closed due to idle timeout.
#[no_mangle]
pub extern "C" fn quic_conn_is_idle_timeout(conn: &mut Connection) -> bool {
    conn.is_idle_timeout()
}

/// Check whether the connection was closed due to stateless reset.
#[no_mangle]
pub extern "C" fn quic_conn_is_reset(conn: &mut Connection) -> bool {
    conn.is_reset()
}

/// Returns the error from the peer, if any.
#[no_mangle]
pub extern "C" fn quic_conn_peer_error(
    conn: &mut Connection,
    is_app: *mut bool,
    error_code: *mut u64,
    reason: &mut *const u8,
    reason_len: &mut size_t,
) -> bool {
    match &conn.peer_error() {
        Some(conn_err) => unsafe {
            *is_app = conn_err.is_app;
            *error_code = conn_err.error_code;
            *reason = conn_err.reason.as_ptr();
            *reason_len = conn_err.reason.len();
            true
        },
        None => false,
    }
}

/// Returns the local error, if any.
#[no_mangle]
pub extern "C" fn quic_conn_local_error(
    conn: &mut Connection,
    is_app: *mut bool,
    error_code: *mut u64,
    reason: &mut *const u8,
    reason_len: &mut size_t,
) -> bool {
    match &conn.local_error() {
        Some(conn_err) => unsafe {
            *is_app = conn_err.is_app;
            *error_code = conn_err.error_code;
            *reason = conn_err.reason.as_ptr();
            *reason_len = conn_err.reason.len();
            true
        },
        None => false,
    }
}

/// Set user context for the connection.
#[no_mangle]
pub extern "C" fn quic_conn_set_context(conn: &mut Connection, data: *mut c_void) {
    conn.set_context(Context(data))
}

/// Get user context for the connection.
#[no_mangle]
pub extern "C" fn quic_conn_context(conn: &mut Connection) -> *mut c_void {
    match conn.context() {
        Some(v) => v.downcast_mut::<Context>().unwrap().0,
        None => ptr::null_mut(),
    }
}

/// Set the callback of keylog output.
/// `cb` is a callback function that will be called for each keylog.
/// `data` is a keylog message and `argp` is user-defined data that will be passed to the callback.
#[no_mangle]
pub extern "C" fn quic_conn_set_keylog(
    conn: &mut Connection,
    cb: extern "C" fn(data: *const u8, data_len: size_t, argp: *mut c_void),
    argp: *mut c_void,
) {
    let argp = atomic::AtomicPtr::new(argp);
    let writer = Box::new(LogWriter { cb, argp });
    conn.set_keylog(Box::new(writer));
}

/// Set keylog file.
/// Note: The API is not applicable for Windows.
#[no_mangle]
#[cfg(unix)]
pub extern "C" fn quic_conn_set_keylog_fd(conn: &mut Connection, fd: c_int) {
    let file = unsafe { std::fs::File::from_raw_fd(fd) };
    let writer = std::io::BufWriter::new(file);
    conn.set_keylog(Box::new(writer));
}

/// Set the callback of qlog output.
/// `cb` is a callback function that will be called for each qlog.
/// `data` is a qlog message and `argp` is user-defined data that will be passed to the callback.
/// `title` and `desc` respectively refer to the "title" and "description" sections of qlog.
#[no_mangle]
#[cfg(feature = "qlog")]
pub extern "C" fn quic_conn_set_qlog(
    conn: &mut Connection,
    cb: extern "C" fn(data: *const u8, data_len: size_t, argp: *mut c_void),
    argp: *mut c_void,
    title: *const c_char,
    desc: *const c_char,
) {
    let argp = atomic::AtomicPtr::new(argp);
    let writer = Box::new(LogWriter { cb, argp });
    let title = unsafe { ffi::CStr::from_ptr(title).to_str().unwrap() };
    let description = unsafe { ffi::CStr::from_ptr(desc).to_str().unwrap() };

    conn.set_qlog(
        Box::new(writer),
        title.to_string(),
        format!("{} id={}", description, conn.trace_id()),
    );
}

/// Set qlog file.
/// Note: The API is not applicable for Windows.
#[no_mangle]
#[cfg(feature = "qlog")]
#[cfg(unix)]
pub extern "C" fn quic_conn_set_qlog_fd(
    conn: &mut Connection,
    fd: c_int,
    title: *const c_char,
    desc: *const c_char,
) {
    let file = unsafe { std::fs::File::from_raw_fd(fd) };
    let writer = std::io::BufWriter::new(file);
    let title = unsafe { ffi::CStr::from_ptr(title).to_str().unwrap() };
    let description = unsafe { ffi::CStr::from_ptr(desc).to_str().unwrap() };

    conn.set_qlog(
        Box::new(writer),
        title.to_string(),
        format!("{} id={}", description, conn.trace_id()),
    );
}

/// Close the connection.
#[no_mangle]
pub extern "C" fn quic_conn_close(
    conn: &mut Connection,
    app: bool,
    err: u64,
    reason: *const u8,
    reason_len: size_t,
) -> c_int {
    let reason = unsafe { slice::from_raw_parts(reason, reason_len) };
    match conn.close(app, err, reason) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set want write flag for a stream.
#[no_mangle]
pub extern "C" fn quic_stream_wantwrite(
    conn: &mut Connection,
    stream_id: u64,
    want: bool,
) -> c_int {
    match conn.stream_want_write(stream_id, want) {
        Ok(_) | Err(Error::Done) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set want read flag for a stream.
#[no_mangle]
pub extern "C" fn quic_stream_wantread(conn: &mut Connection, stream_id: u64, want: bool) -> c_int {
    match conn.stream_want_read(stream_id, want) {
        Ok(_) | Err(Error::Done) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Read data from a stream.
#[no_mangle]
pub extern "C" fn quic_stream_read(
    conn: &mut Connection,
    stream_id: u64,
    out: *mut u8,
    out_len: size_t,
    fin: &mut bool,
) -> ssize_t {
    let out = unsafe { slice::from_raw_parts_mut(out, out_len) };
    let (out_len, out_fin) = match conn.stream_read(stream_id, out) {
        Ok(v) => v,
        Err(_) => return -1,
    };
    *fin = out_fin;
    out_len as ssize_t
}

/// Write data to a stream.
#[no_mangle]
pub extern "C" fn quic_stream_write(
    conn: &mut Connection,
    stream_id: u64,
    buf: *const u8,
    buf_len: size_t,
    fin: bool,
) -> ssize_t {
    let buf = unsafe { slice::from_raw_parts(buf, buf_len) };
    let buf = Bytes::copy_from_slice(buf);
    match conn.stream_write(stream_id, buf, fin) {
        Ok(v) => v as ssize_t,
        Err(e) => e.to_errno() as ssize_t,
    }
}

/// Create a new quic stream with the given id and priority.
/// This is a low-level API for stream creation. It is recommended to use
/// `quic_stream_bidi_new` for bidirectional streams or `quic_stream_uni_new`
/// for undirectional streams.
#[no_mangle]
pub extern "C" fn quic_stream_new(
    conn: &mut Connection,
    stream_id: u64,
    urgency: u8,
    incremental: bool,
) -> c_int {
    match conn.stream_new(stream_id, urgency, incremental) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Create a new quic bidiectional stream with the given priority.
/// If success, the output parameter `stream_id` carrys the id of the created stream.
#[no_mangle]
pub extern "C" fn quic_stream_bidi_new(
    conn: &mut Connection,
    urgency: u8,
    incremental: bool,
    stream_id: &mut u64,
) -> c_int {
    match conn.stream_bidi_new(urgency, incremental) {
        Ok(id) => {
            *stream_id = id;
            0
        }
        Err(e) => e.to_errno() as c_int,
    }
}

/// Create a new quic uniectional stream with the given priority.
/// If success, the output parameter `stream_id` carrys the id of the created stream.
#[no_mangle]
pub extern "C" fn quic_stream_uni_new(
    conn: &mut Connection,
    urgency: u8,
    incremental: bool,
    stream_id: &mut u64,
) -> c_int {
    match conn.stream_uni_new(urgency, incremental) {
        Ok(id) => {
            *stream_id = id;
            0
        }
        Err(e) => e.to_errno() as c_int,
    }
}

/// Shutdown stream reading or writing.
#[no_mangle]
pub extern "C" fn quic_stream_shutdown(
    conn: &mut Connection,
    stream_id: u64,
    direction: Shutdown,
    err: u64,
) -> c_int {
    match conn.stream_shutdown(stream_id, direction, err) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set the priority for a stream.
#[no_mangle]
pub extern "C" fn quic_stream_set_priority(
    conn: &mut Connection,
    stream_id: u64,
    urgency: u8,
    incremental: bool,
) -> c_int {
    match conn.stream_set_priority(stream_id, urgency, incremental) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Return the stream’s send capacity in bytes.
#[no_mangle]
pub extern "C" fn quic_stream_capacity(conn: &mut Connection, stream_id: u64) -> ssize_t {
    match conn.stream_capacity(stream_id) {
        Ok(v) => v as ssize_t,
        Err(e) => e.to_errno() as ssize_t,
    }
}

/// Return true if all the data has been read from the stream.
#[no_mangle]
pub extern "C" fn quic_stream_finished(conn: &mut Connection, stream_id: u64) -> bool {
    conn.stream_finished(stream_id)
}

#[repr(transparent)]
struct Context(*mut c_void);

unsafe impl Send for Context {}
unsafe impl Sync for Context {}

/// Set user context for a stream.
#[no_mangle]
pub extern "C" fn quic_stream_set_context(
    conn: &mut Connection,
    stream_id: u64,
    data: *mut c_void,
) -> c_int {
    match conn.stream_set_context(stream_id, Context(data)) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Return the stream’s user context.
#[no_mangle]
pub extern "C" fn quic_stream_context(conn: &mut Connection, stream_id: u64) -> *mut c_void {
    match conn.stream_context(stream_id) {
        Some(v) => v.downcast_mut::<Context>().unwrap().0,
        None => ptr::null_mut(),
    }
}

#[repr(transparent)]
pub struct TlsConfigSelectorContext(*mut c_void);

#[repr(C)]
pub struct TlsConfigSelectMethods {
    pub get_default: fn(ctx: *mut c_void) -> *mut TlsConfig,
    pub select:
        fn(ctx: *mut c_void, server_name: *const u8, server_name_len: size_t) -> *mut TlsConfig,
}

#[repr(C)]
pub struct TlsConfigSelector {
    pub methods: *const TlsConfigSelectMethods,
    pub context: TlsConfigSelectorContext,
}

unsafe impl Send for TlsConfigSelector {}
unsafe impl Sync for TlsConfigSelector {}

impl crate::tls::TlsConfigSelector for TlsConfigSelector {
    fn get_default(&self) -> Option<Arc<TlsConfig>> {
        let tls_config = unsafe { ((*self.methods).get_default)(self.context.0) };
        if tls_config.is_null() {
            return None;
        }

        let tls_config = unsafe { tls_config.as_mut().unwrap() };
        let tls_config = Arc::new(TlsConfig::new_with_ssl_ctx(tls_config.ssl_ctx()));
        Some(tls_config)
    }

    fn select(&self, server_name: &str) -> Option<Arc<TlsConfig>> {
        let tls_config = unsafe {
            ((*self.methods).select)(
                self.context.0,
                server_name.as_ptr(),
                server_name.len() as size_t,
            )
        };
        if tls_config.is_null() {
            return None;
        }

        let tls_config = unsafe { tls_config.as_mut().unwrap() };
        let tls_config = Arc::new(TlsConfig::new_with_ssl_ctx(tls_config.ssl_ctx()));
        Some(tls_config)
    }
}

#[repr(C)]
pub struct TransportMethods {
    /// Called when a new connection has been created. This callback is called
    /// as soon as connection object is created inside the endpoint, but
    /// before the handshake is done. This callback is optional.
    pub on_conn_created: Option<fn(tctx: *mut c_void, conn: &mut Connection)>,

    /// Called when the handshake is completed. This callback is optional.
    pub on_conn_established: Option<fn(tctx: *mut c_void, conn: &mut Connection)>,

    /// Called when the connection is closed. The connection is no longer
    /// accessible after this callback returns. It is a good time to clean up
    /// the connection context. This callback is optional.
    pub on_conn_closed: Option<fn(tctx: *mut c_void, conn: &mut Connection)>,

    /// Called when the stream is created. This callback is optional.
    pub on_stream_created: Option<fn(tctx: *mut c_void, conn: &mut Connection, stream_id: u64)>,

    /// Called when the stream is readable. This callback is called when either
    /// there are bytes to be read or an error is ready to be collected. This
    /// callback is optional.
    pub on_stream_readable: Option<fn(tctx: *mut c_void, conn: &mut Connection, stream_id: u64)>,

    /// Called when the stream is writable. This callback is optional.
    pub on_stream_writable: Option<fn(tctx: *mut c_void, conn: &mut Connection, stream_id: u64)>,

    /// Called when the stream is closed. The stream is no longer accessible
    /// after this callback returns. It is a good time to clean up the stream
    /// context. This callback is optional.
    pub on_stream_closed: Option<fn(tctx: *mut c_void, conn: &mut Connection, stream_id: u64)>,

    /// Called when client receives a token in NEW_TOKEN frame. This callback
    /// is optional.
    pub on_new_token:
        Option<fn(tctx: *mut c_void, conn: &mut Connection, token: *const u8, token_len: size_t)>,
}

#[repr(transparent)]
pub struct TransportContext(*mut c_void);

/// cbindgen:no-export
#[repr(C)]
pub struct TransportHandler {
    pub methods: *const TransportMethods,
    pub context: TransportContext,
}

impl crate::TransportHandler for TransportHandler {
    fn on_conn_created(&mut self, conn: &mut Connection) {
        unsafe {
            if let Some(f) = (*self.methods).on_conn_created {
                f(self.context.0, conn);
            }
        }
    }

    fn on_conn_established(&mut self, conn: &mut Connection) {
        unsafe {
            if let Some(f) = (*self.methods).on_conn_established {
                f(self.context.0, conn);
            }
        }
    }

    fn on_conn_closed(&mut self, conn: &mut Connection) {
        unsafe {
            if let Some(f) = (*self.methods).on_conn_closed {
                f(self.context.0, conn);
            }
        }
    }

    fn on_stream_created(&mut self, conn: &mut Connection, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_created {
                f(self.context.0, conn, stream_id);
            }
        }
    }

    fn on_stream_readable(&mut self, conn: &mut Connection, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_readable {
                f(self.context.0, conn, stream_id);
            }
        }
    }

    fn on_stream_writable(&mut self, conn: &mut Connection, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_writable {
                f(self.context.0, conn, stream_id);
            }
        }
    }

    fn on_stream_closed(&mut self, conn: &mut Connection, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_closed {
                f(self.context.0, conn, stream_id);
            }
        }
    }

    fn on_new_token(&mut self, conn: &mut Connection, token: Vec<u8>) {
        let token_len = token.len() as size_t;
        let token = token.as_ptr();
        unsafe {
            if let Some(f) = (*self.methods).on_new_token {
                f(self.context.0, conn, token, token_len);
            }
        }
    }
}

#[repr(C)]
pub struct PacketSendMethods {
    /// Called when the connection is sending packets out.
    /// On success, `on_packets_send()` returns the number of messages sent. If
    /// this is less than count, the connection will retry with a further
    /// `on_packets_send()` call to send the remaining messages. This callback
    /// is mandatory.
    pub on_packets_send:
        fn(psctx: *mut c_void, pkts: *mut PacketOutSpec, count: libc::c_uint) -> libc::c_int,
}

#[repr(transparent)]
pub struct PacketSendContext(*mut c_void);

/// cbindgen:no-export
#[repr(C)]
pub struct PacketSendHandler {
    pub methods: *const PacketSendMethods,
    pub context: PacketSendContext,
}

impl crate::PacketSendHandler for PacketSendHandler {
    #[allow(clippy::comparison_chain)]
    fn on_packets_send(&self, pkts: &[(Vec<u8>, crate::PacketInfo)]) -> Result<usize> {
        let mut pkt_specs: Vec<PacketOutSpec> = Vec::with_capacity(pkts.len());
        let mut iovecs: Vec<iovec> = Vec::with_capacity(pkts.len());
        let mut src_addrs: Vec<sockaddr_storage> = Vec::with_capacity(pkts.len());
        let mut dst_addrs: Vec<sockaddr_storage> = Vec::with_capacity(pkts.len());

        // Prepare packets to be send
        for (i, (pkt, info)) in pkts.iter().enumerate() {
            let iov = iovec {
                iov_base: pkt.as_ptr() as *mut c_void,
                iov_len: pkt.len(),
            };
            let mut src_addr: sockaddr_storage = unsafe { mem::zeroed() };
            let src_addr_len = sock_addr_to_c(&info.src, &mut src_addr);
            let mut dst_addr: sockaddr_storage = unsafe { mem::zeroed() };
            let dst_addr_len = sock_addr_to_c(&info.dst, &mut dst_addr);

            iovecs.push(iov);
            src_addrs.push(src_addr);
            dst_addrs.push(dst_addr);

            let pkt_spec = PacketOutSpec {
                iov: &iovecs[i] as *const _ as *mut _,
                iovlen: 1,
                src_addr: &src_addrs[i] as *const _ as *const c_void,
                src_addr_len,
                dst_addr: &dst_addrs[i] as *const _ as *const c_void,
                dst_addr_len,
            };

            pkt_specs.push(pkt_spec);
        }

        // Send packets out
        let count = unsafe {
            ((*self.methods).on_packets_send)(
                self.context.0,
                pkt_specs.as_mut_ptr(),
                pkts.len() as libc::c_uint,
            )
        };
        if count > 0 {
            Ok(count as usize)
        } else if count == 0 {
            Err(Error::Done)
        } else {
            Err(Error::InternalError)
        }
    }
}

fn sock_addr_from_c(addr: &sockaddr, addr_len: socklen_t) -> SocketAddr {
    match addr.sa_family as i32 {
        AF_INET => {
            assert!(addr_len as usize == std::mem::size_of::<sockaddr_in>());
            let in4 = unsafe { *(addr as *const _ as *const sockaddr_in) };

            #[cfg(not(windows))]
            let addr = Ipv4Addr::from(u32::from_be(in4.sin_addr.s_addr));
            #[cfg(windows)]
            let addr = {
                let ip = unsafe { in4.sin_addr.S_un.S_un_b() };
                Ipv4Addr::from([ip.s_b1, ip.s_b2, ip.s_b3, ip.s_b4])
            };

            let port = u16::from_be(in4.sin_port);
            SocketAddrV4::new(addr, port).into()
        }
        AF_INET6 => {
            assert!(addr_len as usize == std::mem::size_of::<sockaddr_in6>());
            let in6 = unsafe { *(addr as *const _ as *const sockaddr_in6) };

            #[cfg(not(windows))]
            let addr = Ipv6Addr::from(in6.sin6_addr.s6_addr);
            #[cfg(windows)]
            let addr = Ipv6Addr::from(*unsafe { in6.sin6_addr.u.Byte() });

            let port = u16::from_be(in6.sin6_port);

            #[cfg(not(windows))]
            let scope_id = in6.sin6_scope_id;
            #[cfg(windows)]
            let scope_id = unsafe { *in6.u.sin6_scope_id() };

            SocketAddrV6::new(addr, port, in6.sin6_flowinfo, scope_id).into()
        }
        _ => unimplemented!("unsupported address type"),
    }
}

fn sock_addr_to_c(addr: &SocketAddr, out: &mut sockaddr_storage) -> socklen_t {
    let sin_port = addr.port().to_be();

    match addr {
        SocketAddr::V4(addr) => unsafe {
            let sa_len = std::mem::size_of::<sockaddr_in>();
            let out_in = out as *mut _ as *mut sockaddr_in;
            let s_addr = u32::from_ne_bytes(addr.ip().octets());

            #[cfg(not(windows))]
            let sin_addr = in_addr { s_addr };
            #[cfg(windows)]
            let sin_addr = {
                let mut s_un = std::mem::zeroed::<in_addr_S_un>();
                *s_un.S_addr_mut() = s_addr;
                in_addr { S_un: s_un }
            };

            *out_in = sockaddr_in {
                sin_family: AF_INET as sa_family_t,
                sin_addr,
                #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
                sin_len: sa_len as u8,
                sin_port,
                sin_zero: std::mem::zeroed(),
            };
            sa_len as socklen_t
        },

        SocketAddr::V6(addr) => unsafe {
            let sa_len = std::mem::size_of::<sockaddr_in6>();
            let out_in6 = out as *mut _ as *mut sockaddr_in6;

            #[cfg(not(windows))]
            let sin6_addr = in6_addr {
                s6_addr: addr.ip().octets(),
            };
            #[cfg(windows)]
            let sin6_addr = {
                let mut u = std::mem::zeroed::<in6_addr_u>();
                *u.Byte_mut() = addr.ip().octets();
                in6_addr { u }
            };

            #[cfg(windows)]
            let u = {
                let mut u = std::mem::zeroed::<SOCKADDR_IN6_LH_u>();
                *u.sin6_scope_id_mut() = addr.scope_id();
                u
            };

            *out_in6 = sockaddr_in6 {
                sin6_family: AF_INET6 as sa_family_t,
                sin6_addr,
                #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
                sin6_len: sa_len as u8,
                sin6_port: sin_port,
                sin6_flowinfo: addr.flowinfo(),

                #[cfg(not(windows))]
                sin6_scope_id: addr.scope_id(),
                #[cfg(windows)]
                u,
            };
            sa_len as socklen_t
        },
    }
}

/// Meta information of an incoming packet.
#[repr(C)]
pub struct PacketInfo<'a> {
    src: &'a sockaddr,
    src_len: socklen_t,
    dst: &'a sockaddr,
    dst_len: socklen_t,
}

impl From<&PacketInfo<'_>> for crate::PacketInfo {
    fn from(info: &PacketInfo) -> crate::PacketInfo {
        crate::PacketInfo {
            src: sock_addr_from_c(info.src, info.src_len),
            dst: sock_addr_from_c(info.dst, info.dst_len),
            time: Instant::now(),
        }
    }
}

/// Data and meta information of an outgoing packet.
#[repr(C)]
pub struct PacketOutSpec {
    iov: *const iovec,
    iovlen: size_t,
    src_addr: *const c_void,
    src_addr_len: socklen_t,
    dst_addr: *const c_void,
    dst_addr_len: socklen_t,
}

#[repr(C)]
pub struct ConnectionIdGeneratorMethods {
    /// Generate a new CID
    pub generate: fn(gctx: *mut c_void) -> ConnectionId,

    /// Return the length of a CID
    pub cid_len: fn(gctx: *mut c_void) -> u8,
}

#[repr(transparent)]
pub struct ConnectionIdGeneratorContext(*mut c_void);

/// cbindgen:no-export
#[repr(C)]
pub struct ConnectionIdGenerator {
    pub methods: *const ConnectionIdGeneratorMethods,
    pub context: ConnectionIdGeneratorContext,
}

impl crate::ConnectionIdGenerator for ConnectionIdGenerator {
    /// Generate a new CID
    fn generate(&mut self) -> ConnectionId {
        unsafe { ((*self.methods).generate)(self.context.0) }
    }

    /// Return the length of a CID
    fn cid_len(&self) -> usize {
        let cid_len = unsafe { ((*self.methods).cid_len)(self.context.0) };
        cid_len as usize
    }
}

/// Extract the header form, version and destination connection id from the
/// QUIC packet.
#[no_mangle]
pub extern "C" fn quic_packet_header_info(
    buf: *mut u8,
    buf_len: size_t,
    dcid_len: u8,
    long_header: &mut bool,
    version: &mut u32,
    dcid: &mut ConnectionId,
) -> c_int {
    let buf = unsafe { slice::from_raw_parts_mut(buf, buf_len) };

    match crate::PacketHeader::header_info(buf, dcid_len as usize) {
        Ok((long, ver, cid)) => {
            *long_header = long;
            *version = ver;
            *dcid = cid;
            0
        }
        Err(e) => e.to_errno() as i32,
    }
}

/// Create default config for HTTP3.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_config_new() -> *mut Http3Config {
    match Http3Config::new() {
        Ok(c) => Box::into_raw(Box::new(c)),
        Err(_) => ptr::null_mut(),
    }
}

/// Destroy the HTTP3 config.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_config_free(config: *mut Http3Config) {
    unsafe {
        let _ = Box::from_raw(config);
    };
}

/// Set the `SETTINGS_MAX_FIELD_SECTION_SIZE` setting.
/// By default no limit is enforced.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_config_set_max_field_section_size(config: &mut Http3Config, v: u64) {
    config.set_max_field_section_size(v);
}

/// Set the `SETTINGS_QPACK_MAX_TABLE_CAPACITY` setting.
/// The default value is `0`.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_config_set_qpack_max_table_capacity(config: &mut Http3Config, v: u64) {
    config.set_qpack_max_table_capacity(v);
}

/// Set the `SETTINGS_QPACK_BLOCKED_STREAMS` setting.
/// The default value is `0`.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_config_set_qpack_blocked_streams(config: &mut Http3Config, v: u64) {
    config.set_qpack_blocked_streams(v);
}

/// Create an HTTP/3 connection using the given QUIC connection. It also
/// initiate the HTTP/3 handshake by opening all control streams and sending
/// the local settings.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_conn_new(
    quic_conn: &mut Connection,
    config: &mut Http3Config,
) -> *mut Http3Connection {
    match Http3Connection::new_with_quic_conn(quic_conn, config) {
        Ok(c) => Box::into_raw(Box::new(c)),
        Err(_) => ptr::null_mut(),
    }
}

/// Destroy the HTTP/3 connection.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_conn_free(conn: *mut Http3Connection) {
    unsafe {
        let _ = Box::from_raw(conn);
    };
}

/// Send goaway with the given id.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_send_goaway(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    id: u64,
) -> i64 {
    match conn.send_goaway(quic_conn, id) {
        Ok(()) => 0,
        Err(e) => e.to_errno() as i64,
    }
}

/// Set HTTP/3 connection events handler.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_conn_set_events_handler(
    conn: &mut Http3Connection,
    methods: *const Http3Methods,
    context: Http3Context,
) {
    let handler = Http3Handler { methods, context };
    conn.set_events_handler(Arc::new(handler));
}

/// Process HTTP/3 settings.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_for_each_setting(
    conn: &Http3Connection,
    cb: extern "C" fn(identifier: u64, value: u64, argp: *mut c_void) -> c_int,
    argp: *mut c_void,
) -> c_int {
    match conn.peer_raw_settings() {
        Some(raw) => {
            for setting in raw {
                let rc = cb(setting.0, setting.1, argp);

                if rc != 0 {
                    return rc;
                }
            }
            0
        }

        None => -1,
    }
}

/// Process internal events of all streams of the specified HTTP/3 connection.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_conn_process_streams(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
) -> c_int {
    match conn.process_streams(quic_conn) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as i32,
    }
}

/// Process HTTP/3 headers.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_for_each_header(
    headers: &Http3Headers,
    cb: extern "C" fn(
        name: *const u8,
        name_len: size_t,
        value: *const u8,
        value_len: size_t,
        argp: *mut c_void,
    ) -> c_int,
    argp: *mut c_void,
) -> c_int {
    for h in headers.headers {
        let rc = cb(
            h.name().as_ptr(),
            h.name().len(),
            h.value().as_ptr(),
            h.value().len(),
            argp,
        );
        if rc != 0 {
            return rc;
        }
    }

    0
}

/// Return true if all the data has been read from the stream.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_stream_read_finished(conn: &mut Connection, stream_id: u64) -> bool {
    conn.stream_finished(stream_id)
}

/// Create a new HTTP/3 request stream.
/// On success the stream ID is returned.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_stream_new(conn: &mut Http3Connection, quic_conn: &mut Connection) -> i64 {
    match conn.stream_new_with_priority(quic_conn, &Http3Priority::default()) {
        Ok(v) => v as i64,
        Err(e) => e.to_errno() as i64,
    }
}

/// Create a new HTTP/3 request stream with the given priority.
/// On success the stream ID is returned.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_stream_new_with_priority(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    priority: &Http3Priority,
) -> i64 {
    match conn.stream_new_with_priority(quic_conn, priority) {
        Ok(v) => v as i64,
        Err(e) => e.to_errno() as i64,
    }
}

/// Close the given HTTP/3 stream.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_stream_close(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    stream_id: u64,
) -> c_int {
    match conn.stream_close(quic_conn, stream_id) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Set priority for an HTTP/3 stream.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_stream_set_priority(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    stream_id: u64,
    priority: &Http3Priority,
) -> c_int {
    match conn.stream_set_priority(quic_conn, stream_id, priority) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

#[cfg(feature = "h3")]
#[repr(C)]
pub struct Header {
    name: *mut u8,
    name_len: usize,
    value: *mut u8,
    value_len: usize,
}

/// Send HTTP/3 request or response headers on the given stream.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_send_headers(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    stream_id: u64,
    headers: *const Header,
    headers_len: size_t,
    fin: bool,
) -> c_int {
    let h3_headers = headers_from_ptr(headers, headers_len);

    match conn.send_headers(quic_conn, stream_id, &h3_headers, fin) {
        Ok(_) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Send HTTP/3 request or response body on the given stream.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_send_body(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    stream_id: u64,
    body: *const u8,
    body_len: size_t,
    fin: bool,
) -> ssize_t {
    if body_len > <ssize_t>::MAX as usize {
        panic!("The provided buffer is too large");
    }

    let body = unsafe { slice::from_raw_parts(body, body_len) };
    match conn.send_body(quic_conn, stream_id, Bytes::copy_from_slice(body), fin) {
        Ok(v) => v as ssize_t,
        Err(e) => e.to_errno(),
    }
}

/// Read request/response body from the given stream.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_recv_body(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    stream_id: u64,
    out: *mut u8,
    out_len: size_t,
) -> ssize_t {
    if out_len > <ssize_t>::MAX as usize {
        panic!("The provided buffer is too large");
    }

    let out = unsafe { slice::from_raw_parts_mut(out, out_len) };
    match conn.recv_body(quic_conn, stream_id, out) {
        Ok(v) => v as ssize_t,
        Err(e) => e.to_errno(),
    }
}

/// Parse HTTP/3 priority data.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_parse_extensible_priority(
    priority: *const u8,
    priority_len: size_t,
    parsed: &mut Http3Priority,
) -> c_int {
    let priority = unsafe { slice::from_raw_parts(priority, priority_len) };

    match Http3Priority::try_from(priority) {
        Ok(v) => {
            parsed.urgency = v.urgency;
            parsed.incremental = v.incremental;
            0
        }
        Err(e) => e.to_errno() as c_int,
    }
}

/// Send a PRIORITY_UPDATE frame on the control stream with specified
/// request stream ID and priority.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_send_priority_update_for_request(
    conn: &mut Http3Connection,
    quic_conn: &mut Connection,
    stream_id: u64,
    priority: &Http3Priority,
) -> c_int {
    match conn.send_priority_update_for_request(quic_conn, stream_id, priority) {
        Ok(()) => 0,
        Err(e) => e.to_errno() as c_int,
    }
}

/// Take the last PRIORITY_UPDATE for the given stream.
#[cfg(feature = "h3")]
#[no_mangle]
pub extern "C" fn http3_take_priority_update(
    conn: &mut Http3Connection,
    prioritized_element_id: u64,
    cb: extern "C" fn(
        priority_field_value: *const u8,
        priority_field_value_len: size_t,
        argp: *mut c_void,
    ) -> c_int,
    argp: *mut c_void,
) -> c_int {
    match conn.take_priority_update(prioritized_element_id) {
        Ok(priority) => {
            let rc = cb(priority.as_ptr(), priority.len(), argp);
            if rc != 0 {
                return rc;
            }
            0
        }

        Err(e) => e.to_errno() as c_int,
    }
}

/// Convert HTTP/3 header.
#[cfg(feature = "h3")]
fn headers_from_ptr<'a>(ptr: *const Header, len: size_t) -> Vec<h3::HeaderRef<'a>> {
    let headers = unsafe { slice::from_raw_parts(ptr, len) };

    let mut out = Vec::new();
    for h in headers {
        out.push({
            let name = unsafe { slice::from_raw_parts(h.name, h.name_len) };
            let value = unsafe { slice::from_raw_parts(h.value, h.value_len) };
            h3::HeaderRef::new(name, value)
        });
    }

    out
}

/// Set logger.
/// `cb` is a callback function that will be called for each log message.
/// `data` is a '\n' terminated log message and `argp` is user-defined data that
/// will be passed to the callback.
/// `level` is a case-insensitive string used for specifying the log level. Valid
/// values are "OFF", "ERROR", "WARN", "INFO", "DEBUG", and "TRACE". If its value
/// is NULL or invalid, the default log level is "OFF".
#[no_mangle]
pub extern "C" fn quic_set_logger(
    cb: extern "C" fn(data: *const u8, data_len: size_t, argp: *mut c_void),
    argp: *mut c_void,
    level: *const c_char,
) {
    let argp = atomic::AtomicPtr::new(argp);
    let logger = Box::new(LogWriter { cb, argp });
    let _ = log::set_boxed_logger(logger);

    let level = unsafe { ffi::CStr::from_ptr(level).to_str().unwrap_or_default() };
    if let Ok(level_filter) = log::LevelFilter::from_str(level) {
        log::set_max_level(level_filter);
    }
}

#[cfg(feature = "h3")]
#[repr(C)]
pub struct Http3Methods {
    /// Called when the stream got headers.
    pub on_stream_headers:
        Option<fn(ctx: *mut c_void, stream_id: u64, headers: &Http3Headers, fin: bool)>,

    /// Called when the stream has buffered data to read.
    pub on_stream_data: Option<fn(ctx: *mut c_void, stream_id: u64)>,

    /// Called when the stream is finished.
    pub on_stream_finished: Option<fn(ctx: *mut c_void, stream_id: u64)>,

    /// Called when the stream receives a RESET_STREAM frame from the peer.
    pub on_stream_reset: Option<fn(ctx: *mut c_void, stream_id: u64, error_code: u64)>,

    /// Called when the stream priority is updated.
    pub on_stream_priority_update: Option<fn(ctx: *mut c_void, stream_id: u64)>,

    /// Called when the connection receives a GOAWAY frame from the peer.
    pub on_conn_goaway: Option<fn(ctx: *mut c_void, stream_id: u64)>,
}

#[cfg(feature = "h3")]
#[repr(transparent)]
pub struct Http3Context(*mut c_void);

#[cfg(feature = "h3")]
#[repr(C)]
pub struct Http3Handler {
    pub methods: *const Http3Methods,
    pub context: Http3Context,
}

#[cfg(feature = "h3")]
unsafe impl Send for Http3Handler {}

#[cfg(feature = "h3")]
unsafe impl Sync for Http3Handler {}

#[cfg(feature = "h3")]
impl crate::h3::Http3Handler for Http3Handler {
    fn on_stream_headers(&self, stream_id: u64, ev: &mut Http3Event) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_headers {
                let (headers, fin) = match ev {
                    Http3Event::Headers { headers, fin } => (Http3Headers { headers }, *fin),
                    _ => unreachable!(),
                };

                f(self.context.0, stream_id, &headers, fin);
            }
        }
    }

    fn on_stream_data(&self, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_data {
                f(self.context.0, stream_id);
            }
        }
    }

    fn on_stream_finished(&self, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_finished {
                f(self.context.0, stream_id);
            }
        }
    }

    fn on_stream_reset(&self, stream_id: u64, error_code: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_reset {
                f(self.context.0, stream_id, error_code);
            }
        }
    }

    fn on_stream_priority_update(&self, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_stream_priority_update {
                f(self.context.0, stream_id);
            }
        }
    }

    fn on_conn_goaway(&self, stream_id: u64) {
        unsafe {
            if let Some(f) = (*self.methods).on_conn_goaway {
                f(self.context.0, stream_id);
            }
        }
    }
}