nlink 0.28.1

Async netlink library for Linux network configuration
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
//! High-level rate limiting API.
//!
//! This module provides a simplified API for common rate limiting use cases,
//! abstracting away the complexity of TC (Traffic Control) configuration.
//!
//! # Overview
//!
//! The rate limiting API provides two main types:
//!
//! - [`RateLimiter`]: Simple interface-wide rate limiting for egress and ingress traffic
//! - [`PerHostLimiter`]: Per-IP or per-subnet rate limiting with customizable rules
//!
//! # Example
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # use nlink::Rate;
//! use nlink::netlink::{Connection, Route};
//! use nlink::netlink::ratelimit::RateLimiter;
//! use std::time::Duration;
//!
//! let conn = Connection::<Route>::new()?;
//!
//! // Simple rate limiting
//! RateLimiter::new("eth0")
//!     .egress(Rate::mbit(100))
//!     .ingress(Rate::gbit(1))
//!     .burst_to(Rate::mbit(150))
//!     .latency(Duration::from_millis(20))
//!     .apply(&conn)
//!     .await?;
//!
//! // Remove limits
//! RateLimiter::new("eth0")
//!     .remove(&conn)
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Implementation Details
//!
//! Under the hood, the rate limiter uses:
//! - **Egress**: HTB qdisc with a single class + fq_codel leaf for AQM
//! - **Ingress**: IFB device + ingress qdisc + mirred redirect + HTB on IFB
//!
//! ```text
//! Egress:
//!   eth0 -> HTB root (1:) -> HTB class (1:1, rate limited) -> fq_codel
//!
//! Ingress:
//!   eth0 ingress -> matchall filter -> mirred redirect -> ifb_eth0 -> HTB -> fq_codel
//! ```

use std::{net::IpAddr, time::Duration};

use super::{
    Connection,
    error::{Error, Result},
    link::IfbLink,
    protocol::Route,
    tc::{FqCodelConfig, HtbClassConfig, HtbQdiscConfig, IngressConfig},
    tc_handle::{FilterPriority, TcHandle},
    tc_recipe::{ReconcileOptions, ReconcileReport, StaleObject, UnmanagedObject},
    tc_recipe_internals::{
        DEFAULT_CLASS_MINOR, DEFAULT_LEAF_MAJOR, LiveTree, dump_live_tree, flower_matches,
        fq_codel_target_matches, htb_class_rates_match, root_htb_options,
    },
};

/// Minor of the single leaf class `RateLimiter` creates under the HTB root.
///
/// The HTB qdisc's `default` and the class it names **must** come from this one
/// constant. They were previously written independently: the qdisc said
/// `default_class(0x10)` — 16 — while the class was created at
/// `TcHandle::new(1, 10)`, decimal 10. So `htb_classify` looked up a class that
/// did not exist, fell through to `HTB_DIRECT`, and transmitted every packet
/// unshaped.
///
/// `RateLimiter` installs no filters, so this default class is the *only* thing
/// standing between traffic and the wire (#258).
const LEAF_CLASS_MINOR: u16 = 10;

// ============================================================================
// RateLimit
// ============================================================================

/// Rate limit configuration.
#[derive(Debug, Clone)]
pub struct RateLimit {
    /// Guaranteed rate.
    pub rate: crate::util::Rate,
    /// Maximum burst rate (ceiling).
    pub ceil: Option<crate::util::Rate>,
    /// Burst size.
    pub burst: Option<crate::util::Bytes>,
    /// Latency target for AQM (Active Queue Management).
    pub latency: Option<Duration>,
}

impl RateLimit {
    /// Create a new rate limit with the specified rate.
    pub fn new(rate: crate::util::Rate) -> Self {
        Self {
            rate,
            ceil: None,
            burst: None,
            latency: None,
        }
    }

    /// Set the ceiling rate (maximum burst rate).
    pub fn ceil(mut self, ceil: crate::util::Rate) -> Self {
        self.ceil = Some(ceil);
        self
    }

    /// Set the burst size.
    pub fn burst(mut self, burst: crate::util::Bytes) -> Self {
        self.burst = Some(burst);
        self
    }

    /// Set the latency target for AQM.
    pub fn latency(mut self, latency: Duration) -> Self {
        self.latency = Some(latency);
        self
    }
}

// ============================================================================
// RateLimiter
// ============================================================================

/// High-level rate limiter for an interface.
///
/// Provides a simple API for rate limiting both egress (upload) and ingress (download)
/// traffic on a network interface.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # use nlink::Rate;
/// use nlink::netlink::{Connection, Route};
/// use nlink::netlink::ratelimit::RateLimiter;
///
/// let conn = Connection::<Route>::new()?;
///
/// // Limit egress to 100 Mbps, ingress to 1 Gbps
/// RateLimiter::new("eth0")
///     .egress(Rate::mbit(100))
///     .ingress(Rate::gbit(1))
///     .apply(&conn)
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct RateLimiter {
    /// Target interface name.
    dev: String,
    /// Egress (upload) rate limit.
    egress: Option<RateLimit>,
    /// Ingress (download) rate limit.
    ingress: Option<RateLimit>,
}

impl RateLimiter {
    /// Create a new rate limiter for the specified interface.
    pub fn new(dev: &str) -> Self {
        Self {
            dev: dev.to_string(),
            egress: None,
            ingress: None,
        }
    }

    /// Set the egress (upload) rate limit.
    pub fn egress(mut self, rate: crate::util::Rate) -> Self {
        self.egress = Some(RateLimit::new(rate));
        self
    }

    /// Set the ingress (download) rate limit.
    pub fn ingress(mut self, rate: crate::util::Rate) -> Self {
        self.ingress = Some(RateLimit::new(rate));
        self
    }

    /// Set the ceiling rate for bursting (applies to both egress and ingress).
    pub fn burst_to(mut self, ceil: crate::util::Rate) -> Self {
        if let Some(ref mut egress) = self.egress {
            egress.ceil = Some(ceil);
        }
        if let Some(ref mut ingress) = self.ingress {
            ingress.ceil = Some(ceil);
        }
        self
    }

    /// Set the burst buffer size (applies to both egress and ingress).
    pub fn burst_size(mut self, size: crate::util::Bytes) -> Self {
        if let Some(ref mut egress) = self.egress {
            egress.burst = Some(size);
        }
        if let Some(ref mut ingress) = self.ingress {
            ingress.burst = Some(size);
        }
        self
    }

    /// Set the latency target for AQM (applies to both egress and ingress).
    pub fn latency(mut self, latency: Duration) -> Self {
        if let Some(ref mut egress) = self.egress {
            egress.latency = Some(latency);
        }
        if let Some(ref mut ingress) = self.ingress {
            ingress.latency = Some(latency);
        }
        self
    }

