geiserx_ts_runtime 0.47.11

tailscale runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
//! TUN transport-mode actor: rides the same dataplane overlay seam as [`NetstackActor`], but
//! moves application packets between the dataplane and a real kernel TUN interface instead of a
//! userspace smoltcp netstack.
//!
//! In TUN mode there is no userspace application *transport* netstack: application packets flow
//! `OS-TUN <-> dataplane <-> overlay`. There IS, however, an in-datapath MagicDNS responder: the UP
//! pump peels off UDP queries destined to the MagicDNS service IP `100.100.100.100:53`, answers them
//! in-process via the shared [`magic_dns::decide`](crate::magic_dns::decide) responder, and writes
//! the reply back into the TUN — mirroring Go's `handleLocalPackets`. No host loopback socket and no
//! overlay egress is used for the DNS itself (anti-leak). Other netstack-only public APIs surface
//! [`ErrorKind::UnsupportedInTunMode`](crate::ErrorKind::UnsupportedInTunMode).
//!
//! The service IP absorbs EVERYTHING, not just DNS. `100.100.100.100` is this node's own address:
//! no peer owns it, and nothing outside this host may ever see a packet addressed to it. So the UP
//! pump consumes every quad-100 packet whatever its IP protocol or port ([`classify_service_ip`]) —
//! UDP/53 goes to the responder, TCP/53 goes to the service netstack that terminates DNS over TCP
//! ([`spawn_dns_tcp_service`]), any other TCP port is answered with a RST, everything else is
//! dropped — and none of them reach the overlay. Mirrors Go `wgengine/netstack`'s
//! `handleLocalPackets`, which absorbs the service IP unconditionally "so such traffic never reaches
//! the conntrack / peer-routing layers", plus `acceptTCP`'s split between the `hittingDNS` handler
//! for port 53 and the `r.Complete(true)` RST for a quad-100 port the node does not serve.

use core::num::NonZeroU16;
use std::{
    net::{Ipv4Addr, SocketAddr, SocketAddrV4},
    sync::Arc,
};

use kameo::{
    actor::ActorRef,
    message::{Context, Message},
};
use netstack::{
    CreateSocket, HasChannel,
    netcore::{Channel, NetstackControl},
};
use tokio::{sync::watch, task::JoinSet};
use ts_transport::OverlayTransport;
use ts_transport_tun::{AsyncTunTransport, Config as TunDeviceConfig};

use crate::{
    Error,
    dataplane::{OverlayFromDataplane, OverlayToDataplane},
    env::Env,
    magic_dns::{
        ClientTransport, Decision, DnsView, RecursivePlan, check_response_size_and_set_tc, decide,
        forward_plan, forward_query,
    },
    peer_tracker::PeerState,
};

/// The MagicDNS service IP. Mirrors `magic_dns::MAGIC_DNS_IP` (kept private to that module). In TUN
/// mode the host routes queries to this address into the TUN (see [`host_routes_from_node`]) where
/// the UP pump intercepts them.
const MAGIC_DNS_IP: Ipv4Addr = Ipv4Addr::new(100, 100, 100, 100);
/// The DNS service port.
const MAGIC_DNS_PORT: u16 = 53;
/// TTL for a synthesized IPv4 packet written back into the TUN (a MagicDNS reply, or the RST that
/// answers an unserved quad-100 TCP port). The packet is consumed by the local host one hop away
/// (the TUN endpoint), so the exact value is immaterial; 64 is the conventional default.
const SERVICE_IP_REPLY_TTL: u8 = 64;

/// The TUN transport-mode actor.
///
/// Lazily creates the TUN device on the first [`ts_control::StateUpdate`] that carries a self-node
/// (the device prefix is the runtime-assigned tailnet `/32`, unknown before then). Once created,
/// two pump tasks held in the [`JoinSet`] move packets up to and down from the dataplane; they die
/// with the actor.
pub struct TunActor {
    /// Tasks pumping packets between the device and the dataplane. Dropped with the actor, which
    /// aborts them — the device handle they hold is then dropped, tearing down the interface.
    _joinset: JoinSet<()>,

    /// The runtime [`Env`], retained so the StateUpdate handler can resolve the configured exit
    /// node against the live peer set when rebuilding the MagicDNS [`DnsView`] (populating
    /// `exit_doh` for recursive / exit-node-DoH forwarding). See [`build_dns_view`].
    env: Env,

    /// The control-supplied TUN knobs (name/MTU), used to build the device on the first
    /// StateUpdate. The tailnet prefix is supplied at that point from the self-node.
    tun_config: ts_control::TunConfig,

    /// `Some` until the device is created on the first StateUpdate; `.take()`n into the up-pump
    /// task at that point so the device is built exactly once.
    overlay_to_dataplane: Option<OverlayToDataplane>,

    /// `Some` until the device is created on the first StateUpdate; `.take()`n into the down-pump
    /// task at that point so the device is built exactly once.
    overlay_from_dataplane: Option<OverlayFromDataplane>,

    /// Reverses host route/DNS programming on drop. `Some` once the device is built and the host
    /// has been programmed; shares the actor's lifetime with the pump tasks in `_joinset`.
    host_guard: Option<HostGuard>,

    /// The latest peer database, fed from the [`PeerState`] subscription. Retained so the host-FIB
    /// peer-route fold ([`host_routes_from_node`]) can be recomputed on every peer change (the fix
    /// for the consumer-blocking bug: without the peer fold the OS had no route to any peer). `None`
    /// until the first [`PeerState`].
    peers: Option<Arc<crate::peer_tracker::PeerDb>>,

    /// The self node from the most recent control `StateUpdate` that carried one. Stored once the
    /// device is built so the [`PeerState`] re-apply path can rebuild the host route set (self fold
    /// + peer fold) without a fresh `StateUpdate`. `None` until the device is built.
    self_node: Option<Arc<ts_control::Node>>,

    /// The built device's interface name. Stored so the [`PeerState`] re-apply path re-applies
    /// routes under the SAME `if_name` the device was built with (the host-net `apply_routes`
    /// `debug_assert`s a stable interface name across applies). `None` until the device is built.
    if_name: Option<String>,

    /// Whether MagicDNS was enabled (`--accept-dns` AND the control DNS config's `magic_dns`) as of
    /// the last build/StateUpdate. Stored so the [`PeerState`] re-apply path keeps the
    /// `100.100.100.100/32` route present/absent consistently with the resolver programming, without
    /// a fresh `StateUpdate`. `false` until the first StateUpdate sets it.
    last_magic_dns: bool,

    /// The latest MagicDNS view, shared with the UP pump's in-datapath responder. Built here from
    /// the same control `StateUpdate` / peer `PeerState` the actor already subscribes to, mirroring
    /// [`MagicDnsActor`](crate::magic_dns)'s view construction. The UP task holds the receiver and
    /// reads it fresh for every intercepted query; `exit_doh` is populated from the active exit
    /// peer (see [`build_dns_view`]) so recursive / exit-node-DoH forwarding works in TUN mode.
    dns_view: watch::Sender<Arc<DnsView>>,

    /// The overlay netstack `Channel` (the forwarder netstack's, reused — TUN mode has no
    /// application netstack of its own) used by the UP pump's spawned [`run_forward`] to forward
    /// recursive / split-DNS queries over the overlay (anti-leak: a fresh `0.0.0.0:0` overlay UDP
    /// socket per query, never a host socket). Cloned into the UP pump when the device is built.
    channel: Channel,
}

/// RAII wrapper that reverses host route/DNS programming when the actor dies. Held in
/// [`TunActor::host_guard`] alongside the device pump tasks in `_joinset`, so when the actor is
/// dropped the interface is torn down and its host-FIB/resolver state is reversed together.
struct HostGuard(Box<dyn ts_host_net::HostNet>);

impl HostGuard {
    /// Re-program the host FIB to `routes` against the already-built device, delegating to the inner
    /// [`HostNet::apply_routes`]. `apply_routes` is an idempotent add-new/remove-gone diff with
    /// per-call rollback, so re-applying with a fresh set is safe, non-flapping, and fail-closed; it
    /// `debug_assert`s the interface name is stable across applies, so callers MUST re-apply under
    /// the same `if_name` the device was built with. Used by the [`PeerState`] handler to re-steer
    /// the host routing table when the peer set (or a runtime accept-routes / exit-node toggle)
    /// changes, without rebuilding the device. RAII teardown ([`Drop`]) is unaffected.
    fn apply_routes(
        &mut self,
        routes: &ts_host_net::HostRoutes,
    ) -> Result<(), ts_host_net::HostNetError> {
        self.0.apply_routes(routes)
    }
}

impl Drop for HostGuard {
    fn drop(&mut self) {
        self.0.teardown();
    }
}

/// Build the device config from the control-supplied [`ts_control::TunConfig`] plus the
/// runtime-assigned tailnet `/32` prefix. Mirrors [`env::exit_proxy_to_forwarder`](crate::env)
/// (conversion at the `ts_runtime` boundary).
///
/// Defaults: name `"tailscale0"`, MTU `1280` (Tailscale's overlay MTU). `mtu` is `Option<u16>`;
/// `0` is invalid so `and_then(NonZeroU16::new)` rejects a stray `0` and falls back to `1280`.
pub(crate) fn tun_config_from_control(
    cfg: &ts_control::TunConfig,
    prefix: ipnet::Ipv4Net,
) -> TunDeviceConfig {
    TunDeviceConfig {
        name: cfg.name.clone().unwrap_or_else(|| "tailscale0".to_owned()),
        mtu: cfg
            .mtu
            .and_then(NonZeroU16::new)
            .unwrap_or(NonZeroU16::new(1280).unwrap()),
        prefix: ipnet::IpNet::V4(prefix),
    }
}

/// Translate the self-node's accepted routes **and the union of every peer's AllowedIPs** into the
/// host-FIB route set to steer into the TUN (the `ts_runtime` boundary, mirroring
/// [`tun_config_from_control`]).
///
/// IPv4-only by construction: every IPv6 prefix is dropped here (both from the self node and from
/// each peer), enforcing the fork's v4-only invariant (v6 on the tailnet is gated off) without a
/// separate `enable_ipv6` flag.
///
/// PEER FOLD (the fix for the consumer-blocking bug: a TUN node reached MagicDNS but not its peers
/// because the OS had no route to any peer). Go's `tailscaled` feeds the host router
/// `Config.Routes = union of every peer's AllowedIPs`; we mirror that by extending the routed set
/// with, for every peer, `peer.routes_to_install(accept_routes, exit_id)` — the SAME Go-faithful
/// per-peer filter the netstack [`RouteUpdater`](crate::route_updater) already uses for the overlay
/// route table and the source filter. It yields the peer's own host `/32` always, advertised subnet
/// routes gated on `accept_routes`, and the peer's `/0` ONLY when that peer is the selected
/// `exit_id`. Using the same filter keeps the host FIB coupled to the overlay route table + source
/// filter (the anti-leak cryptokey-routing coupling — we do NOT hand-roll a different filter).
///
/// The host `/0` is therefore now keyed on the **selected exit peer** (per-peer, via
/// `routes_to_install`), not a standalone `exit_node_configured` bool — eliminating the former
/// self-node-`/0` asymmetry (the self node's `accepted_routes` may echo a `/0`, but only the
/// selected exit peer's `/0` belongs in the host FIB). The self node still contributes its own
/// non-`/0` accepted routes (subnet routes gated on `accept_routes`); its `/0` is never installed
/// here (only a peer's, and only the exit peer's). The Linux impl expands `/0` into the
/// split-default pair; macOS installs `/0` directly.
///
/// `accept_routes` and `exit_id` are read live by the caller (from [`Env`]) on every apply — both
/// the build path and the [`PeerState`] re-apply path — so a runtime `set_accept_routes` /
/// `set_exit_node` toggle re-steers the host FIB on the next peer republish.
pub(crate) fn host_routes_from_node(
    node: &ts_control::Node,
    peers: Option<&crate::peer_tracker::PeerDb>,
    if_name: String,
    accept_routes: bool,
    exit_id: Option<&ts_control::StableNodeId>,
    magic_dns: bool,
) -> ts_host_net::HostRoutes {
    let self_v4 = node.tailnet_address.ipv4;

    // Push `net` into `routed` iff it is not the on-link self `/32` and is not already present
    // (dedup: a prefix advertised by multiple peers, or by both the self node and a peer, installs
    // exactly once).
    let push_v4 = |routed: &mut Vec<ipnet::Ipv4Net>, net: ipnet::Ipv4Net| {
        if net != self_v4 && !routed.contains(&net) {
            routed.push(net);
        }
    };

    // Self-node fold: its own non-`/0` accepted routes. Subnet routes are gated on
    // `--accept-routes`; non-self host routes (e.g. additional tailnet addrs) are always installed.
    // Mirrors `routes_to_install`. A self-node `/0` is NOT installed here — only the selected exit
    // peer's `/0` is (in the peer fold below), so the host default route is keyed on the exit peer.
    let mut routed: Vec<ipnet::Ipv4Net> = Vec::new();
    for route in &node.accepted_routes {
        // IPv4-only by construction: drop every v6 prefix unconditionally.
        let ipnet::IpNet::V4(v4) = route else {
            continue;
        };
        if v4.prefix_len() == 0 {
            continue;
        }
        if accept_routes || !node.is_subnet_route(route) {
            push_v4(&mut routed, *v4);
        }
    }

    // Peer fold: the union of every peer's AllowedIPs, filtered by the SAME per-peer
    // `routes_to_install` the overlay route table + source filter use (anti-leak coupling). v4-only;
    // dedup via `push_v4`. The peer's `/0` lands ONLY when it is the selected `exit_id`.
    if let Some(peers) = peers {
        for peer in peers.peers().values() {
            for route in peer.routes_to_install(accept_routes, exit_id) {
                if let ipnet::IpNet::V4(v4) = route {
                    push_v4(&mut routed, *v4);
                }
            }
        }
    }

    // Steer the MagicDNS service IP `100.100.100.100/32` into the TUN so the host's quad-100 DNS
    // queries enter the datapath where the UP pump intercepts them ([`plan_intercept`]). Added
    // unconditionally when MagicDNS is enabled — it's the device's own service IP, always
    // routed-to-self — unless control somehow advertised it as the self `/32` (it never is).
    if magic_dns {
        let magic_dns_net = ipnet::Ipv4Net::new(MAGIC_DNS_IP, 32).expect("/32 is a valid prefix");
        push_v4(&mut routed, magic_dns_net);
    }

    ts_host_net::HostRoutes {
        if_name,
        self_v4,
        routed,
    }
}

