snare 1.4.0

Network communication testing library for rust
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
#![allow(dead_code)]

use std::{
    cell::RefCell,
    collections::{HashMap, HashSet, VecDeque},
    io,
    net::{IpAddr, SocketAddr},
    sync::{Arc, LazyLock},
    thread::ThreadId,
    time::{Duration, Instant},
    u32,
};

use anymap2::SendSyncAnyMap as AnyMap;
use event_listener::{Event, Listener};
use parking_lot::{Mutex, ReentrantMutex};

use crate::SocketType;
use crate::pcapng::PcapWriter;

/// Maps every test/child thread to its oldest known test-thread ancestor.
static TEST_THREAD_HIERARCHY: LazyLock<Mutex<HashMap<ThreadId, ThreadId>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

/// Per-test state slots, keyed by the root test thread.
static TEST_STATE: LazyLock<ReentrantMutex<RefCell<HashMap<TestThreadId, AnyMap>>>> =
    LazyLock::new(|| ReentrantMutex::new(RefCell::new(HashMap::new())));

/// Under `--cfg snare_global` every thread in the process funnels to this one
/// state slot instead of a per-test slot, so the whole process shares a single
/// in-memory network with no `register_test` / child-thread registration. The
/// slot is keyed by whichever thread resolves it first; the id is arbitrary —
/// the point is that every thread maps to the same key. For a long-running
/// single-process sim (driving real drivers against an in-process emulator),
/// not for isolated `#[test]`s, which want per-test isolation.
#[cfg(snare_global)]
static GLOBAL_SLOT_KEY: LazyLock<TestThreadId> =
    LazyLock::new(|| TestThreadId(std::thread::current().id()));

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct TestThreadId(ThreadId);

impl TestThreadId {
    fn of(id: ThreadId) -> Self {
        // Fast path: already registered.
        {
            let hierarchy = TEST_THREAD_HIERARCHY.lock();
            if hierarchy.contains_key(&id) {
                return Self::resolve_from(&hierarchy, id);
            }
        }
        // Slow path: poll until the parent registers us. The common case
        // resolves in a few ms; heavy CI contention gets up to GRACE_TOTAL.
        const GRACE_TOTAL: Duration = Duration::from_millis(2_000);
        const POLL_INTERVAL: Duration = Duration::from_millis(2);
        let deadline = std::time::Instant::now() + GRACE_TOTAL;
        loop {
            std::thread::sleep(POLL_INTERVAL);
            let hierarchy = TEST_THREAD_HIERARCHY.lock();
            if hierarchy.contains_key(&id) {
                return Self::resolve_from(&hierarchy, id);
            }
            if std::time::Instant::now() >= deadline {
                panic!(
                    "Thread {:?} not registered as test thread or child thread \
                     within {GRACE_TOTAL:?}",
                    id
                );
            }
        }
    }

    fn resolve_from(
        hierarchy: &parking_lot::lock_api::MutexGuard<
            '_,
            parking_lot::RawMutex,
            HashMap<ThreadId, ThreadId>,
        >,
        id: ThreadId,
    ) -> Self {
        let mut current_id = id;
        while let Some(parent_id) = hierarchy.get(&current_id) {
            if parent_id == &current_id {
                break;
            }
            current_id = *parent_id;
        }
        TestThreadId(current_id)
    }

    #[cfg(not(snare_global))]
    fn current() -> Self {
        Self::of(std::thread::current().id())
    }

    #[cfg(snare_global)]
    fn current() -> Self {
        *GLOBAL_SLOT_KEY
    }
}

/// Mark the current thread as the root of a fresh per-test state slot. Call
/// at the top of every `#[test]` that uses snare.
pub fn register_test() {
    let thread_name = std::thread::current().name().map(String::from);

    #[cfg(not(snare_global))]
    {
        let thread_id = std::thread::current().id();
        let mut map = TEST_THREAD_HIERARCHY.lock();
        map.insert(thread_id, thread_id);
        drop(map);
        let test_thread_id = TestThreadId(thread_id);
        TEST_STATE
            .lock()
            .borrow_mut()
            .insert(test_thread_id, AnyMap::new());
    }

    // Under `snare_global` there is one shared slot that auto-vivifies on first
    // access, so calling `register_test` is optional; just run pcap init, which
    // attaches to that shared slot via the `state!` macro.

    // pcap init is in a helper defined after the `state!` macro.
    pcap_init_for_test(thread_name);
}

/// Attach a spawned thread to the current test's state slot. Call from the
/// parent right after `std::thread::spawn(...)` (or use [`ThreadExt::register_as_child`](crate::ThreadExt::register_as_child)).
pub fn register_child_thread(child_thread_id: ThreadId) {
    #[cfg(snare_global)]
    let _ = child_thread_id;
    #[cfg(not(snare_global))]
    {
        let test_thread_id = TestThreadId::current();
        TEST_THREAD_HIERARCHY
            .lock()
            .insert(child_thread_id, test_thread_id.0);
    }
}

/// Variant of [`register_child_thread`] called from inside the spawned thread,
/// naming its parent's `ThreadId`.
pub fn register_thread_child_of(parent_thread_id: ThreadId) {
    #[cfg(snare_global)]
    let _ = parent_thread_id;
    #[cfg(not(snare_global))]
    {
        let child_thread_id = std::thread::current().id();
        TEST_THREAD_HIERARCHY
            .lock()
            .insert(child_thread_id, parent_thread_id);
    }
}

/// Begin pcapng capture for the current test. No-op unless `SNARE_PCAPNG_DIR`
/// is set in the environment. Already-enabled tests are unaffected.
pub fn enable_pcapng() {
    pcap_enable_for_current_test();
}

/// Resolve the current thread's state slot from a `&mut` borrow of the
/// `TEST_STATE` map. In isolated mode an unregistered thread is a hard error;
/// under `snare_global` every thread shares one slot that is created on demand.
#[cfg(not(snare_global))]
macro_rules! slot {
    ($borrow:ident) => {
        $borrow
            .get_mut(&TestThreadId::current())
            .expect("Not a valid test thread")
    };
}
#[cfg(snare_global)]
macro_rules! slot {
    ($borrow:ident) => {
        $borrow
            .entry(TestThreadId::current())
            .or_insert_with(AnyMap::new)
    };
}

macro_rules! state {
    ( $( $var:ident = $idx:ident $(? $default:expr)? );* $(;)? ) => {
        let mut __guard = TEST_STATE.lock();
        let mut __borrow = __guard.borrow_mut();
        let mut __any_map = slot!(__borrow);
        $(
            $(
                if !__any_map.contains::<Mutex<$idx>>() {
                    __any_map.insert::<Mutex<$idx>>(Mutex::new($default));
                }
            )*
        )*
        $(
            #[allow(unused)]
            let mut $var = __any_map.get::<Mutex<$idx>>()
                .expect("Failed to get state")
                .lock();
        )*
    };
}