    /// Apply the rate limits.
    ///
    /// This configures the TC (Traffic Control) subsystem to enforce the
    /// specified rate limits.
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev, egress = self.egress.is_some(), ingress = self.ingress.is_some()))]
    pub async fn apply(&self, conn: &Connection<Route>) -> Result<()> {
        // Apply egress rate limiting
        if let Some(ref egress) = self.egress {
            self.apply_egress(conn, egress).await?;
        }

        // Apply ingress rate limiting
        if let Some(ref ingress) = self.ingress {
            self.apply_ingress(conn, ingress).await?;
        }

        Ok(())
    }

    /// Idempotently converge the interface to this limiter's desired
    /// state, mutating only what drifted (#169 — mirrors
    /// [`PerHostLimiter::reconcile`]).
    ///
    /// Unlike [`apply()`](Self::apply), which tears down the root
    /// qdisc and rebuilds (dropping in-flight queue state), reconcile
    /// dumps the live TC tree and issues only the kernel calls needed
    /// to close the gap. Calling `reconcile()` twice in a row with no
    /// other changes makes **zero** kernel calls on the second
    /// invocation.
    ///
    /// If a live root qdisc is the wrong kind (not the HTB shape this
    /// helper installs), reconcile errors by default; pass
    /// [`ReconcileOptions::with_fallback_to_apply`]`(true)` to trigger
    /// a destructive rebuild via [`apply()`](Self::apply) instead.
    ///
    /// Known approximation: the ingress redirect filter is checked
    /// for **presence** at the ingress hook, not for its mirred
    /// target — re-pointing a hand-modified redirect requires a
    /// `remove()` + `reconcile()`.
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev))]
    pub async fn reconcile(&self, conn: &Connection<Route>) -> Result<ReconcileReport> {
        self.reconcile_with_options(conn, ReconcileOptions::new())
            .await
    }

    /// Compute what [`reconcile()`](Self::reconcile) would do without
    /// making kernel calls.
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev))]
    pub async fn reconcile_dry_run(&self, conn: &Connection<Route>) -> Result<ReconcileReport> {
        self.reconcile_with_options(conn, ReconcileOptions::new().with_dry_run(true))
            .await
    }

    /// [`reconcile()`](Self::reconcile) with explicit
    /// [`ReconcileOptions`].
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev, dry_run = opts.dry_run, fallback = opts.fallback_to_apply))]
    pub async fn reconcile_with_options(
        &self,
        conn: &Connection<Route>,
        opts: ReconcileOptions,
    ) -> Result<ReconcileReport> {
        let link = conn
            .get_link_by_name(&self.dev)
            .await?
            .ok_or_else(|| Error::InvalidMessage(format!("interface not found: {}", self.dev)))?;
        let ifindex = link.ifindex();

        let mut report = ReconcileReport {
            dry_run: opts.dry_run,
            ..ReconcileReport::default()
        };

        // Egress half: HTB shape directly on the interface.
        if let Some(egress) = &self.egress {
            let rebuilt = self
                .reconcile_htb_shape(conn, ifindex, egress, &opts, &mut report, "egress")
                .await?;
            if rebuilt {
                return Ok(report);
            }
        }

        // Ingress half: IFB device + ingress hook + redirect + HTB
        // shape on the IFB.
        if let Some(ingress) = &self.ingress {
            let ifb_name = self.ifb_name();
            let ifb_ifindex = match conn.get_link_by_name(&ifb_name).await? {
                Some(l) => {
                    if !l.is_up() {
                        if !opts.dry_run {
                            conn.set_link_up_by_index(l.ifindex()).await?;
                        }
                        report.changes_made += 1;
                    }
                    Some(l.ifindex())
                }
                None => {
                    if opts.dry_run {
                        // Whole ingress branch pending: link + up +
                        // shape (root, 1:1, 1:10, leaf). The hook +
                        // filter are counted below.
                        report.changes_made += 6;
                        report.root_modified = true;
                        None
                    } else {
                        conn.add_link(IfbLink::new(&ifb_name)).await?;
                        conn.set_link_up(&ifb_name).await?;
                        report.changes_made += 2;
                        Some(
                            conn.get_link_by_name(&ifb_name)
                                .await?
                                .ok_or_else(|| {
                                    Error::InvalidMessage(format!(
                                        "IFB device vanished after creation: {ifb_name}"
                                    ))
                                })?
                                .ifindex(),
                        )
                    }
                }
            };

            // Ingress hook qdisc on the main interface.
            let has_ingress_hook = conn
                .get_qdiscs_by_index(ifindex)
                .await?
                .iter()
                .any(|q| q.kind() == Some("ingress"));
            if !has_ingress_hook {
                if !opts.dry_run {
                    conn.add_qdisc_full(&self.dev, TcHandle::INGRESS, None, IngressConfig::new())
                        .await?;
                }
                report.changes_made += 1;
            }

            // Redirect filter at the ingress hook (presence check).
            let has_redirect = has_ingress_hook
                && !conn
                    .get_filters_by_parent_index(ifindex, TcHandle::INGRESS)
                    .await?
                    .is_empty();
            if !has_redirect {
                if !opts.dry_run {
                    self.add_ingress_redirect(conn, &ifb_name).await?;
                }
                report.changes_made += 1;
            }

            // HTB shape on the IFB side (skipped in dry-run when the
            // IFB doesn't exist yet — already counted above).
            if let Some(ifb_ifindex) = ifb_ifindex {
                let rebuilt = self
                    .reconcile_htb_shape(conn, ifb_ifindex, ingress, &opts, &mut report, "ingress")
                    .await?;
                if rebuilt {
                    return Ok(report);
                }
            }
        }

        Ok(report)
    }

    /// Converge one device's egress tree to the helper's canonical
    /// shape: HTB root `1:` (default `0x10`) → class `1:1` → class
    /// `1:10` → fq_codel leaf `10:`. Returns `true` when a wrong-kind
    /// root triggered the destructive `fallback_to_apply` rebuild (the
    /// caller must stop reconciling — the rebuild already converged
    /// everything).
    async fn reconcile_htb_shape(
        &self,
        conn: &Connection<Route>,
        ifindex: u32,
        limit: &RateLimit,
        opts: &ReconcileOptions,
        report: &mut ReconcileReport,
        ctx: &str,
    ) -> Result<bool> {
        let tree = dump_live_tree(conn, ifindex).await?;
        let root_handle = TcHandle::major_only(1);
        let class_1_1 = TcHandle::new(1, 1);
        let class_1_10 = TcHandle::new(1, LEAF_CLASS_MINOR);
        let leaf_handle = TcHandle::major_only(LEAF_CLASS_MINOR);
        let rate = limit.rate;
        let ceil = limit.ceil.unwrap_or(limit.rate);
        let rate_bps = rate.as_bytes_per_sec();
        let ceil_bps = ceil.as_bytes_per_sec();
        let target_us = limit.latency.map(|d| d.as_micros() as u32);

        let class_cfg = || {
            let mut cfg = HtbClassConfig::new(rate).ceil(ceil);
            if let Some(burst) = limit.burst {
                cfg = cfg.burst(burst);
            }
            cfg.build()
        };
        let leaf_cfg = || {
            let mut cfg = FqCodelConfig::new();
            if let Some(latency) = limit.latency {
                cfg = cfg.target(latency);
            }
            cfg.build()
        };

        // Root HTB.
        match tree.configured_root_qdisc() {
            None => {
                if !opts.dry_run {
                    let cfg = HtbQdiscConfig::new().default_class(LEAF_CLASS_MINOR as u32).build();
                    conn.add_qdisc_by_index_full(ifindex, TcHandle::ROOT, Some(root_handle), cfg)
                        .await
                        .map_err(|e| {
                            e.with_context(format!("RateLimiter::reconcile({ctx}): add HTB root"))
                        })?;
                }
                report.changes_made += 1;
                report.root_modified = true;
            }
            Some(q) if q.kind() != Some("htb") || q.handle() != root_handle => {
                if opts.fallback_to_apply {
                    report.changes_made += 1;
                    report.root_modified = true;
                    if !opts.dry_run {
                        self.apply(conn).await?;
                    }
                    return Ok(true);
                }
                return Err(Error::InvalidMessage(format!(
                    "RateLimiter::reconcile({ctx}): root qdisc is {:?} (handle {}), not HTB \
                     at 1:; pass ReconcileOptions::with_fallback_to_apply(true) to rebuild",
                    q.kind(),
                    q.handle()
                )));
            }
            Some(_) => {}
        }

        // Classes 1:1 and 1:10.
        for (classid, parent) in [(class_1_1, root_handle), (class_1_10, class_1_1)] {
            match tree.class(classid) {
                None => {
                    if !opts.dry_run {
                        conn.add_class_by_index(ifindex, parent, classid, class_cfg())
                            .await
                            .map_err(|e| {
                                e.with_context(format!(
                                    "RateLimiter::reconcile({ctx}): add class {classid}"
                                ))
                            })?;
                    }
                    report.changes_made += 1;
                }
                Some(c) if !htb_class_rates_match(c, rate_bps, ceil_bps) => {
                    if !opts.dry_run {
                        conn.change_class_by_index(ifindex, parent, classid, class_cfg())
                            .await
                            .map_err(|e| {
                                e.with_context(format!(
                                    "RateLimiter::reconcile({ctx}): update class {classid}"
                                ))
                            })?;
                    }
                    report.changes_made += 1;
                }
                Some(_) => {}
            }
        }

        // fq_codel leaf under 1:10.
        match tree.leaf_for(class_1_10) {
            None => {
                if !opts.dry_run {
                    conn.add_qdisc_by_index_full(ifindex, class_1_10, Some(leaf_handle), leaf_cfg())
                        .await
                        .map_err(|e| {
                            e.with_context(format!(
                                "RateLimiter::reconcile({ctx}): add fq_codel leaf"
                            ))
                        })?;
                }
                report.changes_made += 1;
            }
            Some(q) if !fq_codel_target_matches(target_us, q) => {
                if !opts.dry_run {
                    conn.replace_qdisc_by_index_full(
                        ifindex,
                        class_1_10,
                        Some(leaf_handle),
                        leaf_cfg(),
                    )
                    .await
                    .map_err(|e| {
                        e.with_context(format!(
                            "RateLimiter::reconcile({ctx}): update fq_codel leaf"
                        ))
                    })?;
                }
                report.changes_made += 1;
            }
            Some(_) => {}
        }

        Ok(false)
    }

    /// Remove all rate limits from the interface.
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev))]
    pub async fn remove(&self, conn: &Connection<Route>) -> Result<()> {
        // Remove egress qdisc (this removes all egress TC config)
        let _ = conn.del_qdisc(&self.dev, TcHandle::ROOT).await;

        // Remove ingress qdisc
        let _ = conn.del_qdisc(&self.dev, TcHandle::INGRESS).await;

        // Remove IFB device if it exists
        let ifb_name = self.ifb_name();
        let _ = conn.del_link(&ifb_name).await;

        Ok(())
    }

    /// Get the IFB device name for this interface.
    /// Name of the IFB device that carries this interface's ingress
    /// shaping. Must fit `IFNAMSIZ` (16 bytes including the NUL).
    ///
    /// Two bugs lived in the old truncation (#281). `&self.dev[..11]`
    /// is a **byte** slice on a `String`, so a device name with a
    /// multi-byte character near the cut **panicked**. And any two
    /// devices sharing an 11-byte prefix mapped to the same IFB, so
    /// removing shaping on one tore down the other's — silently, since
    /// both `RateLimiter`s believe they own it.
    ///
    /// Long names now get a hash suffix instead of a bare prefix: the
    /// collision needs the full name to match, not the first eleven
    /// bytes, and the slice lands on a char boundary by construction.
    fn ifb_name(&self) -> String {
        const IFNAMSIZ: usize = 15; // 16 including the NUL
        const PREFIX: &str = "ifb_";

        let budget = IFNAMSIZ - PREFIX.len();
        if self.dev.len() <= budget {
            return format!("{PREFIX}{}", self.dev);
        }

        // 4 hex digits of a name hash, so two devices sharing a prefix
        // get different IFBs.
        //
        // FNV-1a rather than `DefaultHasher`: this name has to survive
        // across process invocations — `remove()` must find what
        // `apply()` created — and std explicitly reserves the right to
        // change `DefaultHasher`'s algorithm between releases, which
        // would strand every IFB built by an older binary.
        let hash = {
            let mut h: u32 = 0x811c_9dc5;
            for b in self.dev.as_bytes() {
                h ^= *b as u32;
                h = h.wrapping_mul(0x0100_0193);
            }
            (h ^ (h >> 16)) as u16
        };
        let keep = budget - 5; // 4 hex digits + '_'
        // `floor_char_boundary` is unstable; walk back to one.
        let mut cut = keep.min(self.dev.len());
        while cut > 0 && !self.dev.is_char_boundary(cut) {
            cut -= 1;
        }
        format!("{PREFIX}{}_{hash:04x}", &self.dev[..cut])
    }

    /// Apply egress rate limiting using HTB.
    async fn apply_egress(&self, conn: &Connection<Route>, limit: &RateLimit) -> Result<()> {
        // Remove existing root qdisc (ignore errors if none exists)
        let _ = conn.del_qdisc(&self.dev, TcHandle::ROOT).await;

        // Add HTB qdisc at root with handle 1:
        let htb = HtbQdiscConfig::new().default_class(LEAF_CLASS_MINOR as u32).build();
        conn.add_qdisc_full(
            &self.dev,
            TcHandle::ROOT,
            Some(TcHandle::major_only(1)),
            htb,
        )
        .await?;

        // Add root class (1:1) for the rate limit
        let mut class_config = HtbClassConfig::new(limit.rate);
        if let Some(ceil) = limit.ceil {
            class_config = class_config.ceil(ceil);
        }
        if let Some(burst) = limit.burst {
            class_config = class_config.burst(burst);
        }
        conn.add_class(
            &self.dev,
            TcHandle::major_only(1),
            TcHandle::new(1, 1),
            class_config.build(),
        )
        .await?;

        // Add default class (1:10) under the root class
        let mut default_config = HtbClassConfig::new(limit.rate);
        if let Some(ceil) = limit.ceil {
            default_config = default_config.ceil(ceil);
        }
        if let Some(burst) = limit.burst {
            default_config = default_config.burst(burst);
        }
        conn.add_class(
            &self.dev,
            TcHandle::new(1, 1),
            TcHandle::new(1, LEAF_CLASS_MINOR),
            default_config.build(),
        )
        .await?;

        // Add fq_codel as leaf qdisc for AQM
        let mut fq_codel = FqCodelConfig::new();
        if let Some(latency) = limit.latency {
            fq_codel = fq_codel.target(latency);
        }
        conn.add_qdisc_full(
            &self.dev,
            TcHandle::new(1, LEAF_CLASS_MINOR),
            Some(TcHandle::major_only(LEAF_CLASS_MINOR)),
            fq_codel.build(),
        )
        .await?;

        Ok(())
    }

    /// Apply ingress rate limiting using IFB.
    async fn apply_ingress(&self, conn: &Connection<Route>, limit: &RateLimit) -> Result<()> {
        let ifb_name = self.ifb_name();

        // Create IFB device if it doesn't exist
        if conn.get_link_by_name(&ifb_name).await?.is_none() {
            conn.add_link(IfbLink::new(&ifb_name)).await?;
        }

        // Bring IFB device up
        conn.set_link_up(&ifb_name).await?;

        // Remove existing ingress qdisc on the main interface
        let _ = conn.del_qdisc(&self.dev, TcHandle::INGRESS).await;

        // Add ingress qdisc to the main interface
        conn.add_qdisc_full(&self.dev, TcHandle::INGRESS, None, IngressConfig::new())
            .await?;

        // Add filter to redirect ingress traffic to IFB
        // We need to use a filter with mirred action
        self.add_ingress_redirect(conn, &ifb_name).await?;

        // Now configure HTB on the IFB device
        // Remove existing root qdisc on IFB
        let _ = conn.del_qdisc(&ifb_name, TcHandle::ROOT).await;

        // Add HTB qdisc at root of IFB with handle 1:
        let htb = HtbQdiscConfig::new().default_class(LEAF_CLASS_MINOR as u32).build();
        conn.add_qdisc_full(
            &ifb_name,
            TcHandle::ROOT,
            Some(TcHandle::major_only(1)),
            htb,
        )
        .await?;

        // Add root class (1:1) for the rate limit
        let mut class_config = HtbClassConfig::new(limit.rate);
        if let Some(ceil) = limit.ceil {
            class_config = class_config.ceil(ceil);
        }
        if let Some(burst) = limit.burst {
            class_config = class_config.burst(burst);
        }
        conn.add_class(
            &ifb_name,
            TcHandle::major_only(1),
            TcHandle::new(1, 1),
            class_config.build(),
        )
        .await?;

        // Add default class (1:10) under the root class
        let mut default_config = HtbClassConfig::new(limit.rate);
        if let Some(ceil) = limit.ceil {
            default_config = default_config.ceil(ceil);
        }
        if let Some(burst) = limit.burst {
            default_config = default_config.burst(burst);
        }
        conn.add_class(
            &ifb_name,
            TcHandle::new(1, 1),
            TcHandle::new(1, LEAF_CLASS_MINOR),
            default_config.build(),
        )
        .await?;

        // Add fq_codel as leaf qdisc for AQM
        let mut fq_codel = FqCodelConfig::new();
        if let Some(latency) = limit.latency {
            fq_codel = fq_codel.target(latency);
        }
        conn.add_qdisc_full(
            &ifb_name,
            TcHandle::new(1, LEAF_CLASS_MINOR),
            Some(TcHandle::major_only(LEAF_CLASS_MINOR)),
            fq_codel.build(),
        )
        .await?;

        Ok(())
    }

    /// Add ingress redirect filter using u32 filter with mirred action.
    async fn add_ingress_redirect(&self, conn: &Connection<Route>, ifb_name: &str) -> Result<()> {
        // Get IFB interface index
        let ifb_link = conn
            .get_link_by_name(ifb_name)
            .await?
            .ok_or_else(|| Error::InvalidMessage(format!("IFB device not found: {}", ifb_name)))?;
        let ifb_ifindex = ifb_link.ifindex();

        // Add a u32 filter with mirred redirect action
        // We use the low-level API since matchall doesn't support arbitrary actions yet
        self.add_u32_redirect_filter(conn, ifb_ifindex).await
    }

    /// Add u32 filter with mirred redirect action.
    async fn add_u32_redirect_filter(
        &self,
        conn: &Connection<Route>,
        ifb_ifindex: u32,
    ) -> Result<()> {
        use super::{
            connection::create_request,
            message::NlMsgType,
            types::tc::{
                TcMsg, TcaAttr,
                action::{self, mirred},
                filter::u32 as u32_mod,
                tc_handle,
            },
        };

        // Get interface index
        let link = conn
            .get_link_by_name(&self.dev)
            .await?
            .ok_or_else(|| Error::InvalidMessage(format!("interface not found: {}", self.dev)))?;
        let ifindex = link.ifindex();

        // Build the message
        let tcmsg = TcMsg::new()
            .with_ifindex(ifindex as i32)
            .with_parent(tc_handle::INGRESS)
            .with_filter_info(0x0003, 1); // ETH_P_ALL, priority 1

        // `create_request`, not `ack_request`: `tc_ctl_tfilter` answers
        // a filter add that names no existing handle with
        //
        //   ENOENT "Need both RTM_NEWTFILTER and NLM_F_CREATE to
        //           create a new filter"
        //
        // so without the flag this call never installed anything and
        // `RateLimiter::ingress` failed on every interface.
        let mut builder = create_request(NlMsgType::RTM_NEWTFILTER);
        builder.append(&tcmsg);
        builder.append_attr_str(TcaAttr::Kind as u16, "u32");

        // Options
        let opt_token = builder.nest_start(TcaAttr::Options as u16);

        // Match all packets: `match u32 0 0 at 0`.
        //
        // Built from the typed structs rather than a byte array. The
        // array this replaced was 28 bytes — a 12-byte header plus one
        // key — but `struct tc_u32_sel`'s header is 16 (`offmask` is
        // `__be16` after a 1-byte pad, then `off`, `offoff`, `hoff`,
        // and a `__be32 hmask`). `u32_change` rejects anything shorter
        // than `struct_size(sel, keys, sel->nkeys)`, so the ingress
        // redirect filter never installed and `RateLimiter::ingress`
        // silently shaped nothing.
        let sel_token = builder.nest_start(u32_mod::TCA_U32_SEL);
        let mut sel = u32_mod::TcU32Sel::new();
        sel.set_terminal();
        sel.add_key(u32_mod::TcU32Key::default());
        builder.append_bytes(&sel.to_bytes());
        builder.nest_end(sel_token);

        // Add mirred action
        let act_token = builder.nest_start(u32_mod::TCA_U32_ACT);

        // Action 1: mirred redirect
        let act1_token = builder.nest_start(1);
        builder.append_attr_str(action::TCA_ACT_KIND, "mirred");

        let mirred_opt_token = builder.nest_start(action::TCA_ACT_OPTIONS);
        let mirred_parms = mirred::TcMirred::new(
            mirred::TCA_INGRESS_REDIR,
            ifb_ifindex,
            action::TC_ACT_STOLEN,
        );
        builder.append_attr(mirred::TCA_MIRRED_PARMS, mirred_parms.as_bytes());
        builder.nest_end(mirred_opt_token);

        builder.nest_end(act1_token);
        builder.nest_end(act_token);

        builder.nest_end(opt_token);

        conn.send_ack(builder).await?;
        Ok(())
    }
}