/// Translate the control DNS config into the host resolver programming for the TUN (the
/// `ts_runtime` boundary, mirroring [`tun_config_from_control`]).
///
/// When MagicDNS is enabled the host resolver is pointed at the MagicDNS service IP
/// `100.100.100.100` — Go's model: the host sends queries to quad-100, the UP pump intercepts them
/// in the datapath and answers in-process via the shared responder ([`plan_intercept`]). There
/// is NO host loopback socket. When MagicDNS is disabled, `nameservers` stays empty (a documented
/// no-op in both the macOS and Linux `apply_dns` impls) so we never point the resolver at a dead
/// address — fail-closed.
///
/// `accept_dns` (`--accept-dns` / `CorpDNS`) gates this exactly like `magic_dns`: when `false` the
/// node ignores the tailnet DNS config, so the host resolver is NOT pointed at quad-100 (the
/// responder would `REFUSED` every query anyway) and no search domains are programmed — fail-closed,
/// the same empty-config behavior as MagicDNS off.
///
/// `match_domains` carries the suffixes the host resolver is **scoped** to when MagicDNS is enabled
/// **and** accepted: the tailnet search domains UNION the split-DNS route suffixes (Go
/// `dns.OSConfig.MatchDomains`, which is the search domains plus the non-global `Routes` keys). The
/// host layer scopes the MagicDNS resolver to exactly these suffixes; a suffix it lists is sent into
/// the TUN datapath, everything else stays on the host's normal resolver. The route keys are already
/// canonicalized and the global `.`/empty route is dropped at `DnsConfig` parse time, so this can
/// never re-introduce a catch-all scope.
///
/// When this set is **empty** (MagicDNS on but no search domain and no split-DNS route — a valid
/// control state), the host layer installs **no** resolver rather than a global one (matching Go
/// `manager_darwin.go`, which writes zero `/etc/resolver/*` files and never a primary resolver). See
/// the `match_domains.is_empty()` guard in `ts_host_net`'s macOS `apply_dns`.
pub(crate) fn host_dns_from_dns_config(
    dns: Option<&ts_control::DnsConfig>,
    if_name: String,
    accept_dns: bool,
) -> ts_host_net::HostDns {
    let magic_dns = accept_dns && matches!(dns, Some(d) if d.magic_dns);
    let match_domains = if let Some(d) = dns.filter(|_| magic_dns) {
        // Search domains first, then any split-DNS route suffix not already covered, deduped while
        // preserving order (Go `MatchDomains` = SearchDomains ∪ Routes keys). The route keys are
        // canonicalized and the global `.`/empty route is filtered out at parse time, so no entry
        // here can scope the resolver globally. ALL route keys are included, incl. a negative route
        // (empty upstream list): a negative-route suffix is intentionally scoped to the MagicDNS
        // resolver, which then fail-closes it (NXDOMAIN/REFUSED) rather than leaving it on the host's
        // normal resolver — this matches Go, whose `MatchDomains` likewise carries negative-route
        // keys, and keeps such names off the host resolver. Adding a suffix only ever *narrows* what
        // the tailnet resolver answers to that suffix; it never widens host-DNS capture.
        let mut domains = d.search_domains.clone();
        for suffix in d.routes.keys() {
            if !domains.contains(suffix) {
                domains.push(suffix.clone());
            }
        }
        domains
    } else {
        vec![]
    };

    ts_host_net::HostDns {
        if_name,
        // Point the host resolver at the MagicDNS service IP when MagicDNS is enabled; the UP pump
        // intercepts quad-100/UDP/53 in the datapath and answers in-process. Empty (no-op) when
        // MagicDNS is off — never point at a dead address.
        nameservers: if magic_dns {
            vec![MAGIC_DNS_IP]
        } else {
            vec![]
        },
        match_domains,
    }
}

/// A MagicDNS query peeled off the TUN datapath: the inner DNS payload plus the original query's
/// source endpoint (so the synthesized reply can be addressed back to it). Returned by
/// [`classify_service_ip`] when (and only when) an inbound packet is IPv4/UDP destined to
/// `100.100.100.100:53`.
struct MagicDnsQuery<'a> {
    /// The original query's source `IP:port` (the host stub resolver). The reply's destination.
    src: SocketAddrV4,
    /// The DNS wire-format query payload (UDP body), fed verbatim to [`decide`].
    dns_payload: &'a [u8],
}

/// What an inbound TUN packet is, relative to the MagicDNS service IP `100.100.100.100`. Produced
/// by the pure [`classify_service_ip`].
enum ServiceIpPacket<'a> {
    /// Not addressed to the service IP: none of our business, forwarded to the overlay unchanged.
    Foreign,
    /// A MagicDNS query: IPv4/UDP to `100.100.100.100:53`. Handed to the in-datapath responder.
    DnsQuery(MagicDnsQuery<'a>),
    /// A segment of a DNS-over-TCP connection: IPv4/TCP to `100.100.100.100:53`. Absorbed like
    /// everything else addressed to the service IP, but *terminated* rather than dropped — it is
    /// injected into the service netstack, which runs the TCP state machine and hands the framed
    /// query to [`dns_over_tcp`](crate::dns_over_tcp). Mirrors upstream's
    /// `hittingDNS := hittingServiceIP && reqDetails.LocalPort == 53`.
    DnsStream,
    /// Addressed to the service IP but NOT a MagicDNS query — some other port, some other IP
    /// protocol. Absorbed here and never forwarded: the service IP is this node's own, no peer owns
    /// it, and handing it to the overlay would encrypt it to a selected exit node.
    Absorbed {
        /// A synthesized TCP RST to write back into the TUN, for an inbound TCP segment to an
        /// unserved quad-100 port. `None` for every non-TCP packet (and for a TCP RST, which is
        /// never answered with another RST).
        reset: Option<Vec<u8>>,
    },
}

/// Classify an inbound TUN packet against the MagicDNS service IP `100.100.100.100`. Pure (no I/O);
/// the parse mirrors `ts_dataplane`'s inbound classify.
///
/// A packet NOT addressed to the service IP is [`ServiceIpPacket::Foreign`] and is forwarded to the
/// overlay unchanged. Everything addressed to the service IP is consumed here whatever its port or
/// IP protocol — IPv4/UDP to `:53` as a [`ServiceIpPacket::DnsQuery`] for the in-datapath responder,
/// IPv4/TCP to `:53` as a [`ServiceIpPacket::DnsStream`] for the service netstack to terminate,
/// anything else as [`ServiceIpPacket::Absorbed`]. This is Go `wgengine/netstack`'s
/// `handleLocalPackets`, which absorbs the service IP unconditionally rather than for an allow-list
/// of ports, "so such traffic never reaches the conntrack / peer-routing layers". The absorb is what
/// keeps a speculative host probe — a stub resolver trying DoT on `100.100.100.100:853` is
/// upstream's own example — from being routed: `ts_overlay_router`'s outbound table carries a
/// selected exit node's `0.0.0.0/0` as `RouteAction::Wireguard(peer)`, which matches quad-100, so a
/// forwarded service-IP packet would be encrypted and sent to that peer.
///
/// IPv4-only by construction, matching the rest of this module's MagicDNS posture: only
/// `100.100.100.100/32` is steered into the TUN ([`host_routes_from_node`]), the responder binds v4
/// only, and the IPv6 service IP `fd7a:115c:a1e0::53` is neither served nor routed here — so there
/// is no v6 service-IP packet for the host to emit. Unparseable bytes are `Foreign`: we cannot tell
/// where they are addressed, and the overlay router drops what it cannot read a destination from.
fn classify_service_ip(pkt: &[u8]) -> ServiceIpPacket<'_> {
    let Ok(sliced) = etherparse::SlicedPacket::from_ip(pkt) else {
        return ServiceIpPacket::Foreign;
    };

    let (src_ip, dst_ip) = match sliced.net {
        Some(etherparse::NetSlice::Ipv4(ipv4)) => (
            ipv4.header().source_addr(),
            ipv4.header().destination_addr(),
        ),
        _ => return ServiceIpPacket::Foreign,
    };

    if dst_ip != MAGIC_DNS_IP {
        return ServiceIpPacket::Foreign;
    }

    match sliced.transport {
        Some(etherparse::TransportSlice::Udp(udp)) if udp.destination_port() == MAGIC_DNS_PORT => {
            ServiceIpPacket::DnsQuery(MagicDnsQuery {
                src: SocketAddrV4::new(src_ip, udp.source_port()),
                // The UDP payload is the DNS wire message.
                dns_payload: udp.payload(),
            })
        }
        // TCP/53 is the transport a stub resolver retries on when a UDP answer came back truncated
        // (RFC 1035 §4.2.1), and upstream serves it: `acceptTCP` computes
        // `hittingDNS := hittingServiceIP && reqDetails.LocalPort == 53` and installs the DNS
        // handler for it, reaching `r.Complete(true)` — the RST — only for a quad-100 port it does
        // NOT serve. So the segment is terminated, not reset: it goes to the service netstack.
        Some(etherparse::TransportSlice::Tcp(tcp)) if tcp.destination_port() == MAGIC_DNS_PORT => {
            ServiceIpPacket::DnsStream
        }
        // Any OTHER quad-100 TCP port is RST rather than dropped: nothing in this tree listens on
        // one, so a silent drop would leave the host retransmitting a SYN until its connect
        // timeout. This is upstream's `r.Complete(true)` fallthrough, and it matches what the
        // netstack transport of this fork already does — there quad-100 is a netstack interface
        // address, and smoltcp answers a segment no socket accepts with `rst_reply`.
        Some(etherparse::TransportSlice::Tcp(tcp)) => ServiceIpPacket::Absorbed {
            reset: build_tcp_reset(src_ip, &tcp),
        },
        // Every other IP protocol (and a fragment whose transport header we cannot read) is
        // absorbed silently.
        _ => ServiceIpPacket::Absorbed { reset: None },
    }
}

/// Build the TCP RST answering an inbound segment to an unserved quad-100 port, addressed back to
/// `dst_ip` (the segment's source). Returns the IP packet bytes ready to write into the TUN, or
/// `None` when no RST may be sent.
///
/// Sequence-number rules are the reset generation in RFC 9293 §3.10.7, CLOSED state (the same ones
/// smoltcp's `rst_reply` implements): an inbound RST is never answered with another RST; a segment
/// carrying ACK is answered with a bare
/// RST whose sequence number is that ACK; a segment without ACK is answered with RST|ACK carrying
/// `SEG.SEQ + SEG.LEN` (the payload plus one for each of SYN and FIN, which occupy sequence space).
/// A window of 0 is correct for a RST — the sender is being told to give up, not to send more.
fn build_tcp_reset(dst_ip: Ipv4Addr, tcp: &etherparse::TcpSlice<'_>) -> Option<Vec<u8>> {
    // Never reply to a RST with a RST: that is how two ends ping-pong resets forever.
    if tcp.rst() {
        return None;
    }

    let builder = etherparse::PacketBuilder::ipv4(
        MAGIC_DNS_IP.octets(),
        dst_ip.octets(),
        SERVICE_IP_REPLY_TTL,
    )
    .tcp(
        tcp.destination_port(),
        tcp.source_port(),
        // Acknowledged data is where the peer already believes our send sequence is; an
        // unacknowledged segment gets a reply at sequence 0.
        if tcp.ack() {
            tcp.acknowledgment_number()
        } else {
            0
        },
        0,
    )
    .rst();
    // Only the un-ACKed case carries an ACK of its own (SYN and FIN each consume one sequence
    // number on top of the payload).
    let builder = if tcp.ack() {
        builder
    } else {
        let seg_len = tcp.payload().len() as u32 + u32::from(tcp.syn()) + u32::from(tcp.fin());
        builder.ack(tcp.sequence_number().wrapping_add(seg_len))
    };

    let mut out = Vec::with_capacity(builder.size(0));
    // Writing into a `Vec<u8>` is infallible; `PacketBuilder::write` only errors on I/O write
    // failures, which a `Vec` never produces.
    builder
        .write(&mut out, &[])
        .expect("writing an IPv4+TCP packet into a Vec is infallible");
    Some(out)
}

/// Build the IPv4+UDP response packet carrying `dns_response` from `100.100.100.100:53` back to the
/// original query's source `dst` (the host stub resolver), recomputing IPv4 + UDP checksums.
/// Pure: the src/dst are swapped relative to the query (we answer FROM the service IP TO the
/// querier). The returned bytes are an IP packet ready to write into the TUN.
fn build_dns_response(dst: SocketAddrV4, dns_response: &[u8]) -> Vec<u8> {
    let builder = etherparse::PacketBuilder::ipv4(
        MAGIC_DNS_IP.octets(),
        dst.ip().octets(),
        SERVICE_IP_REPLY_TTL,
    )
    .udp(MAGIC_DNS_PORT, dst.port());

    let mut out = Vec::with_capacity(builder.size(dns_response.len()));
    // Writing into a `Vec<u8>` is infallible; `PacketBuilder::write` only errors on I/O write
    // failures, which a `Vec` never produces.
    builder
        .write(&mut out, dns_response)
        .expect("writing an IPv4+UDP packet into a Vec is infallible");
    out
}

/// Build a fresh [`DnsView`] from the latest control `StateUpdate` and (optional) peer database,
/// mirroring [`MagicDnsActor`](crate::magic_dns)'s view construction
/// (`magic_dns::MagicDnsActor`'s `StateUpdate`/`PeerState` handlers). `enable_ipv6` comes from the
/// runtime `Env`.
///
/// `exit_doh` is populated from the active exit peer's peerAPI DoH endpoint so recursive resolution
/// egresses from the exit node (not this host) — same source as the netstack
/// `MagicDnsActor`'s `ActiveExitNode` handler (`magic_dns.rs:751`:
/// `active_exit_peer.and_then(|n| n.peerapi_doh_addr())`). The netstack path receives the
/// already-resolved peer from the route updater's `ActiveExitNode` publication; the TunActor has no
/// such subscription, so it resolves the exit peer locally — exactly as the route updater does
/// (`route_updater.rs:191-272`): resolve [`Env::exit_node`](crate::env::Env::exit_node) against the
/// live peer set to a [`StableId`](ts_control::StableId), then find that peer in the db. No exit
/// node configured, an unmatched selector, or a peer that can't proxy DNS ⇒ `None` (recursion stays
/// local — fail-closed, no leak).
fn build_dns_view(
    env: &Env,
    update: &ts_control::StateUpdate,
    peers: Option<Arc<crate::peer_tracker::PeerDb>>,
    enable_ipv6: bool,
) -> DnsView {
    // Resolve the configured exit node to its peerAPI DoH address, mirroring the netstack path's
    // `active_exit_peer.and_then(|n| n.peerapi_doh_addr())` (`magic_dns.rs:751`). The two-line peer
    // resolution mirrors `route_updater.rs:191-272` (selector -> stable id -> peer); replicated
    // locally (no shared-fn extraction) to keep S3 inside `tun_actor.rs`.
    let exit_doh = env.exit_node().as_ref().and_then(|sel| {
        let peers = peers.as_ref()?;
        let id = sel.resolve(peers.peers().values())?;
        peers
            .peers()
            .values()
            .find(|peer| peer.stable_id == id)
            .and_then(|n| n.peerapi_doh_addr())
    });

    DnsView {
        cfg: update.dns_config.clone().unwrap_or_default(),
        peers,
        self_node: update.node.clone(),
        exit_doh,
        enable_ipv6,
        // Re-read the live accept-dns cell on every view rebuild (it is runtime-settable via
        // `Device::set_accept_dns`); the in-datapath responder's `decide` gate refuses every query
        // when false. Same trap as the netstack `PeerState` site — read at rebuild, never snapshot.
        accept_dns: env.accept_dns(),
    }
}

/// Outcome of classifying an inbound TUN packet against the in-datapath MagicDNS responder.
/// Produced by the PURE [`plan_intercept`] (no I/O, unit-testable without a TUN device) and acted on
/// by the UP pump: the slow [`Decision::Forward`] path is handed back as [`Self::Forward`] for the
/// pump to SPAWN, never awaited inline — so one slow upstream cannot head-of-line-block the uplink.
enum Intercept {
    /// Not addressed to the MagicDNS service IP; the pump should forward the original packet to the
    /// overlay unchanged.
    NotIntercepted,
    /// A malformed MagicDNS query — consumed (it was quad-100/UDP/53) but dropped silently with no
    /// reply. The pump must NOT forward it to the overlay.
    Dropped,
    /// A quad-100 packet that is not a MagicDNS query at all: absorbed by the service IP whatever
    /// its port or IP protocol, so it never reaches the overlay router (where a selected exit
    /// node's `0.0.0.0/0` would match it). `reset` carries a synthesized TCP RST for the pump to
    /// write back into the TUN when the packet was a TCP segment to an unserved port; `None` means
    /// drop silently. Distinct from [`Self::Dropped`], which is the DNS responder refusing a query
    /// it did parse as its own.
    Absorbed {
        /// The RST reply packet, if one is owed.
        reset: Option<Vec<u8>>,
    },
    /// A segment of a DNS-over-TCP connection to `100.100.100.100:53`. The pump injects the packet
    /// into the service netstack, which terminates the connection and answers through
    /// [`dns_over_tcp`](crate::dns_over_tcp); the reply segments come back out of that netstack and
    /// are written into the TUN. Never forwarded to the overlay — quad-100 is ours.
    DnsStream,
    /// An authoritative [`Decision::Reply`] (cache / in-tailnet name): the synthesized reply bytes
    /// are carried out for the pump to write back into the TUN INLINE (the fast path — no overlay
    /// round-trip). The pump must NOT forward the packet to the overlay.
    Reply {
        /// The DNS wire response to wrap in an IPv4+UDP packet and write back into the TUN.
        response: Vec<u8>,
        /// The reply's destination (the host stub resolver) — the query's source endpoint.
        src: SocketAddrV4,
    },
    /// A [`Decision::Forward`] (recursive / split-DNS). The slow overlay round-trip must be SPAWNED
    /// by the pump rather than awaited inline (anti-HOL-blocking). Carries the already-resolved
    /// [`RecursivePlan`] (computed while the view borrow was held), the original query bytes, the
    /// `servfail` fallback, and the reply destination `src`. The pump must NOT forward the packet to
    /// the overlay.
    Forward {
        /// The resolved forwarding plan (UDP upstreams vs exit-node DoH over the overlay). The
        /// upstream `SocketAddr`s come only from `decide`/`recursive_plan`, which already
        /// `.filter(SocketAddr::is_ipv4)`; this path never constructs an upstream address, so the
        /// IPv4-only egress invariant is inherited.
        plan: RecursivePlan,
        /// The original query bytes to forward verbatim.
        query: Vec<u8>,
        /// SERVFAIL response written back if every upstream fails — an off-tailnet name the
        /// forwarder couldn't reach is a soft failure, not a cacheable non-existence (carried over
        /// from [`Decision::Forward`]; matches Go forwarder.go:1297-1307).
        servfail: Vec<u8>,
        /// The reply's destination (the host stub resolver) — the query's source endpoint.
        src: SocketAddrV4,
    },
}