// macro_rules! drop_all {
//     ( $( $var:ident ),* $(,)? ) => {
//         $(
//             drop($var);
//         )*
//     };
// }

type TcpConnections = HashMap<usize, TcpConnection>;
type TcpListeners = HashMap<SocketAddr, TcpListenerState>;
type UdpConnections = Vec<UdpConnection>;
type LocalPortsUsed = HashSet<SocketAddr>;
type ValidIpAddrs = HashSet<IpAddr>;
type Next = (usize, u16);
type NewDataEvent = Arc<Event>;
type Quiescence = HashMap<SocketAddr, QuiesceEntry>;
type TcpPolicies = HashMap<SocketAddr, TcpPolicy>;
type UdpPolicies = HashMap<SocketAddr, UdpPolicy>;
type ListenerBehaviors = HashMap<SocketAddr, ListenerBehavior>;
type RecordedEvents = Vec<RecordedEntry>;
type RngState = u64;

pub(crate) struct PcapState {
    pub writer: Option<PcapWriter>,
    pub test_name: Option<String>,
}

impl Default for PcapState {
    fn default() -> Self {
        Self {
            writer: None,
            test_name: None,
        }
    }
}

fn pcap_init_for_test(thread_name: Option<String>) {
    state!(pcap = PcapState ? PcapState::default());
    pcap.test_name = thread_name.clone();
    if let Some(name) = thread_name.as_deref() {
        if crate::pcapng::env_force_match(name) {
            pcap.writer = crate::pcapng::open_writer(name);
        }
    }
}

fn pcap_enable_for_current_test() {
    state!(pcap = PcapState ? PcapState::default());
    if pcap.writer.is_some() {
        return;
    }
    let name = pcap
        .test_name
        .clone()
        .or_else(|| std::thread::current().name().map(String::from));
    if let Some(name) = name {
        pcap.writer = crate::pcapng::open_writer(&name);
    }
}

#[inline]
fn with_pcap<F: FnOnce(&mut PcapWriter)>(f: F) {
    state!(pcap = PcapState ? PcapState::default());
    if let Some(w) = pcap.writer.as_mut() {
        f(w);
    }
}

pub(crate) fn pcap_tcp_open(client: SocketAddr, server: SocketAddr) {
    with_pcap(|w| w.tcp_open(client, server));
}

pub(crate) fn pcap_tcp_data(src: SocketAddr, dst: SocketAddr, data: &[u8]) {
    with_pcap(|w| w.tcp_data(src, dst, data));
}

pub(crate) fn pcap_tcp_fin(src: SocketAddr, dst: SocketAddr) {
    with_pcap(|w| w.tcp_fin(src, dst));
}

pub(crate) fn pcap_tcp_rst(src: SocketAddr, dst: SocketAddr) {
    with_pcap(|w| w.tcp_rst(src, dst));
}

pub(crate) fn pcap_udp(src: SocketAddr, dst: SocketAddr, data: &[u8]) {
    with_pcap(|w| w.udp_datagram(src, dst, data));
}

/// Which direction(s) a Quiesce window suppresses readiness in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuiesceMode {
    /// Both inbound (peer → SUT) and outbound (SUT → peer).
    Both,
    /// Inbound only — peer is "deaf"; SUT can still send.
    InboundOnly,
    /// Outbound only — SUT can read but its writes won't drain (stuck recv-window).
    OutboundOnly,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct QuiesceEntry {
    pub until: Instant,
    pub mode: QuiesceMode,
}

/// Per-link TCP policy applied to a SUT-side address.
#[derive(Debug, Default, Clone, Copy)]
pub struct TcpPolicy {
    /// Delay applied to bytes coming INTO this addr (peer → us).
    pub inbound_latency: Duration,
    /// Cap on the SUT-side incoming buffer. Writes back-pressure when full.
    pub recv_window: Option<usize>,
}

/// Per-socket UDP link policy.
#[derive(Debug, Default, Clone, Copy)]
pub struct UdpPolicy {
    /// Inbound latency (peer → us).
    pub inbound_latency: Duration,
    /// Per-packet drop probability in `[0, 1]`.
    pub loss_rate: f32,
    /// Per-packet duplicate probability in `[0, 1]`.
    pub duplicate_rate: f32,
    /// Extra per-packet random delay, uniform in `[0, jitter]`.
    pub reorder_jitter: Duration,
    /// Cap on the SUT's outbound queue. Sends return `WouldBlock` when full.
    pub send_queue_depth: Option<usize>,
    /// Max datagram size; oversized sends return `InvalidInput`.
    pub mtu: Option<usize>,
}

/// How a TCP listener responds to incoming `connect()` calls.
#[derive(Debug, Clone, Copy)]
pub enum ListenerBehavior {
    /// Accept immediately (default).
    Accepting,
    /// Refuse with `ECONNREFUSED`.
    Refusing,
    /// Reject connect attempts until `Instant`, then resume accepting.
    DelayingUntil(Instant),
}

/// An event captured by the per-test recording log. See [`recorded_events`].
#[derive(Debug, Clone)]
pub enum RecordedEvent {
    TcpSendFromTest {
        from: SocketAddr,
        to: SocketAddr,
        len: usize,
    },
    TcpResetFromTest {
        addr: SocketAddr,
    },
    TcpCloseFromTest {
        addr: SocketAddr,
    },
    UdpSendFromTest {
        from: SocketAddr,
        to: SocketAddr,
        len: usize,
        dropped: bool,
        duplicated: bool,
    },
    UdpCloseFromTest {
        addr: SocketAddr,
    },
    Quiesce {
        addr: SocketAddr,
        dur: Duration,
        mode: QuiesceMode,
    },
    SocketErrorFromTest {
        addr: SocketAddr,
        kind: io::ErrorKind,
    },
}

/// A timestamped [`RecordedEvent`].
#[derive(Debug, Clone)]
pub struct RecordedEntry {
    pub at: Instant,
    pub event: RecordedEvent,
}

static DEFAULT_VALID_IP_ADDRS: LazyLock<HashSet<IpAddr>> = LazyLock::new(|| {
    let mut valid_ip_addrs = HashSet::new();
    valid_ip_addrs.insert("0.0.0.0".parse().unwrap());
    valid_ip_addrs.insert("127.0.0.1".parse().unwrap());
    valid_ip_addrs.insert("::1".parse().unwrap());
    valid_ip_addrs.insert("::".parse().unwrap());
    valid_ip_addrs
});
static DEFAULT_NEXT: (usize, u16) = (0, 40_000);

#[derive(Debug)]
pub(crate) struct Packet {
    pub data: Vec<u8>,
    pub dest: SocketAddr,
    pub source: SocketAddr,
}

#[derive(Debug)]
pub(crate) struct UdpConnection {
    pub bound_addr: SocketAddr,
    pub from_local: VecDeque<Packet>,
    pub to_local: VecDeque<Packet>,
    /// Inbound packets waiting on latency / reorder jitter before joining `to_local`.
    pub pending_inbound: VecDeque<(Instant, Packet)>,
    pub failure_queue: Vec<io::Result<()>>,
    pub external_error: Option<io::Error>,
    pub is_destroyed: bool,
}