// ============================================================================
// PerHostLimiter
// ============================================================================

/// Per-IP or per-subnet rate limiting.
///
/// Allows setting different rate limits for different hosts or subnets.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # use nlink::Rate;
/// use nlink::netlink::{Connection, Route};
/// use nlink::netlink::ratelimit::PerHostLimiter;
///
/// let conn = Connection::<Route>::new()?;
///
/// PerHostLimiter::new("eth0", Rate::mbit(10))
///     .limit_ip("192.168.1.100".parse()?, Rate::mbit(100))
///     .limit_subnet("10.0.0.0/8", Rate::mbit(50))?
///     .limit_port(80, Rate::mbit(500))
///     .apply(&conn)
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct PerHostLimiter {
    /// Target interface name.
    dev: String,
    /// Default rate.
    default_rate: crate::util::Rate,
    /// Per-host rules.
    rules: Vec<HostRule>,
    /// Latency target for AQM.
    latency: Option<Duration>,
}

/// A rate limiting rule for a specific host or match condition.
#[derive(Debug, Clone)]
pub struct HostRule {
    /// Match condition.
    match_: HostMatch,
    /// Rate limit.
    rate: crate::util::Rate,
    /// Ceiling rate.
    ceil: Option<crate::util::Rate>,
}

/// Match condition for per-host limiting.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum HostMatch {
    /// Match a specific IP address.
    Ip(IpAddr),
    /// Match a subnet (address and prefix length).
    Subnet(IpAddr, u8),
    /// Match a destination port.
    Port(u16),
    /// Match a port range.
    PortRange(u16, u16),
    /// Match source IP address.
    SrcIp(IpAddr),
    /// Match source subnet.
    SrcSubnet(IpAddr, u8),
}