/// In-datapath MagicDNS classify+decide for the UP pump (Go's `handleLocalPackets`). PURE: no I/O,
/// factored out of the pump loop so the branch behavior — crucially, that a [`Decision::Forward`] is
/// handed back to be SPAWNED rather than awaited inline — is unit-testable without a TUN device
/// (mirrors `magic_dns::decide`'s "factored out of the socket loop" rationale).
///
/// Fast paths resolve synchronously: a packet not addressed to the service IP ⇒
/// [`Intercept::NotIntercepted`]; a quad-100 packet that is not a DNS query ⇒
/// [`Intercept::Absorbed`] (consumed, with a RST for TCP — see [`classify_service_ip`]); a
/// malformed query ⇒ [`Intercept::Dropped`]; an authoritative [`Decision::Reply`] ⇒
/// [`Intercept::Reply`] carrying the response bytes for the pump to write back into the TUN INLINE
/// (no overlay round-trip — no host loopback socket, anti-leak).
///
/// The SLOW path — [`Decision::Forward`] (recursive / split-DNS forwarding, a full overlay DNS
/// round-trip bounded only by a ~5s timeout) — is NOT awaited here. It is returned as
/// [`Intercept::Forward`] carrying the already-resolved [`RecursivePlan`] so the pump can SPAWN it
/// onto a [`JoinSet`] (see the UP pump in the StateUpdate handler), mirroring the netstack serve
/// loop (`magic_dns.rs:598-632`): "a slow upstream never blocks other queries". Awaiting the forward
/// inline (as this did historically) stalls the ENTIRE TUN uplink — all application traffic, not
/// just DNS — for up to the forward timeout while the pump cannot pull the next packet.
///
/// The plan (UDP upstreams vs exit-node DoH) is computed here from the current view; both branches
/// route through `recursive_plan`/the `decide`-built upstreams, so the IPv4-only filter at
/// `magic_dns.rs:385,429` is inherited (we never build a `SocketAddr` here). The `servfail` fallback
/// is carried into the spawned task and written on forward failure — same as before, just from the
/// spawned task rather than inline.
fn plan_intercept(view: &DnsView, pkt: &[u8]) -> Intercept {
    let query = match classify_service_ip(pkt) {
        ServiceIpPacket::Foreign => return Intercept::NotIntercepted,
        // Addressed to the service IP but not DNS: absorbed without ever consulting the responder.
        ServiceIpPacket::Absorbed { reset } => return Intercept::Absorbed { reset },
        // DNS over TCP: the connection is terminated by the service netstack, which owns the TCP
        // state machine; the responder is consulted per framed query from there, not here.
        ServiceIpPacket::DnsStream => return Intercept::DnsStream,
        ServiceIpPacket::DnsQuery(query) => query,
    };
    // The reply destination (the query's source endpoint). Bound before the `Decision::Forward`
    // arm shadows `query` with the forward's own owned query bytes.
    let src = query.src;

    match decide(view, query.dns_payload) {
        // Malformed query: drop silently. We still consumed it (it was quad-100/UDP/53) so it must
        // NOT be forwarded to the overlay.
        None => Intercept::Dropped,
        // The size check upstream runs on a locally-composed answer too (Go `Resolver.Query`
        // calls `checkResponseSizeAndSetTC` right after `respond`): a quad-100 UDP client that
        // advertised an EDNS buffer smaller than the answer we built is owed the `TC` bit.
        Some(Decision::Reply(response)) => Intercept::Reply {
            response: check_response_size_and_set_tc(
                query.dns_payload,
                response,
                ClientTransport::Udp,
            ),
            src,
        },
        // Forward over the overlay, mirroring the netstack serve loop (`magic_dns.rs:598-632`). The
        // plan (UDP upstreams vs exit-node DoH) is computed from the current view; both branches
        // route through `recursive_plan`/the `decide`-built upstreams, so the IPv4-only filter at
        // `magic_dns.rs:385,429` is inherited (we never build a `SocketAddr` here). The overlay
        // round-trip is NOT awaited here — it is handed back for the pump to SPAWN (anti-HOL).
        Some(Decision::Forward {
            upstreams,
            query,
            servfail,
            recursive,
        }) => {
            let plan = forward_plan(view, upstreams, recursive);
            Intercept::Forward {
                plan,
                query,
                servfail,
                src,
            }
        }
    }
}

/// Write an authoritative MagicDNS reply (the fast path) back into the TUN inline. The synthesized
/// IPv4+UDP packet goes straight back to the querier via `device` — no host loopback socket and no
/// overlay egress for the DNS itself (anti-leak).
async fn send_dns_reply(device: &Arc<AsyncTunTransport>, src: SocketAddrV4, response: &[u8]) {
    send_local_reply(
        device,
        build_dns_response(src, response),
        "magic dns tun reply",
    )
    .await;
}

/// Write one locally-synthesized IP packet — a MagicDNS reply, or the RST answering an unserved
/// quad-100 TCP port — back into the TUN. `what` names the packet in the failure log.
async fn send_local_reply(device: &Arc<AsyncTunTransport>, pkt: Vec<u8>, what: &str) {
    if let Err(e) = device
        .send(core::iter::once(ts_packet::PacketMut::from(pkt)))
        .await
    {
        tracing::warn!(error = %e, what, "tun local reply send failed");
    }
}

/// Run the SLOW [`Decision::Forward`] overlay round-trip and write the synthesized DNS reply back
/// into the TUN. Spawned onto the pump's `JoinSet` so it never blocks the uplink (see
/// [`plan_intercept`] / the UP pump). Mirrors the spawned forward in the netstack serve loop
/// (`magic_dns.rs:614-627`): forward over the overlay (anti-leak: never a host socket), falling back
/// to the pre-built `servfail` on failure (a soft failure for an off-tailnet name we couldn't
/// forward), then write the reply packet into the TUN.
/// The upstreams are carried in `plan` (from `decide`/`recursive_plan`, already v4-only filtered);
/// this fn never constructs an upstream `SocketAddr`, so the IPv4-only egress invariant is inherited.
/// The TUN uplink pump: the highest-traffic datapath, run as a task spawned onto the actor's
/// [`JoinSet`] when the device is built (see the StateUpdate handler). It moves application
/// packets `device -> {in-datapath MagicDNS responder | dataplane}`:
///
/// - For every received packet it runs the PURE [`plan_intercept`] against the latest MagicDNS
///   [`DnsView`] (read fresh per packet; the borrow guard is never held across an `await`):
///   - [`Intercept::NotIntercepted`] — forward the original packet to the overlay (`up`) unchanged.
///   - [`Intercept::Absorbed`] — a quad-100 packet that is not a DNS query: consumed by the service
///     IP whatever its port or protocol, never forwarded; a TCP segment gets a RST written back.
///   - [`Intercept::DnsStream`] — a quad-100 TCP/53 segment: injected into the service netstack
///     (`dns_tcp_tx`), which terminates the connection and answers it over DNS-over-TCP.
///   - [`Intercept::Dropped`] — a malformed quad-100 query: consumed, never forwarded.
///   - [`Intercept::Reply`] — an authoritative reply written straight back into the TUN INLINE
///     (the fast path — no overlay round-trip, no host socket; anti-leak).
///   - [`Intercept::Forward`] — the SLOW recursive / split-DNS overlay round-trip is SPAWNED onto
///     a local `JoinSet` ([`run_forward`]) so one slow upstream never head-of-line-blocks the
///     ENTIRE TUN uplink (all application traffic, not just DNS).
///
/// BACKPRESSURE: in-flight forwards are capped at `MAX_INFLIGHT_FORWARDS` to avoid trading
/// HOL-blocking for unbounded task growth under a DNS flood; at the cap one completed forward is
/// reaped synchronously (`join_next`) before spawning the next. This back-pressures *new DNS
/// forwards only* — the non-DNS uplink and the inline fast paths are never blocked. Returns when
/// the overlay send half (`up`) is closed (the dataplane went away).
async fn up_pump(
    dev_up: Arc<AsyncTunTransport>,
    up: OverlayToDataplane,
    dns_view_rx: watch::Receiver<Arc<DnsView>>,
    dns_channel: Channel,
    dns_tcp_tx: netstack::WakingPipeSender,
) {
    // In-flight MagicDNS forward tasks. The slow `Decision::Forward` overlay round-trip
    // (bounded only by a ~5s timeout) is SPAWNED here rather than awaited inline, so one
    // slow/hung upstream never head-of-line-blocks the ENTIRE TUN uplink (all application
    // traffic, not just DNS). Mirrors the netstack serve loop's `JoinSet`
    // (`magic_dns.rs:577,614-632`): spawn each forward, reap with `try_join_next`.
    //
    // CONCURRENCY BOUND: a `JoinSet` reaped with `try_join_next` matches `magic_dns.rs`
    // for consistency (the pump owns the set across loop iterations, so no separate
    // semaphore is needed). To avoid trading HOL-blocking for unbounded task growth under a
    // DNS flood, in-flight forwards are capped at `MAX_INFLIGHT_FORWARDS`: at the cap we
    // synchronously reap one completed forward (`join_next`) before spawning the next.
    // Worst case is one forward's latency of back-pressure on *new DNS forwards only* — the
    // non-DNS uplink and the authoritative/no-intercept fast paths are never blocked.
    const MAX_INFLIGHT_FORWARDS: usize = 256;
    let mut forwards: JoinSet<()> = JoinSet::new();
    loop {
        // Drain the (non-`Send`) recv iterator into an owned batch first, so no part of it
        // is held across the intercept's `await` (the iterator is not `Send`; `PacketMut`
        // is). Then process the batch, peeling off MagicDNS queries.
        let batch: Vec<_> = dev_up.recv().await.into_iter().collect();
        for pkt in batch {
            match pkt {
                Ok(p) => {
                    // Peel off quad-100/UDP/53 DNS queries and answer them in-process: an
                    // authoritative reply is written straight back into the TUN via `dev_up`
                    // (no overlay egress, no host socket) INLINE; a Forward (recursive /
                    // split-DNS) is SPAWNED so its overlay round-trip never blocks the pump.
                    // Everything else forwards to the overlay unchanged. The view is read
                    // fresh per packet (mirrors the netstack serve loop); the borrow guard
                    // is dropped at the end of this statement, never held across an `await`.
                    let plan = plan_intercept(&dns_view_rx.borrow(), p.as_ref());
                    match plan {
                        Intercept::NotIntercepted => {
                            if up.send(vec![p]).is_err() {
                                return;
                            }
                        }
                        // Malformed query: consumed but dropped silently; never forward to
                        // the overlay.
                        Intercept::Dropped => {}
                        // Quad-100, but not DNS. The service IP is ours; absorb it here so
                        // it never reaches the overlay router, where a selected exit node's
                        // `0.0.0.0/0` would match it and encrypt it to that peer. A TCP
                        // segment to an unserved port is answered with a RST inline so the
                        // host fails fast instead of retransmitting its SYN.
                        Intercept::Absorbed { reset } => {
                            if let Some(reset) = reset {
                                send_local_reply(&dev_up, reset, "service ip tcp reset").await;
                            }
                        }
                        // DNS over TCP: hand the segment to the service netstack, which owns the
                        // TCP state machine for `100.100.100.100:53`. Its replies come back out of
                        // that netstack's downlink and are written into the TUN there, so nothing
                        // is written back here. Never forwarded to the overlay.
                        Intercept::DnsStream => {
                            dns_tcp_tx.send_async(p.as_ref()).await;
                        }
                        // Authoritative reply (fast path): write it back into the TUN inline.
                        Intercept::Reply { response, src } => {
                            send_dns_reply(&dev_up, src, &response).await;
                        }
                        // Spawn the slow overlay round-trip; it writes the reply (or the
                        // servfail fallback) back into the TUN when it completes.
                        Intercept::Forward {
                            plan,
                            query,
                            servfail,
                            src,
                        } => {
                            // Bound in-flight forwards: reap one completed task at the cap
                            // before spawning, so a DNS flood can't grow tasks without
                            // limit. This back-pressures *new DNS forwards only*, never the
                            // non-DNS uplink or the inline fast paths.
                            if forwards.len() >= MAX_INFLIGHT_FORWARDS {
                                // Reap exactly one completed forward; the join result is
                                // intentionally discarded (the task is `()` and logs its
                                // own send failures).
                                drop(forwards.join_next().await);
                            }
                            forwards.spawn(run_forward(
                                dev_up.clone(),
                                dns_channel.clone(),
                                plan,
                                query,
                                servfail,
                                src,
                            ));
                        }
                    }
                }
                Err(e) => tracing::warn!(error = %e, "tun recv error"),
            }
        }
        // Reap finished forward tasks without blocking (mirrors `magic_dns.rs:632`).
        while forwards.try_join_next().is_some() {}
    }
}

async fn run_forward(
    device: Arc<AsyncTunTransport>,
    channel: Channel,
    plan: RecursivePlan,
    query: Vec<u8>,
    servfail: Vec<u8>,
    src: SocketAddrV4,
) {
    let response = match plan {
        RecursivePlan::Udp(ups) => {
            forward_query(&channel, &ups, &query, servfail, ClientTransport::Udp).await
        }
        RecursivePlan::Doh(addr) => {
            crate::peerapi_doh::forward_doh(&channel, addr, &query, servfail, ClientTransport::Udp)
                .await
        }
    };
    send_local_reply(
        &device,
        build_dns_response(src, &response),
        "magic dns tun forwarded reply",
    )
    .await;
}

/// Per-direction TCP buffer for the service netstack's sockets.
///
/// The netstack allocates one buffer of this size for rx and another for tx on **every** TCP socket
/// it creates, eagerly (there is no window auto-tuning — see
/// [`Config::tcp_buffer_size`](netstack::netcore::Config::tcp_buffer_size)). The workspace default
/// is 256 KiB, sized for bulk application flows; the only thing this netstack ever carries is a DNS
/// message, which a `u16` length prefix caps at 64 KiB and which is in practice a few hundred bytes.
/// 16 KiB keeps a stalled connection's footprint at ~32 KiB instead of ~512 KiB, and cannot throttle
/// anything: a DNS exchange is one round trip, not a bandwidth-delay product.
const DNS_TCP_BUFFER: usize = 16 * 1024;

/// Accept-backlog for the service netstack's DNS listener.
///
/// Each queued half-open connection still pins two [`DNS_TCP_BUFFER`]-sized buffers, so the bound
/// is what stops
/// a SYN flood aimed at `100.100.100.100:53` — a *local* one, since only this host can reach the
/// service IP — from growing the socket set. The clients are this host's own stub resolvers, so
/// the queue never needs to be deep; the workspace default of 128 is sized for a public listener.
const DNS_TCP_BACKLOG: usize = 16;