#[derive(Debug)]
pub(crate) struct TcpConnection {
    pub stream_id: usize,
    pub local_addr: SocketAddr,
    pub peer_addr: SocketAddr,
    pub incoming: VecDeque<u8>,
    /// Inbound chunks waiting on latency before joining `incoming`.
    pub pending_inbound: VecDeque<(Instant, Vec<u8>)>,
    pub read_shutdown: bool,
    pub write_shutdown: bool,
    pub failure_queue: Vec<io::Result<()>>,
    pub external_error: Option<io::Error>,
    pub peer_stream_id: Option<usize>,
    pub nonblocking: bool,
    pub nodelay: bool,
    pub ttl: u32,
    pub linger: Option<Duration>,
    pub read_timeout: Option<Duration>,
    pub write_timeout: Option<Duration>,
    pub ref_count: usize,
    pub owns_port: bool,
    pub is_destroyed: bool,
    /// Set by `TesterAction::ResetTcp`; surfaces `ECONNRESET` on the next read/write.
    pub reset_pending: bool,
}

#[derive(Debug)]
pub(crate) struct TcpListenerState {
    pub bound_addr: SocketAddr,
    pub pending_streams: VecDeque<usize>,
    pub nonblocking: bool,
    pub error: Option<io::Error>,
    pub is_closed: bool,
    pub ref_count: usize,
}

pub(crate) fn is_port_available(addr: SocketAddr) -> bool {
    state!(local_ports_used = LocalPortsUsed ? HashSet::new());
    !local_ports_used.contains(&addr)
}

/// Whitelist `ip` as a bindable address for this test. The default whitelist
/// covers `0.0.0.0`, `127.0.0.1`, `::`, and `::1`.
pub fn add_ip_addr(ip: IpAddr) {
    state!(valid_ip_addrs = ValidIpAddrs ? DEFAULT_VALID_IP_ADDRS.clone());
    valid_ip_addrs.insert(ip);
}

pub(crate) fn is_ip_addr_valid(ip: IpAddr) -> bool {
    state!(valid_ip_addrs = ValidIpAddrs ? DEFAULT_VALID_IP_ADDRS.clone());
    valid_ip_addrs.contains(&ip)
}

pub(crate) fn trigger_event() {
    state!(new_data_event = NewDataEvent ? Arc::new(Event::new()));
    new_data_event.notify(u32::MAX);
}

pub(crate) fn set_quiesce(addr: SocketAddr, until: Instant, mode: QuiesceMode) {
    {
        state!(quiesce = Quiescence ? HashMap::new());
        quiesce.insert(addr, QuiesceEntry { until, mode });
    }
    record(RecordedEvent::Quiesce {
        addr,
        dur: until.saturating_duration_since(Instant::now()),
        mode,
    });
}

/// Suppress mio readiness on `addr` (both directions) for `dur`. Bytes still
/// buffer; `Waker::wake()` still fires.
pub fn quiesce(addr: SocketAddr, dur: Duration) {
    set_quiesce(addr, Instant::now() + dur, QuiesceMode::Both);
}

/// [`quiesce`] with an explicit [`QuiesceMode`].
pub fn quiesce_with_mode(addr: SocketAddr, dur: Duration, mode: QuiesceMode) {
    set_quiesce(addr, Instant::now() + dur, mode);
}

/// Returns the active quiesce entry for `addr`, pruning if expired.
pub(crate) fn quiesce_entry(addr: SocketAddr) -> Option<QuiesceEntry> {
    state!(quiesce = Quiescence ? HashMap::new());
    let now = Instant::now();
    // Prune all expired entries; cheap because the map is usually tiny.
    quiesce.retain(|_, entry| entry.until > now);
    quiesce.get(&addr).copied()
}

pub(crate) fn is_quiesced_inbound(addr: SocketAddr) -> bool {
    matches!(
        quiesce_entry(addr),
        Some(QuiesceEntry {
            mode: QuiesceMode::Both | QuiesceMode::InboundOnly,
            ..
        })
    )
}

pub(crate) fn is_quiesced_outbound(addr: SocketAddr) -> bool {
    matches!(
        quiesce_entry(addr),
        Some(QuiesceEntry {
            mode: QuiesceMode::Both | QuiesceMode::OutboundOnly,
            ..
        })
    )
}

// ----- Policy helpers -----

/// Delay all inbound bytes for the SUT-side TCP `addr` by `latency`.
pub fn set_tcp_inbound_latency(addr: SocketAddr, latency: Duration) {
    state!(policies = TcpPolicies ? HashMap::new());
    policies.entry(addr).or_default().inbound_latency = latency;
}

/// Cap the SUT-side TCP receive buffer for `addr`. `None` removes the cap.
pub fn set_tcp_recv_window(addr: SocketAddr, window: Option<usize>) {
    state!(policies = TcpPolicies ? HashMap::new());
    policies.entry(addr).or_default().recv_window = window;
}

pub(crate) fn tcp_policy(addr: SocketAddr) -> TcpPolicy {
    state!(policies = TcpPolicies ? HashMap::new());
    policies.get(&addr).copied().unwrap_or_default()
}

/// Mutate the [`UdpPolicy`] for the socket bound at `addr`. The closure runs
/// against a default-initialized policy on first call.
pub fn set_udp_policy(addr: SocketAddr, policy_fn: impl FnOnce(&mut UdpPolicy)) {
    state!(policies = UdpPolicies ? HashMap::new());
    let entry = policies.entry(addr).or_default();
    policy_fn(entry);
}

pub(crate) fn udp_policy(addr: SocketAddr) -> UdpPolicy {
    state!(policies = UdpPolicies ? HashMap::new());
    policies.get(&addr).copied().unwrap_or_default()
}

/// Configure how the listener bound at `addr` responds to new connects.
pub fn set_listener_behavior(addr: SocketAddr, behavior: ListenerBehavior) {
    state!(behaviors = ListenerBehaviors ? HashMap::new());
    behaviors.insert(addr, behavior);
}

pub(crate) fn listener_behavior(addr: SocketAddr) -> ListenerBehavior {
    state!(behaviors = ListenerBehaviors ? HashMap::new());
    behaviors
        .get(&addr)
        .copied()
        .unwrap_or(ListenerBehavior::Accepting)
}

// ----- Port introspection -----

/// Returns the SUT-side local addr of the connection whose peer is `peer_addr`.
/// Lets tests target the SUT's ephemeral port without sending a discovery packet.
pub fn peek_local_addr_for_peer(peer_addr: SocketAddr) -> Option<SocketAddr> {
    state!(tcp_connections = TcpConnections ? HashMap::new());
    tcp_connections
        .values()
        .find(|c| c.peer_addr == peer_addr && !c.is_destroyed)
        .map(|c| c.local_addr)
}