impl PerHostLimiter {
    /// Create a new per-host rate limiter with a default rate for unmatched
    /// traffic.
    pub fn new(dev: &str, default_rate: crate::util::Rate) -> Self {
        Self {
            dev: dev.to_string(),
            default_rate,
            rules: Vec::new(),
            latency: None,
        }
    }

    /// Add a rate limit for a specific IP address.
    pub fn limit_ip(mut self, ip: IpAddr, rate: crate::util::Rate) -> Self {
        self.rules.push(HostRule {
            match_: HostMatch::Ip(ip),
            rate,
            ceil: None,
        });
        self
    }

    /// Add a rate limit for a specific IP address with ceiling.
    pub fn limit_ip_with_ceil(
        mut self,
        ip: IpAddr,
        rate: crate::util::Rate,
        ceil: crate::util::Rate,
    ) -> Self {
        self.rules.push(HostRule {
            match_: HostMatch::Ip(ip),
            rate,
            ceil: Some(ceil),
        });
        self
    }

    /// Add a rate limit for a subnet.
    pub fn limit_subnet(mut self, subnet: &str, rate: crate::util::Rate) -> Result<Self> {
        let (addr, prefix) = parse_subnet(subnet)?;
        self.rules.push(HostRule {
            match_: HostMatch::Subnet(addr, prefix),
            rate,
            ceil: None,
        });
        Ok(self)
    }

    /// Add a rate limit for a source IP address.
    pub fn limit_src_ip(mut self, ip: IpAddr, rate: crate::util::Rate) -> Self {
        self.rules.push(HostRule {
            match_: HostMatch::SrcIp(ip),
            rate,
            ceil: None,
        });
        self
    }

    /// Add a rate limit for a source subnet.
    pub fn limit_src_subnet(mut self, subnet: &str, rate: crate::util::Rate) -> Result<Self> {
        let (addr, prefix) = parse_subnet(subnet)?;
        self.rules.push(HostRule {
            match_: HostMatch::SrcSubnet(addr, prefix),
            rate,
            ceil: None,
        });
        Ok(self)
    }

    /// Add a rate limit for a destination port.
    pub fn limit_port(mut self, port: u16, rate: crate::util::Rate) -> Self {
        self.rules.push(HostRule {
            match_: HostMatch::Port(port),
            rate,
            ceil: None,
        });
        self
    }

    /// Add a rate limit for a port range.
    pub fn limit_port_range(mut self, start: u16, end: u16, rate: crate::util::Rate) -> Self {
        self.rules.push(HostRule {
            match_: HostMatch::PortRange(start, end),
            rate,
            ceil: None,
        });
        self
    }

    /// Set the latency target for AQM.
    pub fn latency(mut self, latency: Duration) -> Self {
        self.latency = Some(latency);
        self
    }