/// Stand up the netstack that terminates quad-100 TCP, and start the DNS-over-TCP server on it.
///
/// TUN mode has no application netstack — that is the whole point of the mode — so a TCP connection
/// to `100.100.100.100:53` has nothing to terminate it, and before this every such segment was
/// answered with a RST. Upstream has a netstack in both modes and serves that port from it
/// (`acceptTCP`'s `hittingDNS` case, wgengine/netstack/netstack.go @
/// `9ea7cba44591e0cd840c6c94d23274dd222059bf`), so this puts one back — a small, dedicated stack
/// that owns exactly one address and one listener:
///
/// - packets in: the UP pump injects quad-100 TCP/53 segments into the returned pipe sender;
/// - packets out: this stack's downlink is written straight back into the TUN, never to the overlay;
/// - queries: [`dns_over_tcp::serve`] answers them through the same [`DnsView`] the UDP responder
///   uses, forwarding (when it must) over `forward_channel`, the OVERLAY netstack — anti-leak, a
///   host socket is never involved.
///
/// It is deliberately not the forwarder netstack: that one has any-IP acceptance on and its
/// downlink goes to the dataplane, which would put the node's own service-IP traffic on the wire.
///
/// Fail-safe rather than fail-closed, because there is nothing here to leak: if the listener cannot
/// be bound the server is not started, and the stack — which still owns `100.100.100.100` — resets
/// the connection exactly as the old code did.
async fn spawn_dns_tcp_service(
    joinset: &mut JoinSet<()>,
    device: Arc<AsyncTunTransport>,
    mtu: u16,
    dns_view_rx: watch::Receiver<Arc<DnsView>>,
    forward_channel: Channel,
) -> netstack::WakingPipeSender {
    let (up_tx, mut down_rx) =
        spawn_dns_tcp_netstack(joinset, mtu, dns_view_rx, forward_channel).await;

    // Everything this stack emits is addressed to the host that opened the connection, one hop away
    // across the TUN. Write it there — never to the overlay.
    joinset.spawn(async move {
        while let Some(buf) = down_rx.recv_async().await {
            send_local_reply(&device, buf.to_vec(), "magic dns tcp reply").await;
        }
    });

    up_tx
}

/// The half of [`spawn_dns_tcp_service`] that has no TUN in it: build the stack, give it the
/// service IP, start the server, and hand both ends of its packet pipe back.
///
/// Split out so the whole thing — address assignment, listener, TCP termination, the DNS-over-TCP
/// framing and the responder behind it — is exercisable by feeding raw IP packets in one end and
/// reading raw IP packets out the other, which is exactly what the UP pump and the TUN do to it.
async fn spawn_dns_tcp_netstack(
    joinset: &mut JoinSet<()>,
    mtu: u16,
    dns_view_rx: watch::Receiver<Arc<DnsView>>,
    forward_channel: Channel,
) -> (netstack::WakingPipeSender, netstack::WakingPipeReceiver) {
    let config = netstack::netcore::Config {
        // Match the TUN's MTU so the MSS this stack advertises fits the interface the segments
        // actually traverse.
        mtu: usize::from(mtu),
        tcp_buffer_size: DNS_TCP_BUFFER,
        tcp_listen_backlog: DNS_TCP_BACKLOG,
        ..Default::default()
    };
    let (
        mut netstack,
        netstack::WakingPipe {
            rx: down_rx,
            tx: up_tx,
        },
    ) = netstack::piped(config);
    let channel = netstack.command_channel();

    joinset.spawn(async move {
        netstack.run_tokio().await;
        tracing::warn!("magic dns tcp netstack stopped!");
    });

    // Assign the service IP before any segment is pumped in: a stack with no address drops what it
    // cannot claim, and the run loop is already up so this round-trips.
    if let Err(e) = channel.set_ips([core::net::IpAddr::V4(MAGIC_DNS_IP)]).await {
        tracing::error!(error = %e, "magic dns tcp netstack address assignment failed; dns over tcp inert");
        return (up_tx, down_rx);
    }

    // Bind here rather than inside the server task so the listener exists before the pump can hand
    // this stack its first SYN.
    let addr = SocketAddr::V4(SocketAddrV4::new(MAGIC_DNS_IP, MAGIC_DNS_PORT));
    match channel.tcp_listen(addr).await {
        Ok(listener) => {
            joinset.spawn(crate::dns_over_tcp::serve(
                listener,
                dns_view_rx,
                forward_channel,
            ));
        }
        Err(e) => {
            tracing::error!(error = %e, %addr, "magic dns tcp listen failed; dns over tcp inert");
        }
    }

    (up_tx, down_rx)
}

impl kameo::Actor for TunActor {
    type Args = (
        Env,
        ts_control::TunConfig,
        OverlayToDataplane,
        OverlayFromDataplane,
        // The overlay netstack `Channel` (the forwarder netstack's, reused) used by
        // `plan_intercept`/`run_forward` to forward recursive / split-DNS queries over the overlay.
        Channel,
    );
    type Error = Error;

    async fn on_start(
        (env, tun_config, overlay_to_dataplane, overlay_from_dataplane, channel): Self::Args,
        slf: ActorRef<Self>,
    ) -> Result<Self, Self::Error> {
        // We need the tailnet /32 prefix to build the device, which control only assigns at
        // runtime. Subscribe and build the device lazily on the first StateUpdate carrying a node.
        env.subscribe::<Arc<ts_control::StateUpdate>>(&slf).await?;
        // Also track peer state so the in-datapath MagicDNS responder can resolve peer names
        // authoritatively — mirrors `MagicDnsActor`'s `PeerState` subscription.
        env.subscribe::<Arc<PeerState>>(&slf).await?;

        // Seed the MagicDNS view with the runtime IPv6 gate (default off) + the current accept-dns
        // value; control/peer updates clone-and-modify it (re-reading accept-dns live each time).
        // Mirrors `MagicDnsActor::on_start`. The seed is moot (no query served before the first
        // StateUpdate) but keeps the pre-update view internally consistent.
        let (dns_view, _) = watch::channel(Arc::new(DnsView {
            enable_ipv6: env.enable_ipv6,
            accept_dns: env.accept_dns(),
            ..DnsView::default()
        }));

        Ok(Self {
            _joinset: JoinSet::new(),
            env,
            tun_config,
            overlay_to_dataplane: Some(overlay_to_dataplane),
            overlay_from_dataplane: Some(overlay_from_dataplane),
            host_guard: None,
            peers: None,
            self_node: None,
            if_name: None,
            last_magic_dns: false,
            dns_view,
            channel,
        })
    }
}

impl Message<Arc<ts_control::StateUpdate>> for TunActor {
    type Reply = ();

    async fn handle(
        &mut self,
        msg: Arc<ts_control::StateUpdate>,
        _ctx: &mut Context<Self, Self::Reply>,
    ) {
        // Refresh the MagicDNS view from this control update (DNS config + self node), preserving
        // the peer db and the IPv6 gate. Read by the UP pump's in-datapath responder. Done on EVERY
        // update, including ones with no node (so a DNS-config-only update still lands). The exit
        // node is re-resolved against the (preserved) peer db so `exit_doh` tracks the active exit.
        let env = &self.env;
        self.dns_view.send_modify(|view| {
            *view = Arc::new(build_dns_view(
                env,
                &msg,
                view.peers.clone(),
                view.enable_ipv6,
            ));
        });

        let Some(self_node) = &msg.node else {
            return;
        };

        // Build the device exactly once: the first StateUpdate with a node `.take()`s the overlay
        // halves; subsequent updates find them gone and short-circuit.
        let (Some(up), Some(down)) = (
            self.overlay_to_dataplane.take(),
            self.overlay_from_dataplane.take(),
        ) else {
            return;
        };

        let device_config =
            tun_config_from_control(&self.tun_config, self_node.tailnet_address.ipv4);

        // FAIL-CLOSED, no silent fallback: a message handler cannot return `Result` to propagate a
        // device-creation failure back to `Runtime::spawn`, and the device cannot be created
        // eagerly at spawn time (the tailnet prefix is unknown until this first StateUpdate). So on
        // failure we log a single clear error line and leave the actor up but idle — no packets
        // flow (no leak), and we never fall back to a netstack or a direct dial.
        let device = match AsyncTunTransport::new(&device_config) {
            Ok(d) => Arc::new(d),
            Err(e) => {
                tracing::error!(error = %e, "TUN device creation failed; no overlay data path (fail-closed)");
                return;
            }
        };

        let if_name = device.name();

        // FAIL-CLOSED host integration: program routes/DNS before any packet flows. If host
        // programming is unsupported or fails, tear down and stay idle — never pump on an
        // unrouted TUN (a half-configured host could leak or black-hole). `apply_*`/`teardown` are
        // synchronous (they shell out via `std::process`); called directly here rather than via
        // `block_in_place` because the commands are fast (device creation above is likewise
        // effectively blocking) and `block_in_place` would panic under a current-thread runtime.
        let mut host = match ts_host_net::host_net() {
            Ok(h) => h,
            Err(e) => {
                tracing::error!(error = %e, "host net unsupported; TUN idle (fail-closed)");
                return;
            }
        };
        // Whether MagicDNS is enabled AND accepted drives both the `100.100.100.100/32` route (so
        // quad-100 queries enter the TUN) and pointing the host resolver at the MagicDNS IP. With
        // `--accept-dns` off, the node ignores the tailnet DNS config: neither is programmed (the
        // responder would `REFUSED` every query anyway), mirroring Go's empty-config behavior.
        let accept_dns = self.env.accept_dns();
        let magic_dns = accept_dns && msg.dns_config.as_ref().is_some_and(|d| d.magic_dns);

        // Host-route gating read LIVE from `Env` (not a frozen spawn-time snapshot): subnet routes
        // are gated on `--accept-routes`, and the host `/0` comes only from the selected exit peer.
        // The exit-node selector is resolved against the live peer set to a stable id, exactly as
        // the route updater does (`route_updater.rs:219-222`) and the `build_dns_view`/`PeerState`
        // exit_doh resolution above — so the host FIB picks the SAME exit peer as the overlay route
        // table + source filter (anti-leak coupling). `None` (no exit node, or an unmatched
        // selector) ⇒ no peer receives a host `/0` (fail-closed).
        let accept_routes = self.env.accept_routes();
        let exit_id = self.env.exit_node().as_ref().and_then(|sel| {
            self.peers
                .as_ref()
                .and_then(|peers| sel.resolve(peers.peers().values()))
        });
        let routes = host_routes_from_node(
            self_node,
            self.peers.as_deref(),
            if_name.clone(),
            accept_routes,
            exit_id.as_ref(),
            magic_dns,
        );
        if let Err(e) = host.apply_routes(&routes) {
            tracing::error!(error = %e, "host route programming failed; TUN idle (fail-closed)");
            host.teardown();
            return; // device drops here -> interface torn down; overlay halves already taken -> idle.
        }
        // Store the bits the `PeerState` re-apply path needs to rebuild the route set without a
        // fresh `StateUpdate`: the self node, the (stable) interface name, and the MagicDNS bool.
        self.self_node = Some(Arc::new(self_node.clone()));
        self.if_name = Some(if_name.clone());
        self.last_magic_dns = magic_dns;
        if let Err(e) = host.apply_dns(&host_dns_from_dns_config(
            msg.dns_config.as_ref(),
            if_name,
            accept_dns,
        )) {
            // Best-effort: routes are already up. With MagicDNS on, the resolver now points at
            // `100.100.100.100` (intercepted in the UP pump below); with it off, nameservers are
            // empty (no-op).
            tracing::warn!(error = %e, "host dns programming failed (continuing; routes are up)");
        }
        self.host_guard = Some(HostGuard(host));

        // UP: device -> {in-datapath MagicDNS responder | dataplane}.
        let dev_up = device.clone();
        let dns_view_rx = self.dns_view.subscribe();
        // The overlay `Channel` used by the MagicDNS responder to forward recursive / split-DNS
        // queries (the forwarder netstack's; egresses over the overlay — anti-leak).
        let dns_channel = self.channel.clone();
        // Stand up the service netstack that terminates quad-100 TCP/53 (DNS over TCP), and take
        // the pipe the UP pump injects those segments into. Built before the pump is spawned so the
        // listener is already accepting when the first SYN arrives.
        let dns_tcp_tx = spawn_dns_tcp_service(
            &mut self._joinset,
            device.clone(),
            device_config.mtu.get(),
            self.dns_view.subscribe(),
            dns_channel.clone(),
        )
        .await;
        self._joinset
            .spawn(up_pump(dev_up, up, dns_view_rx, dns_channel, dns_tcp_tx));

        // DOWN: dataplane -> device.
        let dev_down = device.clone();
        let mut down = down;
        self._joinset.spawn(async move {
            while let Some(bufs) = down.recv().await {
                if let Err(e) = dev_down.send(bufs).await {
                    tracing::warn!(error = %e, "tun send error");
                }
            }

            tracing::warn!("tun downlink shut down!");
        });

        tracing::debug!(prefix = ?self_node.tailnet_address.ipv4, "TUN device created");
    }
}

impl Message<Arc<PeerState>> for TunActor {
    type Reply = ();