// ----- Recording -----

pub(crate) fn record(event: RecordedEvent) {
    state!(log = RecordedEvents ? Vec::new());
    log.push(RecordedEntry {
        at: Instant::now(),
        event,
    });
}

/// Snapshot of the per-test event log, oldest first.
pub fn recorded_events() -> Vec<RecordedEntry> {
    state!(log = RecordedEvents ? Vec::new());
    log.clone()
}

/// Clear the per-test event log. Useful for scoping assertions to one phase.
pub fn clear_recorded_events() {
    state!(log = RecordedEvents ? Vec::new());
    log.clear();
}

// ----- RNG -----

static RNG_EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);

fn next_rand() -> u32 {
    // Tiny xorshift64 PRNG. Seeded lazily from a process-wide monotonic epoch
    // on first use; tests that want determinism can call `seed_rng` first.
    state!(rng = RngState ? {
        let nanos = RNG_EPOCH.elapsed().as_nanos() as u64;
        if nanos == 0 { 0xa5a5_a5a5_a5a5_a5a5 } else { nanos }
    });
    let mut x = *rng;
    if x == 0 {
        x = 0xa5a5_a5a5_a5a5_a5a5;
    }
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;
    *rng = x;
    (x as u32) ^ ((x >> 32) as u32)
}

fn rand_unit() -> f32 {
    (next_rand() as f32) / (u32::MAX as f32)
}

/// Seed the per-test RNG used for UDP loss / duplicate / reorder. Use for
/// deterministic policy tests.
pub fn seed_rng(seed: u64) {
    state!(rng = RngState ? 0);
    let s = if seed == 0 {
        0xa5a5_a5a5_a5a5_a5a5
    } else {
        seed
    };
    *rng = s;
}

// ----- Virtual clock (time-source shim) -----

/// Backing store for the [`snare::time`](crate::time) shim. One virtual clock
/// per state slot drives both `Instant` and `SystemTime`, so it resolves
/// through the same thread-chain hierarchy — and honours `--cfg snare_global`
/// — as every other piece of shim state.
///
/// The reading is `value = value_anchor + real_elapsed_since_anchor * rate`.
/// `Instant::now()` returns `value` (measured from the virtual epoch);
/// `SystemTime::now()` returns `wall_base + value`. `rate` is a non-negative
/// multiplier: `0` freezes the clock (paused), `1` tracks real time, `>1` runs
/// fast. A negative rate is rejected — it would let `now()` move backwards.
struct VirtualClock {
    real_anchor: Instant,
    value_anchor_nanos: u128,
    wall_base_nanos: u128,
    rate: f64,
}

impl VirtualClock {
    fn new() -> Self {
        let wall_base_nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        Self {
            real_anchor: Instant::now(),
            value_anchor_nanos: 0,
            wall_base_nanos,
            rate: 1.0,
        }
    }

    fn value_nanos(&self) -> u128 {
        let real = self.real_anchor.elapsed().as_nanos();
        // float->int casts saturate rather than wrap/UB, so a huge rate is safe.
        let scaled = (real as f64 * self.rate) as u128;
        self.value_anchor_nanos.saturating_add(scaled)
    }

    fn wall_nanos(&self) -> u128 {
        self.wall_base_nanos.saturating_add(self.value_nanos())
    }

    fn reanchor(&mut self) {
        self.value_anchor_nanos = self.value_nanos();
        self.real_anchor = Instant::now();
    }

    fn set_rate(&mut self, rate: f64) {
        assert!(
            rate.is_finite() && rate >= 0.0,
            "time rate must be finite and non-negative (got {rate}); a negative \
             rate would break the monotonicity of Instant::now()"
        );
        self.reanchor();
        self.rate = rate;
    }

    fn set_value_nanos(&mut self, nanos: u128) {
        self.reanchor();
        self.value_anchor_nanos = nanos;
    }
}

/// Per-slot notifier woken whenever the virtual clock is mutated (`rate` or
/// `value` change). Threads blocked in [`virtual_sleep`] listen on it so a
/// paused clock can be un-paused or advanced from another thread. A distinct
/// newtype rather than a reuse of [`NewDataEvent`] so socket traffic and clock
/// edits don't wake each other's waiters.
struct ClockEvent(Arc<Event>);

fn nanos_to_duration(nanos: u128) -> Duration {
    Duration::new(
        (nanos / 1_000_000_000) as u64,
        (nanos % 1_000_000_000) as u32,
    )
}

pub(crate) fn clock_mono_now() -> Duration {
    state!(clock = VirtualClock ? VirtualClock::new());
    nanos_to_duration(clock.value_nanos())
}

pub(crate) fn clock_wall_now() -> Duration {
    state!(clock = VirtualClock ? VirtualClock::new());
    nanos_to_duration(clock.wall_nanos())
}

/// Set how fast virtual time advances relative to real time: `1.0` tracks the
/// real clock, `0.0` pauses it (`Instant::now()` / `SystemTime::now()` stop
/// advancing), `>1.0` runs fast. Panics on a negative or non-finite rate — a
/// negative rate would violate the monotonicity of `Instant::now()`.
pub fn set_time_rate(rate: f64) {
    {
        state!(clock = VirtualClock ? VirtualClock::new());
        clock.set_rate(rate);
    }
    notify_clock_change();
}

/// The current virtual-time advance rate. See [`set_time_rate`].
pub fn time_rate() -> f64 {
    state!(clock = VirtualClock ? VirtualClock::new());
    clock.rate
}

/// Freeze virtual time. Equivalent to `set_time_rate(0.0)`.
pub fn pause_time() {
    set_time_rate(0.0);
}

/// Resume virtual time at real-time speed. Equivalent to `set_time_rate(1.0)`.
pub fn resume_time() {
    set_time_rate(1.0);
}

/// Set the clock's current value: the reading of `snare::time::Instant::now()`
/// measured from the virtual epoch, and the offset added to the wall base for
/// `SystemTime::now()`. Moving the value backwards breaks `Instant`
/// monotonicity, so only do it while the SUT holds no live `Instant`s.
pub fn set_time_value(value: Duration) {
    {
        state!(clock = VirtualClock ? VirtualClock::new());
        clock.set_value_nanos(value.as_nanos());
    }
    notify_clock_change();
}

/// The clock's current value — the elapsed virtual time reported by
/// `snare::time::Instant::now()` since the virtual epoch.
pub fn time_value() -> Duration {
    clock_mono_now()
}

/// Jump virtual time forward by `by`. Works regardless of rate, so it advances
/// the clock even while paused.
pub fn advance_time(by: Duration) {
    {
        state!(clock = VirtualClock ? VirtualClock::new());
        let advanced = clock.value_nanos().saturating_add(by.as_nanos());
        clock.set_value_nanos(advanced);
    }
    notify_clock_change();
}