    /// Apply the per-host rate limits.
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev, rules = self.rules.len()))]
    pub async fn apply(&self, conn: &Connection<Route>) -> Result<()> {
        // Remove existing root qdisc
        let _ = conn.del_qdisc(&self.dev, TcHandle::ROOT).await;

        // Add HTB qdisc at root with handle 1:
        //
        // Rule classes occupy minors 2..=n+1, so the default class is n+2.
        // This said `n + 1` — the *last rule's* class — so with any rules at
        // all, unmatched traffic was shaped at the last rule's rate instead of
        // `default_rate`; with none, it named the inner class 1:1 and
        // htb_classify fell through to HTB_DIRECT, bypassing the shaper
        // entirely. `reconcile_inner` always used n+2, so the two verbs
        // disagreed and apply-then-reconcile was never a no-op (#269).
        let default_minor = DEFAULT_CLASS_MINOR;
        let default_classid = default_minor as u32;
        let htb = HtbQdiscConfig::new().default_class(default_classid).build();
        conn.add_qdisc_full(
            &self.dev,
            TcHandle::ROOT,
            Some(TcHandle::major_only(1)),
            htb,
        )
        .await?;

        // Add root class (1:1) with sum of all rates as ceiling
        let parent_classid = TcHandle::new(1, 1);
        let major_only_1 = TcHandle::major_only(1);
        let total_rate: crate::util::Rate =
            self.default_rate + self.rules.iter().map(|r| r.rate).sum::<crate::util::Rate>();
        let root_config = HtbClassConfig::new(total_rate).ceil(total_rate).build();
        conn.add_class(&self.dev, major_only_1, parent_classid, root_config)
            .await?;

        // Add classes for each rule
        for (i, rule) in self.rules.iter().enumerate() {
            let classid = TcHandle::new(1, (i + 2) as u16);
            let leaf_handle = TcHandle::major_only((i + 10) as u16);
            let class_config = HtbClassConfig::new(rule.rate).ceil(rule.ceil.unwrap_or(rule.rate));
            conn.add_class(&self.dev, parent_classid, classid, class_config.build())
                .await?;

            // Add fq_codel leaf qdisc
            let mut fq_codel = FqCodelConfig::new();
            if let Some(latency) = self.latency {
                fq_codel = fq_codel.target(latency);
            }
            conn.add_qdisc_full(&self.dev, classid, Some(leaf_handle), fq_codel.build())
                .await?;

            // Add flower filter to classify traffic to this class
            self.add_filter_for_rule(conn, i, rule).await?;
        }

        // Add default class for unmatched traffic
        let default_classid = TcHandle::new(1, default_minor);
        let default_handle = TcHandle::major_only(DEFAULT_LEAF_MAJOR);
        let default_config = HtbClassConfig::new(self.default_rate)
            .ceil(self.default_rate)
            .build();
        conn.add_class(&self.dev, parent_classid, default_classid, default_config)
            .await?;

        // Add fq_codel leaf for default class
        let mut fq_codel = FqCodelConfig::new();
        if let Some(latency) = self.latency {
            fq_codel = fq_codel.target(latency);
        }
        conn.add_qdisc_full(
            &self.dev,
            default_classid,
            Some(default_handle),
            fq_codel.build(),
        )
        .await?;

        Ok(())
    }

    /// Remove the per-host rate limits.
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev))]
    pub async fn remove(&self, conn: &Connection<Route>) -> Result<()> {
        let _ = conn.del_qdisc(&self.dev, TcHandle::ROOT).await;
        Ok(())
    }

    // ---- reconcile ----

    /// Non-destructively converge the live TC tree to match this
    /// limiter's desired state.
    ///
    /// Unlike [`apply()`], `reconcile()` dumps the existing tree, diffs
    /// it against what the helper would build, and emits the minimum
    /// set of `add_*` / `change_*` / `del_*` operations to converge.
    /// Calling `reconcile()` twice in a row with no other changes makes
    /// **zero** kernel calls on the second invocation.
    ///
    /// If the live root qdisc is the wrong kind (not HTB), reconcile
    /// returns an error by default. Pass [`ReconcileOptions::with_fallback_to_apply`]`(true)`
    /// to instead trigger a destructive rebuild via [`apply()`].
    ///
    /// [`apply()`]: Self::apply
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev, rules = self.rules.len()))]
    pub async fn reconcile(&self, conn: &Connection<Route>) -> Result<ReconcileReport> {
        self.reconcile_with_options(conn, ReconcileOptions::new())
            .await
    }

    /// Compute what [`reconcile()`] would do without making kernel calls.
    ///
    /// [`reconcile()`]: Self::reconcile
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev, rules = self.rules.len()))]
    pub async fn reconcile_dry_run(&self, conn: &Connection<Route>) -> Result<ReconcileReport> {
        self.reconcile_with_options(conn, ReconcileOptions::new().with_dry_run(true))
            .await
    }

    /// [`reconcile()`] with explicit [`ReconcileOptions`].
    ///
    /// [`reconcile()`]: Self::reconcile
    #[tracing::instrument(level = "info", skip_all, fields(dev = %self.dev, rules = self.rules.len(), dry_run = opts.dry_run, fallback = opts.fallback_to_apply))]
    pub async fn reconcile_with_options(
        &self,
        conn: &Connection<Route>,
        opts: ReconcileOptions,
    ) -> Result<ReconcileReport> {
        // Resolve interface for typed-by-index calls.
        let link = conn
            .get_link_by_name(&self.dev)
            .await?
            .ok_or_else(|| Error::InvalidMessage(format!("interface not found: {}", self.dev)))?;
        let ifindex = link.ifindex();
        self.reconcile_inner(conn, ifindex, opts).await
    }

    async fn reconcile_inner(
        &self,
        conn: &Connection<Route>,
        ifindex: u32,
        opts: ReconcileOptions,
    ) -> Result<ReconcileReport> {
        let mut report = ReconcileReport {
            dry_run: opts.dry_run,
            ..ReconcileReport::default()
        };

        let tree = dump_live_tree(conn, ifindex).await?;

        let parent_classid = TcHandle::new(1, 1);
        let root_handle = TcHandle::major_only(1);
        let default_minor = DEFAULT_CLASS_MINOR;
        let default_classid = TcHandle::new(1, default_minor);
        let default_leaf_handle = TcHandle::major_only(DEFAULT_LEAF_MAJOR);
        let total_rate: crate::util::Rate =
            self.default_rate + self.rules.iter().map(|r| r.rate).sum::<crate::util::Rate>();
        let target_us = self.latency.map(|d| d.as_micros() as u32);

        // 1. Root HTB qdisc.
        match tree.configured_root_qdisc() {
            None => {
                if !opts.dry_run {
                    let cfg = HtbQdiscConfig::new()
                        .default_class(default_minor as u32)
                        .build();
                    conn.add_qdisc_by_index_full(ifindex, TcHandle::ROOT, Some(root_handle), cfg)
                        .await
                        .map_err(|e| e.with_context("PerHostLimiter::reconcile: add HTB root"))?;
                }
                report.changes_made += 1;
                report.root_modified = true;
            }
            Some(q) => {
                let kind_ok = q.kind() == Some("htb") && q.handle() == root_handle;
                if !kind_ok {
                    if opts.fallback_to_apply {
                        if opts.dry_run {
                            report.changes_made += 1;
                            report.root_modified = true;
                            return Ok(report);
                        }
                        return self.apply_as_reconcile(conn).await;
                    }
                    return Err(Error::InvalidMessage(format!(
                        "PerHostLimiter::reconcile: root qdisc on {} is {:?} (handle {}), \
                         not HTB at 1:; pass ReconcileOptions::with_fallback_to_apply(true) \
                         to rebuild",
                        self.dev,
                        q.kind(),
                        q.handle()
                    )));
                }
                let default_ok = root_htb_options(&tree)
                    .map(|opts| opts.default_class == default_minor as u32)
                    .unwrap_or(false);
                if !default_ok {
                    if !opts.dry_run {
                        let cfg = HtbQdiscConfig::new()
                            .default_class(default_minor as u32)
                            .build();
                        conn.change_qdisc_by_index_full(
                            ifindex,
                            TcHandle::ROOT,
                            Some(root_handle),
                            cfg,
                        )
                        .await
                        .map_err(|e| {
                            e.with_context("PerHostLimiter::reconcile: update HTB root")
                        })?;
                    }
                    report.changes_made += 1;
                    report.root_modified = true;
                }
            }
        }

        // 2. Parent class 1:1 with rate=ceil=total_rate.
        let total_bps = total_rate.as_bytes_per_sec();
        match tree.class(parent_classid) {
            None => {
                if !opts.dry_run {
                    let cfg = HtbClassConfig::new(total_rate).ceil(total_rate).build();
                    conn.add_class_by_index(ifindex, root_handle, parent_classid, cfg)
                        .await
                        .map_err(|e| {
                            e.with_context("PerHostLimiter::reconcile: add parent class 1:1")
                        })?;
                }
                report.changes_made += 1;
                report.root_modified = true;
            }
            Some(c) => {
                if !htb_class_rates_match(c, total_bps, total_bps) {
                    if !opts.dry_run {
                        let cfg = HtbClassConfig::new(total_rate).ceil(total_rate).build();
                        conn.change_class_by_index(ifindex, root_handle, parent_classid, cfg)
                            .await
                            .map_err(|e| {
                                e.with_context("PerHostLimiter::reconcile: update parent class 1:1")
                            })?;
                    }
                    report.changes_made += 1;
                    report.root_modified = true;
                }
            }
        }

        // 3. Per-rule classes + fq_codel leaves + filters.
        for (i, rule) in self.rules.iter().enumerate() {
            let classid = TcHandle::new(1, (i + 2) as u16);
            let leaf_handle = TcHandle::major_only((i + 10) as u16);
            let class_rate = rule.rate;
            let class_ceil = rule.ceil.unwrap_or(rule.rate);
            let class_rate_bps = class_rate.as_bytes_per_sec();
            let class_ceil_bps = class_ceil.as_bytes_per_sec();

            let mut rule_added = false;
            let mut rule_modified = false;

            // 3a. Class.
            match tree.class(classid) {
                None => {
                    if !opts.dry_run {
                        let cfg = HtbClassConfig::new(class_rate).ceil(class_ceil).build();
                        conn.add_class_by_index(ifindex, parent_classid, classid, cfg)
                            .await
                            .map_err(|e| {
                                e.with_context(format!(
                                    "PerHostLimiter::reconcile: add class {classid}"
                                ))
                            })?;
                    }
                    report.changes_made += 1;
                    rule_added = true;
                }
                Some(c) => {
                    if !htb_class_rates_match(c, class_rate_bps, class_ceil_bps) {
                        if !opts.dry_run {
                            let cfg = HtbClassConfig::new(class_rate).ceil(class_ceil).build();
                            conn.change_class_by_index(ifindex, parent_classid, classid, cfg)
                                .await
                                .map_err(|e| {
                                    e.with_context(format!(
                                        "PerHostLimiter::reconcile: update class {classid}"
                                    ))
                                })?;
                        }
                        report.changes_made += 1;
                        rule_modified = true;
                    }
                }
            }

            // 3b. fq_codel leaf.
            match tree.leaf_for(classid) {
                None => {
                    if !opts.dry_run {
                        let mut leaf = FqCodelConfig::new();
                        if let Some(latency) = self.latency {
                            leaf = leaf.target(latency);
                        }
                        conn.add_qdisc_by_index_full(
                            ifindex,
                            classid,
                            Some(leaf_handle),
                            leaf.build(),
                        )
                        .await
                        .map_err(|e| {
                            e.with_context(format!(
                                "PerHostLimiter::reconcile: add fq_codel leaf at {classid}"
                            ))
                        })?;
                    }
                    report.changes_made += 1;
                    if !rule_added {
                        rule_modified = true;
                    }
                }
                Some(q) => {
                    if !fq_codel_target_matches(target_us, q) {
                        if !opts.dry_run {
                            let mut leaf = FqCodelConfig::new();
                            if let Some(latency) = self.latency {
                                leaf = leaf.target(latency);
                            }
                            conn.replace_qdisc_by_index_full(
                                ifindex,
                                classid,
                                Some(leaf_handle),
                                leaf.build(),
                            )
                            .await
                            .map_err(|e| {
                                e.with_context(format!(
                                    "PerHostLimiter::reconcile: update fq_codel leaf at \
                                     {classid}"
                                ))
                            })?;
                        }
                        report.changes_made += 1;
                        if !rule_added {
                            rule_modified = true;
                        }
                    }
                }
            }

            // 3c. Filter(s) at root parent. Plain matches use one
            // priority (i+1); Port matches use two (i+1 and i+1+100).
            self.reconcile_filter_for_rule(
                conn,
                ifindex,
                &tree,
                i,
                rule,
                classid,
                opts,
                &mut rule_added,
                &mut rule_modified,
                &mut report,
            )
            .await?;

            if rule_added {
                report.rules_added += 1;
            } else if rule_modified {
                report.rules_modified += 1;
            }
        }

        // 4. Default class — always present in the desired tree.
        let default_bps = self.default_rate.as_bytes_per_sec();
        match tree.class(default_classid) {
            None => {
                if !opts.dry_run {
                    let cfg = HtbClassConfig::new(self.default_rate)
                        .ceil(self.default_rate)
                        .build();
                    conn.add_class_by_index(ifindex, parent_classid, default_classid, cfg)
                        .await
                        .map_err(|e| {
                            e.with_context("PerHostLimiter::reconcile: add default class")
                        })?;
                }
                report.changes_made += 1;
                report.default_modified = true;
            }
            Some(c) => {
                if !htb_class_rates_match(c, default_bps, default_bps) {
                    if !opts.dry_run {
                        let cfg = HtbClassConfig::new(self.default_rate)
                            .ceil(self.default_rate)
                            .build();
                        conn.change_class_by_index(ifindex, parent_classid, default_classid, cfg)
                            .await
                            .map_err(|e| {
                                e.with_context("PerHostLimiter::reconcile: update default class")
                            })?;
                    }
                    report.changes_made += 1;
                    report.default_modified = true;
                }
            }
        }

        // 4b. Default fq_codel leaf — always present.
        match tree.leaf_for(default_classid) {
            None => {
                if !opts.dry_run {
                    let mut leaf = FqCodelConfig::new();
                    if let Some(latency) = self.latency {
                        leaf = leaf.target(latency);
                    }
                    conn.add_qdisc_by_index_full(
                        ifindex,
                        default_classid,
                        Some(default_leaf_handle),
                        leaf.build(),
                    )
                    .await
                    .map_err(|e| {
                        e.with_context("PerHostLimiter::reconcile: add default fq_codel leaf")
                    })?;
                }
                report.changes_made += 1;
                report.default_modified = true;
            }
            Some(q) => {
                if !fq_codel_target_matches(target_us, q) {
                    if !opts.dry_run {
                        let mut leaf = FqCodelConfig::new();
                        if let Some(latency) = self.latency {
                            leaf = leaf.target(latency);
                        }
                        conn.replace_qdisc_by_index_full(
                            ifindex,
                            default_classid,
                            Some(default_leaf_handle),
                            leaf.build(),
                        )
                        .await
                        .map_err(|e| {
                            e.with_context(
                                "PerHostLimiter::reconcile: update default fq_codel leaf",
                            )
                        })?;
                    }
                    report.changes_made += 1;
                    report.default_modified = true;
                }
            }
        }

        // 5. Stale removal.
        self.collect_stale_and_unmanaged(&tree, &mut report, conn, ifindex, opts)
            .await?;

        Ok(report)
    }

    #[allow(clippy::too_many_arguments)]
    async fn reconcile_filter_for_rule(
        &self,
        conn: &Connection<Route>,
        ifindex: u32,
        tree: &LiveTree,
        index: usize,
        rule: &HostRule,
        classid: TcHandle,
        opts: ReconcileOptions,
        rule_added: &mut bool,
        rule_modified: &mut bool,
        report: &mut ReconcileReport,
    ) -> Result<()> {
        use super::filter::FlowerFilter;

        const ETH_P_IP: u16 = 0x0800;
        const ETH_P_IPV6: u16 = 0x86DD;

        // `.ipv4()` on the port filters is load-bearing, not decoration:
        // cls_flower discards `ip_proto` and the port keys unless the
        // request carries TCA_FLOWER_KEY_ETH_TYPE, and a port rule
        // without it installs as a match-all that claims every packet
        // on the interface (#288). The address setters imply it; the
        // L4 ones do not.

        let priority = (index + 1) as u16;
        let root_handle = TcHandle::major_only(1);

        // For each filter we want to install for this rule, check vs
        // the live tree at that priority.
        let want: Vec<(u16, u16, FlowerFilter)> = match &rule.match_ {
            HostMatch::Ip(ip) | HostMatch::Subnet(ip, _) => {
                let prefix = match &rule.match_ {
                    HostMatch::Subnet(_, p) => *p,
                    _ => {
                        if ip.is_ipv4() {
                            32
                        } else {
                            128
                        }
                    }
                };
                match ip {
                    IpAddr::V4(addr) => vec![(
                        ETH_P_IP,
                        priority,
                        FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .dst_ipv4(*addr, prefix)
                            .build(),
                    )],
                    IpAddr::V6(addr) => vec![(
                        ETH_P_IPV6,
                        priority,
                        FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .dst_ipv6(*addr, prefix)
                            .build(),
                    )],
                }
            }
            HostMatch::SrcIp(ip) | HostMatch::SrcSubnet(ip, _) => {
                let prefix = match &rule.match_ {
                    HostMatch::SrcSubnet(_, p) => *p,
                    _ => {
                        if ip.is_ipv4() {
                            32
                        } else {
                            128
                        }
                    }
                };
                match ip {
                    IpAddr::V4(addr) => vec![(
                        ETH_P_IP,
                        priority,
                        FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .src_ipv4(*addr, prefix)
                            .build(),
                    )],
                    IpAddr::V6(addr) => vec![(
                        ETH_P_IPV6,
                        priority,
                        FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .src_ipv6(*addr, prefix)
                            .build(),
                    )],
                }
            }
            HostMatch::Port(port) => vec![
                (
                    ETH_P_IP,
                    priority,
                    FlowerFilter::new()
                        .classid(classid)
                        .priority(priority)
                        .ipv4()
                        .ip_proto_tcp()
                        .dst_port(*port)
                        .build(),
                ),
                (
                    ETH_P_IP,
                    priority + 100,
                    FlowerFilter::new()
                        .classid(classid)
                        .priority(priority + 100)
                        .ipv4()
                        .ip_proto_udp()
                        .dst_port(*port)
                        .build(),
                ),
            ],
            HostMatch::PortRange(_, _) => {
                // Port ranges are intentionally complex (multiple
                // filters); skip incremental reconcile for them and
                // require apply() instead. A full reconcile of these
                // rules is a follow-up.
                Vec::new()
            }
        };

        for (proto, prio, filter) in want {
            let live = tree.filter_at_priority(prio);
            // Compare the match keys, not just kind + classid: both the
            // priority and the classid come from the rule's *index*, so
            // an edited rule reused them and reconcile saw no change
            // (#270).
            let ok = live
                .map(|f| flower_matches(&filter, proto, f))
                .unwrap_or(false);
            if !ok {
                if !opts.dry_run {
                    if let Some(stale) = live {
                        let _ = conn
                            .del_filter_by_index(ifindex, root_handle, stale.protocol(), prio)
                            .await;
                    }
                    conn.add_filter_by_index_full(ifindex, root_handle, None, proto, prio, filter)
                        .await
                        .map_err(|e| {
                            e.with_context(format!(
                                "PerHostLimiter::reconcile: add filter prio={prio} \
                             classid={classid}"
                            ))
                        })?;
                }
                report.changes_made += 1;
                if !*rule_added {
                    *rule_modified = true;
                }
            }
        }
        Ok(())
    }

    async fn apply_as_reconcile(&self, conn: &Connection<Route>) -> Result<ReconcileReport> {
        let n = self.rules.len();
        self.apply(conn).await?;
        Ok(ReconcileReport {
            // 1 root + 1 parent + 3 per rule (class+leaf+filter, +1 for
            // Port matches' UDP companion) + 1 default class + 1 default
            // leaf. Estimate; off-by-one for Port matches is ok.
            changes_made: 2 + 3 * n + 2,
            rules_added: n,
            root_modified: true,
            default_modified: true,
            ..ReconcileReport::default()
        })
    }

    async fn collect_stale_and_unmanaged(
        &self,
        tree: &LiveTree,
        report: &mut ReconcileReport,
        conn: &Connection<Route>,
        ifindex: u32,
        opts: ReconcileOptions,
    ) -> Result<()> {
        let n = self.rules.len();
        let parent_classid = TcHandle::new(1, 1);
        let root_handle = TcHandle::major_only(1);
        // Rule classes only; the default sits at DEFAULT_CLASS_MINOR.
        let max_minor = (n + 1) as u16;

        // Filters first, then classes. `htb_delete` refuses a class
        // any filter still points at:
        //
        //   if (cl->children || qdisc_class_in_use(&cl->common)) {
        //           NL_SET_ERR_MSG(extack, "HTB class in use");
        //           return -EBUSY;
        //   }
        //
        // so removing a rule used to fail with EBUSY partway through
        // (#291) — the class went first and its filter was still bound.
        // Stale filters at root parent. PerHostLimiter installs in the
        // operator band (priority i+1, i in 0..n) and recipe-band
        // companions (priority i+1+100 for Port matches). To stay
        // conservative, only treat priority `1..=n` and `101..=100+n`
        // as managed; anything else is unmanaged.
        let mut stale_filters: Vec<(u16, u16, TcHandle)> = Vec::new();
        for f in &tree.root_filters {
            let prio = f.priority();
            // Managed bands.
            let in_low = prio >= 1 && (prio as usize) <= n;
            let in_high = prio >= 101 && (prio as usize) <= 100 + n;
            // Out-of-band entries are unmanaged (left alone).
            if !in_low && !in_high {
                report.unmanaged.push(UnmanagedObject {
                    kind: "filter",
                    handle: f.parent(),
                    priority: Some(FilterPriority::new(prio)),
                });
                continue;
            }
            // In a managed band but no desired rule maps here? The
            // simplest rule: every prio in [1, n] should map to a rule;
            // every prio in [101, 100+n] only exists when that rule's
            // match_ is `Port`. We can't easily tell here without
            // knowing the rule's match shape, so we *only* delete a
            // high-band entry that has no rule index assigned — i.e.
            // (prio - 100 - 1) > n. The same for low-band.
            let i_low = (prio as usize).checked_sub(1);
            let i_high = (prio as usize).checked_sub(101);
            let mapped_index = i_high.filter(|&i| i < n).or(i_low.filter(|&i| i < n));
            if mapped_index.is_none() {
                stale_filters.push((prio, f.protocol(), f.parent()));
            }
        }
        for (prio, proto, parent) in stale_filters {
            if !opts.dry_run {
                let _ = conn
                    .del_filter_by_index(ifindex, root_handle, proto, prio)
                    .await;
            }
            report.changes_made += 1;
            report.stale_removed.push(StaleObject {
                kind: "filter",
                handle: parent,
                priority: Some(FilterPriority::new(prio)),
            });
        }
        // Stale classes in major 1:.
        let mut stale_classes: Vec<TcHandle> = Vec::new();
        for handle in tree.classes.keys() {
            if handle.major() != 1 {
                continue;
            }
            let minor = handle.minor();
            if minor == 0 || minor == 1 {
                continue;
            }
            if (minor >= 2 && minor <= max_minor) || minor == DEFAULT_CLASS_MINOR {
                continue;
            }
            stale_classes.push(*handle);
        }
        for handle in &stale_classes {
            if let Some(q) = tree.leaf_for(*handle) {
                let leaf_handle = q.handle();
                if !opts.dry_run {
                    let _ = conn
                        .del_qdisc_by_index_full(ifindex, *handle, Some(leaf_handle))
                        .await;
                }
            }
            if !opts.dry_run
                && let Err(e) = conn
                    .del_class_by_index(ifindex, parent_classid, *handle)
                    .await
                && !e.is_not_found()
            {
                return Err(e.with_context(format!(
                    "PerHostLimiter::reconcile: remove stale class {handle}"
                )));
            }
            report.changes_made += 1;
            report.rules_removed += 1;
            report.stale_removed.push(StaleObject {
                kind: "class",
                handle: *handle,
                priority: None,
            });
        }

        Ok(())
    }

    /// Add a flower filter for a specific rule.
    async fn add_filter_for_rule(
        &self,
        conn: &Connection<Route>,
        index: usize,
        rule: &HostRule,
    ) -> Result<()> {
        use super::filter::FlowerFilter;

        // tcm_info etherproto values. The kernel walks the per-protocol
        // dispatch table before flower's own KEY_ETH_TYPE attribute is
        // consulted, so passing the wrong value here means the filter
        // never matches its intended packets.
        const ETH_P_IP: u16 = 0x0800;
        const ETH_P_IPV6: u16 = 0x86DD;

        let classid = TcHandle::new(1, (index + 2) as u16);
        let priority = (index + 1) as u16;

        match &rule.match_ {
            HostMatch::Ip(ip) | HostMatch::Subnet(ip, _) => {
                let prefix = match &rule.match_ {
                    HostMatch::Subnet(_, p) => *p,
                    _ => {
                        if ip.is_ipv4() {
                            32
                        } else {
                            128
                        }
                    }
                };

                match ip {
                    IpAddr::V4(addr) => {
                        let filter = FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .dst_ipv4(*addr, prefix)
                            .build();
                        conn.add_filter_full(
                            &self.dev,
                            TcHandle::major_only(1),
                            None,
                            ETH_P_IP,
                            priority,
                            filter,
                        )
                        .await?;
                    }
                    IpAddr::V6(addr) => {
                        let filter = FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .dst_ipv6(*addr, prefix)
                            .build();
                        conn.add_filter_full(
                            &self.dev,
                            TcHandle::major_only(1),
                            None,
                            ETH_P_IPV6,
                            priority,
                            filter,
                        )
                        .await?;
                    }
                }
            }
            HostMatch::SrcIp(ip) | HostMatch::SrcSubnet(ip, _) => {
                let prefix = match &rule.match_ {
                    HostMatch::SrcSubnet(_, p) => *p,
                    _ => {
                        if ip.is_ipv4() {
                            32
                        } else {
                            128
                        }
                    }
                };

                match ip {
                    IpAddr::V4(addr) => {
                        let filter = FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .src_ipv4(*addr, prefix)
                            .build();
                        conn.add_filter_full(
                            &self.dev,
                            TcHandle::major_only(1),
                            None,
                            ETH_P_IP,
                            priority,
                            filter,
                        )
                        .await?;
                    }
                    IpAddr::V6(addr) => {
                        let filter = FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .src_ipv6(*addr, prefix)
                            .build();
                        conn.add_filter_full(
                            &self.dev,
                            TcHandle::major_only(1),
                            None,
                            ETH_P_IPV6,
                            priority,
                            filter,
                        )
                        .await?;
                    }
                }
            }
            HostMatch::Port(port) => {
                // Match both TCP and UDP. L4 port matching at the IP layer
                // dispatches under ETH_P_IP — and `.ipv4()` must say so
                // in the flower keys too, or cls_flower drops the port
                // match and installs a match-all (#288).
                let tcp_filter = FlowerFilter::new()
                    .classid(classid)
                    .priority(priority)
                    .ipv4()
                    .ip_proto_tcp()
                    .dst_port(*port)
                    .build();
                conn.add_filter_full(
                    &self.dev,
                    TcHandle::major_only(1),
                    None,
                    ETH_P_IP,
                    priority,
                    tcp_filter,
                )
                .await?;

                let udp_filter = FlowerFilter::new()
                    .classid(classid)
                    .priority(priority + 100) // Different priority to avoid conflict
                    .ipv4()
                    .ip_proto_udp()
                    .dst_port(*port)
                    .build();
                conn.add_filter_full(
                    &self.dev,
                    TcHandle::major_only(1),
                    None,
                    ETH_P_IP,
                    priority + 100,
                    udp_filter,
                )
                .await?;
            }
            HostMatch::PortRange(start, end) => {
                // For port ranges, we need to add individual filters or use u32
                // For simplicity, we'll add filters for each port in small ranges
                // or skip for large ranges
                if *end - *start <= 10 {
                    for port in *start..=*end {
                        let filter = FlowerFilter::new()
                            .classid(classid)
                            .priority(priority)
                            .ipv4()
                            .ip_proto_tcp()
                            .dst_port(port)
                            .build();
                        let _ = conn
                            .add_filter_full(
                                &self.dev,
                                TcHandle::major_only(1),
                                None,
                                ETH_P_IP,
                                priority,
                                filter,
                            )
                            .await;
                    }
                }
                // For larger ranges, we'd need u32 filter with masks
            }
        }

        Ok(())
    }
}