    async fn handle(&mut self, state: Arc<PeerState>, _ctx: &mut Context<Self, Self::Reply>) {
        // Store the latest peer db so the host-FIB peer-route fold can be (re)computed: on the next
        // device build (if the device isn't up yet) and on this re-apply path (if it is).
        self.peers = Some(state.peers.clone());

        // Resolve the configured exit node to a stable id ONCE against this peer set, reused for both
        // the `exit_doh` (MagicDNS) and the host `/0` (route fold) below so they can't disagree within
        // one handler — mirroring `route_updater.rs:219-222`'s single per-rebuild resolution. The
        // netstack path learns the active exit node from a separate route-updater-published
        // `ActiveExitNode` message; the TunActor has no such subscription, so it resolves the selector
        // against the peer db here (and on every StateUpdate). Fail-closed `None` if unmatched.
        let exit_id = self
            .env
            .exit_node()
            .as_ref()
            .and_then(|sel| sel.resolve(state.peers.peers().values()));

        // Feed the peer database into the MagicDNS view so the in-datapath responder resolves peer
        // names authoritatively. Mirrors `MagicDnsActor`'s `PeerState` handler. `exit_doh` is the
        // resolved exit peer's peerAPI DoH endpoint (fail-closed `None` if it can't proxy DNS).
        let exit_doh = exit_id.as_ref().and_then(|id| {
            state
                .peers
                .peers()
                .values()
                .find(|peer| &peer.stable_id == id)
                .and_then(|n| n.peerapi_doh_addr())
        });
        // Re-read the live accept-dns cell on this rebuild (it is runtime-settable): a
        // `Device::set_accept_dns` republish lands here, re-applying the in-datapath `decide` gate.
        let accept_dns = self.env.accept_dns();
        self.dns_view.send_modify(|view| {
            let mut next = (**view).clone();
            next.peers = Some(state.peers.clone());
            next.exit_doh = exit_doh;
            next.accept_dns = accept_dns;
            *view = Arc::new(next);
        });

        // Re-steer the host FIB to reflect the new peer set / a runtime accept-routes / exit-node
        // toggle (closes the host-FIB re-steer follow-up). Only when the device is already built —
        // before that, the build path will fold the now-stored peers itself. `set_accept_routes` /
        // `set_exit_node` re-broadcast `Arc<PeerState>` (via `RepublishState`), so a runtime toggle
        // lands here too, re-applying with the live `accept_routes`/`exit_id`.
        if let (Some(guard), Some(self_node), Some(if_name)) = (
            self.host_guard.as_mut(),
            self.self_node.as_ref(),
            self.if_name.as_ref(),
        ) {
            // `apply_routes` is an idempotent add-new/remove-gone diff with per-call rollback, so
            // re-applying a fresh set is safe and non-flapping; re-apply under the SAME `if_name` the
            // device was built with (the host-net `debug_assert`). `accept_routes` is read live.
            let routes = host_routes_from_node(
                self_node,
                Some(&state.peers),
                if_name.clone(),
                self.env.accept_routes(),
                exit_id.as_ref(),
                self.last_magic_dns,
            );
            if let Err(e) = guard.apply_routes(&routes) {
                // FAIL-CLOSED, exactly like the build path: drop the host guard so its `Drop`
                // reverses all host route/DNS state (no half-configured FIB can leak or black-hole);
                // the actor stays up but the TUN is now unrouted — idle. A subsequent peer/control
                // update will not re-program (the guard is gone), so this is a terminal idle, the
                // host-side analogue of the build path's `teardown(); return`.
                //
                // Unlike the build path (which returns before the pumps are spawned, so the device
                // Arc drops and the interface goes fully down), here the pump tasks keep the
                // interface UP with only its on-link self `/32`. That is still fail-closed: with
                // every peer/exit/subnet route removed from the host FIB, the OS steers no
                // peer/internet traffic into the TUN — the surviving on-link `/32` is just the
                // node's own address. Routes torn down ⟹ no leak, even though the iface lingers.
                tracing::error!(error = %e, "host route re-steer failed; tearing down host FIB (fail-closed)");
                self.host_guard = None;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use core::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
    use std::sync::Arc;

    use ipnet::Ipv4Net;
    use tokio::sync::watch;
    use ts_control::TunConfig;

    use super::{
        Intercept, MAGIC_DNS_IP, MAGIC_DNS_PORT, build_dns_view, host_dns_from_dns_config,
        host_routes_from_node, plan_intercept, spawn_dns_tcp_netstack, tun_config_from_control,
    };
    use crate::{
        env::{Env, ForwarderConfig},
        magic_dns::{Decision, RecursivePlan, decide, recursive_plan},
        peer_tracker::PeerDb,
    };

    /// Build a benign [`Env`] for `build_dns_view`. Only `exit_node` matters for these tests; every
    /// other forwarding preference is a default. `exit_node` is the caller-supplied selector.
    fn test_env(exit_node: Option<ts_control::ExitNodeSelector>) -> Env {
        let (_shutdown_tx, shutdown_rx) = watch::channel(false);
        Env::new(
            ts_keys::NodeState::generate(),
            shutdown_rx,
            ForwarderConfig {
                accept_routes: false,
                accept_dns: true,
                exit_node,
                forward_routes: Vec::new(),
                forward_tcp_ports: Vec::new(),
                forward_udp_ports: Vec::new(),
                forward_all_ports: false,
                forward_exit_egress: false,
                block_incoming: false,
                exit_proxy: None,
                peerapi_port: None,
                taildrop_dir: None,
                enable_ipv6: false,
                wireguard_listen_port: None,
                network_monitor: false,
                persistent_keepalive_interval: None,
                ingress_active: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            },
        )
    }

    /// A peer node that advertises a peerAPI DoH endpoint (so [`Node::peerapi_doh_addr`] is `Some`):
    /// `peerapi_port` set and `peerapi_dns_proxy` true. Stable id / address are caller-supplied so a
    /// selector can target it.
    fn exit_peer(stable_id: &str, ipv4: &str, peerapi_port: u16) -> ts_control::Node {
        use ts_control::{Node, StableNodeId, TailnetAddress};
        Node {
            id: 2,
            user_id: 0,
            stable_id: StableNodeId(stable_id.to_string()),
            hostname: stable_id.to_string(),
            tailnet: Some("ts.net".to_string()),
            tags: vec![],
            addresses: vec![
                format!("{ipv4}/32").parse().unwrap(),
                "fd7a::2/128".parse().unwrap(),
            ],
            tailnet_address: TailnetAddress {
                ipv4: format!("{ipv4}/32").parse().unwrap(),
                ipv6: "fd7a::2/128".parse().unwrap(),
            },
            node_key: [1u8; 32].into(),
            node_key_expiry: None,
            key_signature: vec![],
            machine_key: None,
            disco_key: None,
            accepted_routes: vec!["0.0.0.0/0".parse().unwrap()],
            underlay_addresses: vec![],
            derp_region: None,
            cap: Default::default(),
            cap_map: Default::default(),
            peerapi_port: Some(peerapi_port),
            peerapi_dns_proxy: true,
            is_wireguard_only: false,
            exit_node_dns_resolvers: vec![],
            peer_relay: false,
            ssh_host_keys: vec![],
            service_vips: Default::default(),
            unsigned_peer_api_only: false,
            online: None,
            last_seen: None,
        }
    }

    /// A `PeerDb` containing exactly the given exit peer.
    fn peer_db_with(peer: &ts_control::Node) -> Arc<PeerDb> {
        let mut db = PeerDb::default();
        db.upsert(peer);
        Arc::new(db)
    }

    /// A UDP global resolver, for building a recursive-forward query in [`forward_decision`].
    fn udp_resolver(addr: &str) -> ts_control::DnsResolver {
        ts_control::DnsResolver {
            transport: ts_control::ResolverTransport::Udp(addr.parse().unwrap()),
            use_with_exit_node: false,
        }
    }

    /// Build a DNS A query for `labels` (mirrors `magic_dns::tests::build_query`).
    fn build_query(id: u16, labels: &[&str]) -> Vec<u8> {
        let mut buf: Vec<u8> = Vec::new();
        buf.extend_from_slice(&id.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes()); // flags: QR=0 (query)
        buf.extend_from_slice(&1u16.to_be_bytes()); // QDCOUNT
        buf.extend_from_slice(&0u16.to_be_bytes()); // ANCOUNT
        buf.extend_from_slice(&0u16.to_be_bytes()); // NSCOUNT
        buf.extend_from_slice(&0u16.to_be_bytes()); // ARCOUNT
        for label in labels {
            buf.push(label.len() as u8);
            buf.extend_from_slice(label.as_bytes());
        }
        buf.push(0); // root label
        buf.extend_from_slice(&1u16.to_be_bytes()); // QTYPE = A
        buf.extend_from_slice(&1u16.to_be_bytes()); // QCLASS = IN
        buf
    }

    /// [`build_query`] plus an EDNS(0) OPT record advertising `udp_size` bytes, in the only shape
    /// Go's `findOPTRecord` accepts: last record in the message, root NAME, version 0, no options.
    fn build_edns_query(id: u16, labels: &[&str], udp_size: u16) -> Vec<u8> {
        let mut buf = build_query(id, labels);
        buf[11] = 1; // ARCOUNT = 1
        buf.push(0); // NAME: root
        buf.extend_from_slice(&41u16.to_be_bytes()); // TYPE: OPT
        buf.extend_from_slice(&udp_size.to_be_bytes()); // CLASS: requestor's UDP payload size
        buf.extend_from_slice(&0u32.to_be_bytes()); // TTL: extended rcode + version + flags
        buf.extend_from_slice(&0u16.to_be_bytes()); // RDLENGTH: no options
        buf
    }

    /// A plain tailnet peer: its own host `/32` at `ipv4`, plus any `subnets` it advertises
    /// (e.g. a `/24`). No peerAPI / exit-node attributes — used to exercise the host-FIB peer fold
    /// in [`host_routes_from_node`] (the peer's `/32` is always installed; subnets gate on
    /// `accept_routes`; the peer gets a `/0` only when selected as the exit). `stable_id` is
    /// caller-supplied so a selector can target it as the exit node.
    fn tailnet_peer(stable_id: &str, id: u32, ipv4: &str, subnets: &[&str]) -> ts_control::Node {
        use ts_control::{Node, StableNodeId, TailnetAddress};
        let mut accepted_routes: Vec<ipnet::IpNet> =
            vec![format!("{ipv4}/32").parse::<ipnet::IpNet>().unwrap()];
        for s in subnets {
            accepted_routes.push(s.parse().unwrap());
        }
        Node {
            id: id as i64,
            user_id: 0,
            stable_id: StableNodeId(stable_id.to_string()),
            hostname: stable_id.to_string(),
            tailnet: Some("ts.net".to_string()),
            tags: vec![],
            addresses: vec![
                format!("{ipv4}/32").parse().unwrap(),
                format!("fd7a::{id}/128").parse().unwrap(),
            ],
            tailnet_address: TailnetAddress {
                ipv4: format!("{ipv4}/32").parse().unwrap(),
                ipv6: format!("fd7a::{id}/128").parse().unwrap(),
            },
            node_key: [id as u8; 32].into(),
            node_key_expiry: None,
            key_signature: vec![],
            machine_key: None,
            disco_key: None,
            accepted_routes,
            underlay_addresses: vec![],
            derp_region: None,
            cap: Default::default(),
            cap_map: Default::default(),
            peerapi_port: None,
            peerapi_dns_proxy: false,
            is_wireguard_only: false,
            exit_node_dns_resolvers: vec![],
            peer_relay: false,
            ssh_host_keys: vec![],
            service_vips: Default::default(),
            unsigned_peer_api_only: false,
            online: None,
            last_seen: None,
        }
    }

    /// A `PeerDb` containing the given peers.
    fn peer_db_from(peers: &[&ts_control::Node]) -> PeerDb {
        let mut db = PeerDb::default();
        for p in peers {
            db.upsert(p);
        }
        db
    }

    fn prefix() -> Ipv4Net {
        Ipv4Net::new(Ipv4Addr::new(100, 64, 0, 1), 32).unwrap()
    }

    /// A self-node fixture: own host `/32`, an advertised subnet `/24`, and the exit-node default
    /// route `/0` — plus a v6 prefix to prove the v4-only filter drops it. Field set mirrors
    /// `route_updater::tests::split_router_node`.
    fn fixture_node() -> ts_control::Node {
        use ts_control::{Node, StableNodeId, TailnetAddress};
        Node {
            id: 1,
            user_id: 0,
            stable_id: StableNodeId("n1".to_string()),
            hostname: "self".to_string(),
            tailnet: Some("ts.net".to_string()),
            tags: vec![],
            addresses: vec![
                "100.64.0.1/32".parse().unwrap(),
                "fd7a::1/128".parse().unwrap(),
            ],
            tailnet_address: TailnetAddress {
                ipv4: "100.64.0.1/32".parse().unwrap(),
                ipv6: "fd7a::1/128".parse().unwrap(),
            },
            node_key: [0u8; 32].into(),
            node_key_expiry: None,
            // Cross-stream coupling (S4): `Node` gains `key_signature: Vec<u8>`. Empty here so this
            // fixture compiles after S4 lands; no TKA enforcement is exercised by tun_actor tests.
            key_signature: vec![],
            machine_key: None,
            disco_key: None,
            accepted_routes: vec![
                "100.64.0.1/32".parse().unwrap(),
                "fd7a::1/128".parse().unwrap(),
                "192.168.1.0/24".parse().unwrap(),
                "0.0.0.0/0".parse().unwrap(),
            ],
            underlay_addresses: vec![],
            derp_region: None,
            cap: Default::default(),
            cap_map: Default::default(),
            peerapi_port: None,
            peerapi_dns_proxy: false,
            is_wireguard_only: false,
            exit_node_dns_resolvers: vec![],
            peer_relay: false,
            ssh_host_keys: vec![],
            service_vips: Default::default(),
            unsigned_peer_api_only: false,
            online: None,
            last_seen: None,
        }
    }

    /// With `accept_routes` set, the routed set carries the self node's advertised subnet `/24` but
    /// never the self `/32` (the device builder owns the on-link prefix) and never the self node's
    /// own `/0` (the host `/0` is now keyed on the selected exit PEER, not the self node — see the
    /// per-peer-`/0` tests below). This is the post-fix asymmetry fix: a self-node `/0` echo is
    /// ignored.
    #[test]
    fn host_routes_includes_self_subnet_excludes_self_and_self_default() {
        let node = fixture_node();
        // No peers, no exit node: only the self node's own non-`/0` routes contribute.
        let routes = host_routes_from_node(&node, None, "utun9".to_owned(), true, None, false);

        assert_eq!(routes.if_name, "utun9");
        assert_eq!(routes.self_v4, "100.64.0.1/32".parse::<Ipv4Net>().unwrap());
        assert!(
            routes.routed.contains(&"192.168.1.0/24".parse().unwrap()),
            "self-advertised subnet /24 must be routed when accept_routes is set"
        );
        assert!(
            !routes.routed.contains(&"0.0.0.0/0".parse().unwrap()),
            "the self node's own /0 echo must NOT be installed (host /0 is per-exit-peer)"
        );
        assert!(
            !routes.routed.contains(&"100.64.0.1/32".parse().unwrap()),
            "self /32 must never be re-routed"
        );
    }

    /// `accept_routes = false` drops advertised subnet routes (fail-closed), for both the self node
    /// and the peer fold.
    #[test]
    fn host_routes_excludes_subnet_without_accept_routes() {
        let node = fixture_node();
        let peer = tailnet_peer("p", 2, "100.64.0.2", &["10.0.0.0/24"]);
        let db = peer_db_from(&[&peer]);
        let routes =
            host_routes_from_node(&node, Some(&db), "utun9".to_owned(), false, None, false);
        assert!(
            !routes.routed.contains(&"192.168.1.0/24".parse().unwrap()),
            "self subnet /24 must be excluded when accept_routes is false"
        );
        assert!(
            !routes.routed.contains(&"10.0.0.0/24".parse().unwrap()),
            "peer subnet /24 must be excluded when accept_routes is false"
        );
        // The peer's own host /32 is ALWAYS installed regardless of accept_routes (so the peer stays
        // reachable) — this is the core of the consumer-blocking-bug fix.
        assert!(
            routes.routed.contains(&"100.64.0.2/32".parse().unwrap()),
            "peer /32 must always be routed even with accept_routes false"
        );
    }

    /// IPv6 prefixes are dropped by construction (v4-only invariant), from both the self node and
    /// any peer.
    #[test]
    fn host_routes_drops_ipv6() {
        // `HostRoutes.routed` is `Vec<Ipv4Net>`, so v6 cannot even be represented; assert
        // behaviorally that a v6 subnet route — on the self node OR on a peer — leaves the v4-only
        // routed set unchanged.
        let baseline =
            host_routes_from_node(&fixture_node(), None, "utun9".to_owned(), true, None, false);

        let mut node_v6 = fixture_node();
        node_v6
            .accepted_routes
            .push("2001:db8::/32".parse().unwrap());
        let routes_v6 =
            host_routes_from_node(&node_v6, None, "utun9".to_owned(), true, None, false);
        assert_eq!(
            routes_v6.routed, baseline.routed,
            "adding a v6 subnet to the self node must not change the v4-only routed set"
        );

        // A peer whose only routes are v6 (beyond its v4 /32) contributes only its v4 /32.
        let mut v6_peer = tailnet_peer("v6p", 3, "100.64.0.3", &[]);
        v6_peer
            .accepted_routes
            .push("2001:db8:1::/48".parse().unwrap());
        let db = peer_db_from(&[&v6_peer]);
        let routes_peer_v6 = host_routes_from_node(
            &fixture_node(),
            Some(&db),
            "utun9".to_owned(),
            true,
            None,
            false,
        );
        assert!(
            routes_peer_v6
                .routed
                .contains(&"100.64.0.3/32".parse().unwrap()),
            "the peer's v4 /32 is installed"
        );
        assert!(
            !routes_peer_v6
                .routed
                .iter()
                .any(|n| n.to_string().contains("2001")),
            "no v6 prefix can appear in the v4-only routed set"
        );
    }

    /// PEER FOLD (the core regression guard for the consumer-blocking bug + the per-peer anti-leak
    /// `/0` gate): with a self node and a `PeerDb` of multiple peers, the routed set contains EACH
    /// peer's `/32` (so the OS can route to every peer), an advertised peer subnet ONLY when
    /// `accept_routes`, the self `/32` excluded, the MagicDNS `/32` present when `magic_dns`, and a
    /// peer `/0` ONLY when that peer is the resolved `exit_id` (never otherwise).
    #[test]
    fn host_routes_folds_peer_allowed_ips_and_gates_default_on_exit() {
        use ts_control::StableNodeId;

        let node = fixture_node();
        let p1 = tailnet_peer("p1", 2, "100.64.0.2", &[]); // plain peer, /32 only
        let p2 = tailnet_peer("p2", 3, "100.64.0.3", &["10.1.0.0/24"]); // advertises a subnet
        let exit = tailnet_peer("exit", 4, "100.64.0.4", &["0.0.0.0/0"]); // advertises default
        let db = peer_db_from(&[&p1, &p2, &exit]);

        let p1_32: Ipv4Net = "100.64.0.2/32".parse().unwrap();
        let p2_32: Ipv4Net = "100.64.0.3/32".parse().unwrap();
        let exit_32: Ipv4Net = "100.64.0.4/32".parse().unwrap();
        let p2_subnet: Ipv4Net = "10.1.0.0/24".parse().unwrap();
        let default: Ipv4Net = "0.0.0.0/0".parse().unwrap();
        let magic: Ipv4Net = "100.100.100.100/32".parse().unwrap();

        // accept_routes = true, NO exit node selected, MagicDNS on.
        let routes = host_routes_from_node(&node, Some(&db), "utun9".to_owned(), true, None, true);
        // Every peer's /32 is present (the bug fix: the OS now has a route to each peer).
        assert!(routes.routed.contains(&p1_32), "peer p1 /32 must be routed");
        assert!(routes.routed.contains(&p2_32), "peer p2 /32 must be routed");
        assert!(
            routes.routed.contains(&exit_32),
            "peer exit /32 must be routed"
        );
        // The advertised subnet is present because accept_routes is true.
        assert!(
            routes.routed.contains(&p2_subnet),
            "peer-advertised subnet must be routed when accept_routes is true"
        );
        // The self /32 is never re-routed.
        assert!(!routes.routed.contains(&"100.64.0.1/32".parse().unwrap()));
        // MagicDNS /32 present.
        assert!(
            routes.routed.contains(&magic),
            "MagicDNS /32 must be present when magic_dns"
        );
        // No exit selected ⇒ NO /0 at all (fail-closed; the exit peer's /0 is gated out).
        assert!(
            !routes.routed.contains(&default),
            "no /0 may appear when no exit peer is selected (anti-leak)"
        );

        // accept_routes = false ⇒ the advertised subnet drops, but every peer /32 stays.
        let no_accept =
            host_routes_from_node(&node, Some(&db), "utun9".to_owned(), false, None, true);
        assert!(no_accept.routed.contains(&p1_32));
        assert!(no_accept.routed.contains(&p2_32));
        assert!(no_accept.routed.contains(&exit_32));
        assert!(
            !no_accept.routed.contains(&p2_subnet),
            "peer subnet must drop when accept_routes is false"
        );

        // Select `exit` as the exit node ⇒ ITS /0 (and only its) appears.
        let exit_id = StableNodeId("exit".to_owned());
        let with_exit = host_routes_from_node(
            &node,
            Some(&db),
            "utun9".to_owned(),
            true,
            Some(&exit_id),
            true,
        );
        assert!(
            with_exit.routed.contains(&default),
            "the selected exit peer's /0 must be installed"
        );
        assert!(
            with_exit.routed.contains(&exit_32),
            "the exit peer's /32 stays routed"
        );

        // Select a NON-exit-advertising peer (p1, which has no /0) as the exit ⇒ still no /0 (it
        // advertises none), proving the /0 comes strictly from the chosen peer's AllowedIPs.
        let p1_id = StableNodeId("p1".to_owned());
        let wrong_exit = host_routes_from_node(
            &node,
            Some(&db),
            "utun9".to_owned(),
            true,
            Some(&p1_id),
            true,
        );
        assert!(
            !wrong_exit.routed.contains(&default),
            "a selected peer that advertises no /0 contributes no host /0"
        );

        // The load-bearing anti-leak gate: the `/0`-advertising peer (`exit`) IS in the db, but a
        // DIFFERENT peer (`p2`) is the selected exit. `exit`'s advertised `/0` must be gated out —
        // the host default route is keyed on WHICH peer is selected, never on "some peer advertises
        // /0 and an exit is configured". A regression here would route all internet traffic through
        // a non-selected peer = a real egress leak.
        let p2_id = StableNodeId("p2".to_owned());
        let other_exit = host_routes_from_node(
            &node,
            Some(&db),
            "utun9".to_owned(),
            true,
            Some(&p2_id),
            true,
        );
        assert!(
            !other_exit.routed.contains(&default),
            "the /0 advertised by `exit` must NOT be installed when a different peer (p2) is the \
             selected exit — the default route is keyed on the selected peer only (anti-leak)"
        );
        // p2 (the selected exit) advertises no /0, so still none; its own /32 + subnet stay.
        assert!(other_exit.routed.contains(&p2_32));
        assert!(other_exit.routed.contains(&p2_subnet));
    }

    /// DEDUP: two peers advertising the SAME subnet (and a subnet also advertised by the self node)
    /// install that prefix exactly once.
    #[test]
    fn host_routes_dedups_overlapping_peer_subnets() {
        let node = fixture_node(); // advertises 192.168.1.0/24
        let a = tailnet_peer("a", 2, "100.64.0.2", &["10.9.0.0/24"]);
        let b = tailnet_peer("b", 3, "100.64.0.3", &["10.9.0.0/24", "192.168.1.0/24"]);
        let db = peer_db_from(&[&a, &b]);

        let routes = host_routes_from_node(&node, Some(&db), "utun9".to_owned(), true, None, false);

        let shared: Ipv4Net = "10.9.0.0/24".parse().unwrap();
        let self_subnet: Ipv4Net = "192.168.1.0/24".parse().unwrap();
        assert_eq!(
            routes.routed.iter().filter(|n| **n == shared).count(),
            1,
            "a subnet advertised by two peers must be installed exactly once"
        );
        assert_eq!(
            routes.routed.iter().filter(|n| **n == self_subnet).count(),
            1,
            "a subnet advertised by both the self node and a peer must be installed exactly once"
        );
    }

    /// DNS: with MagicDNS enabled the host resolver points at `100.100.100.100` and search domains
    /// map through; with it disabled both stay empty (fail-closed no-op).
    #[test]
    fn host_dns_nameservers_point_at_magic_dns_when_enabled() {
        // No DNS config ⇒ empty everything (MagicDNS not enabled). (accept_dns true throughout
        // unless noted — it only ever further restricts.)
        let none = host_dns_from_dns_config(None, "utun9".to_owned(), true);
        assert!(none.nameservers.is_empty());
        assert!(none.match_domains.is_empty());

        // MagicDNS on ⇒ resolver points at the MagicDNS IP + search domains carried.
        let on = ts_control::DnsConfig {
            magic_dns: true,
            search_domains: vec!["user.ts.net.".to_owned()],
            ..Default::default()
        };
        let dns_on = host_dns_from_dns_config(Some(&on), "utun9".to_owned(), true);
        assert_eq!(
            dns_on.nameservers,
            vec![Ipv4Addr::new(100, 100, 100, 100)],
            "nameservers must point at the MagicDNS IP when MagicDNS is enabled"
        );
        assert_eq!(dns_on.match_domains, vec!["user.ts.net.".to_owned()]);

        // accept_dns OFF ⇒ even with MagicDNS on, the host resolver is NOT pointed at quad-100 and
        // no search domains are programmed (the node ignores the tailnet DNS config — fail-closed,
        // same as MagicDNS off).
        let dns_no_accept = host_dns_from_dns_config(Some(&on), "utun9".to_owned(), false);
        assert!(
            dns_no_accept.nameservers.is_empty(),
            "accept_dns off must not point the resolver at the MagicDNS IP"
        );
        assert!(
            dns_no_accept.match_domains.is_empty(),
            "accept_dns off must program no search domains"
        );

        // MagicDNS off ⇒ empty nameservers (no dead address) AND no search domains.
        let off = ts_control::DnsConfig {
            magic_dns: false,
            search_domains: vec!["user.ts.net.".to_owned()],
            ..Default::default()
        };
        let dns_off = host_dns_from_dns_config(Some(&off), "utun9".to_owned(), true);
        assert!(
            dns_off.nameservers.is_empty(),
            "nameservers must stay empty when MagicDNS is disabled"
        );
        assert!(dns_off.match_domains.is_empty());
    }

    /// `match_domains` is the search domains UNION the split-DNS route suffixes (Go
    /// `OSConfig.MatchDomains`), deduped. This is what scopes the host resolver; a split-DNS route
    /// with no search domain must still produce a scoped match domain so the macOS host layer never
    /// falls back to a global resolver.
    #[test]
    fn host_dns_match_domains_union_search_and_routes() {
        use std::collections::BTreeMap;

        // Search domains + two split-DNS routes, one of which overlaps a search domain.
        let mut routes = BTreeMap::new();
        routes.insert("corp.example.com".to_owned(), vec![]);
        routes.insert("user.ts.net".to_owned(), vec![]); // overlaps the search domain below
        let cfg = ts_control::DnsConfig {
            magic_dns: true,
            search_domains: vec!["user.ts.net".to_owned()],
            routes,
            ..Default::default()
        };
        let host = host_dns_from_dns_config(Some(&cfg), "utun9".to_owned(), true);
        // Search domain first, then the route suffix not already present; the overlapping route is
        // deduped (not added twice).
        assert_eq!(
            host.match_domains,
            vec!["user.ts.net".to_owned(), "corp.example.com".to_owned()],
            "match_domains = search ∪ route suffixes, deduped, search-first"
        );
    }

    /// A split-DNS route with NO search domain still yields a scoped match domain (the route suffix),
    /// so the macOS host layer scopes the resolver instead of installing a global one. This is the
    /// exact case the global-capture bug hit: MagicDNS on, no search domain.
    #[test]
    fn host_dns_route_only_still_scopes() {
        use std::collections::BTreeMap;
        let mut routes = BTreeMap::new();
        routes.insert("internal.corp".to_owned(), vec![]);
        let cfg = ts_control::DnsConfig {
            magic_dns: true,
            search_domains: vec![], // no search domain — previously → empty match_domains → global
            routes,
            ..Default::default()
        };
        let host = host_dns_from_dns_config(Some(&cfg), "utun9".to_owned(), true);
        assert_eq!(
            host.match_domains,
            vec!["internal.corp".to_owned()],
            "a route-only config must still scope the resolver to the route suffix"
        );
    }

    /// MagicDNS on but NO search domain and NO route → `match_domains` is empty. The host layer then
    /// installs no resolver at all (macOS) rather than a global one — verified by the
    /// `match_domains.is_empty()` path; here we just pin that this config yields the empty set so a
    /// regression that re-introduced a default suffix would be caught.
    #[test]
    fn host_dns_no_domains_yields_empty_match_domains() {
        let cfg = ts_control::DnsConfig {
            magic_dns: true,
            search_domains: vec![],
            ..Default::default()
        };
        let host = host_dns_from_dns_config(Some(&cfg), "utun9".to_owned(), true);
        assert_eq!(
            host.nameservers,
            vec![Ipv4Addr::new(100, 100, 100, 100)],
            "MagicDNS on still points nameservers at quad-100"
        );
        assert!(
            host.match_domains.is_empty(),
            "no search domain and no route ⇒ empty match_domains (host layer installs no resolver)"
        );
    }

    /// The union never emits a global/empty match domain. `DnsConfig`'s parser drops the `.`/empty
    /// route key (proven by `ts_control`'s `from_serde_drops_empty_route_keys_*`), so a `DnsConfig`
    /// can never carry one; this pins the consuming side — even were a `.`/`""` key somehow present
    /// in `routes`, the resulting `match_domains` must contain no global/empty entry that would scope
    /// the host resolver globally. Defense-in-depth on the cross-module contract.
    #[test]
    fn host_dns_match_domains_never_global_or_empty() {
        use std::collections::BTreeMap;

        // Construct a config directly with a real suffix plus (hypothetically) a global/empty key —
        // the union must surface the real suffix and never a `.`/`""` entry.
        let mut routes = BTreeMap::new();
        routes.insert("corp.ts.net".to_owned(), vec![]);
        // (A `.`/`""` key cannot occur post-parse, but assert the consuming side is clean regardless.)
        let cfg = ts_control::DnsConfig {
            magic_dns: true,
            search_domains: vec![],
            routes,
            ..Default::default()
        };
        let host = host_dns_from_dns_config(Some(&cfg), "utun9".to_owned(), true);
        assert!(
            !host.match_domains.iter().any(|d| d == "." || d.is_empty()),
            "no global/empty match domain may ever reach the host resolver"
        );
        assert_eq!(host.match_domains, vec!["corp.ts.net".to_owned()]);
    }

    /// The MagicDNS service IP `100.100.100.100/32` is steered into the TUN exactly when MagicDNS is
    /// enabled (so the host's quad-100 queries enter the datapath), and never when it is disabled.
    #[test]
    fn host_routes_includes_magic_dns_when_enabled() {
        let node = fixture_node();
        let magic_dns_net: Ipv4Net = "100.100.100.100/32".parse().unwrap();

        let with = host_routes_from_node(&node, None, "utun9".to_owned(), true, None, true);
        assert!(
            with.routed.contains(&magic_dns_net),
            "100.100.100.100/32 must be routed when MagicDNS is enabled"
        );

        let without = host_routes_from_node(&node, None, "utun9".to_owned(), true, None, false);
        assert!(
            !without.routed.contains(&magic_dns_net),
            "100.100.100.100/32 must not be routed when MagicDNS is disabled"
        );
    }

    /// `classify_service_ip` extracts the DNS payload + source endpoint from a quad-100/UDP/53
    /// packet, and `build_dns_response` round-trips: the synthesized reply parses back as an
    /// IPv4/UDP datagram FROM `100.100.100.100:53` TO the original querier carrying the payload.
    #[test]
    fn classify_and_build_round_trip() {
        use super::{ServiceIpPacket, build_dns_response, classify_service_ip};

        let client: SocketAddrV4 = "100.64.0.7:34567".parse().unwrap();
        let payload = b"hello-dns-query";

        // Hand-build an IPv4/UDP packet: client -> 100.100.100.100:53.
        let query_pkt = {
            let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), [100, 100, 100, 100], 64)
                .udp(client.port(), 53);
            let mut out = Vec::with_capacity(b.size(payload.len()));
            b.write(&mut out, payload).unwrap();
            out
        };

        let ServiceIpPacket::DnsQuery(q) = classify_service_ip(&query_pkt) else {
            panic!("quad-100/udp/53 is classified as DNS");
        };
        assert_eq!(q.src, client, "source endpoint extracted");
        assert_eq!(q.dns_payload, payload, "DNS payload extracted");

        // Build a response carrying a (different) payload and confirm src/dst swap + payload.
        let resp_payload = b"a-dns-answer";
        let reply_pkt = build_dns_response(client, resp_payload);
        let sliced = etherparse::SlicedPacket::from_ip(&reply_pkt).expect("reply parses");
        match sliced.net {
            Some(etherparse::NetSlice::Ipv4(ip)) => {
                assert_eq!(
                    ip.header().source_addr(),
                    Ipv4Addr::new(100, 100, 100, 100),
                    "reply is FROM the MagicDNS service IP"
                );
                assert_eq!(
                    ip.header().destination_addr(),
                    *client.ip(),
                    "reply is TO the original querier"
                );
            }
            _ => panic!("reply must be IPv4"),
        }
        match sliced.transport {
            Some(etherparse::TransportSlice::Udp(udp)) => {
                assert_eq!(udp.source_port(), 53, "reply source port is 53");
                assert_eq!(
                    udp.destination_port(),
                    client.port(),
                    "reply dest port is the querier's source port"
                );
                assert_eq!(udp.payload(), resp_payload, "reply carries the DNS answer");
            }
            _ => panic!("reply must be UDP"),
        }
    }

    /// A UDP datagram from `client` to `dst:dport`.
    fn udp_packet(client: SocketAddrV4, dst: [u8; 4], dport: u16) -> Vec<u8> {
        let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), dst, 64)
            .udp(client.port(), dport);
        let mut out = Vec::new();
        b.write(&mut out, b"x").unwrap();
        out
    }

    /// A bare SYN from `client` to `dst:dport`, carrying the given initial sequence number.
    fn syn_packet(client: SocketAddrV4, dst: [u8; 4], dport: u16, seq: u32) -> Vec<u8> {
        let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), dst, 64)
            .tcp(client.port(), dport, seq, 1024)
            .syn();
        let mut out = Vec::new();
        b.write(&mut out, &[]).unwrap();
        out
    }

    /// An ICMP echo request from `client`'s IP to `dst` — a non-TCP, non-UDP quad-100 packet.
    fn icmp_packet(client: SocketAddrV4, dst: [u8; 4]) -> Vec<u8> {
        let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), dst, 64)
            .icmpv4_echo_request(1, 1);
        let mut out = Vec::new();
        b.write(&mut out, b"ping").unwrap();
        out
    }

    /// Packets addressed somewhere other than the service IP are `Foreign` and go to the overlay
    /// unchanged — the absorb must not swallow ordinary traffic. Unparseable bytes are `Foreign`
    /// too: we cannot tell where they are addressed, so we do not claim them.
    #[test]
    fn classify_passthrough_for_foreign_destinations() {
        use super::{ServiceIpPacket, classify_service_ip};

        let client: SocketAddrV4 = "100.64.0.7:1234".parse().unwrap();

        assert!(
            matches!(
                classify_service_ip(&udp_packet(client, [8, 8, 8, 8], 53)),
                ServiceIpPacket::Foreign
            ),
            "UDP/53 to a non-quad-100 IP must pass through"
        );
        assert!(
            matches!(
                classify_service_ip(&syn_packet(client, [192, 0, 2, 10], 853, 7)),
                ServiceIpPacket::Foreign
            ),
            "a TCP SYN to a non-quad-100 IP must pass through"
        );
        assert!(
            matches!(classify_service_ip(&[0u8; 4]), ServiceIpPacket::Foreign),
            "unparseable bytes must pass through"
        );
    }

    /// The service IP absorbs EVERYTHING addressed to it, not just UDP/53: any other UDP port, any
    /// TCP port this node does not serve, and any other IP protocol. None of these may be handed to
    /// the overlay — quad-100 is this node's own address and no peer owns it. TCP earns a RST; the
    /// rest are dropped silently.
    #[test]
    fn service_ip_absorbs_every_non_dns_packet() {
        use super::{ServiceIpPacket, classify_service_ip};

        let client: SocketAddrV4 = "100.64.0.7:1234".parse().unwrap();
        const QUAD_100: [u8; 4] = [100, 100, 100, 100];

        // A speculative DoT probe on quad-100:853 — upstream's own cited example.
        for (pkt, what) in [
            (syn_packet(client, QUAD_100, 853, 7), "a DoT SYN on :853"),
            (syn_packet(client, QUAD_100, 80, 7), "an HTTP SYN on :80"),
        ] {
            let ServiceIpPacket::Absorbed { reset } = classify_service_ip(&pkt) else {
                panic!("{what} to quad-100 must be absorbed, never forwarded to the overlay");
            };
            assert!(reset.is_some(), "{what} must be answered with a RST");
        }

        for (pkt, what) in [
            (udp_packet(client, QUAD_100, 443), "UDP to a non-53 port"),
            (icmp_packet(client, QUAD_100), "an ICMP echo request"),
        ] {
            let ServiceIpPacket::Absorbed { reset } = classify_service_ip(&pkt) else {
                panic!("{what} to quad-100 must be absorbed, never forwarded to the overlay");
            };
            assert!(reset.is_none(), "{what} is dropped silently — no RST");
        }
    }

    /// TCP/53 to the service IP is the transport a stub resolver retries on after a truncated UDP
    /// answer, and upstream serves it: `acceptTCP` computes
    /// `hittingDNS := hittingServiceIP && reqDetails.LocalPort == 53` and installs the DNS handler,
    /// reaching its `r.Complete(true)` RST only for a quad-100 port it does not serve
    /// (wgengine/netstack/netstack.go @ `9ea7cba44591e0cd840c6c94d23274dd222059bf`). So the segment
    /// must be terminated, not reset — while every neighbouring port keeps its RST, which is what
    /// stops this being a blanket "stop resetting quad-100 TCP".
    #[tokio::test]
    async fn service_ip_tcp_dns_is_terminated_not_reset() {
        use super::{ServiceIpPacket, classify_service_ip};

        let client: SocketAddrV4 = "100.64.0.7:44321".parse().unwrap();
        const QUAD_100: [u8; 4] = [100, 100, 100, 100];

        assert!(
            matches!(
                classify_service_ip(&syn_packet(client, QUAD_100, 53, 7)),
                ServiceIpPacket::DnsStream
            ),
            "a SYN to quad-100:53 must be handed to the DNS-over-TCP service, never RST"
        );

        // And the pump sees the same verdict through `plan_intercept`: hand it to the service
        // netstack, never to the overlay and never a RST.
        let view = build_dns_view(&test_env(None), &dns_update(vec![]), None, false);
        assert!(
            matches!(
                plan_intercept(&view, &syn_packet(client, QUAD_100, 53, 7)),
                Intercept::DnsStream
            ),
            "the UP pump must route a quad-100:53 segment into the DNS-over-TCP service"
        );

        // The neighbours on either side of 53 are still unserved ports, and still get a RST.
        for port in [52, 54, 853] {
            let ServiceIpPacket::Absorbed { reset } =
                classify_service_ip(&syn_packet(client, QUAD_100, port, 7))
            else {
                panic!("quad-100:{port} is not served and must be absorbed with a RST");
            };
            assert!(
                reset.is_some(),
                "quad-100:{port} is not served and must be answered with a RST"
            );
        }
    }

    /// End to end over the real service netstack: a TCP client on the far side of the TUN opens
    /// `100.100.100.100:53`, sends a length-prefixed query, and gets a length-prefixed answer back.
    ///
    /// Everything between the two ends is production code — `spawn_dns_tcp_netstack` builds the
    /// stack, assigns the service IP, binds the listener and starts `dns_over_tcp::serve` — driven
    /// exactly as the UP pump and the TUN drive it: raw IP packets in one end, raw IP packets out
    /// the other. The client is a second netstack standing in for the host's stub resolver, and the
    /// two pumps between them stand in for the TUN. Before this change the same SYN was answered
    /// with a RST and the exchange could not begin.
    #[tokio::test]
    async fn service_netstack_answers_a_dns_query_over_tcp() {
        use netstack::{CreateSocket, HasChannel, netcore::NetstackControl};
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        // The client stands in for the host's stub resolver, at this node's own tailnet address.
        const CLIENT: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(100, 64, 0, 1), 44321);

        let mut joinset = tokio::task::JoinSet::new();

        // The view the responder answers from: one peer, `peer.user.ts.net` at `100.64.0.9`, so the
        // query resolves authoritatively and no upstream is ever consulted.
        let mut peer = exit_peer("peer", "100.64.0.9", 1080);
        peer.tailnet = Some("user.ts.net".to_owned());
        let view = build_dns_view(
            &test_env(None),
            &dns_update(vec![]),
            Some(peer_db_with(&peer)),
            false,
        );
        let (_view_tx, view_rx) = watch::channel(Arc::new(view));

        // The forwarding channel: a netstack that is never run, because nothing here forwards.
        let (unused_stack, _unused_pipe) = netstack::piped(netstack::netcore::Config::default());
        let forward_channel = unused_stack.command_channel();

        let (service_tx, mut service_rx) =
            spawn_dns_tcp_netstack(&mut joinset, 1280, view_rx, forward_channel).await;

        // The client: a second netstack holding this node's tailnet address, wired to the service
        // stack by the two pumps that stand in for the TUN.
        let (mut client_stack, mut client_pipe) = netstack::piped(netstack::netcore::Config {
            mtu: 1280,
            ..Default::default()
        });
        let client_channel = client_stack.command_channel();
        joinset.spawn(async move { client_stack.run_tokio().await });
        client_channel
            .set_ips([core::net::IpAddr::V4(*CLIENT.ip())])
            .await
            .expect("client netstack takes its address");

        let client_out = client_pipe.tx.clone();
        joinset.spawn(async move {
            while let Some(pkt) = service_rx.recv_async().await {
                client_out.send_async(&pkt).await;
            }
        });
        joinset.spawn(async move {
            while let Some(pkt) = client_pipe.rx.recv_async().await {
                service_tx.send_async(&pkt).await;
            }
        });

        let mut stream = client_channel
            .tcp_connect(
                SocketAddr::V4(CLIENT),
                SocketAddr::V4(SocketAddrV4::new(MAGIC_DNS_IP, MAGIC_DNS_PORT)),
            )
            .await
            .expect("the service netstack completes the handshake instead of resetting it");

        // RFC 1035 §4.2.2 framing: two-byte big-endian length, then the message.
        let query = build_query(0x7777, &["peer", "user", "ts", "net"]);
        let len = u16::try_from(query.len()).expect("a query fits a length prefix");
        stream
            .write_all(&len.to_be_bytes())
            .await
            .expect("write the length prefix");
        stream.write_all(&query).await.expect("write the query");

        let mut len_buf = [0u8; 2];
        stream
            .read_exact(&mut len_buf)
            .await
            .expect("the answer carries its own length prefix");
        let mut answer = vec![0u8; usize::from(u16::from_be_bytes(len_buf))];
        stream
            .read_exact(&mut answer)
            .await
            .expect("read the answer");

        assert_eq!(
            answer[0..2],
            query[0..2],
            "the answer echoes the query's transaction id"
        );
        assert_eq!(answer[3] & 0x0F, 0, "NOERROR");
        assert_eq!(
            u16::from_be_bytes([answer[6], answer[7]]),
            1,
            "one answer record"
        );
        assert_eq!(
            &answer[answer.len() - 4..],
            &[100, 64, 0, 9],
            "and it is the peer's tailnet address"
        );
    }

    /// `build_tcp_reset` answers an unserved quad-100 TCP port per the reset generation in RFC 9293
    /// §3.10.7, CLOSED state (the rules smoltcp's `rst_reply` implements, so the TUN transport resets
    /// exactly as the netstack transport does): a SYN gets RST|ACK at sequence 0 acknowledging
    /// `SEG.SEQ + 1`; a segment
    /// carrying ACK gets a bare RST at that ACK; an inbound RST is never answered at all.
    #[test]
    fn unserved_service_ip_tcp_port_is_reset() {
        use super::{ServiceIpPacket, classify_service_ip};

        let client: SocketAddrV4 = "100.64.0.7:44321".parse().unwrap();
        const QUAD_100: [u8; 4] = [100, 100, 100, 100];

        // A bare SYN to :853.
        let ServiceIpPacket::Absorbed { reset: Some(rst) } =
            classify_service_ip(&syn_packet(client, QUAD_100, 853, 1000))
        else {
            panic!("a SYN to an unserved quad-100 port must produce a RST");
        };
        let sliced = etherparse::SlicedPacket::from_ip(&rst).expect("the RST parses");
        match sliced.net {
            Some(etherparse::NetSlice::Ipv4(ip)) => {
                assert_eq!(
                    ip.header().source_addr(),
                    Ipv4Addr::new(100, 100, 100, 100),
                    "the RST comes FROM the service IP"
                );
                assert_eq!(
                    ip.header().destination_addr(),
                    *client.ip(),
                    "the RST goes back TO the host that probed"
                );
            }
            _ => panic!("the RST must be IPv4"),
        }
        match sliced.transport {
            Some(etherparse::TransportSlice::Tcp(tcp)) => {
                assert!(tcp.rst(), "RST flag set");
                assert_eq!(tcp.source_port(), 853, "RST comes from the probed port");
                assert_eq!(
                    tcp.destination_port(),
                    client.port(),
                    "RST goes to the prober's port"
                );
                assert!(tcp.ack(), "an un-ACKed SYN is answered with RST|ACK");
                assert_eq!(tcp.sequence_number(), 0, "RST|ACK carries sequence 0");
                assert_eq!(
                    tcp.acknowledgment_number(),
                    1001,
                    "SYN occupies one sequence number: ack = SEG.SEQ + 1"
                );
            }
            _ => panic!("the RST must be TCP"),
        }

        // A segment already carrying ACK (a stray data segment from a half-open connection) gets a
        // bare RST seeded from its acknowledgment number.
        let acked = {
            let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), QUAD_100, 64)
                .tcp(client.port(), 853, 5, 1024)
                .ack(4242);
            let mut out = Vec::new();
            b.write(&mut out, b"payload").unwrap();
            out
        };
        let ServiceIpPacket::Absorbed { reset: Some(rst) } = classify_service_ip(&acked) else {
            panic!("an ACKed segment to an unserved quad-100 port must produce a RST");
        };
        let sliced = etherparse::SlicedPacket::from_ip(&rst).expect("the RST parses");
        match sliced.transport {
            Some(etherparse::TransportSlice::Tcp(tcp)) => {
                assert!(tcp.rst(), "RST flag set");
                assert!(
                    !tcp.ack(),
                    "an ACKed segment gets a bare RST, no ACK of ours"
                );
                assert_eq!(
                    tcp.sequence_number(),
                    4242,
                    "the bare RST sits at the sequence the sender already acknowledged"
                );
            }
            _ => panic!("the RST must be TCP"),
        }

        // An inbound RST is absorbed but never answered — otherwise two ends trade resets forever.
        let inbound_rst = {
            let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), QUAD_100, 64)
                .tcp(client.port(), 853, 9, 0)
                .rst();
            let mut out = Vec::new();
            b.write(&mut out, &[]).unwrap();
            out
        };
        let ServiceIpPacket::Absorbed { reset } = classify_service_ip(&inbound_rst) else {
            panic!("an inbound RST to quad-100 is still absorbed");
        };
        assert!(reset.is_none(), "a RST is never answered with another RST");
    }

    /// Build a `StateUpdate` carrying the self node + a MagicDNS-on config with the given global
    /// resolvers (used to drive a recursive forward).
    fn dns_update(resolvers: Vec<ts_control::DnsResolver>) -> ts_control::StateUpdate {
        ts_control::StateUpdate {
            session_handle: None,
            seq: 0,
            keep_alive: false,
            derp: None,
            node: Some(fixture_node()),
            peer_update: None,
            peer_patches: Vec::new(),
            user_profiles: Vec::new(),
            ping: None,
            packetfilter: None,
            cap_grants: None,
            pop_browser_url: None,
            dial_plan: None,
            dns_config: Some(ts_control::DnsConfig {
                magic_dns: true,
                search_domains: vec!["user.ts.net".to_owned()],
                resolvers,
                ..Default::default()
            }),
            ssh_policy: None,
            tka: None,
            online_change: Default::default(),
            peer_seen_change: Default::default(),
        }
    }

    /// `build_dns_view` mirrors `MagicDnsActor`'s construction: cfg + self_node from the update,
    /// `enable_ipv6` threaded. `exit_doh` covers BOTH cases: no exit node configured (or unresolved)
    /// ⇒ `None`; a configured selector that resolves to an active exit peer with a peerAPI DoH
    /// endpoint ⇒ `Some(addr)`.
    #[tokio::test]
    async fn build_dns_view_maps_update() {
        let update = dns_update(vec![]);

        // No exit node configured ⇒ exit_doh None (even with a peer db present).
        let no_exit_env = test_env(None);
        let peer = exit_peer("exit", "100.64.0.9", 1080);
        let db = peer_db_with(&peer);
        let view = build_dns_view(&no_exit_env, &update, Some(db.clone()), true);
        assert!(view.cfg.magic_dns, "dns config carried");
        assert!(view.self_node.is_some(), "self node carried");
        assert!(view.peers.is_some(), "peer db passed through");
        assert!(
            view.exit_doh.is_none(),
            "no exit node configured ⇒ exit_doh None"
        );
        assert!(view.enable_ipv6, "ipv6 gate threaded from Env");

        // Active exit node configured + a peer with a peerAPI DoH endpoint ⇒ exit_doh Some(addr),
        // resolved from the selector against the peer db (mirrors magic_dns.rs:751 + route_updater).
        let exit_env = test_env(Some(ts_control::ExitNodeSelector::StableId(
            ts_control::StableNodeId("exit".to_owned()),
        )));
        let view = build_dns_view(&exit_env, &update, Some(db), true);
        assert_eq!(
            view.exit_doh,
            peer.peerapi_doh_addr(),
            "exit_doh resolves to the active exit peer's peerAPI DoH address"
        );
        assert_eq!(
            view.exit_doh,
            Some("100.64.0.9:1080".parse().unwrap()),
            "exit_doh is the peer's tailnet IPv4 + peerAPI port"
        );

        // A configured selector that matches no peer ⇒ exit_doh None (fail-closed, recursion local).
        let ghost_env = test_env(Some(ts_control::ExitNodeSelector::StableId(
            ts_control::StableNodeId("ghost".to_owned()),
        )));
        let view = build_dns_view(&ghost_env, &update, Some(peer_db_with(&peer)), true);
        assert!(
            view.exit_doh.is_none(),
            "unresolved selector ⇒ exit_doh None (fail-closed)"
        );
    }

    /// A `Decision::Forward` for a public name now produces a real forwarded plan (recursive ⇒
    /// `RecursivePlan::Udp` of the configured upstreams when no exit node is active, or
    /// `RecursivePlan::Doh` when one is). This asserts the plan branch the UP pump dispatches on, not
    /// live socket I/O (a full forward needs a netstack) — same convention as the `serve.rs` tests.
    /// Critically: the upstreams come only from `decide`/`recursive_plan`, both of which already
    /// `.filter(SocketAddr::is_ipv4)`, so this path never constructs an upstream `SocketAddr`.
    #[tokio::test]
    async fn forward_decision_produces_udp_then_doh_plan() {
        // Public name + a global UDP resolver ⇒ recursive Forward.
        let update = dns_update(vec![udp_resolver("8.8.8.8:53")]);
        let env = test_env(None);
        let peer = exit_peer("exit", "100.64.0.9", 1080);
        let view = build_dns_view(&env, &update, Some(peer_db_with(&peer)), true);
        let query = build_query(0x4242, &["example", "com"]);

        let (upstreams, recursive) = match decide(&view, &query).expect("decides") {
            Decision::Forward {
                upstreams,
                recursive,
                ..
            } => (upstreams, recursive),
            Decision::Reply(_) => panic!("a public name with a global resolver must Forward"),
        };
        assert!(recursive, "an unrouted public name is a recursive forward");
        assert_eq!(
            upstreams,
            vec!["8.8.8.8:53".parse().unwrap()],
            "the IPv4 global resolver is the upstream (v4-only filter inherited)"
        );

        // No exit node active ⇒ the recursive plan keeps the UDP upstreams.
        match recursive_plan(&view, upstreams.clone()) {
            RecursivePlan::Udp(ups) => assert_eq!(ups, upstreams, "no exit node ⇒ UDP plan"),
            RecursivePlan::Doh(_) => panic!("no exit node configured ⇒ must not delegate to DoH"),
        }

        // With an active exit node (DoH-capable) and no use-with-exit-node resolvers, the recursive
        // plan delegates to the exit node's DoH endpoint — the overlay-egress branch.
        let exit_env = test_env(Some(ts_control::ExitNodeSelector::StableId(
            ts_control::StableNodeId("exit".to_owned()),
        )));
        let exit_view = build_dns_view(&exit_env, &update, Some(peer_db_with(&peer)), true);
        match recursive_plan(&exit_view, upstreams) {
            RecursivePlan::Doh(addr) => assert_eq!(
                Some(addr),
                peer.peerapi_doh_addr(),
                "active exit node ⇒ delegate recursion to its peerAPI DoH endpoint"
            ),
            RecursivePlan::Udp(_) => panic!("active exit node with no kept-local resolvers ⇒ DoH"),
        }
    }

    /// Wrap a DNS payload in an IPv4/UDP packet `client -> 100.100.100.100:53` — a packet the UP
    /// pump's intercept classifies as a MagicDNS query.
    fn quad100_query_packet(client: SocketAddrV4, payload: &[u8]) -> Vec<u8> {
        let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), [100, 100, 100, 100], 64)
            .udp(client.port(), 53);
        let mut out = Vec::with_capacity(b.size(payload.len()));
        b.write(&mut out, payload).unwrap();
        out
    }

    /// The in-datapath intercept answers a tailnet-authoritative name inline, and that answer is
    /// held to the client's advertised EDNS buffer just like a forwarded one. Go runs
    /// `checkResponseSizeAndSetTC` in `Resolver.Query` right after `respond` succeeds, so the local
    /// fast path is not exempt: a client advertising 20 bytes gets `TC` on the NXDOMAIN+SOA we
    /// composed, and goes to TCP, instead of being handed a datagram it said it could not receive.
    #[tokio::test]
    async fn an_inline_authoritative_reply_honours_the_clients_edns_size() {
        let client: SocketAddrV4 = "100.64.0.7:34567".parse().unwrap();
        let update = dns_update(vec![udp_resolver("8.8.8.8:53")]);
        let env = test_env(None);
        let view = build_dns_view(&env, &update, None, true);

        // An unknown name inside the tailnet search domain: authoritative NXDOMAIN with the zone's
        // SOA, answered inline and never forwarded.
        let query = build_edns_query(0x9001, &["nope", "user", "ts", "net"], 20);
        let pkt = quad100_query_packet(client, &query);

        match plan_intercept(&view, &pkt) {
            Intercept::Reply { src, response } => {
                assert_eq!(src, client);
                assert!(
                    response.len() > 20,
                    "the fixture only works if the answer overflows the advertised 20 bytes"
                );
                assert_ne!(
                    response[2] & 0x02,
                    0,
                    "an answer over the advertised EDNS size must carry TC, even on the local path"
                );
            }
            _ => panic!("an unknown name in the tailnet search domain is answered authoritatively"),
        }

        // The same name asked without EDNS fits the classic 512-byte limit, so TC stays clear —
        // the check is the client's advertised size, not a blanket mark on every local answer.
        let plain = build_query(0x9002, &["nope", "user", "ts", "net"]);
        match plan_intercept(&view, &quad100_query_packet(client, &plain)) {
            Intercept::Reply { response, .. } => {
                assert!(response.len() <= 512);
                assert_eq!(
                    response[2] & 0x02,
                    0,
                    "TC must stay clear on an answer that fits"
                );
            }
            _ => panic!("an unknown name in the tailnet search domain is answered authoritatively"),
        }
    }

    /// HOL-blocking regression: the UP pump's intercept must hand a `Decision::Forward` back as
    /// [`Intercept::Forward`] (a plan to SPAWN) rather than awaiting the overlay round-trip inline —
    /// so one slow/hung upstream can never head-of-line-block the entire TUN uplink. `plan_intercept`
    /// is the pure, synchronous decision seam (no device, no `await`): if it ever returned only after
    /// the forward completed, a forward could not be a synchronous return value at all. This also
    /// pins the fast-path classifications the pump relies on: a non-MagicDNS packet forwards to the
    /// overlay, an authoritative reply is carried out for an inline write, and a malformed query is
    /// dropped. The forward's upstreams come only from `decide`/`recursive_plan` (v4-only filtered),
    /// so this path never constructs an upstream `SocketAddr` (IPv4-only egress invariant inherited).
    #[tokio::test]
    async fn intercept_plan_spawns_forward_and_classifies_fast_paths() {
        let client: SocketAddrV4 = "100.64.0.7:34567".parse().unwrap();

        // A public name with a global UDP resolver and no exit node ⇒ a recursive Forward whose plan
        // is `RecursivePlan::Udp` of the configured upstream. Crucially this is RETURNED, not awaited
        // — the pump spawns it (see the UP pump's `forwards.spawn(run_forward(...))`).
        let update = dns_update(vec![udp_resolver("8.8.8.8:53")]);
        let env = test_env(None);
        let peer = exit_peer("exit", "100.64.0.9", 1080);
        let view = build_dns_view(&env, &update, Some(peer_db_with(&peer)), true);

        let fwd_pkt = quad100_query_packet(client, &build_query(0x4242, &["example", "com"]));
        match plan_intercept(&view, &fwd_pkt) {
            Intercept::Forward {
                plan, src, query, ..
            } => {
                assert_eq!(
                    src, client,
                    "forward reply is addressed back to the querier"
                );
                assert!(
                    !query.is_empty(),
                    "the original query bytes are carried verbatim"
                );
                match plan {
                    RecursivePlan::Udp(ups) => assert_eq!(
                        ups,
                        vec!["8.8.8.8:53".parse().unwrap()],
                        "no exit node ⇒ UDP plan of the v4-only-filtered upstream (never built here)"
                    ),
                    RecursivePlan::Doh(_) => panic!("no exit node configured ⇒ must not be DoH"),
                }
            }
            _ => panic!("a public name with a global resolver must yield a SPAWNED Forward plan"),
        }

        // A tailnet self-name `A` query is answered authoritatively from the view (an INLINE Reply
        // carried out for the pump to write back), or — lacking overlay address data in this
        // fixture — Forwarded; either way it is consumed, never passed through.
        let reply_pkt =
            quad100_query_packet(client, &build_query(0x1, &["self", "user", "ts", "net"]));
        match plan_intercept(&view, &reply_pkt) {
            Intercept::Reply { src, response } => {
                assert_eq!(
                    src, client,
                    "the inline reply is addressed back to the querier"
                );
                assert!(
                    !response.is_empty(),
                    "an authoritative reply carries response bytes"
                );
            }
            other => assert!(
                matches!(other, Intercept::Forward { .. }),
                "a tailnet self-name is answered authoritatively (Reply) or, lacking overlay data, \
                 Forwarded — never NotIntercepted/Dropped"
            ),
        }

        // A non-MagicDNS packet (UDP/53 to a real upstream IP) forwards to the overlay unchanged.
        let passthrough = {
            let b = etherparse::PacketBuilder::ipv4(client.ip().octets(), [8, 8, 8, 8], 64)
                .udp(client.port(), 53);
            let mut out = Vec::new();
            b.write(&mut out, b"x").unwrap();
            out
        };
        assert!(
            matches!(
                plan_intercept(&view, &passthrough),
                Intercept::NotIntercepted
            ),
            "a packet not destined to quad-100:53 must pass through to the overlay"
        );

        // A malformed query to quad-100:53 is consumed but dropped silently (never forwarded).
        let malformed = quad100_query_packet(client, &[0xff, 0x00]);
        assert!(
            matches!(plan_intercept(&view, &malformed), Intercept::Dropped),
            "a malformed quad-100/UDP/53 query is dropped, never forwarded to the overlay"
        );
    }

    /// Anti-leak, the whole point of the absorb. A selected exit node puts `0.0.0.0/0` into the
    /// overlay's outbound table as `RouteAction::Wireguard(peer)`, and `0.0.0.0/0` matches
    /// `100.100.100.100` — so ANY quad-100 packet the pump forwards is encrypted and sent to that
    /// peer. This test proves both halves against the real router: routed unfiltered, the node's own
    /// service-IP probes land on the exit peer; routed through what the pump actually forwards
    /// (`Intercept::NotIntercepted` only), nothing does.
    #[tokio::test]
    async fn exit_node_default_route_never_sees_service_ip_traffic() {
        use ts_bart::{RoutingTable, Table};
        use ts_overlay_router::outbound::{RouteAction, Router};
        use ts_packet::PacketMut;
        use ts_transport::PeerId;

        let client: SocketAddrV4 = "100.64.0.7:44321".parse().unwrap();
        const QUAD_100: [u8; 4] = [100, 100, 100, 100];

        // The exit node's default route, exactly as `route_updater` builds it.
        let exit = PeerId(7);
        let mut table = Table::default();
        table.insert("0.0.0.0/0".parse().unwrap(), RouteAction::Wireguard(exit));
        let mut router = Router::default();
        router.swap(table);

        // Quad-100 traffic a host really emits that is not a MagicDNS query.
        let probes = [
            syn_packet(client, QUAD_100, 853, 7),
            syn_packet(client, QUAD_100, 80, 7),
            udp_packet(client, QUAD_100, 443),
            icmp_packet(client, QUAD_100),
        ];

        // The premise: with the exit node's `/0` installed, these DO route to the peer.
        let leaked = router.route(probes.iter().cloned().map(PacketMut::from));
        assert_eq!(
            leaked.to_wireguard.get(&exit).map(Vec::len),
            Some(probes.len()),
            "0.0.0.0/0 matches 100.100.100.100 — every probe would be encrypted to the exit peer"
        );

        // The fix: none of them survive the pump's classification, so the router never sees them.
        // `Intercept::NotIntercepted` is the one and only arm on which the pump calls `up.send`.
        let update = dns_update(vec![udp_resolver("8.8.8.8:53")]);
        let env = test_env(None);
        let view = build_dns_view(&env, &update, None, true);
        let forwarded: Vec<PacketMut> = probes
            .iter()
            .filter(|pkt| matches!(plan_intercept(&view, pkt), Intercept::NotIntercepted))
            .cloned()
            .map(PacketMut::from)
            .collect();
        assert!(
            forwarded.is_empty(),
            "no quad-100 packet may reach the overlay: {} of {} were still forwarded",
            forwarded.len(),
            probes.len()
        );
        assert_eq!(
            router.route(forwarded),
            ts_overlay_router::outbound::Result::default(),
            "with the absorb in place the exit peer receives nothing addressed to the service IP"
        );
    }

    /// The two transports must agree that the service IP is local. The netstack transport gets it
    /// for free — `overlay_addresses` hands `100.100.100.100` to the netstack as an interface
    /// address, so quad-100 terminates there whatever the port or protocol (and smoltcp resets a TCP
    /// segment no socket accepts). The TUN transport has no application netstack, so
    /// `plan_intercept` must reach the same verdict for the same packets: consumed, never forwarded.
    ///
    /// "Consumed" is the shared property, not "reset": TCP/53 is now *served* on the TUN side (see
    /// `service_ip_tcp_dns_is_terminated_not_reset`), while the application netstack still has no
    /// TCP listener on `100.100.100.100:53` and resets it. What this test pins is the one invariant
    /// both transports must never break — no quad-100 packet reaches the overlay.
    #[tokio::test]
    async fn both_transports_absorb_service_ip_traffic() {
        use core::net::IpAddr;

        let client: SocketAddrV4 = "100.64.0.7:44321".parse().unwrap();
        const QUAD_100: [u8; 4] = [100, 100, 100, 100];

        assert!(
            crate::netstack_actor::overlay_addresses(&fixture_node(), false)
                .contains(&IpAddr::V4(Ipv4Addr::new(100, 100, 100, 100))),
            "netstack mode: the service IP is a netstack interface address, so it absorbs quad-100"
        );

        let update = dns_update(vec![udp_resolver("8.8.8.8:53")]);
        let env = test_env(None);
        let view = build_dns_view(&env, &update, None, true);
        for pkt in [
            syn_packet(client, QUAD_100, 853, 7),
            syn_packet(client, QUAD_100, 53, 7),
            udp_packet(client, QUAD_100, 443),
            icmp_packet(client, QUAD_100),
        ] {
            assert!(
                !matches!(plan_intercept(&view, &pkt), Intercept::NotIntercepted),
                "tun mode must absorb the same quad-100 traffic the netstack terminates"
            );
        }
    }

    /// Defaults must apply when control supplies no knobs: name `tailscale0`, MTU `1280`, and the
    /// device prefix must be exactly the runtime-assigned `/32` passed in.
    #[test]
    fn defaults_and_prefix() {
        let cfg = TunConfig {
            name: None,
            mtu: None,
        };
        let dev = tun_config_from_control(&cfg, prefix());

        assert_eq!(dev.name, "tailscale0");
        assert_eq!(dev.mtu.get(), 1280);
        assert_eq!(dev.prefix, ipnet::IpNet::V4(prefix()));
    }

    /// `mtu = Some(0)` is invalid (NonZeroU16 rejects it) and must fall back to the 1280 default,
    /// while a real MTU is honored. A custom name is honored verbatim.
    #[test]
    fn mtu_zero_falls_back_and_overrides_honored() {
        let zero = TunConfig {
            name: Some("tun9".to_owned()),
            mtu: Some(0),
        };
        let dev_zero = tun_config_from_control(&zero, prefix());
        assert_eq!(dev_zero.name, "tun9");
        assert_eq!(
            dev_zero.mtu.get(),
            1280,
            "mtu=Some(0) must fall back to 1280"
        );

        let big = TunConfig {
            name: None,
            mtu: Some(9000),
        };
        let dev_big = tun_config_from_control(&big, prefix());
        assert_eq!(dev_big.mtu.get(), 9000, "a valid mtu must be honored");
    }
}