fn clock_event() -> Arc<Event> {
    state!(clock_event = ClockEvent ? ClockEvent(Arc::new(Event::new())));
    clock_event.0.clone()
}

fn notify_clock_change() {
    clock_event().notify(u32::MAX);
}

/// Block the calling thread until the virtual clock advances by `dur`. Unlike
/// [`std::thread::sleep`] this honours the shim's time source: while the clock
/// is paused (`rate == 0`) the thread stays parked until another thread
/// advances it, and a fast clock (`rate > 1`) returns after proportionally less
/// real time. Each iteration re-registers on [`ClockEvent`] *before* reading
/// the clock, so a rate/value change from another thread can never be missed.
pub(crate) fn virtual_sleep(dur: Duration) {
    if dur.is_zero() {
        return;
    }
    let deadline = clock_mono_now()
        .as_nanos()
        .saturating_add(dur.as_nanos());
    loop {
        let listener = clock_event().listen();
        let now = clock_mono_now().as_nanos();
        if now >= deadline {
            return;
        }
        let remaining_nanos = deadline - now;
        let rate = time_rate();
        if rate > 0.0 {
            let real_secs = (remaining_nanos as f64 / 1_000_000_000.0) / rate;
            let real_remaining = if real_secs.is_finite() && real_secs < 3600.0 {
                Duration::from_secs_f64(real_secs)
            } else {
                Duration::from_secs(3600)
            };
            listener.wait_timeout(real_remaining);
        } else {
            listener.wait();
        }
    }
}

pub(crate) fn wait_for_event(timeout: Option<Duration>) -> bool {
    let guard = TEST_STATE.lock();
    let mut borrow = guard.borrow_mut();
    let any_map = slot!(borrow);
    if !any_map.contains::<Mutex<NewDataEvent>>() {
        any_map.insert::<Mutex<NewDataEvent>>(Mutex::new(Arc::new(Event::new())));
    }
    #[allow(unused)]
    let mut new_data_event = any_map
        .get::<Mutex<NewDataEvent>>()
        .expect("Failed to get state")
        .lock();
    let listener = new_data_event.clone().listen();
    drop(new_data_event);
    drop(borrow);
    drop(guard);
    if let Some(dur) = timeout {
        listener.wait_timeout(dur).is_some()
    } else {
        listener.wait();
        true
    }
}