/// Parse a subnet string like "10.0.0.0/8" into address and prefix length.
fn parse_subnet(subnet: &str) -> Result<(IpAddr, u8)> {
    let parts: Vec<&str> = subnet.split('/').collect();
    if parts.len() != 2 {
        return Err(Error::InvalidMessage(format!(
            "invalid subnet format: {}",
            subnet
        )));
    }

    let addr: IpAddr = parts[0]
        .parse()
        .map_err(|_| Error::InvalidMessage(format!("invalid IP address: {}", parts[0])))?;

    let prefix: u8 = parts[1]
        .parse()
        .map_err(|_| Error::InvalidMessage(format!("invalid prefix length: {}", parts[1])))?;

    // Validate prefix length
    let max_prefix = if addr.is_ipv4() { 32 } else { 128 };
    if prefix > max_prefix {
        return Err(Error::InvalidMessage(format!(
            "prefix length {} exceeds maximum {} for address type",
            prefix, max_prefix
        )));
    }

    Ok((addr, prefix))
}

#[cfg(test)]
mod tests {
    use super::*;


    // ====================================================================
    // #258 / #269 — the HTB `default` must name a class that exists
    // ====================================================================
    //
    // Three separate default-class bugs shipped because nothing checked
    // that `defcls` and the created class agreed. When `htb_classify`
    // cannot resolve `defcls` it returns HTB_DIRECT and the packet
    // leaves the interface unshaped — no error, no log, just a rate
    // limit that silently does nothing.

