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
//! Server mode implementation
//!
//! Listens for incoming connections and handles bandwidth tests.
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream, UdpSocket};
use tokio::sync::{Mutex, Semaphore, watch};
use tokio::task::JoinHandle;
use tracing::{debug, error, info, warn};
use crate::acl::{Acl, AclConfig};
use crate::auth::{self, AuthConfig};
use crate::net::{self, AddressFamily};
use crate::protocol::{
ControlMessage, Direction, PROTOCOL_VERSION, Protocol, StreamInterval, TestResult,
versions_compatible,
};
use crate::quic;
use crate::rate_limit::{RateLimitConfig, RateLimitGuard, RateLimiter};
use crate::stats::TestStats;
use crate::tcp::{self, TcpConfig};
use crate::tui::server::{ActiveTestInfo, ServerEvent};
use crate::udp;
use tokio::sync::mpsc;
/// Maximum control message line length to prevent memory DoS
const MAX_LINE_LENGTH: usize = 8192;
/// Maximum streams a client can request
const MAX_STREAMS: u8 = 128;
/// Maximum test duration a client can request (1 hour)
const MAX_TEST_DURATION: Duration = Duration::from_secs(3600);
/// Timeout for control-plane handshake reads (prevents DoS from idle connections)
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
/// Timeout for initial first-line read on new connections (shorter to resist slow-loris)
const INITIAL_READ_TIMEOUT: Duration = Duration::from_secs(5);
/// Interval between progress/stats updates sent to the client
const STATS_INTERVAL: Duration = Duration::from_secs(1);
/// How often to check for cancellation in send/receive loops
const CANCEL_CHECK_TIMEOUT: Duration = Duration::from_millis(10);
/// Brief delay before sending final result to allow buffered writes to flush
const RESULT_FLUSH_DELAY: Duration = Duration::from_millis(100);
/// Timeout for accepting a data stream connection on per-stream listeners
const STREAM_ACCEPT_TIMEOUT: Duration = Duration::from_secs(10);
/// Maximum time to wait for all expected data streams to connect
const STREAM_COLLECTION_TIMEOUT: Duration = Duration::from_secs(30);
/// Default UDP/QUIC bitrate when not specified by client (1 Gbps)
const DEFAULT_BITRATE_BPS: u64 = 1_000_000_000;
pub struct ServerConfig {
pub port: u16,
pub one_off: bool,
/// Maximum test duration (server-side limit)
pub max_duration: Option<Duration>,
#[cfg(feature = "prometheus")]
pub prometheus_port: Option<u16>,
/// Prometheus push gateway URL for pushing metrics at test completion
pub push_gateway_url: Option<String>,
/// Authentication configuration
pub auth: AuthConfig,
/// Access control list configuration
pub acl: AclConfig,
/// Rate limiting configuration
pub rate_limit: RateLimitConfig,
/// Address family (IPv4, IPv6, dual-stack)
pub address_family: AddressFamily,
/// Channel to send events to TUI
pub tui_tx: Option<mpsc::Sender<ServerEvent>>,
/// Enable QUIC protocol support (binds additional UDP port)
pub enable_quic: bool,
/// Maximum concurrent client handlers (defense against connection floods)
pub max_concurrent: u32,
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
port: crate::protocol::DEFAULT_PORT,
one_off: false,
max_duration: None,
#[cfg(feature = "prometheus")]
prometheus_port: None,
push_gateway_url: None,
auth: AuthConfig::default(),
acl: AclConfig::default(),
rate_limit: RateLimitConfig::default(),
address_family: AddressFamily::default(),
tui_tx: None,
enable_quic: true,
max_concurrent: 100,
}
}
}
/// Security context shared across client handlers
struct SecurityContext {
psk: Option<String>,
acl: Acl,
rate_limiter: Option<Arc<RateLimiter>>,
address_family: AddressFamily,
tui_tx: Option<mpsc::Sender<ServerEvent>>,
push_gateway_url: Option<String>,
}
struct ActiveTest {
#[allow(dead_code)]
stats: Arc<TestStats>,
#[allow(dead_code)]
cancel_tx: watch::Sender<bool>,
#[allow(dead_code)]
pause_tx: watch::Sender<bool>,
#[allow(dead_code)]
data_ports: Vec<u16>,
/// Channel for receiving data connections in single-port TCP mode
#[allow(dead_code)]
data_stream_tx: Option<mpsc::Sender<(TcpStream, u16)>>, // (stream, stream_index)
/// Control connection peer IP (for DataHello validation)
control_peer_ip: std::net::IpAddr,
}
pub struct Server {
config: ServerConfig,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
}
impl Server {
pub fn new(config: ServerConfig) -> Self {
Self {
config,
active_tests: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn run(&self) -> anyhow::Result<()> {
let listener =
net::create_tcp_listener(self.config.port, self.config.address_family).await?;
// Create QUIC endpoint on the same port (UDP) - only if enabled
let quic_endpoint = if self.config.enable_quic {
let (cert, key) = quic::generate_self_signed_cert()?;
let bind_addr: SocketAddr = match self.config.address_family {
AddressFamily::V4Only => format!("0.0.0.0:{}", self.config.port).parse()?,
AddressFamily::V6Only | AddressFamily::DualStack => {
format!("[::]:{}", self.config.port).parse()?
}
};
let endpoint = quic::create_server_endpoint(bind_addr, cert, key)?;
info!("QUIC endpoint ready on port {}", self.config.port);
Some(endpoint)
} else {
None
};
// Initialize security context
let acl = self.config.acl.build()?;
let rate_limiter = self.config.rate_limit.build();
if self.config.auth.psk.is_some() {
info!("PSK authentication enabled");
}
if acl.is_configured() {
info!("ACL configured");
}
if rate_limiter.is_some() {
info!(
"Rate limiting enabled: {} per IP",
self.config.rate_limit.max_per_ip.unwrap_or(0)
);
}
let security = Arc::new(SecurityContext {
psk: self.config.auth.psk.clone(),
acl,
rate_limiter: rate_limiter.clone(),
address_family: self.config.address_family,
tui_tx: self.config.tui_tx.clone(),
push_gateway_url: self.config.push_gateway_url.clone(),
});
// Start rate limiter cleanup task if enabled
if let Some(limiter) = rate_limiter.clone() {
limiter.start_cleanup_task();
}
// Semaphore to limit concurrent handlers (defense against connection floods)
let handler_semaphore = Arc::new(Semaphore::new(self.config.max_concurrent as usize));
// Pre-handshake semaphore: limits concurrent connections that haven't yet been
// classified (Hello vs DataHello). Prevents connection-flood DoS where attackers
// open many sockets that stall during the 5s initial read timeout.
let conn_semaphore = Arc::new(Semaphore::new(self.config.max_concurrent as usize * 4));
// Shutdown channel for one-off mode (watch allows multiple receivers)
let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
// Spawn QUIC acceptor task (only if QUIC is enabled)
if let Some(quic_endpoint) = quic_endpoint {
let quic_security = security.clone();
let quic_active_tests = self.active_tests.clone();
let quic_max_duration = self.config.max_duration;
let quic_rate_limiter = rate_limiter.clone();
let quic_semaphore = handler_semaphore.clone();
let quic_one_off = self.config.one_off;
let quic_shutdown_tx = shutdown_tx.clone();
let mut quic_shutdown_rx = shutdown_rx.clone();
tokio::spawn(async move {
loop {
// Use select! to accept connections OR receive shutdown signal
let incoming = tokio::select! {
result = quic_endpoint.accept() => {
match result {
Some(incoming) => incoming,
None => break, // Endpoint closed
}
}
_ = quic_shutdown_rx.changed() => {
if *quic_shutdown_rx.borrow() {
debug!("QUIC shutdown signal received");
break;
}
continue;
}
};
let peer_addr = incoming.remote_address();
let peer_ip = peer_addr.ip();
// Check ACL
if !quic_security.acl.is_allowed(peer_ip) {
warn!("QUIC connection rejected by ACL: {}", peer_addr);
if let Some(tx) = &quic_security.tui_tx {
let _ = tx.try_send(ServerEvent::ConnectionBlocked);
}
continue;
}
// Check rate limit
if let Some(ref limiter) = quic_rate_limiter
&& let Err(e) = limiter.check(peer_ip)
{
warn!("QUIC rate limit exceeded for {}: {}", peer_addr, e);
if let Some(tx) = &quic_security.tui_tx {
let _ = tx.try_send(ServerEvent::ConnectionBlocked);
}
continue;
}
// Acquire semaphore permit to limit concurrent handlers
let permit = match quic_semaphore.clone().try_acquire_owned() {
Ok(permit) => permit,
Err(_) => {
warn!(
"Max concurrent handlers reached, rejecting QUIC: {}",
peer_addr
);
continue;
}
};
info!("QUIC client connected: {}", peer_addr);
let security = quic_security.clone();
let active_tests = quic_active_tests.clone();
let rate_limiter = quic_rate_limiter.clone();
let shutdown_tx = quic_shutdown_tx.clone();
let one_off = quic_one_off;
let handle = tokio::spawn(async move {
let _permit = permit; // Held until task completes
let result = handle_quic_client(
incoming,
peer_addr,
active_tests,
quic_max_duration,
&security,
)
.await;
// Release rate limit slot
if let Some(limiter) = &rate_limiter {
limiter.release(peer_ip);
}
match &result {
Ok(()) => true,
Err(e) => {
error!("QUIC client error {}: {}", peer_addr, e);
false
}
}
});
if one_off {
// Only signal shutdown if test completed successfully
let shutdown_tx = shutdown_tx.clone();
tokio::spawn(async move {
if let Ok(true) = handle.await {
let _ = shutdown_tx.send(true);
}
});
}
}
});
}
// Register mDNS service for discovery
#[cfg(feature = "discovery")]
let _mdns = register_mdns_service(self.config.port);
// Spawn Prometheus metrics server if enabled
#[cfg(feature = "prometheus")]
if let Some(prom_port) = self.config.prometheus_port {
use crate::output::prometheus::{MetricsServer, register_metrics};
register_metrics();
let metrics_server = MetricsServer::new(prom_port);
tokio::spawn(async move {
if let Err(e) = metrics_server.run().await {
error!("Prometheus metrics server error: {}", e);
}
});
}
// TCP accept loop uses the same shutdown channel as QUIC
let mut tcp_shutdown_rx = shutdown_rx.clone();
loop {
// Use select! to accept connections OR receive shutdown signal
let (stream, peer_addr) = tokio::select! {
result = listener.accept() => result?,
_ = tcp_shutdown_rx.changed() => {
if *tcp_shutdown_rx.borrow() {
debug!("Shutdown signal received, exiting accept loop");
break;
}
continue;
}
};
let peer_ip = peer_addr.ip();
// Check ACL (cheap, no state change)
if !security.acl.is_allowed(peer_ip) {
warn!("Connection rejected by ACL: {}", peer_addr);
if let Some(tx) = &security.tui_tx {
let _ = tx.try_send(ServerEvent::ConnectionBlocked);
}
drop(stream);
continue;
}
// Acquire pre-handshake permit (limits concurrent unclassified connections)
let conn_permit = match conn_semaphore.clone().try_acquire_owned() {
Ok(permit) => permit,
Err(_) => {
debug!(
"Pre-handshake connection limit reached, dropping: {}",
peer_addr
);
drop(stream);
continue;
}
};
// Spawn a task per connection to avoid slow-loris blocking the accept loop.
// The spawned task reads the first line, parses, and routes.
let active_tests = self.active_tests.clone();
let handler_semaphore = handler_semaphore.clone();
let security = security.clone();
let base_port = self.config.port;
let max_duration = self.config.max_duration;
let one_off = self.config.one_off;
let shutdown_tx = shutdown_tx.clone();
tokio::spawn(async move {
let result = handle_new_connection(
stream,
peer_addr,
active_tests,
handler_semaphore,
security,
base_port,
max_duration,
one_off,
shutdown_tx,
)
.await;
// Release pre-handshake permit when connection is classified/done
drop(conn_permit);
if let Err(e) = result {
debug!("Connection handling error from {}: {}", peer_addr, e);
}
});
}
Ok(())
}
}
/// Handle a newly accepted TCP connection.
/// Reads the first line, parses the message type, and routes accordingly.
/// Runs in its own spawned task to prevent slow-loris blocking the accept loop.
#[allow(clippy::too_many_arguments)]
async fn handle_new_connection(
mut stream: TcpStream,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
handler_semaphore: Arc<Semaphore>,
security: Arc<SecurityContext>,
base_port: u16,
max_duration: Option<Duration>,
one_off: bool,
shutdown_tx: watch::Sender<bool>,
) -> anyhow::Result<()> {
let peer_ip = peer_addr.ip();
// Read first line with short timeout to resist slow-loris attacks
let line = tokio::time::timeout(
INITIAL_READ_TIMEOUT,
read_first_line_unbuffered(&mut stream, MAX_LINE_LENGTH),
)
.await
.map_err(|_| anyhow::anyhow!("Initial read timeout from {}", peer_addr))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::DataHello {
test_id,
stream_index,
} => {
// Quick validation: reject unknown test_ids immediately (Fix 2: DataHello flood)
let test_exists = active_tests.lock().await.contains_key(&test_id);
if !test_exists {
debug!("DataHello for unknown test {} from {}", test_id, peer_addr);
return Ok(());
}
// Route data connection (no semaphore/rate-limit needed, control connection holds those)
route_data_hello(stream, peer_addr, active_tests, test_id, stream_index).await?;
}
ControlMessage::Hello { .. } => {
// Control connection - acquire rate limit and semaphore
let rate_limit_guard = if let Some(limiter) = &security.rate_limiter {
if let Err(e) = limiter.check(peer_ip) {
warn!("Rate limit exceeded for {}: {}", peer_addr, e);
if let Some(tx) = &security.tui_tx {
let _ = tx.try_send(ServerEvent::ConnectionBlocked);
}
return Ok(());
}
Some(RateLimitGuard::new(limiter.clone(), peer_ip))
} else {
None
};
let permit = match handler_semaphore.try_acquire_owned() {
Ok(permit) => permit,
Err(_) => {
warn!("Max concurrent handlers reached, rejecting: {}", peer_addr);
return Ok(());
}
};
info!("Client connected: {}", peer_addr);
let handle = tokio::spawn(async move {
let _permit = permit;
let _rate_guard = rate_limit_guard;
let result = handle_client_with_first_message(
stream,
peer_addr,
active_tests,
base_port,
max_duration,
&security,
msg,
)
.await;
match &result {
Ok(()) => true, // test completed successfully
Err(e) => {
error!("Client error {}: {}", peer_addr, e);
false // handshake/auth/test failed
}
}
});
if one_off {
// Only signal shutdown if a test actually completed successfully
// (failed handshakes/auth should not terminate the server)
if let Ok(true) = handle.await {
let _ = shutdown_tx.send(true);
}
}
}
other => {
warn!("Unexpected first message from {}: {:?}", peer_addr, other);
}
}
Ok(())
}
/// Read first line without buffering (to avoid losing data after DataHello)
async fn read_first_line_unbuffered(
stream: &mut TcpStream,
max_len: usize,
) -> anyhow::Result<String> {
use tokio::io::AsyncReadExt;
let mut line = Vec::with_capacity(256);
let mut buf = [0u8; 1];
loop {
let n = stream.read(&mut buf).await?;
if n == 0 {
return Err(anyhow::anyhow!("Connection closed"));
}
if buf[0] == b'\n' {
break;
}
line.push(buf[0]);
// DoS guard: reject lines that exceed maximum length
if line.len() >= max_len {
return Err(anyhow::anyhow!(
"Line exceeds maximum length of {} bytes",
max_len
));
}
}
Ok(String::from_utf8_lossy(&line).to_string())
}
/// Route DataHello connection to its test (no rate-limit/semaphore needed)
async fn route_data_hello(
stream: TcpStream,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
test_id: String,
stream_index: u16,
) -> anyhow::Result<()> {
debug!(
"DataHello from {} for test {} stream {}",
peer_addr, test_id, stream_index
);
// Look up the test and validate peer IP matches control connection
let tx = {
let tests = active_tests.lock().await;
if let Some(test) = tests.get(&test_id) {
// Security: Validate DataHello comes from same IP as control connection
// Use normalize_ip to handle IPv4-mapped IPv6 addresses (::ffff:x.x.x.x vs x.x.x.x)
let expected_ip = net::normalize_ip(test.control_peer_ip);
let actual_ip = net::normalize_ip(peer_addr.ip());
if expected_ip != actual_ip {
warn!(
"DataHello IP mismatch for test {}: expected {}, got {}",
test_id,
test.control_peer_ip,
peer_addr.ip()
);
return Err(anyhow::anyhow!("DataHello from unauthorized IP"));
}
test.data_stream_tx.clone()
} else {
None
}
};
if let Some(tx) = tx {
// Stream is ready for data transfer
if tx.send((stream, stream_index)).await.is_err() {
warn!("Failed to route data stream - test may have ended");
}
} else {
warn!(
"DataHello for unknown/completed test {} from {}",
test_id, peer_addr
);
}
Ok(())
}
/// Route incoming connection: either DataHello (route to test) or Hello (control connection)
/// Note: Currently unused - kept for potential multi-port mode fallback
#[allow(dead_code)]
async fn route_connection(
mut stream: TcpStream,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
base_port: u16,
server_max_duration: Option<Duration>,
security: &SecurityContext,
) -> anyhow::Result<()> {
// Read first line without buffering to avoid losing data bytes after DataHello
let line = tokio::time::timeout(
HANDSHAKE_TIMEOUT,
read_first_line_unbuffered(&mut stream, MAX_LINE_LENGTH),
)
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::DataHello {
test_id,
stream_index,
} => {
// This is a data connection for an active test
debug!(
"DataHello from {} for test {} stream {}",
peer_addr, test_id, stream_index
);
// Look up the test and validate peer IP matches control connection
let tx = {
let tests = active_tests.lock().await;
if let Some(test) = tests.get(&test_id) {
// Security: Validate DataHello comes from same IP as control connection
// Use normalize_ip to handle IPv4-mapped IPv6 addresses (::ffff:x.x.x.x vs x.x.x.x)
let expected_ip = net::normalize_ip(test.control_peer_ip);
let actual_ip = net::normalize_ip(peer_addr.ip());
if expected_ip != actual_ip {
warn!(
"DataHello IP mismatch for test {}: expected {}, got {}",
test_id,
test.control_peer_ip,
peer_addr.ip()
);
return Err(anyhow::anyhow!("DataHello from unauthorized IP"));
}
test.data_stream_tx.clone()
} else {
None
}
};
if let Some(tx) = tx {
// Stream is ready for data transfer (no buffered bytes lost)
if tx.send((stream, stream_index)).await.is_err() {
warn!("Failed to route data stream - test may have ended");
}
} else {
warn!(
"DataHello for unknown/completed test {} from {}",
test_id, peer_addr
);
}
Ok(())
}
ControlMessage::Hello { .. } => {
// This is a control connection - proceed with normal handling
handle_client_with_first_message(
stream,
peer_addr,
active_tests,
base_port,
server_max_duration,
security,
msg,
)
.await
}
other => {
warn!("Unexpected first message from {}: {:?}", peer_addr, other);
Err(anyhow::anyhow!("Expected Hello or DataHello"))
}
}
}
/// Handle client with security checks (auth)
/// Note: Currently unused - kept for potential multi-port mode fallback
#[allow(dead_code)]
async fn handle_client_secure(
stream: TcpStream,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
base_port: u16,
server_max_duration: Option<Duration>,
security: &SecurityContext,
) -> anyhow::Result<()> {
handle_client_with_auth(
stream,
peer_addr,
active_tests,
base_port,
server_max_duration,
security,
)
.await
}
/// Handle QUIC client connection
async fn handle_quic_client(
incoming: quinn::Incoming,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
server_max_duration: Option<Duration>,
security: &SecurityContext,
) -> anyhow::Result<()> {
use tokio::io::BufReader;
let connection = incoming.await?;
debug!("QUIC connection established with {}", peer_addr);
// Accept control stream (bidirectional)
let (mut ctrl_send, ctrl_recv) = connection.accept_bi().await?;
let mut ctrl_reader = BufReader::new(ctrl_recv);
let mut line = String::new();
// Read client hello (bounded to prevent DoS, with timeout)
tokio::time::timeout(
HANDSHAKE_TIMEOUT,
read_bounded_line(&mut ctrl_reader, &mut line),
)
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout waiting for hello"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
let auth_nonce = match msg {
ControlMessage::Hello { version, .. } => {
if !versions_compatible(&version, PROTOCOL_VERSION) {
let error = ControlMessage::error(format!(
"Incompatible protocol version: {} (server: {})",
version, PROTOCOL_VERSION
));
ctrl_send
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Protocol version mismatch"));
}
// Send server hello (with auth challenge if required)
if security.psk.is_some() {
let nonce = auth::generate_nonce();
let hello = ControlMessage::server_hello_with_auth(nonce.clone());
ctrl_send
.write_all(format!("{}\n", hello.serialize()?).as_bytes())
.await?;
Some(nonce)
} else {
let hello = ControlMessage::server_hello();
ctrl_send
.write_all(format!("{}\n", hello.serialize()?).as_bytes())
.await?;
None
}
}
_ => {
let error = ControlMessage::error("Expected hello message");
ctrl_send
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Expected hello message"));
}
};
// Handle authentication if required
if let Some(nonce) = auth_nonce {
tokio::time::timeout(
HANDSHAKE_TIMEOUT,
read_bounded_line(&mut ctrl_reader, &mut line),
)
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout waiting for auth"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::AuthResponse { response } => {
let psk = security.psk.as_ref().ok_or_else(|| {
anyhow::anyhow!("PSK required for authentication but not configured")
})?;
if !auth::verify_response(&nonce, psk, &response) {
if let Some(tx) = &security.tui_tx {
let _ = tx.try_send(ServerEvent::AuthFailure);
}
let error = ControlMessage::error("Authentication failed");
ctrl_send
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Authentication failed"));
}
let success = ControlMessage::auth_success();
ctrl_send
.write_all(format!("{}\n", success.serialize()?).as_bytes())
.await?;
}
_ => {
let error = ControlMessage::error("Expected auth response");
ctrl_send
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Expected auth response"));
}
}
}
// Read test start (with timeout)
tokio::time::timeout(
HANDSHAKE_TIMEOUT,
read_bounded_line(&mut ctrl_reader, &mut line),
)
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout waiting for test start"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::TestStart {
id,
protocol,
streams,
duration_secs,
direction,
bitrate: _,
congestion: _,
} => {
if protocol != Protocol::Quic {
let error = ControlMessage::error("Expected QUIC protocol for QUIC connection");
ctrl_send
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Protocol mismatch"));
}
if streams == 0 || streams > MAX_STREAMS {
let error = ControlMessage::error(format!(
"Invalid stream count {} (must be 1-{})",
streams, MAX_STREAMS
));
ctrl_send
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Invalid stream count"));
}
let mut duration = Duration::from_secs(duration_secs as u64);
// Handle infinite duration (0) - apply server max if set
if duration == Duration::ZERO {
if let Some(max_dur) = server_max_duration {
duration = max_dur;
warn!(
"Infinite duration requested, capped to server max {}s",
max_dur.as_secs()
);
}
// else: allow infinite if no server max
} else {
if duration > MAX_TEST_DURATION {
duration = MAX_TEST_DURATION;
}
if let Some(max_dur) = server_max_duration
&& duration > max_dur
{
duration = max_dur;
}
}
let duration_display = if duration == Duration::ZERO {
"∞".to_string()
} else {
format!("{}s", duration.as_secs())
};
info!(
"QUIC test requested: {} streams, {} mode, {}",
streams, direction, duration_display
);
// Send test ack (no data ports for QUIC - streams are multiplexed)
let ack = ControlMessage::TestAck {
id: id.clone(),
data_ports: vec![], // Empty for QUIC
};
ctrl_send
.write_all(format!("{}\n", ack.serialize()?).as_bytes())
.await?;
// Run QUIC test
run_quic_test(
&connection,
ctrl_reader,
ctrl_send,
&id,
streams,
duration,
direction,
active_tests,
peer_addr,
security.tui_tx.clone(),
&security.push_gateway_url,
)
.await?;
}
_ => {
let error = ControlMessage::error("Expected test_start message");
ctrl_send
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Expected test_start"));
}
}
Ok(())
}
/// Handle client with pre-read first message (Hello already parsed in route_connection)
async fn handle_client_with_first_message(
stream: TcpStream,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
_base_port: u16,
server_max_duration: Option<Duration>,
security: &SecurityContext,
first_msg: ControlMessage,
) -> anyhow::Result<()> {
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
let mut line = String::new();
// Process pre-read Hello message
let (auth_nonce, client_capabilities) = match first_msg {
ControlMessage::Hello {
version,
capabilities,
..
} => {
if !versions_compatible(&version, PROTOCOL_VERSION) {
let error = ControlMessage::error(format!(
"Incompatible protocol version: {} (server: {})",
version, PROTOCOL_VERSION
));
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Protocol version mismatch"));
}
// Send server hello (with auth challenge if required)
if security.psk.is_some() {
let nonce = auth::generate_nonce();
let hello = ControlMessage::server_hello_with_auth(nonce.clone());
writer
.write_all(format!("{}\n", hello.serialize()?).as_bytes())
.await?;
(Some(nonce), capabilities)
} else {
let hello = ControlMessage::server_hello();
writer
.write_all(format!("{}\n", hello.serialize()?).as_bytes())
.await?;
(None, capabilities)
}
}
_ => {
return Err(anyhow::anyhow!("Expected Hello message"));
}
};
// Handle auth response if needed
if let Some(nonce) = auth_nonce {
tokio::time::timeout(HANDSHAKE_TIMEOUT, read_bounded_line(&mut reader, &mut line))
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout waiting for auth"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::AuthResponse { response } => {
let psk = security.psk.as_ref().ok_or_else(|| {
anyhow::anyhow!("PSK required for authentication but not configured")
})?;
if !auth::verify_response(&nonce, psk, &response) {
if let Some(tx) = &security.tui_tx {
let _ = tx.try_send(ServerEvent::AuthFailure);
}
let error = ControlMessage::error("Authentication failed");
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Authentication failed"));
}
let success = ControlMessage::auth_success();
writer
.write_all(format!("{}\n", success.serialize()?).as_bytes())
.await?;
}
_ => {
let error = ControlMessage::error("Expected auth response");
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Expected auth response"));
}
}
}
// Determine if client supports single-port TCP
let client_supports_single_port = client_capabilities
.as_ref()
.is_some_and(|caps| caps.iter().any(|c| c == "single_port_tcp"));
// Continue with test handling
handle_test_request(
&mut reader,
&mut writer,
peer_addr,
active_tests,
server_max_duration,
security,
client_supports_single_port,
)
.await
}
/// Handle client with authentication (for plain TCP)
#[allow(dead_code)]
async fn handle_client_with_auth(
stream: TcpStream,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
_base_port: u16,
server_max_duration: Option<Duration>,
security: &SecurityContext,
) -> anyhow::Result<()> {
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
let mut line = String::new();
// Perform authentication handshake
let auth_nonce = perform_auth_handshake(&mut reader, &mut writer, security).await?;
// If auth was required, verify the response
if let Some(nonce) = auth_nonce {
tokio::time::timeout(HANDSHAKE_TIMEOUT, read_bounded_line(&mut reader, &mut line))
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout waiting for auth"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::AuthResponse { response } => {
let psk = security.psk.as_ref().ok_or_else(|| {
anyhow::anyhow!("PSK required for authentication but not configured")
})?;
if !auth::verify_response(&nonce, psk, &response) {
if let Some(tx) = &security.tui_tx {
let _ = tx.try_send(ServerEvent::AuthFailure);
}
let error = ControlMessage::error("Authentication failed");
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Authentication failed"));
}
// Send auth success
let success = ControlMessage::auth_success();
writer
.write_all(format!("{}\n", success.serialize()?).as_bytes())
.await?;
}
_ => {
let error = ControlMessage::error("Expected auth response");
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Expected auth response"));
}
}
}
// Continue with normal test handling
// Note: dead code path - assumes single-port capable client
handle_test_request(
&mut reader,
&mut writer,
peer_addr,
active_tests,
server_max_duration,
security,
true,
)
.await
}
/// Perform authentication handshake, returns nonce if auth was required
#[allow(dead_code)]
async fn perform_auth_handshake<W: tokio::io::AsyncWrite + Unpin>(
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
writer: &mut W,
security: &SecurityContext,
) -> anyhow::Result<Option<String>> {
let mut line = String::new();
// Read client hello (with timeout)
tokio::time::timeout(HANDSHAKE_TIMEOUT, read_bounded_line(reader, &mut line))
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout waiting for hello"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::Hello { version, .. } => {
if !versions_compatible(&version, PROTOCOL_VERSION) {
let error = ControlMessage::error(format!(
"Incompatible protocol version: {} (server: {})",
version, PROTOCOL_VERSION
));
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Protocol version mismatch"));
}
// Send server hello (with auth challenge if required)
if security.psk.is_some() {
let nonce = auth::generate_nonce();
let hello = ControlMessage::server_hello_with_auth(nonce.clone());
writer
.write_all(format!("{}\n", hello.serialize()?).as_bytes())
.await?;
Ok(Some(nonce))
} else {
let hello = ControlMessage::server_hello();
writer
.write_all(format!("{}\n", hello.serialize()?).as_bytes())
.await?;
Ok(None)
}
}
_ => {
let error = ControlMessage::error("Expected hello message");
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
Err(anyhow::anyhow!("Expected hello message"))
}
}
}
/// Handle test request after authentication
async fn handle_test_request(
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
writer: &mut tokio::net::tcp::OwnedWriteHalf,
peer_addr: SocketAddr,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
server_max_duration: Option<Duration>,
security: &SecurityContext,
client_supports_single_port: bool,
) -> anyhow::Result<()> {
let mut line = String::new();
// Read test request (with timeout)
tokio::time::timeout(HANDSHAKE_TIMEOUT, read_bounded_line(reader, &mut line))
.await
.map_err(|_| anyhow::anyhow!("Handshake timeout waiting for test start"))??;
let msg: ControlMessage = ControlMessage::deserialize(line.trim())?;
match msg {
ControlMessage::TestStart {
id,
protocol,
streams,
duration_secs,
direction,
bitrate,
congestion,
} => {
// Validate stream count
if streams == 0 || streams > MAX_STREAMS {
let error = ControlMessage::error(format!(
"Invalid stream count {} (must be 1-{})",
streams, MAX_STREAMS
));
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Invalid stream count"));
}
// Calculate effective duration
let mut duration = Duration::from_secs(duration_secs as u64);
// Handle infinite duration (0) - apply server max if set
if duration == Duration::ZERO {
if let Some(max_dur) = server_max_duration {
duration = max_dur;
warn!(
"Infinite duration requested, capped to server max {}s",
max_dur.as_secs()
);
}
// else: allow infinite if no server max
} else {
if duration > MAX_TEST_DURATION {
duration = MAX_TEST_DURATION;
warn!(
"Client requested {}s, capped to {}s",
duration_secs,
MAX_TEST_DURATION.as_secs()
);
}
if let Some(max_dur) = server_max_duration
&& duration > max_dur
{
duration = max_dur;
warn!(
"Client requested {}s, capped to server max {}s",
duration_secs,
max_dur.as_secs()
);
}
}
// Validate congestion control algorithm (TCP only)
if protocol == Protocol::Tcp
&& let Some(ref algo) = congestion
&& let Err(e) = tcp::validate_congestion(algo)
{
let error = ControlMessage::error(format!(
"Unsupported congestion control algorithm '{}': {}",
algo, e
));
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
return Err(anyhow::anyhow!("Invalid congestion algorithm"));
}
let duration_display = if duration == Duration::ZERO {
"∞".to_string()
} else {
format!("{}s", duration.as_secs())
};
info!(
"Test requested: {} {} streams, {} mode, {}",
protocol, streams, direction, duration_display
);
// Run the actual test
let result = run_test(
reader,
writer,
&id,
protocol,
streams,
duration,
direction,
bitrate,
congestion,
active_tests.clone(),
security.address_family,
peer_addr,
security.tui_tx.clone(),
&security.push_gateway_url,
client_supports_single_port,
)
.await;
result.map(|_| ())
}
_ => {
let error = ControlMessage::error("Expected test_start message");
writer
.write_all(format!("{}\n", error.serialize()?).as_bytes())
.await?;
Err(anyhow::anyhow!("Expected test_start"))
}
}
}
/// Run a QUIC bandwidth test
#[allow(clippy::too_many_arguments)]
async fn run_quic_test(
connection: &quinn::Connection,
mut ctrl_reader: BufReader<quinn::RecvStream>,
mut ctrl_send: quinn::SendStream,
id: &str,
streams: u8,
duration: Duration,
direction: Direction,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
peer_addr: SocketAddr,
tui_tx: Option<mpsc::Sender<ServerEvent>>,
push_gateway_url: &Option<String>,
) -> anyhow::Result<()> {
// Create test stats
let stats = Arc::new(TestStats::new(id.to_string(), streams));
let (cancel_tx, cancel_rx) = watch::channel(false);
let (pause_tx, pause_rx) = watch::channel(false);
// Store active test
{
let mut tests = active_tests.lock().await;
tests.insert(
id.to_string(),
ActiveTest {
stats: stats.clone(),
cancel_tx,
pause_tx,
data_ports: vec![],
data_stream_tx: None,
control_peer_ip: peer_addr.ip(),
},
);
}
// Notify TUI
if let Some(tx) = &tui_tx {
let _ = tx.try_send(ServerEvent::TestStarted(ActiveTestInfo {
id: id.to_string(),
client_ip: peer_addr.ip(),
protocol: "QUIC".to_string(),
direction: direction.to_string(),
streams,
started: std::time::Instant::now(),
duration_secs: duration.as_secs() as u32,
bytes: 0,
throughput_mbps: 0.0,
}));
}
#[cfg(feature = "prometheus")]
crate::output::prometheus::on_test_start();
// Spawn data stream handlers
let mut handles = Vec::new();
for i in 0..streams {
let stream_stats = stats.streams[i as usize].clone();
let cancel = cancel_rx.clone();
let pause = pause_rx.clone();
let conn = connection.clone();
let handle = tokio::spawn(async move {
match direction {
Direction::Upload => {
// Server receives - accept uni stream from client with timeout
let mut cancel_rx = cancel.clone();
let accept_result = tokio::select! {
result = conn.accept_uni() => result.ok(),
_ = tokio::time::sleep(HANDSHAKE_TIMEOUT) => {
debug!("Timeout waiting for client to open uni stream");
None
}
_ = cancel_rx.changed() => {
debug!("Cancelled while waiting for uni stream");
None
}
};
if let Some(recv) = accept_result
&& let Err(e) = quic::receive_quic_data(recv, stream_stats, cancel).await
{
debug!("QUIC receive ended: {}", e);
}
}
Direction::Download => {
// Server sends - open uni stream to client
match conn.open_uni().await {
Ok(send) => {
if let Err(e) =
quic::send_quic_data(send, stream_stats, duration, cancel, pause)
.await
{
debug!("QUIC send ended: {}", e);
}
}
Err(e) => debug!("Failed to open uni stream: {}", e),
}
}
Direction::Bidir => {
// Accept bidir stream from client with timeout
let mut cancel_rx = cancel.clone();
let accept_result = tokio::select! {
result = conn.accept_bi() => result.ok(),
_ = tokio::time::sleep(HANDSHAKE_TIMEOUT) => {
debug!("Timeout waiting for client to open bi stream");
None
}
_ = cancel_rx.changed() => {
debug!("Cancelled while waiting for bi stream");
None
}
};
if let Some((send, recv)) = accept_result {
let send_stats = stream_stats.clone();
let recv_stats = stream_stats;
let send_cancel = cancel.clone();
let recv_cancel = cancel;
let send_pause = pause;
let send_handle = tokio::spawn(async move {
let _ = quic::send_quic_data(
send,
send_stats,
duration,
send_cancel,
send_pause,
)
.await;
});
let recv_handle = tokio::spawn(async move {
let _ = quic::receive_quic_data(recv, recv_stats, recv_cancel).await;
});
let _ = tokio::join!(send_handle, recv_handle);
}
}
}
});
handles.push(handle);
}
// Send interval updates
let mut interval_timer = tokio::time::interval(STATS_INTERVAL);
let start = std::time::Instant::now();
let mut line = String::new();
loop {
tokio::select! {
_ = interval_timer.tick() => {
// Duration::ZERO means infinite - only break if duration is set
if duration != Duration::ZERO && start.elapsed() >= duration {
break;
}
let intervals = stats.record_intervals();
let stream_intervals: Vec<StreamInterval> = stats.streams.iter()
.zip(intervals.iter())
.map(|(s, i)| s.to_interval(i))
.collect();
let aggregate = stats.to_aggregate(&intervals);
let interval_msg = ControlMessage::Interval {
id: id.to_string(),
elapsed_ms: stats.elapsed_ms(),
streams: stream_intervals,
aggregate: aggregate.clone(),
};
if let Some(tx) = &tui_tx {
let _ = tx.try_send(ServerEvent::TestUpdated {
id: id.to_string(),
bytes: aggregate.bytes,
throughput_mbps: aggregate.throughput_mbps,
});
}
if ctrl_send.write_all(format!("{}\n", interval_msg.serialize()?).as_bytes()).await.is_err() {
warn!("Failed to send interval");
break;
}
}
}
// Check for cancel message (non-blocking, bounded read)
let read_result = tokio::time::timeout(
CANCEL_CHECK_TIMEOUT,
read_bounded_line(&mut ctrl_reader, &mut line),
)
.await;
if let Ok(Ok(n)) = read_result
&& n > 0
{
match ControlMessage::deserialize(line.trim()) {
Ok(ControlMessage::Cancel {
id: cancel_id,
reason,
}) if cancel_id == id => {
info!("QUIC test {} cancelled: {}", id, reason);
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.cancel_tx.send(true);
}
let cancelled = ControlMessage::Cancelled { id: id.to_string() };
ctrl_send
.write_all(format!("{}\n", cancelled.serialize()?).as_bytes())
.await?;
break;
}
Ok(ControlMessage::Pause { id: pause_id }) if pause_id == id => {
info!("QUIC test {} paused", id);
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.pause_tx.send(true);
}
}
Ok(ControlMessage::Resume { id: resume_id }) if resume_id == id => {
info!("QUIC test {} resumed", id);
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.pause_tx.send(false);
}
}
_ => {}
}
}
}
// Signal handlers to stop
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.cancel_tx.send(true);
}
// Wait for handlers to complete
let results = futures::future::join_all(handles).await;
for result in results {
if let Err(e) = result
&& e.is_panic()
{
error!("QUIC stream handler panicked: {:?}", e);
}
}
// Send final result
let duration_ms = stats.elapsed_ms();
let bytes_total = stats.total_bytes();
let throughput_mbps = if duration_ms > 0 {
(bytes_total as f64 * 8.0) / (duration_ms as f64 / 1000.0) / 1_000_000.0
} else {
0.0
};
let stream_results: Vec<_> = stats
.streams
.iter()
.map(|s| s.to_result(duration_ms))
.collect();
let result = ControlMessage::Result(TestResult {
id: id.to_string(),
bytes_total,
duration_ms,
throughput_mbps,
streams: stream_results,
tcp_info: None,
udp_stats: None,
});
ctrl_send
.write_all(format!("{}\n", result.serialize()?).as_bytes())
.await?;
// Finish the control stream to ensure result is sent
ctrl_send.finish()?;
// Give client time to receive the result before connection closes
tokio::time::sleep(RESULT_FLUSH_DELAY).await;
#[cfg(feature = "prometheus")]
crate::output::prometheus::on_test_complete(&stats);
// Push metrics to gateway if configured
crate::output::push_gateway::maybe_push_metrics(push_gateway_url, &stats).await;
if let Some(tx) = &tui_tx {
let _ = tx.try_send(ServerEvent::TestCompleted {
id: id.to_string(),
bytes: bytes_total,
});
}
active_tests.lock().await.remove(id);
info!(
"QUIC test {} complete: {:.2} Mbps, {} bytes",
id, throughput_mbps, bytes_total
);
Ok(())
}
/// Run the actual bandwidth test
#[allow(clippy::too_many_arguments)]
async fn run_test(
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
writer: &mut tokio::net::tcp::OwnedWriteHalf,
id: &str,
protocol: Protocol,
streams: u8,
duration: Duration,
direction: Direction,
bitrate: Option<u64>,
congestion: Option<String>,
active_tests: Arc<Mutex<HashMap<String, ActiveTest>>>,
address_family: AddressFamily,
peer_addr: SocketAddr,
tui_tx: Option<mpsc::Sender<ServerEvent>>,
push_gateway_url: &Option<String>,
client_supports_single_port: bool,
) -> anyhow::Result<(u64, u64, f64)> {
let mut line = String::new();
// For TCP: single-port mode (data connections come on control port)
// For UDP: allocate per-stream sockets
let mut data_ports = Vec::new();
let mut udp_sockets: Vec<Arc<UdpSocket>> = Vec::new();
// Create cancel channel early so fallback listeners can use it
let (cancel_tx, cancel_rx) = watch::channel(false);
let (pause_tx, pause_rx) = watch::channel(false);
let (data_stream_tx, data_stream_rx) = match protocol {
Protocol::Tcp if client_supports_single_port => {
// Single-port mode: data connections will be routed via channel
let (tx, rx) = mpsc::channel::<(TcpStream, u16)>(streams as usize);
(Some(tx), Some(rx))
}
Protocol::Tcp => {
// Multi-port fallback for legacy clients without single_port_tcp capability
let (tx, rx) = mpsc::channel::<(TcpStream, u16)>(streams as usize);
let expected_ip = net::normalize_ip(peer_addr.ip());
for i in 0..streams {
let listener = net::create_tcp_listener(0, address_family).await?;
data_ports.push(listener.local_addr()?.port());
debug!(
"TCP data port {} allocated for stream {}",
data_ports.last().unwrap(),
i
);
let tx = tx.clone();
let stream_index = i as u16;
let mut cancel = cancel_rx.clone();
tokio::spawn(async move {
// Use select! with cancel to avoid leaking listener tasks
let accept_result = tokio::select! {
result = listener.accept() => result,
_ = cancel.changed() => return,
};
match accept_result {
Ok((stream, data_peer)) => {
// Validate peer IP matches control connection
let actual_ip = net::normalize_ip(data_peer.ip());
if actual_ip != expected_ip {
warn!(
"Multi-port data connection from unauthorized IP {} (expected {})",
data_peer.ip(),
expected_ip
);
return;
}
let _ = tx.send((stream, stream_index)).await;
}
Err(e) => {
warn!("Failed to accept on data port: {}", e);
}
}
});
}
// Don't store tx in active_tests since we don't need DataHello routing
(None, Some(rx))
}
Protocol::Udp => {
for _ in 0..streams {
let socket = net::create_udp_socket(0, address_family).await?;
data_ports.push(socket.local_addr()?.port());
debug!("UDP port {} allocated", data_ports.last().unwrap());
udp_sockets.push(Arc::new(socket));
}
(None, None)
}
Protocol::Quic => {
// QUIC uses its own connection model with multiplexed streams
return Err(anyhow::anyhow!(
"QUIC protocol requires QUIC endpoint, not TCP control"
));
}
};
// Create test stats
let stats = Arc::new(TestStats::new(id.to_string(), streams));
// Store active test BEFORE sending TestAck to avoid race condition
// (client may send DataHello immediately after receiving TestAck)
{
let mut tests = active_tests.lock().await;
tests.insert(
id.to_string(),
ActiveTest {
stats: stats.clone(),
cancel_tx,
pause_tx,
data_ports: data_ports.clone(),
data_stream_tx,
control_peer_ip: peer_addr.ip(),
},
);
}
// Send test ack with allocated ports
let ack = ControlMessage::TestAck {
id: id.to_string(),
data_ports: data_ports.clone(),
};
writer
.write_all(format!("{}\n", ack.serialize()?).as_bytes())
.await?;
// Notify TUI that test started
if let Some(tx) = &tui_tx {
let _ = tx.try_send(ServerEvent::TestStarted(ActiveTestInfo {
id: id.to_string(),
client_ip: peer_addr.ip(),
protocol: protocol.to_string(),
direction: direction.to_string(),
streams,
started: std::time::Instant::now(),
duration_secs: duration.as_secs() as u32,
bytes: 0,
throughput_mbps: 0.0,
}));
}
// Notify metrics that test started
#[cfg(feature = "prometheus")]
crate::output::prometheus::on_test_start();
// Spawn data stream handlers
// For TCP: spawn stream collection in background to not block interval loop
// For UDP: handlers are spawned immediately
let (tcp_collection_handle, udp_handles) = match protocol {
Protocol::Tcp => {
// Single-port mode: spawn stream collection in background
// This allows interval loop and cancel handling to run while waiting for streams
if let Some(rx) = data_stream_rx {
let stats_clone = stats.clone();
let cancel_clone = cancel_rx.clone();
let pause_clone = pause_rx.clone();
let handle = tokio::spawn(async move {
spawn_tcp_stream_handlers(
rx,
streams as usize,
stats_clone,
direction,
duration,
cancel_clone,
congestion.clone(),
bitrate,
pause_clone,
)
.await
});
(Some(handle), Vec::new())
} else {
(None, Vec::new())
}
}
Protocol::Udp => {
let handles = spawn_udp_handlers(
udp_sockets,
stats.clone(),
direction,
duration,
bitrate.unwrap_or(DEFAULT_BITRATE_BPS),
cancel_rx.clone(),
pause_rx.clone(),
)
.await;
(None, handles)
}
Protocol::Quic => {
// Unreachable - QUIC returns early above
(None, Vec::new())
}
};
// Start interval loop IMMEDIATELY (don't wait for TCP stream collection)
let mut interval_timer = tokio::time::interval(STATS_INTERVAL);
let start = std::time::Instant::now();
loop {
tokio::select! {
_ = interval_timer.tick() => {
// Duration::ZERO means infinite - only break if duration is set
if duration != Duration::ZERO && start.elapsed() >= duration {
break;
}
let intervals = stats.record_intervals();
let stream_intervals: Vec<StreamInterval> = stats.streams.iter()
.zip(intervals.iter())
.map(|(s, i)| s.to_interval(i))
.collect();
let aggregate = stats.to_aggregate(&intervals);
let interval_msg = ControlMessage::Interval {
id: id.to_string(),
elapsed_ms: stats.elapsed_ms(),
streams: stream_intervals,
aggregate: aggregate.clone(),
};
// Notify TUI of progress
if let Some(tx) = &tui_tx {
let _ = tx.try_send(ServerEvent::TestUpdated {
id: id.to_string(),
bytes: aggregate.bytes,
throughput_mbps: aggregate.throughput_mbps,
});
}
if writer.write_all(format!("{}\n", interval_msg.serialize()?).as_bytes()).await.is_err() {
warn!("Failed to send interval, client may have disconnected");
break;
}
}
}
// Check for cancel/pause/resume messages (bounded read)
let read_result =
tokio::time::timeout(CANCEL_CHECK_TIMEOUT, read_bounded_line(reader, &mut line)).await;
if let Ok(Ok(n)) = read_result
&& n > 0
{
match ControlMessage::deserialize(line.trim()) {
Ok(ControlMessage::Cancel {
id: cancel_id,
reason,
}) if cancel_id == id => {
info!("Test {} cancelled: {}", id, reason);
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.cancel_tx.send(true);
}
let cancelled = ControlMessage::Cancelled { id: id.to_string() };
writer
.write_all(format!("{}\n", cancelled.serialize()?).as_bytes())
.await?;
break;
}
Ok(ControlMessage::Pause { id: pause_id }) if pause_id == id => {
info!("Test {} paused", id);
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.pause_tx.send(true);
}
}
Ok(ControlMessage::Resume { id: resume_id }) if resume_id == id => {
info!("Test {} resumed", id);
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.pause_tx.send(false);
}
}
_ => {}
}
}
}
// Signal handlers to stop
if let Some(test) = active_tests.lock().await.get(id) {
let _ = test.cancel_tx.send(true);
}
// Wait for all data handlers to complete
match (tcp_collection_handle, udp_handles) {
(Some(handle), _) => {
// TCP: wait for stream collection task, then wait for individual handlers
match handle.await {
Ok(tcp_handles) => {
let results = futures::future::join_all(tcp_handles).await;
for result in results {
if let Err(e) = result
&& e.is_panic()
{
error!("TCP stream handler panicked: {:?}", e);
}
}
}
Err(e) => {
if e.is_panic() {
error!("TCP stream collection task panicked: {:?}", e);
} else {
warn!("TCP stream collection task was cancelled");
}
}
}
}
(None, handles) if !handles.is_empty() => {
// UDP/QUIC: wait for handlers directly
let results = futures::future::join_all(handles).await;
for result in results {
if let Err(e) = result
&& e.is_panic()
{
error!("UDP/QUIC stream handler panicked: {:?}", e);
}
}
}
_ => {}
}
// Send final result
let duration_ms = stats.elapsed_ms();
let bytes_total = stats.total_bytes();
let throughput_mbps = if duration_ms > 0 {
(bytes_total as f64 * 8.0) / (duration_ms as f64 / 1000.0) / 1_000_000.0
} else {
0.0
};
let stream_results: Vec<_> = stats
.streams
.iter()
.map(|s| s.to_result(duration_ms))
.collect();
let result = ControlMessage::Result(TestResult {
id: id.to_string(),
bytes_total,
duration_ms,
throughput_mbps,
streams: stream_results,
tcp_info: stats.get_tcp_info(),
udp_stats: stats.aggregate_udp_stats(),
});
// Cleanup active test entry BEFORE sending result
// This ensures cleanup happens even if the write fails
active_tests.lock().await.remove(id);
// Notify metrics that test completed
#[cfg(feature = "prometheus")]
crate::output::prometheus::on_test_complete(&stats);
// Push metrics to gateway if configured
crate::output::push_gateway::maybe_push_metrics(push_gateway_url, &stats).await;
// Notify TUI that test completed
if let Some(tx) = &tui_tx {
let _ = tx.try_send(ServerEvent::TestCompleted {
id: id.to_string(),
bytes: bytes_total,
});
}
// Send result (after cleanup so stale entries don't persist on failure)
writer
.write_all(format!("{}\n", result.serialize()?).as_bytes())
.await?;
info!(
"Test {} complete: {:.2} Mbps, {} bytes",
id, throughput_mbps, bytes_total
);
Ok((bytes_total, duration_ms, throughput_mbps))
}
/// Read a line with bounded length to prevent memory DoS
async fn read_bounded_line<R: tokio::io::AsyncBufRead + Unpin>(
reader: &mut R,
buf: &mut String,
) -> anyhow::Result<usize> {
buf.clear();
let mut total = 0;
loop {
let bytes = reader.fill_buf().await?;
if bytes.is_empty() {
return Ok(total);
}
if let Some(newline_pos) = bytes.iter().position(|&b| b == b'\n') {
let to_read = newline_pos + 1;
if total + to_read > MAX_LINE_LENGTH {
return Err(anyhow::anyhow!("Line exceeds maximum length"));
}
// Use lossy conversion to handle partial UTF-8 sequences at buffer boundaries
buf.push_str(&String::from_utf8_lossy(&bytes[..to_read]));
reader.consume(to_read);
return Ok(total + to_read);
}
let len = bytes.len();
if total + len > MAX_LINE_LENGTH {
return Err(anyhow::anyhow!("Line exceeds maximum length"));
}
// Use lossy conversion to handle partial UTF-8 sequences at buffer boundaries
buf.push_str(&String::from_utf8_lossy(bytes));
reader.consume(len);
total += len;
}
}
/// Legacy multi-port TCP handler (kept for potential fallback)
#[allow(dead_code, clippy::too_many_arguments)]
async fn spawn_tcp_handlers(
listeners: Vec<TcpListener>,
stats: Arc<TestStats>,
direction: Direction,
duration: Duration,
cancel: watch::Receiver<bool>,
congestion: Option<String>,
bitrate: Option<u64>,
pause: watch::Receiver<bool>,
) -> Vec<JoinHandle<()>> {
let num_streams = listeners.len().max(1) as u64;
let per_stream_bitrate = bitrate.map(|b| if b == 0 { 0 } else { (b / num_streams).max(1) });
let mut handles = Vec::new();
for (i, listener) in listeners.into_iter().enumerate() {
let cancel = cancel.clone();
let pause = pause.clone();
let stream_stats = stats.streams[i].clone();
let test_stats = stats.clone();
let congestion = congestion.clone();
let handle = tokio::spawn(async move {
// Timeout on accept to prevent blocking forever if client never connects
let accept_result =
tokio::time::timeout(STREAM_ACCEPT_TIMEOUT, listener.accept()).await;
let stream = match accept_result {
Ok(Ok((stream, _))) => stream,
Ok(Err(e)) => {
warn!("Accept error: {}", e);
return;
}
Err(_) => {
warn!("Accept timeout - client never connected to data port");
return;
}
};
// Use high-speed config for server - we want maximum throughput
let mut config = TcpConfig::high_speed();
config.congestion = congestion.clone();
// Store fd for TCP_INFO interval polling
#[cfg(unix)]
{
use std::os::unix::io::AsRawFd;
stream_stats.set_tcp_info_fd(stream.as_raw_fd());
}
// Capture TCP_INFO before transfer starts
if let Some(info) = tcp::get_stream_tcp_info(&stream) {
test_stats.add_tcp_info(info);
}
match direction {
Direction::Upload => {
// Server receives data
match tcp::receive_data(stream, stream_stats.clone(), cancel, config).await {
Ok(Some(info)) => test_stats.add_tcp_info(info),
Ok(None) => {}
Err(e) => tracing::warn!("Stream {} receive error: {}", i, e),
}
}
Direction::Download => {
// Server sends data - capture final TCP_INFO for RTT/retransmits
match tcp::send_data(
stream,
stream_stats.clone(),
duration,
config,
cancel,
per_stream_bitrate,
pause,
)
.await
{
Ok(Some(info)) => test_stats.add_tcp_info(info),
Ok(None) => {}
Err(e) => tracing::warn!("Stream {} send error: {}", i, e),
}
}
Direction::Bidir => {
// Configure socket BEFORE splitting (nodelay, window, buffers)
if let Err(e) = tcp::configure_stream(&stream, &config) {
tracing::error!("Failed to configure TCP socket: {}", e);
stream_stats.clear_tcp_info_fd();
return;
}
// Split socket for concurrent send/receive
let (read_half, write_half) = stream.into_split();
let send_stats = stream_stats.clone();
let recv_stats = stream_stats.clone();
let final_stats = stream_stats.clone();
let send_cancel = cancel.clone();
let recv_cancel = cancel;
let send_pause = pause;
let send_config = TcpConfig {
buffer_size: config.buffer_size,
nodelay: config.nodelay,
window_size: config.window_size,
congestion: config.congestion.clone(),
};
let recv_config = config;
let send_handle = tokio::spawn(async move {
tcp::send_data_half(
write_half,
send_stats,
duration,
send_config,
send_cancel,
per_stream_bitrate,
send_pause,
)
.await
});
let recv_handle = tokio::spawn(async move {
tcp::receive_data_half(read_half, recv_stats, recv_cancel, recv_config)
.await
});
// Wait for both to complete and reunite halves to get TCP_INFO
let (send_result, recv_result) = tokio::join!(send_handle, recv_handle);
if let (Ok(Ok(write_half)), Ok(Ok(read_half))) = (send_result, recv_result)
&& let Ok(stream) = read_half.reunite(write_half)
&& let Some(info) = tcp::get_stream_tcp_info(&stream)
{
final_stats.add_retransmits(info.retransmits);
test_stats.add_tcp_info(info);
}
}
}
// Clear fd to prevent stale fd reuse after stream closes
stream_stats.clear_tcp_info_fd();
});
handles.push(handle);
}
handles
}
/// Single-port TCP mode: receive streams from channel and spawn handlers
#[allow(clippy::too_many_arguments)]
async fn spawn_tcp_stream_handlers(
mut rx: mpsc::Receiver<(TcpStream, u16)>,
num_streams: usize,
stats: Arc<TestStats>,
direction: Direction,
duration: Duration,
cancel: watch::Receiver<bool>,
congestion: Option<String>,
bitrate: Option<u64>,
pause: watch::Receiver<bool>,
) -> Vec<JoinHandle<()>> {
let per_stream_bitrate = bitrate.map(|b| {
if b == 0 {
0
} else {
(b / num_streams as u64).max(1)
}
});
let mut handles = Vec::new();
let mut received = vec![false; num_streams];
let deadline = tokio::time::Instant::now() + STREAM_COLLECTION_TIMEOUT;
let mut cancel = cancel;
// Receive all expected streams from channel
while received.iter().any(|&r| !r) {
// Check cancel signal first
if *cancel.borrow() {
warn!("Test cancelled during stream collection");
break;
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
warn!("Timeout waiting for all data streams");
break;
}
// Use select! to check both stream arrival and cancel signal
let stream_result = tokio::select! {
biased;
result = cancel.changed() => {
match result {
Ok(()) if *cancel.borrow() => {
warn!("Test cancelled during stream collection");
break;
}
Ok(()) => continue,
Err(_) => {
warn!("Cancel channel closed during stream collection");
break;
}
}
}
result = tokio::time::timeout(remaining, rx.recv()) => result,
};
match stream_result {
Ok(Some((stream, stream_index))) => {
let i = stream_index as usize;
if i >= num_streams {
warn!("Invalid stream index: {}", stream_index);
continue;
}
if received[i] {
warn!("Duplicate stream index: {}", stream_index);
continue;
}
received[i] = true;
let cancel = cancel.clone();
let pause = pause.clone();
let stream_stats = stats.streams[i].clone();
let test_stats = stats.clone();
let congestion = congestion.clone();
let handle = tokio::spawn(async move {
let mut config = TcpConfig::high_speed();
config.congestion = congestion;
// Store fd for TCP_INFO interval polling
#[cfg(unix)]
{
use std::os::unix::io::AsRawFd;
stream_stats.set_tcp_info_fd(stream.as_raw_fd());
}
// Capture TCP_INFO before transfer starts
if let Some(info) = tcp::get_stream_tcp_info(&stream) {
test_stats.add_tcp_info(info);
}
match direction {
Direction::Upload => {
match tcp::receive_data(stream, stream_stats.clone(), cancel, config)
.await
{
Ok(Some(info)) => test_stats.add_tcp_info(info),
Ok(None) => {}
Err(e) => tracing::warn!("Stream {} receive error: {}", i, e),
}
}
Direction::Download => {
match tcp::send_data(
stream,
stream_stats.clone(),
duration,
config,
cancel,
per_stream_bitrate,
pause,
)
.await
{
Ok(Some(info)) => test_stats.add_tcp_info(info),
Ok(None) => {}
Err(e) => tracing::warn!("Stream {} send error: {}", i, e),
}
}
Direction::Bidir => {
if let Err(e) = tcp::configure_stream(&stream, &config) {
tracing::error!("Failed to configure TCP socket: {}", e);
stream_stats.clear_tcp_info_fd();
return;
}
let (read_half, write_half) = stream.into_split();
let send_stats = stream_stats.clone();
let recv_stats = stream_stats.clone();
let final_stats = stream_stats.clone();
let send_cancel = cancel.clone();
let recv_cancel = cancel;
let send_pause = pause;
let send_config = config.clone();
let recv_config = config;
let send_handle = tokio::spawn(async move {
tcp::send_data_half(
write_half,
send_stats,
duration,
send_config,
send_cancel,
per_stream_bitrate,
send_pause,
)
.await
});
let recv_handle = tokio::spawn(async move {
tcp::receive_data_half(
read_half,
recv_stats,
recv_cancel,
recv_config,
)
.await
});
let (send_result, recv_result) = tokio::join!(send_handle, recv_handle);
if let (Ok(Ok(write_half)), Ok(Ok(read_half))) =
(send_result, recv_result)
&& let Ok(stream) = read_half.reunite(write_half)
&& let Some(info) = tcp::get_stream_tcp_info(&stream)
{
final_stats.add_retransmits(info.retransmits);
test_stats.add_tcp_info(info);
}
}
}
// Clear fd to prevent stale fd reuse after stream closes
stream_stats.clear_tcp_info_fd();
});
handles.push(handle);
}
Ok(None) => {
warn!("Data stream channel closed");
break;
}
Err(_) => {
warn!("Timeout waiting for data stream");
break;
}
}
}
handles
}
async fn spawn_udp_handlers(
sockets: Vec<Arc<UdpSocket>>,
stats: Arc<TestStats>,
direction: Direction,
duration: Duration,
bitrate: u64,
cancel: watch::Receiver<bool>,
pause: watch::Receiver<bool>,
) -> Vec<JoinHandle<()>> {
let mut handles = Vec::new();
// Divide bitrate evenly across streams (matching client behavior)
// Clamp to at least 1 bps to prevent integer division underflow
// Only bitrate=0 means unlimited (explicit -b 0)
let num_streams = sockets.len().max(1) as u64;
let per_stream_bitrate = if bitrate == 0 {
0 // Unlimited mode (explicit -b 0)
} else {
(bitrate / num_streams).max(1)
};
for (i, socket) in sockets.into_iter().enumerate() {
let stream_stats = stats.streams[i].clone();
let test_stats = stats.clone();
let cancel = cancel.clone();
let pause = pause.clone();
let handle = tokio::spawn(async move {
match direction {
Direction::Upload => {
// Server receives UDP - capture stats
if let Ok((udp_stats, _bytes)) =
udp::receive_udp(socket, stream_stats, cancel, pause).await
{
test_stats.add_udp_stats(udp_stats);
}
}
Direction::Download => {
// Wait for client's hello packet to learn their address
match udp::wait_for_client(&socket, STREAM_ACCEPT_TIMEOUT).await {
Ok(client_addr) => {
// Server sends UDP at per-stream rate to client
let _ = udp::send_udp_paced(
socket,
Some(client_addr),
per_stream_bitrate,
duration,
stream_stats,
cancel,
pause,
)
.await;
}
Err(e) => {
warn!("UDP reverse: failed to get client address: {}", e);
}
}
}
Direction::Bidir => {
// Wait for client's first packet to learn their address
match udp::wait_for_client(&socket, STREAM_ACCEPT_TIMEOUT).await {
Ok(client_addr) => {
// UDP can send/receive concurrently on same socket
let send_socket = socket.clone();
let recv_socket = socket;
let send_stats = stream_stats.clone();
let recv_stats = stream_stats;
let send_cancel = cancel.clone();
let recv_cancel = cancel;
let send_pause = pause.clone();
let recv_pause = pause;
let test_stats_copy = test_stats.clone();
let send_handle = tokio::spawn(async move {
let _ = udp::send_udp_paced(
send_socket,
Some(client_addr),
per_stream_bitrate,
duration,
send_stats,
send_cancel,
send_pause,
)
.await;
});
let recv_handle = tokio::spawn(async move {
if let Ok((udp_stats, _bytes)) = udp::receive_udp(
recv_socket,
recv_stats,
recv_cancel,
recv_pause,
)
.await
{
test_stats_copy.add_udp_stats(udp_stats);
}
});
let _ = tokio::join!(send_handle, recv_handle);
}
Err(e) => {
warn!("UDP bidir: failed to get client address: {}", e);
}
}
}
}
});
handles.push(handle);
}
handles
}
/// Register mDNS service for server discovery
#[cfg(feature = "discovery")]
fn register_mdns_service(port: u16) -> Option<mdns_sd::ServiceDaemon> {
// Use the shared registration from discover module
match crate::discover::register_server(port) {
Ok(mdns) => Some(mdns),
Err(e) => {
warn!("Failed to register mDNS service: {}", e);
None
}
}
}