pub(crate) fn add_tcp_connection(
    local_addr: SocketAddr,
    peer_addr: SocketAddr,
    owns_port: bool,
) -> usize {
    state!(
        tcp_connections = TcpConnections ? HashMap::new();
        local_ports_used = LocalPortsUsed ? HashSet::new();
        next = Next ? DEFAULT_NEXT;
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    if owns_port {
        local_ports_used.insert(local_addr);
    }
    let stream_id = next.0;
    next.0 += 1;
    tcp_connections.insert(
        stream_id,
        TcpConnection {
            stream_id,
            local_addr,
            peer_addr,
            incoming: VecDeque::new(),
            pending_inbound: VecDeque::new(),
            read_shutdown: false,
            write_shutdown: false,
            failure_queue: Vec::new(),
            external_error: None,
            peer_stream_id: None,
            nonblocking: false,
            nodelay: false,
            ttl: 64,
            linger: None,
            read_timeout: None,
            write_timeout: None,
            ref_count: 1,
            owns_port,
            is_destroyed: false,
            reset_pending: false,
        },
    );
    new_data_event.notify(u32::MAX);
    stream_id
}

pub(crate) fn add_udp_connection(bound_addr: SocketAddr) {
    state!(
        udp_connections = UdpConnections ? Vec::new();
        local_ports_used = LocalPortsUsed ? HashSet::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );

    local_ports_used.insert(bound_addr);
    udp_connections.push(UdpConnection {
        bound_addr,
        from_local: VecDeque::new(),
        to_local: VecDeque::new(),
        pending_inbound: VecDeque::new(),
        failure_queue: Vec::new(),
        external_error: None,
        is_destroyed: false,
    });
    new_data_event.notify(u32::MAX);
}

pub(crate) fn with_tcp_connection<T, F: FnOnce(&mut TcpConnection) -> T>(
    stream_id: usize,
    func: F,
) -> T {
    state!(
        tcp_connections = TcpConnections ? HashMap::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    let connection = tcp_connections.get_mut(&stream_id);
    if let Some(conn) = connection {
        let ret = func(conn);
        new_data_event.notify(u32::MAX);
        ret
    } else {
        panic!("No connection found for stream id: {}", stream_id);
    }
}

/// Like [`with_tcp_connection`] but returns `None` when the connection has already
/// been removed instead of panicking. Callers on the hot path (socket read/write)
/// use this so a peer that closed/dropped its end surfaces as a graceful
/// `ConnectionReset`, matching a real socket, rather than panicking a driver's
/// I/O thread.
pub(crate) fn try_with_tcp_connection<T, F: FnOnce(&mut TcpConnection) -> T>(
    stream_id: usize,
    func: F,
) -> Option<T> {
    state!(
        tcp_connections = TcpConnections ? HashMap::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    tcp_connections.get_mut(&stream_id).map(|conn| {
        let ret = func(conn);
        new_data_event.notify(u32::MAX);
        ret
    })
}

pub(crate) fn remove_tcp_connection(stream_id: usize) -> Option<TcpConnection> {
    state!(
        tcp_connections = TcpConnections ? HashMap::new();
        local_ports_used = LocalPortsUsed ? HashSet::new();
    );
    if let Some(conn) = tcp_connections.remove(&stream_id) {
        if conn.owns_port {
            local_ports_used.remove(&conn.local_addr);
        }
        Some(conn)
    } else {
        None
    }
}

pub(crate) fn add_tcp_listener_state(addr: SocketAddr) {
    state!(
        tcp_listeners = TcpListeners ? HashMap::new();
        local_ports_used = LocalPortsUsed ? HashSet::new();
    );
    local_ports_used.insert(addr);
    tcp_listeners.insert(
        addr,
        TcpListenerState {
            bound_addr: addr,
            pending_streams: VecDeque::new(),
            nonblocking: false,
            error: None,
            is_closed: false,
            ref_count: 1,
        },
    );
}

pub(crate) fn remove_tcp_listener_state(addr: SocketAddr) -> Option<TcpListenerState> {
    state!(
        tcp_listeners = TcpListeners ? HashMap::new();
        local_ports_used = LocalPortsUsed ? HashSet::new();
    );
    if let Some(listener) = tcp_listeners.get_mut(&addr) {
        if listener.ref_count > 1 {
            listener.ref_count -= 1;
            return None;
        }
    } else {
        return None;
    }
    let state = tcp_listeners.remove(&addr);
    if state.is_some() {
        local_ports_used.remove(&addr);
    }
    state
}

pub(crate) fn clone_tcp_listener_state(addr: SocketAddr) -> io::Result<()> {
    with_tcp_listener_state(addr, |listener| {
        listener.ref_count += 1;
    });
    Ok(())
}

pub(crate) fn with_tcp_listener_state<T, F: FnOnce(&mut TcpListenerState) -> T>(
    addr: SocketAddr,
    func: F,
) -> T {
    state!(tcp_listeners = TcpListeners ? HashMap::new());
    let listener = tcp_listeners.get_mut(&addr);
    if let Some(listener) = listener {
        func(listener)
    } else {
        panic!("No listener found for address: {}", addr);
    }
}

pub(crate) fn find_tcp_listener(target: SocketAddr) -> Option<SocketAddr> {
    state!(tcp_listeners = TcpListeners ? HashMap::new());
    if tcp_listeners.contains_key(&target) {
        return Some(target);
    }
    tcp_listeners
        .keys()
        .find(|addr| addr.port() == target.port() && addr.ip().is_unspecified())
        .copied()
}

pub(crate) fn assign_tcp_stream_to_listener(listener_addr: SocketAddr, stream_id: usize) {
    with_tcp_listener_state(listener_addr, |listener| {
        listener.pending_streams.push_back(stream_id);
    });
    state!(new_data_event = NewDataEvent ? Arc::new(Event::new()));
    new_data_event.notify(u32::MAX);
}

pub(crate) fn reserve_ephemeral_addr(ip: IpAddr) -> SocketAddr {
    state!(
        local_ports_used = LocalPortsUsed ? HashSet::new();
        next = Next ? DEFAULT_NEXT
    );
    loop {
        let mut port = next.1;
        if port == 0 {
            port = 40_000;
        }
        let addr = SocketAddr::new(ip, port);
        if local_ports_used.insert(addr) {
            next.1 = port.wrapping_add(1);
            break addr;
        }
        next.1 = port.wrapping_add(1);
    }
}

pub(crate) fn with_udp_connection<T, F: FnOnce(&mut UdpConnection) -> T>(
    binded_addr: SocketAddr,
    func: F,
) -> T {
    state!(
        udp_connection = UdpConnections ? Vec::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    let connection = udp_connection
        .iter_mut()
        .find(|conn| conn.bound_addr == binded_addr);
    if let Some(conn) = connection {
        let ret = func(conn);
        new_data_event.notify(u32::MAX);
        ret
    } else {
        panic!("No connection found for address: {}", binded_addr);
    }
}

pub(crate) fn mark_peer_read_shutdown(peer_id: usize) {
    with_tcp_connection(peer_id, |peer_state| {
        peer_state.read_shutdown = true;
    });
}

pub(crate) fn release_stream(stream_id: usize) -> Option<usize> {
    with_tcp_connection(stream_id, |conn| {
        if conn.ref_count > 1 {
            conn.ref_count -= 1;
            return None;
        }
        Some(())
    })?;
    if let Some(conn) = remove_tcp_connection(stream_id) {
        conn.peer_stream_id
    } else {
        None
    }
}

pub(crate) fn notify_peer_dropped(peer_id: usize) {
    with_tcp_connection(peer_id, |peer| {
        peer.peer_stream_id = None;
        peer.read_shutdown = true;
        peer.external_error = Some(io::Error::new(
            io::ErrorKind::ConnectionReset,
            "peer disconnected",
        ));
    });
}

pub(crate) fn send_udp_from_test(from_addr: SocketAddr, to_addr: SocketAddr, data: Vec<u8>) {
    let policy = udp_policy(to_addr);
    let len = data.len();
    let data_for_pcap = data.clone();

    // MTU rejection: oversize datagram is silently dropped on the wire.
    if let Some(mtu) = policy.mtu {
        if data.len() > mtu {
            record(RecordedEvent::UdpSendFromTest {
                from: from_addr,
                to: to_addr,
                len,
                dropped: true,
                duplicated: false,
            });
            return;
        }
    }

    let dropped = policy.loss_rate > 0.0 && rand_unit() < policy.loss_rate;
    if dropped {
        record(RecordedEvent::UdpSendFromTest {
            from: from_addr,
            to: to_addr,
            len,
            dropped: true,
            duplicated: false,
        });
        return;
    }

    let jitter_ns = if policy.reorder_jitter.is_zero() {
        0
    } else {
        (rand_unit() * policy.reorder_jitter.as_nanos() as f32) as u64
    };
    let total_delay = policy.inbound_latency + Duration::from_nanos(jitter_ns);
    let duplicated = policy.duplicate_rate > 0.0 && rand_unit() < policy.duplicate_rate;

    let pkt = |data: Vec<u8>| Packet {
        data,
        dest: to_addr,
        source: from_addr,
    };

    // Soft-fail if the destination UDP socket isn't bound yet (matches real
    // wire — UDP send to a non-existent listener is silently dropped). This
    // avoids panicking the tester loop when there's a race between the SUT
    // calling `bind` and the tester firing its first cyclic send.
    let delivered = {
        state!(
            udp_connections = UdpConnections ? Vec::new();
            new_data_event = NewDataEvent ? Arc::new(Event::new());
        );
        if let Some(conn) = udp_connections.iter_mut().find(|c| c.bound_addr == to_addr) {
            if total_delay.is_zero() {
                conn.to_local.push_back(pkt(data.clone()));
                if duplicated {
                    conn.to_local.push_back(pkt(data));
                }
            } else {
                let release_at = Instant::now() + total_delay;
                conn.pending_inbound
                    .push_back((release_at, pkt(data.clone())));
                if duplicated {
                    conn.pending_inbound.push_back((release_at, pkt(data)));
                }
            }
            new_data_event.notify(u32::MAX);
            true
        } else {
            false
        }
    };

    if delivered {
        record(RecordedEvent::UdpSendFromTest {
            from: from_addr,
            to: to_addr,
            len,
            dropped: false,
            duplicated,
        });
        pcap_udp(from_addr, to_addr, &data_for_pcap);
        if duplicated {
            pcap_udp(from_addr, to_addr, &data_for_pcap);
        }
    }
}

/// Inject a TCP chunk as if `from_addr` had sent it to the SUT at `to_addr`.
/// Honors latency / recv_window / other policies; soft-fails if the SUT has
/// already disconnected.
pub fn inject_tcp_from_test(from_addr: SocketAddr, to_addr: SocketAddr, data: Vec<u8>) {
    send_tcp_from_test(from_addr, to_addr, data);
}

pub(crate) fn send_tcp_from_test(from_addr: SocketAddr, to_addr: SocketAddr, data: Vec<u8>) {
    let policy = tcp_policy(to_addr);
    let len = data.len();
    let total_delay = policy.inbound_latency;
    // Pcap path is opt-in; clone once up front (cheap vs. the I/O cost of
    // tests, only used by the pcap tap below).
    let data_for_pcap = data.clone();

    let outcome: Result<bool, ()> = {
        state!(
            tcp_connections = TcpConnections ? HashMap::new();
            new_data_event = NewDataEvent ? Arc::new(Event::new());
        );
        let connection = tcp_connections
            .values_mut()
            .find(|conn| conn.local_addr == to_addr && conn.peer_addr == from_addr);
        match connection {
            Some(conn) => {
                if let Some(window) = policy.recv_window {
                    let queued = conn.incoming.len()
                        + conn
                            .pending_inbound
                            .iter()
                            .map(|(_, b)| b.len())
                            .sum::<usize>();
                    if queued + data.len() > window {
                        // Soft-drop on a stalled receive window. Test code
                        // that cares can inspect the recv-window via policy.
                        Ok(false)
                    } else {
                        if total_delay.is_zero() {
                            conn.incoming.extend(data);
                        } else {
                            conn.pending_inbound
                                .push_back((Instant::now() + total_delay, data));
                        }
                        new_data_event.notify(u32::MAX);
                        Ok(true)
                    }
                } else {
                    if total_delay.is_zero() {
                        conn.incoming.extend(data);
                    } else {
                        conn.pending_inbound
                            .push_back((Instant::now() + total_delay, data));
                    }
                    new_data_event.notify(u32::MAX);
                    Ok(true)
                }
            }
            None => Err(()),
        }
    };
    match outcome {
        Ok(true) => {
            record(RecordedEvent::TcpSendFromTest {
                from: from_addr,
                to: to_addr,
                len,
            });
            pcap_tcp_data(from_addr, to_addr, &data_for_pcap);
        }
        Ok(false) => {}
        Err(()) => {
            // Soft-fail: SUT dropped the connection before delivery. Real
            // wire would silently discard or surface RST; treat as a no-op
            // here rather than panicking and killing the tester loop.
        }
    }
}

/// Move expired pending-inbound chunks into `incoming`. Driven by the
/// readiness oracle so latency-delayed bytes surface on time.
pub(crate) fn release_pending_for_tcp(addr: SocketAddr) -> bool {
    state!(
        tcp_connections = TcpConnections ? HashMap::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    let now = Instant::now();
    let mut released = false;
    if let Some(conn) = tcp_connections.values_mut().find(|c| c.local_addr == addr) {
        while let Some((deadline, _)) = conn.pending_inbound.front() {
            if *deadline > now {
                break;
            }
            let (_, data) = conn.pending_inbound.pop_front().unwrap();
            conn.incoming.extend(data);
            released = true;
        }
    }
    if released {
        new_data_event.notify(u32::MAX);
    }
    released
}

pub(crate) fn release_pending_for_udp(addr: SocketAddr) -> bool {
    state!(
        udp_connections = UdpConnections ? Vec::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    let now = Instant::now();
    let mut released = false;
    if let Some(conn) = udp_connections.iter_mut().find(|c| c.bound_addr == addr) {
        while let Some((deadline, _)) = conn.pending_inbound.front() {
            if *deadline > now {
                break;
            }
            let (_, pkt) = conn.pending_inbound.pop_front().unwrap();
            conn.to_local.push_back(pkt);
            released = true;
        }
    }
    if released {
        new_data_event.notify(u32::MAX);
    }
    released
}

/// Earliest pending-release deadline across all connections; the run loop
/// caps its sleep at this so delayed bytes surface on schedule.
pub(crate) fn earliest_pending_release() -> Option<Instant> {
    let mut earliest: Option<Instant> = None;
    {
        state!(tcp_connections = TcpConnections ? HashMap::new());
        for conn in tcp_connections.values() {
            if let Some((d, _)) = conn.pending_inbound.front() {
                earliest = Some(earliest.map_or(*d, |e| e.min(*d)));
            }
        }
    }
    {
        state!(udp_connections = UdpConnections ? Vec::new());
        for conn in udp_connections.iter() {
            if let Some((d, _)) = conn.pending_inbound.front() {
                earliest = Some(earliest.map_or(*d, |e| e.min(*d)));
            }
        }
    }
    earliest
}

/// Mark the TCP connection bound at `addr` as RST. The next read/write returns
/// `ECONNRESET`. Distinct from a clean close: this is the synchronous form of
/// [`TesterAction::ResetTcp`](crate::TesterAction::ResetTcp).
pub fn reset_tcp(addr: SocketAddr) {
    reset_tcp_from_test(addr);
}

/// Mark a TCP connection as RST (matched by SUT-side local addr).
pub(crate) fn reset_tcp_from_test(addr: SocketAddr) {
    let peer = {
        state!(
            tcp_connections = TcpConnections ? HashMap::new();
            new_data_event = NewDataEvent ? Arc::new(Event::new());
        );
        if let Some(conn) = tcp_connections.values_mut().find(|c| c.local_addr == addr) {
            conn.reset_pending = true;
            conn.read_shutdown = true;
            conn.external_error = Some(io::Error::new(
                io::ErrorKind::ConnectionReset,
                "connection reset by peer",
            ));
            new_data_event.notify(u32::MAX);
            Some(conn.peer_addr)
        } else {
            None
        }
    };
    if let Some(peer_addr) = peer {
        record(RecordedEvent::TcpResetFromTest { addr });
        // RST is sourced from the test-side peer, since `reset_tcp_from_test`
        // is the "the remote side just sent a RST" path.
        pcap_tcp_rst(peer_addr, addr);
    }
}

pub(crate) fn raise_udp_socket_error_from_test(addr: SocketAddr, err: io::Error) {
    state!(
        udp_connections = UdpConnections ? Vec::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    if let Some(conn) = udp_connections
        .iter_mut()
        .find(|conn| conn.bound_addr == addr)
    {
        conn.external_error = Some(err);
        new_data_event.notify(u32::MAX);
    }
    // Soft-fail: socket not bound yet / already gone. Match wire semantics.
}

pub(crate) fn raise_tcp_socket_error_from_test(addr: SocketAddr, err: io::Error) {
    state!(
        tcp_connections = TcpConnections ? HashMap::new();
        new_data_event = NewDataEvent ? Arc::new(Event::new());
    );
    if let Some(conn) = tcp_connections
        .values_mut()
        .find(|conn| conn.local_addr == addr)
    {
        conn.external_error = Some(err);
        new_data_event.notify(u32::MAX);
    }
    // Soft-fail.
}

pub(crate) fn close_socket_from_test(addr: SocketAddr, socket_type: SocketType) {
    let mut found = false;
    match socket_type {
        SocketType::Udp => {
            {
                state!(
                    udp_connections = UdpConnections ? Vec::new();
                    new_data_event = NewDataEvent ? Arc::new(Event::new());
                );
                if let Some(conn) = udp_connections.iter_mut().find(|c| c.bound_addr == addr) {
                    conn.is_destroyed = true;
                    new_data_event.notify(u32::MAX);
                    found = true;
                }
            }
            if found {
                record(RecordedEvent::UdpCloseFromTest { addr });
            }
            // Soft-fail if the socket isn't bound (not yet, or already gone).
        }
        SocketType::Tcp => {
            {
                state!(
                    tcp_connections = TcpConnections ? HashMap::new();
                    new_data_event = NewDataEvent ? Arc::new(Event::new());
                );
                if let Some(conn) = tcp_connections.values_mut().find(|c| c.local_addr == addr) {
                    conn.is_destroyed = true;
                    new_data_event.notify(u32::MAX);
                    found = true;
                }
            }
            if found {
                record(RecordedEvent::TcpCloseFromTest { addr });
            }
            // Soft-fail.
        }
    }
}

/// SUT-outbound UDP send. Returns `WouldBlock` on a full send queue and
/// `InvalidInput` over MTU; otherwise enqueues into `from_local`.
pub(crate) fn enqueue_udp_outbound(bound_addr: SocketAddr, pkt: Packet) -> io::Result<()> {
    let policy = udp_policy(bound_addr);
    if let Some(mtu) = policy.mtu {
        if pkt.data.len() > mtu {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "datagram exceeds configured MTU",
            ));
        }
    }
    let pcap_capture = (pkt.source, pkt.dest, pkt.data.clone());
    {
        state!(
            udp_connections = UdpConnections ? Vec::new();
            new_data_event = NewDataEvent ? Arc::new(Event::new());
        );
        let sender_idx = udp_connections
            .iter()
            .position(|c| c.bound_addr == bound_addr)
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotConnected, "no such UDP socket"))?;
        if let Some(cap) = policy.send_queue_depth {
            if udp_connections[sender_idx].from_local.len() >= cap {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    "UDP send queue full",
                ));
            }
        }
        // If a socket is bound at the destination, deliver straight into its
        // inbound queue — this is what lets two real in-process sockets (e.g. a
        // driver and a raw emulated device under `snare_global`) exchange
        // datagrams without the tester framework pumping `from_local`. Virtual
        // testers don't bind a UDP socket, so they fall through to `from_local`
        // and are still served by `pop_latest_packet`.
        if let Some(dest_idx) = udp_connections.iter().position(|c| c.bound_addr == pkt.dest) {
            udp_connections[dest_idx].to_local.push_back(pkt);
        } else {
            udp_connections[sender_idx].from_local.push_back(pkt);
        }
        new_data_event.notify(u32::MAX);
    }
    pcap_udp(pcap_capture.0, pcap_capture.1, &pcap_capture.2);
    Ok(())
}

pub(crate) fn pop_latest_packet(addr: SocketAddr) -> Option<Packet> {
    state!(udp_connections = UdpConnections ? Vec::new());
    for conn in udp_connections.iter_mut() {
        if let Some(idx) = conn.from_local.iter().position(|pkt| pkt.dest == addr) {
            return conn.from_local.remove(idx);
        }
    }
    None
}

pub(crate) fn has_pending_udp_packet(addr: SocketAddr) -> bool {
    state!(udp_connections = UdpConnections ? Vec::new());
    udp_connections
        .iter()
        .any(|conn| conn.from_local.iter().any(|pkt| pkt.dest == addr))
}

pub(crate) fn has_pending_tcp_data(addr: SocketAddr) -> bool {
    state!(tcp_connections = TcpConnections ? HashMap::new());
    tcp_connections
        .values()
        .any(|conn| conn.local_addr == addr && !conn.incoming.is_empty())
}

pub(crate) struct TcpListenerStatus {
    pub pending: bool,
    pub error: bool,
    pub closed: bool,
}

pub(crate) struct TcpStreamStatus {
    pub readable: bool,
    pub writable: bool,
    pub error: bool,
    pub read_closed: bool,
    pub write_closed: bool,
}

pub(crate) struct UdpSocketStatus {
    pub readable: bool,
    pub writable: bool,
    pub error: bool,
    pub closed: bool,
}

pub(crate) fn tcp_listener_status(addr: SocketAddr) -> Option<TcpListenerStatus> {
    state!(tcp_listeners = TcpListeners ? HashMap::new());
    let listener = tcp_listeners.get(&addr)?;
    Some(TcpListenerStatus {
        pending: !listener.pending_streams.is_empty(),
        error: listener.error.is_some(),
        closed: listener.is_closed,
    })
}

pub(crate) fn tcp_stream_status(addr: SocketAddr) -> Option<TcpStreamStatus> {
    // Move any latency-released bytes into `incoming` first so the readiness
    // we return reflects the post-deadline state.
    release_pending_for_tcp(addr);
    let inbound_quiesced = is_quiesced_inbound(addr);
    let outbound_quiesced = is_quiesced_outbound(addr);
    state!(tcp_connections = TcpConnections ? HashMap::new());
    let conn = tcp_connections
        .values()
        .find(|conn| conn.local_addr == addr)?;
    let read_closed = conn.read_shutdown || conn.peer_stream_id.is_none() || conn.is_destroyed;
    let write_closed = conn.write_shutdown || conn.is_destroyed;
    let raw_readable = !conn.incoming.is_empty();
    let raw_writable = !write_closed && conn.peer_stream_id.is_some();
    Some(TcpStreamStatus {
        readable: raw_readable && !inbound_quiesced,
        writable: raw_writable && !outbound_quiesced,
        error: conn.external_error.is_some(),
        read_closed,
        write_closed,
    })
}

pub(crate) fn udp_socket_status(addr: SocketAddr) -> Option<UdpSocketStatus> {
    release_pending_for_udp(addr);
    let inbound_quiesced = is_quiesced_inbound(addr);
    let outbound_quiesced = is_quiesced_outbound(addr);
    state!(udp_connections = UdpConnections ? Vec::new());
    let conn = udp_connections
        .iter()
        .find(|conn| conn.bound_addr == addr)?;
    let closed = conn.is_destroyed;
    Some(UdpSocketStatus {
        readable: !conn.to_local.is_empty() && !inbound_quiesced,
        writable: !closed && !outbound_quiesced,
        error: conn.external_error.is_some(),
        closed,
    })
}

pub(crate) fn tcp_connection_peer_addr(local_addr: SocketAddr) -> Option<SocketAddr> {
    state!(tcp_connections = TcpConnections ? HashMap::new());
    tcp_connections
        .values()
        .find(|conn| conn.local_addr == local_addr)
        .map(|conn| conn.peer_addr)
}

pub(crate) fn peek_tcp_stream_data(addr: SocketAddr) -> Vec<u8> {
    state!(tcp_connections = TcpConnections ? HashMap::new());
    let connection = tcp_connections
        .values_mut()
        .find(|conn| conn.local_addr == addr);
    if let Some(conn) = connection {
        conn.incoming.iter().copied().collect()
    } else {
        return Vec::new();
    }
}

pub(crate) fn consume_tcp_stream_data(addr: SocketAddr, amount: usize) {
    state!(tcp_connections = TcpConnections ? HashMap::new());
    let connection = tcp_connections
        .values_mut()
        .find(|conn| conn.local_addr == addr);
    if let Some(conn) = connection {
        for _ in 0..amount {
            conn.incoming.pop_front();
        }
    } else {
        return;
    }
}