    /// Read `default` out of an `HtbQdiscConfig`'s serialized options.
    fn htb_defcls(cfg: &HtbQdiscConfig) -> u32 {
        use crate::netlink::{tc::QdiscConfig, types::tc::qdisc::htb::TCA_HTB_INIT};

        let mut builder = crate::netlink::builder::MessageBuilder::new(0, 0);
        let start = builder.len();
        cfg.write_options(&mut builder).expect("write options");
        let blob = builder.as_bytes()[start..builder.len()].to_vec();

        // TCA_HTB_INIT payload is `struct tc_htb_glob`:
        //   version, rate2quantum, defcls, debug, direct_pkts
        // so `defcls` is the third u32.
        let mut input = &blob[..];
        while input.len() >= 4 {
            let len = u16::from_ne_bytes(input[..2].try_into().unwrap()) as usize;
            let ty = u16::from_ne_bytes(input[2..4].try_into().unwrap()) & 0x3FFF;
            assert!(len >= 4 && input.len() >= len, "malformed htb options");
            if ty == TCA_HTB_INIT {
                let p = &input[4..len];
                assert!(p.len() >= 12, "tc_htb_glob truncated");
                return u32::from_ne_bytes(p[8..12].try_into().unwrap());
            }
            let aligned = (len + 3) & !3;
            if input.len() <= aligned {
                break;
            }
            input = &input[aligned..];
        }
        panic!("no TCA_HTB_INIT in HtbQdiscConfig options");
    }

    #[test]
    fn ratelimiter_default_class_is_the_class_it_creates() {
        // `default_class(0x10)` (16) against a class at `1:10` (10) is
        // exactly the shape of #258. Both now read one constant.
        let cfg = HtbQdiscConfig::new()
            .default_class(LEAF_CLASS_MINOR as u32)
            .build();
        assert_eq!(htb_defcls(&cfg), LEAF_CLASS_MINOR as u32);
        assert_eq!(
            TcHandle::new(1, LEAF_CLASS_MINOR).minor(),
            htb_defcls(&cfg) as u16,
            "HTB default names a minor no class is created at"
        );
    }

    #[test]
    fn per_host_default_class_never_collides_with_a_rule_class() {
        // Rule i takes minor i+2, so n rules occupy 2..=n+1. The default
        // used to be n+2 in `reconcile` and n+1 in `apply` — the latter
        // being the *last rule's* class (#269). It is now a constant
        // outside the rules' range entirely, so no rule count can reach
        // it and no HTB `default` ever needs rewriting (#291).
        for n in 0..64usize {
            let rule_minors: Vec<u16> = (0..n).map(|i| (i + 2) as u16).collect();
            assert!(
                !rule_minors.contains(&DEFAULT_CLASS_MINOR),
                "n={n}: default class collides with a rule class"
            );
        }
        assert_ne!(DEFAULT_CLASS_MINOR, 0, "0 is the qdisc itself");
        assert_ne!(DEFAULT_CLASS_MINOR, 1, "1:1 is the parent class");
    }

    #[test]
    fn per_host_default_class_is_the_class_the_htb_default_names() {
        // `apply` and `reconcile` both read the same constant, so the
        // qdisc's `defcls` and the class that gets created cannot drift
        // apart the way they did in #258 and #269.
        let cfg = HtbQdiscConfig::new()
            .default_class(DEFAULT_CLASS_MINOR as u32)
            .build();
        assert_eq!(htb_defcls(&cfg), DEFAULT_CLASS_MINOR as u32);
        assert_eq!(
            TcHandle::new(1, DEFAULT_CLASS_MINOR).minor(),
            htb_defcls(&cfg) as u16
        );
    }

    // ====================================================================
    // #268 — ingress/clsact are parent-fixed
    // ====================================================================

    #[test]
    fn hook_qdiscs_declare_their_only_legal_parent() {
        use crate::netlink::tc::{ClsactConfig, FqCodelConfig, IngressConfig, QdiscConfig};

        // `ingress_init`/`clsact_init` answer EOPNOTSUPP for any parent
        // but TC_H_INGRESS, so `add_qdisc`'s TC_H_ROOT default could
        // never work for these two.
        assert_eq!(IngressConfig::new().fixed_parent(), Some(TcHandle::INGRESS));
        assert_eq!(ClsactConfig::new().fixed_parent(), Some(TcHandle::INGRESS));
        // Real schedulers keep the root default.
        assert_eq!(FqCodelConfig::new().build().fixed_parent(), None);
    }

    #[test]
    fn test_rate_limit_new() {
        use crate::util::Rate;
        let limit = RateLimit::new(Rate::bytes_per_sec(1_000_000));
        assert_eq!(limit.rate, Rate::bytes_per_sec(1_000_000));
        assert!(limit.ceil.is_none());
        assert!(limit.burst.is_none());
    }

    #[test]
    fn test_rate_limit_typed_units() {
        use crate::util::Rate;
        let limit = RateLimit::new(Rate::mbit(100));
        assert_eq!(limit.rate.as_bytes_per_sec(), 12_500_000);

        let limit = RateLimit::new(Rate::gbit(1));
        assert_eq!(limit.rate.as_bytes_per_sec(), 125_000_000);
    }

    #[test]
    fn test_rate_limiter_builder() {
        use crate::util::Rate;
        let limiter = RateLimiter::new("eth0")
            .egress(Rate::bytes_per_sec(1_000_000))
            .ingress(Rate::bytes_per_sec(2_000_000))
            .burst_to(Rate::bytes_per_sec(3_000_000));

        assert_eq!(limiter.dev, "eth0");
        assert!(limiter.egress.is_some());
        assert!(limiter.ingress.is_some());
        assert_eq!(
            limiter.egress.as_ref().unwrap().rate,
            Rate::bytes_per_sec(1_000_000)
        );
        assert_eq!(
            limiter.egress.as_ref().unwrap().ceil,
            Some(Rate::bytes_per_sec(3_000_000))
        );
        assert_eq!(
            limiter.ingress.as_ref().unwrap().rate,
            Rate::bytes_per_sec(2_000_000)
        );
        assert_eq!(
            limiter.ingress.as_ref().unwrap().ceil,
            Some(Rate::bytes_per_sec(3_000_000))
        );
    }

    #[test]
    fn test_ifb_name_generation() {
        let limiter = RateLimiter::new("eth0");
        assert_eq!(limiter.ifb_name(), "ifb_eth0");

        let limiter = RateLimiter::new("verylonginterfacename");
        assert!(limiter.ifb_name().len() <= 15);
    }

    #[test]
    fn ifb_names_do_not_collide_on_a_shared_prefix() {
        // The old truncation took the first 11 bytes, so any two
        // devices sharing that prefix mapped to the same IFB — and
        // removing shaping on one tore down the other's (#281).
        let a = RateLimiter::new("verylongname-aaaa").ifb_name();
        let b = RateLimiter::new("verylongname-bbbb").ifb_name();
        assert_ne!(a, b, "distinct devices must get distinct IFBs");
        assert!(a.len() <= 15 && b.len() <= 15, "{a} / {b}");
    }

    #[test]
    fn ifb_name_does_not_panic_on_a_multibyte_name() {
        // `&self.dev[..11]` is a *byte* slice on a `String`: a
        // multi-byte character straddling the cut panicked (#281).
        // Interface names are bytes to the kernel, so a name like this
        // is unusual but reachable — and a panic is never the answer.
        for dev in ["ααααααααααααααα", "eth-日本語-interface", "ααα"] {
            let name = RateLimiter::new(dev).ifb_name();
            assert!(name.len() <= 15, "{dev} -> {name} ({} bytes)", name.len());
        }
    }

    #[test]
    fn ifb_name_is_stable() {
        // Same device, same IFB — `remove()` has to find what `apply()`
        // created, possibly from a differently-compiled binary. The
        // literal is the point: it pins the hash so a change to it
        // shows up here rather than as an orphaned IFB in production.
        let a = RateLimiter::new("verylonginterfacename").ifb_name();
        assert_eq!(a, RateLimiter::new("verylonginterfacename").ifb_name());
        assert_eq!(a, "ifb_verylo_32f8");
    }

    #[test]
    fn test_parse_subnet() {
        let (addr, prefix) = parse_subnet("10.0.0.0/8").unwrap();
        assert_eq!(addr, "10.0.0.0".parse::<IpAddr>().unwrap());
        assert_eq!(prefix, 8);

        let (addr, prefix) = parse_subnet("192.168.1.0/24").unwrap();
        assert_eq!(addr, "192.168.1.0".parse::<IpAddr>().unwrap());
        assert_eq!(prefix, 24);

        let (addr, prefix) = parse_subnet("2001:db8::/32").unwrap();
        assert!(addr.is_ipv6());
        assert_eq!(prefix, 32);

        // Invalid formats
        assert!(parse_subnet("10.0.0.0").is_err());
        assert!(parse_subnet("10.0.0.0/33").is_err());
    }

    #[test]
    fn test_per_host_limiter_builder() {
        use crate::util::Rate;
        let limiter = PerHostLimiter::new("eth0", Rate::mbit(10));
        assert_eq!(limiter.dev, "eth0");
        assert_eq!(limiter.default_rate, Rate::mbit(10));
        assert!(limiter.rules.is_empty());
    }

    #[test]
    fn test_per_host_limiter_with_rules() {
        use crate::util::Rate;
        let limiter = PerHostLimiter::new("eth0", Rate::mbit(10))
            .limit_ip("192.168.1.100".parse().unwrap(), Rate::mbit(100))
            .limit_subnet("10.0.0.0/8", Rate::mbit(50))
            .unwrap()
            .limit_port(80, Rate::mbit(500));

        assert_eq!(limiter.rules.len(), 3);
    }
}