net-lattice-backend-linux 0.12.1

Linux backend for Net Lattice: implements net-lattice-platform's provider traits via Netlink.
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
//! Linux backend for Net Lattice: implements `net-lattice-platform`'s provider
//! traits via Netlink.
//!
//! Only ever compiled for `target_os = "linux"` — its dependencies
//! (`rtnetlink`, Linux-only) are gated the same way in `Cargo.toml`. See
//! ARCHITECTURE.md for how this crate binds `net-lattice-platform`'s generic
//! `RouteProvider::Route` associated type to the concrete
//! `net_lattice_model::route::Route`.

#![cfg(target_os = "linux")]

use std::hash::{Hash, Hasher};
use std::net::IpAddr;

use futures::{StreamExt, TryStreamExt};
use net_lattice_core::{Error, Id, PlatformErrorCode, Result};
use net_lattice_model::dns::{DnsConfig, NewDnsConfig};
use net_lattice_model::event::{ChangeKind, Event, EventFilter};
use net_lattice_model::ifaddr::{InterfaceAddress, InterfaceAddressId, NewInterfaceAddress};
use net_lattice_model::interface::{AdminState, Interface, InterfaceKind, OperationalState};
use net_lattice_model::mac::MacAddress;
use net_lattice_model::neighbor::{NeighborEntry, NeighborId, NeighborState};
use net_lattice_model::route::{Route, RouteId};
use net_lattice_model::{IpAddress, Network};
use net_lattice_platform::{
    AddressMutator, AddressProvider, Capability, CapabilityProvider, DnsMutator, DnsProvider,
    EventProvider, EventReceiver, InterfaceProvider, NeighborProvider, RouteProvider,
};
#[cfg(feature = "async")]
use net_lattice_platform::{TokioEventProvider, TokioEventReceiver};
use rtnetlink::packet_route::RouteNetlinkMessage;
use rtnetlink::packet_route::address::{AddressAttribute, AddressMessage};
use rtnetlink::packet_route::link::{LinkAttribute, LinkLayerType, LinkMessage, State};
use rtnetlink::packet_route::neighbour::{
    NeighbourAddress, NeighbourAttribute, NeighbourMessage, NeighbourState as RtNeighbourState,
};
use rtnetlink::packet_route::route::{RouteAddress, RouteAttribute, RouteMessage};
use rtnetlink::{Handle, MulticastGroup, RouteMessageBuilder};

/// The Linux Netlink-backed implementation of Net Lattice's provider traits.
pub struct LinuxBackend {
    runtime: tokio::runtime::Runtime,
    handle: Handle,
}

struct LinuxWatch {
    connection: tokio::task::JoinHandle<()>,
    events: tokio::task::JoinHandle<()>,
}

impl Drop for LinuxWatch {
    fn drop(&mut self) {
        self.events.abort();
        self.connection.abort();
    }
}

impl LinuxBackend {
    pub fn new() -> Result<Self> {
        let runtime =
            tokio::runtime::Runtime::new().map_err(|err| Error::Platform(io_error_code(&err)))?;
        // `rtnetlink::new_connection` constructs a `tokio::io::unix::AsyncFd`
        // socket synchronously, which requires an active Tokio reactor
        // context at construction time (not just when later polled) -
        // without `_guard`, this panics with "there is no reactor running"
        // the moment `add_route`/`remove_route`/`routes` first drives it.
        let _guard = runtime.enter();
        let (connection, handle, _) =
            rtnetlink::new_connection().map_err(|err| Error::Platform(io_error_code(&err)))?;
        runtime.spawn(connection);
        Ok(Self { runtime, handle })
    }
}

fn io_error_code(err: &std::io::Error) -> PlatformErrorCode {
    PlatformErrorCode::Linux(err.raw_os_error().unwrap_or(0))
}

fn rtnetlink_error_code(err: &rtnetlink::Error) -> PlatformErrorCode {
    match err {
        rtnetlink::Error::NetlinkError(message) => {
            PlatformErrorCode::Linux(message.code.map(i32::from).unwrap_or(0))
        }
        _ => PlatformErrorCode::Linux(0),
    }
}

/// Placeholder identity scheme, same rationale as `synthesize_route_id`: an
/// interface address has no kernel-assigned numeric ID, so this hashes its
/// interface and network together (the pair `RTM_GETADDR` itself keys
/// entries by).
fn synthesize_interface_address_id(interface_index: u32, network: &Network) -> InterfaceAddressId {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    interface_index.hash(&mut hasher);
    network.hash(&mut hasher);
    InterfaceAddressId::new(hasher.finish())
}

fn message_to_interface_address(message: &AddressMessage) -> Option<InterfaceAddress> {
    let interface_index = message.header.index;
    let prefix_len = message.header.prefix_len;

    let mut address_addr = None;
    let mut broadcast = None;
    for attribute in &message.attributes {
        match attribute {
            // `IFA_LOCAL`, when present, is the actual assigned address —
            // `IFA_ADDRESS` alone (no `IFA_LOCAL`) names the *peer* address
            // on a point-to-point link, so prefer `Local` and only fall
            // back to `Address` when there is no separate local entry.
            AddressAttribute::Local(addr) => address_addr = Some(*addr),
            AddressAttribute::Address(addr) if address_addr.is_none() => {
                address_addr = Some(*addr);
            }
            AddressAttribute::Broadcast(addr) => {
                broadcast = Some(std_ip_to_ip_address(IpAddr::V4(*addr)));
            }
            _ => {}
        }
    }

    let network = match address_addr? {
        IpAddr::V4(addr) => {
            let prefix = net_lattice_ip::Ipv4PrefixLength::new(prefix_len)?;
            Network::from(net_lattice_ip::Ipv4Network::new(addr.into(), prefix))
        }
        IpAddr::V6(addr) => {
            let prefix = net_lattice_ip::Ipv6PrefixLength::new(prefix_len)?;
            Network::from(net_lattice_ip::Ipv6Network::new(addr.into(), prefix))
        }
    };

    let mut entry = InterfaceAddress::new(
        synthesize_interface_address_id(interface_index, &network),
        interface_index,
        network,
    );
    if let Some(broadcast) = broadcast {
        entry = entry.with_broadcast(broadcast);
    }
    Some(entry)
}

impl AddressProvider for LinuxBackend {
    type InterfaceAddress = InterfaceAddress;

    fn addresses(&self) -> Result<Vec<Self::InterfaceAddress>> {
        self.runtime.block_on(async {
            let mut messages = self.handle.address().get().execute();
            let mut addresses = Vec::new();
            while let Some(message) = messages
                .try_next()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))?
            {
                addresses.extend(message_to_interface_address(&message));
            }
            Ok(addresses)
        })
    }
}

impl AddressMutator for LinuxBackend {
    type NewInterfaceAddress = NewInterfaceAddress;
    type InterfaceAddress = InterfaceAddress;

    fn add_address(&self, address: Self::NewInterfaceAddress) -> Result<Self::InterfaceAddress> {
        if matches!(address.address, Network::V6(_)) && address.broadcast.is_some() {
            return Err(Error::InvalidState);
        }
        let interface_index = address.interface_id.value() as u32;
        let (ip, prefix_len) = network_to_std(address.address);
        self.runtime.block_on(async {
            let mut request = self.handle.address().add(interface_index, ip, prefix_len);
            if let Some(broadcast) = address.broadcast {
                request
                    .message_mut()
                    .attributes
                    .push(AddressAttribute::Broadcast(broadcast.into()));
            }
            request
                .execute()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))
        })?;

        self.addresses()?
            .into_iter()
            .find(|observed| {
                observed.interface_index == interface_index && observed.address == address.address
            })
            .ok_or(Error::InvalidState)
    }

    fn remove_address(&self, address: Self::InterfaceAddress) -> Result<()> {
        self.runtime.block_on(async {
            let mut messages = self.handle.address().get().execute();
            while let Some(message) = messages
                .try_next()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))?
            {
                if message_to_interface_address(&message)
                    .is_some_and(|observed| observed.id == address.id)
                {
                    return self
                        .handle
                        .address()
                        .del(message)
                        .execute()
                        .await
                        .map_err(|err| Error::Platform(rtnetlink_error_code(&err)));
                }
            }
            Err(Error::NotFound)
        })
    }
}

/// Placeholder identity scheme: a route has no kernel-assigned numeric ID,
/// so this hashes its defining fields. See ARCHITECTURE.md's open Object
/// Identity question — this is not a long-term answer, only enough to give
/// `Stage 0.1` a `RouteId` to work with.
///
/// Hashes destination, gateway, and outgoing interface together so that
/// two routes to the same destination that differ only in gateway or
/// interface (a common case with multiple default routes, or ECMP-like
/// setups) don't collide on the same `RouteId`.
fn synthesize_route_id(message: &RouteMessage) -> RouteId {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    message.header.destination_prefix_length.hash(&mut hasher);
    for attribute in &message.attributes {
        match attribute {
            RouteAttribute::Destination(addr) => {
                route_address_to_ip(addr).hash(&mut hasher);
            }
            RouteAttribute::Gateway(addr) => {
                route_address_to_ip(addr).hash(&mut hasher);
            }
            RouteAttribute::Oif(index) => {
                index.hash(&mut hasher);
            }
            _ => {}
        }
    }
    RouteId::new(hasher.finish())
}

fn route_address_to_ip(address: &RouteAddress) -> Option<IpAddr> {
    match address {
        RouteAddress::Inet(addr) => Some(IpAddr::V4(*addr)),
        RouteAddress::Inet6(addr) => Some(IpAddr::V6(*addr)),
        _ => None,
    }
}

fn std_ip_to_ip_address(addr: IpAddr) -> IpAddress {
    match addr {
        IpAddr::V4(addr) => IpAddress::from(net_lattice_ip::Ipv4Address::from(addr)),
        IpAddr::V6(addr) => IpAddress::from(net_lattice_ip::Ipv6Address::from(addr)),
    }
}

fn message_to_route(message: &RouteMessage) -> Option<Route> {
    let mut destination_addr = None;
    let mut gateway = None;
    let mut metric = None;
    let mut interface_index = None;

    for attribute in &message.attributes {
        match attribute {
            RouteAttribute::Destination(addr) => {
                destination_addr = route_address_to_ip(addr);
            }
            RouteAttribute::Gateway(addr) => {
                gateway = route_address_to_ip(addr).map(std_ip_to_ip_address);
            }
            RouteAttribute::Priority(priority) => {
                metric = Some(*priority);
            }
            RouteAttribute::Oif(index) => {
                interface_index = Some(*index);
            }
            _ => {}
        }
    }

    let destination_addr = destination_addr?;
    let prefix_len = message.header.destination_prefix_length;
    let destination = match destination_addr {
        IpAddr::V4(addr) => {
            let prefix = net_lattice_ip::Ipv4PrefixLength::new(prefix_len)?;
            Network::from(net_lattice_ip::Ipv4Network::new(addr.into(), prefix))
        }
        IpAddr::V6(addr) => {
            let prefix = net_lattice_ip::Ipv6PrefixLength::new(prefix_len)?;
            Network::from(net_lattice_ip::Ipv6Network::new(addr.into(), prefix))
        }
    };

    let mut route = Route::new(synthesize_route_id(message), destination);
    if let Some(gateway) = gateway {
        route = route.with_gateway(gateway);
    }
    if let Some(metric) = metric {
        route = route.with_metric(metric);
    }
    if let Some(interface_index) = interface_index {
        route = route.with_interface_index(interface_index);
    }
    Some(route)
}

fn ip_address_to_std(address: IpAddress) -> IpAddr {
    match address {
        IpAddress::V4(addr) => IpAddr::V4(addr.into()),
        IpAddress::V6(addr) => IpAddr::V6(addr.into()),
    }
}

fn network_to_std(network: Network) -> (IpAddr, u8) {
    match network {
        Network::V4(net) => (IpAddr::V4(net.address().into()), net.prefix().value()),
        Network::V6(net) => (IpAddr::V6(net.address().into()), net.prefix().value()),
    }
}

impl RouteProvider for LinuxBackend {
    type Route = Route;

    fn routes(&self) -> Result<Vec<Self::Route>> {
        self.runtime.block_on(async {
            let route_handle = self.handle.route();

            let mut v4 = route_handle
                .get(RouteMessageBuilder::<std::net::Ipv4Addr>::new().build())
                .execute();
            let mut v6 = route_handle
                .get(RouteMessageBuilder::<std::net::Ipv6Addr>::new().build())
                .execute();

            let mut routes = Vec::new();
            while let Some(message) = v4
                .try_next()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))?
            {
                routes.extend(message_to_route(&message));
            }
            while let Some(message) = v6
                .try_next()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))?
            {
                routes.extend(message_to_route(&message));
            }
            Ok(routes)
        })
    }

    fn add_route(&self, route: Self::Route) -> Result<()> {
        self.runtime.block_on(async {
            let (destination, prefix_len) = network_to_std(route.destination);
            let message = match destination {
                IpAddr::V4(addr) => {
                    let mut builder = RouteMessageBuilder::<std::net::Ipv4Addr>::new()
                        .destination_prefix(addr, prefix_len);
                    if let Some(IpAddr::V4(gateway)) = route.gateway.map(ip_address_to_std) {
                        builder = builder.gateway(gateway);
                    }
                    if let Some(metric) = route.metric {
                        builder = builder.priority(metric);
                    }
                    if let Some(interface_index) = route.interface_index {
                        builder = builder.output_interface(interface_index);
                    }
                    builder.build()
                }
                IpAddr::V6(addr) => {
                    let mut builder = RouteMessageBuilder::<std::net::Ipv6Addr>::new()
                        .destination_prefix(addr, prefix_len);
                    if let Some(IpAddr::V6(gateway)) = route.gateway.map(ip_address_to_std) {
                        builder = builder.gateway(gateway);
                    }
                    if let Some(metric) = route.metric {
                        builder = builder.priority(metric);
                    }
                    if let Some(interface_index) = route.interface_index {
                        builder = builder.output_interface(interface_index);
                    }
                    builder.build()
                }
            };

            self.handle
                .route()
                .add(message)
                .execute()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))
        })
    }

    fn remove_route(&self, route: Self::Route) -> Result<()> {
        self.runtime.block_on(async {
            let (destination, prefix_len) = network_to_std(route.destination);
            let message = match destination {
                IpAddr::V4(addr) => {
                    let mut builder = RouteMessageBuilder::<std::net::Ipv4Addr>::new()
                        .destination_prefix(addr, prefix_len);
                    if let Some(interface_index) = route.interface_index {
                        builder = builder.output_interface(interface_index);
                    }
                    builder.build()
                }
                IpAddr::V6(addr) => {
                    let mut builder = RouteMessageBuilder::<std::net::Ipv6Addr>::new()
                        .destination_prefix(addr, prefix_len);
                    if let Some(interface_index) = route.interface_index {
                        builder = builder.output_interface(interface_index);
                    }
                    builder.build()
                }
            };

            self.handle
                .route()
                .del(message)
                .execute()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))
        })
    }
}

/// Maps Linux `ARPHRD_*` link-layer types (`LinkLayerType`) to the
/// cross-platform [`InterfaceKind`]. Anything not covered falls back to
/// `Other`, carrying the raw type code for diagnostics.
fn link_layer_type_to_kind(link_layer_type: LinkLayerType) -> InterfaceKind {
    match link_layer_type {
        LinkLayerType::Ether => InterfaceKind::Ethernet,
        LinkLayerType::Loopback => InterfaceKind::Loopback,
        LinkLayerType::Ppp => InterfaceKind::PointToPoint,
        LinkLayerType::Ieee80211
        | LinkLayerType::Ieee80211Prism
        | LinkLayerType::Ieee80211Radiotap => InterfaceKind::Wireless,
        other => InterfaceKind::Other(u16::from(other) as u32),
    }
}

fn message_to_interface(message: &LinkMessage) -> Interface {
    let index = message.header.index;
    let mut name = String::new();
    let mut mac = None;
    let mut mtu = None;
    let mut operational_state = OperationalState::Unknown;

    for attribute in &message.attributes {
        match attribute {
            LinkAttribute::IfName(value) => name = value.clone(),
            LinkAttribute::Address(bytes) if bytes.len() == 6 => {
                let mut octets = [0u8; 6];
                octets.copy_from_slice(bytes);
                mac = Some(MacAddress::new(octets));
            }
            LinkAttribute::Mtu(value) => mtu = Some(*value),
            LinkAttribute::OperState(state) => {
                operational_state = match state {
                    State::Up => OperationalState::Up,
                    State::Down | State::LowerLayerDown | State::NotPresent => {
                        OperationalState::Down
                    }
                    State::Dormant => OperationalState::NoCarrier,
                    _ => OperationalState::Unknown,
                };
            }
            _ => {}
        }
    }

    let admin_state = if message
        .header
        .flags
        .contains(rtnetlink::packet_route::link::LinkFlags::Up)
    {
        AdminState::Up
    } else {
        AdminState::Down
    };

    let kind = link_layer_type_to_kind(message.header.link_layer_type);

    let mut interface = Interface::new(Id::new(index as u64), index, name, kind)
        .with_admin_state(admin_state)
        .with_operational_state(operational_state);
    if let Some(mac) = mac {
        interface = interface.with_mac(mac);
    }
    if let Some(mtu) = mtu {
        interface = interface.with_mtu(mtu);
    }
    interface
}

impl InterfaceProvider for LinuxBackend {
    type Interface = Interface;

    fn interfaces(&self) -> Result<Vec<Self::Interface>> {
        self.runtime.block_on(async {
            let mut links = self.handle.link().get().execute();
            let mut interfaces = Vec::new();
            while let Some(message) = links
                .try_next()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))?
            {
                interfaces.push(message_to_interface(&message));
            }
            Ok(interfaces)
        })
    }
}

/// Placeholder identity scheme, same rationale as `synthesize_route_id`: a
/// neighbor entry has no kernel-assigned numeric ID, so this hashes its
/// interface and address together (the pair the kernel itself keys entries
/// by, via `RTM_GETNEIGH`).
fn synthesize_neighbor_id(interface_index: u32, address: &IpAddress) -> NeighborId {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    interface_index.hash(&mut hasher);
    address.hash(&mut hasher);
    NeighborId::new(hasher.finish())
}

/// Maps Linux `NUD_*` neighbor states (`NeighbourState`) to the
/// cross-platform [`NeighborState`].
fn neighbour_state_to_state(state: RtNeighbourState) -> NeighborState {
    match state {
        RtNeighbourState::Incomplete => NeighborState::Incomplete,
        RtNeighbourState::Reachable => NeighborState::Reachable,
        RtNeighbourState::Stale => NeighborState::Stale,
        RtNeighbourState::Delay => NeighborState::Delay,
        RtNeighbourState::Probe => NeighborState::Probe,
        RtNeighbourState::Failed => NeighborState::Failed,
        RtNeighbourState::Permanent => NeighborState::Permanent,
        _ => NeighborState::Unknown,
    }
}

fn message_to_neighbor(message: &NeighbourMessage) -> Option<NeighborEntry> {
    let interface_index = message.header.ifindex;
    let mut address = None;
    let mut mac = None;

    for attribute in &message.attributes {
        match attribute {
            NeighbourAttribute::Destination(NeighbourAddress::Inet(addr)) => {
                address = Some(std_ip_to_ip_address(IpAddr::V4(*addr)));
            }
            NeighbourAttribute::Destination(NeighbourAddress::Inet6(addr)) => {
                address = Some(std_ip_to_ip_address(IpAddr::V6(*addr)));
            }
            NeighbourAttribute::LinkLayerAddress(bytes) if bytes.len() == 6 => {
                let mut octets = [0u8; 6];
                octets.copy_from_slice(bytes);
                mac = Some(MacAddress::new(octets));
            }
            _ => {}
        }
    }

    let address = address?;
    let mut entry = NeighborEntry::new(
        synthesize_neighbor_id(interface_index, &address),
        interface_index,
        address,
    )
    .with_state(neighbour_state_to_state(message.header.state));
    if let Some(mac) = mac {
        entry = entry.with_mac(mac);
    }
    Some(entry)
}

impl NeighborProvider for LinuxBackend {
    type NeighborEntry = NeighborEntry;

    fn neighbors(&self) -> Result<Vec<Self::NeighborEntry>> {
        self.runtime.block_on(async {
            let mut messages = self.handle.neighbours().get().execute();
            let mut neighbors = Vec::new();
            while let Some(message) = messages
                .try_next()
                .await
                .map_err(|err| Error::Platform(rtnetlink_error_code(&err)))?
            {
                neighbors.extend(message_to_neighbor(&message));
            }
            Ok(neighbors)
        })
    }
}

/// Parses the `nameserver`/`search`/`domain` directives out of a
/// `resolv.conf`-format file (`man 5 resolv.conf`) — the same format on
/// Linux and BSD/macOS, so this parser is shared verbatim by
/// `net-lattice-backend-darwin`.
///
/// `domain` is folded into `search_domains` too: it is the legacy
/// single-domain predecessor of `search` and every modern resolver treats a
/// lone `domain` entry as an implicit one-element search list.
fn parse_resolv_conf(contents: &str) -> DnsConfig {
    let mut config = DnsConfig::new();
    for line in contents.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
            continue;
        }
        let mut parts = line.split_whitespace();
        match parts.next() {
            Some("nameserver") => {
                if let Some(addr) = parts.next().and_then(|s| s.parse::<IpAddr>().ok()) {
                    config.nameservers.push(std_ip_to_ip_address(addr));
                }
            }
            Some("search") | Some("domain") => {
                config
                    .search_domains
                    .extend(parts.map(|domain| domain.to_string()));
            }
            _ => {}
        }
    }
    config
}

fn render_resolv_conf(config: &NewDnsConfig) -> String {
    let mut contents = String::new();
    for nameserver in &config.nameservers {
        contents.push_str("nameserver ");
        contents.push_str(&nameserver.to_string());
        contents.push('\n');
    }
    if !config.search_domains.is_empty() {
        contents.push_str("search ");
        contents.push_str(&config.search_domains.join(" "));
        contents.push('\n');
    }
    contents
}

fn write_resolv_conf(path: &std::path::Path, config: &NewDnsConfig) -> Result<()> {
    std::fs::write(path, render_resolv_conf(config)).map_err(|err| resolv_conf_error(&err))
}

fn resolv_conf_error(err: &std::io::Error) -> Error {
    match err.kind() {
        std::io::ErrorKind::NotFound => Error::NotFound,
        std::io::ErrorKind::PermissionDenied => Error::PermissionDenied,
        _ => Error::Platform(io_error_code(err)),
    }
}

impl CapabilityProvider for LinuxBackend {
    /// `IPV6` unconditionally: every provider this backend implements
    /// (routes, interfaces, neighbors, addresses) already handles both
    /// address families. `MONITORING` unconditionally too, now that
    /// `EventProvider` is implemented below. `VRF`/`NAMESPACES` are left
    /// unset — Linux genuinely supports both at the kernel level, but Net
    /// Lattice doesn't implement either yet, and a `Capability` this
    /// backend can't actually act on would be a lie to the caller.
    fn capabilities(&self) -> Capability {
        Capability::IPV6 | Capability::MONITORING | Capability::DNS_MUTATION
    }
}

/// Maps one Netlink route/link/neighbour/address notification to an
/// [`Event`]. Reuses the existing `message_to_*` conversion functions
/// (built for the one-shot `routes()`/`interfaces()`/... dumps) purely to
/// derive the same `Id` a consumer would see from those methods — a
/// notification's `DelFoo` variant tells us an object was removed. Netlink
/// uses the corresponding `NewFoo` message for both creation and mutation,
/// so it is reported as `Changed` rather than incorrectly promising an add;
/// only the `Id` needs deriving here.
///
/// Returns `None` for Netlink message kinds this backend doesn't turn into
/// an `Event` (link property changes, neighbour tables, ...) and for any
/// notification whose attributes don't parse into an `Id` (extremely rare
/// for the kernel's own unsolicited notifications, but the parsers are
/// intentionally lenient rather than panicking on unexpected input).
fn route_netlink_message_to_event(message: RouteNetlinkMessage) -> Option<Event> {
    match message {
        RouteNetlinkMessage::NewRoute(msg) => message_to_route(&msg).map(|route| Event::Route {
            id: route.id,
            kind: ChangeKind::Changed,
        }),
        RouteNetlinkMessage::DelRoute(msg) => message_to_route(&msg).map(|route| Event::Route {
            id: route.id,
            kind: ChangeKind::Removed,
        }),
        RouteNetlinkMessage::NewLink(msg) => Some(Event::Interface {
            id: Id::new(msg.header.index as u64),
            kind: ChangeKind::Changed,
        }),
        RouteNetlinkMessage::DelLink(msg) => Some(Event::Interface {
            id: Id::new(msg.header.index as u64),
            kind: ChangeKind::Removed,
        }),
        RouteNetlinkMessage::NewNeighbour(msg) => {
            message_to_neighbor(&msg).map(|entry| Event::Neighbor {
                id: entry.id,
                kind: ChangeKind::Changed,
            })
        }
        RouteNetlinkMessage::DelNeighbour(msg) => {
            message_to_neighbor(&msg).map(|entry| Event::Neighbor {
                id: entry.id,
                kind: ChangeKind::Removed,
            })
        }
        RouteNetlinkMessage::NewAddress(msg) => {
            message_to_interface_address(&msg).map(|addr| Event::Address {
                id: addr.id,
                kind: ChangeKind::Changed,
            })
        }
        RouteNetlinkMessage::DelAddress(msg) => {
            message_to_interface_address(&msg).map(|addr| Event::Address {
                id: addr.id,
                kind: ChangeKind::Removed,
            })
        }
        _ => None,
    }
}

impl EventProvider for LinuxBackend {
    type Event = Event;
    type EventFilter = EventFilter;

    /// Opens a *second*, independent Netlink socket subscribed to the
    /// `RTNLGRP_LINK`/`RTNLGRP_NEIGH`/`RTNLGRP_IPV4_ROUTE`/
    /// `RTNLGRP_IPV6_ROUTE`/`RTNLGRP_IPV4_IFADDR`/`RTNLGRP_IPV6_IFADDR`
    /// multicast groups (`rtnetlink::new_multicast_connection`, the same
    /// mechanism `ip monitor` uses) — separate from `self.handle`'s socket,
    /// which only ever sends request/reply traffic. Two background tasks
    /// are spawned onto `self.runtime`: one drives the new socket's
    /// connection (required for it to make progress at all, mirroring
    /// `LinuxBackend::new`'s `connection` task), the other reads
    /// unsolicited notifications off it and forwards mapped `Event`s into
    /// the channel `EventReceiver` reads from.
    ///
    /// DNS resolver configuration changes (`/etc/resolv.conf`) have no
    /// Netlink signal — see `Event`'s doc comment — so no `Event::Dns` is
    /// ever produced by this backend.
    fn watch(&self) -> Result<EventReceiver<Self::Event>> {
        self.watch_filtered(EventFilter::ALL)
    }
    fn watch_filtered(&self, filter: Self::EventFilter) -> Result<EventReceiver<Self::Event>> {
        let groups = [
            MulticastGroup::Link,
            MulticastGroup::Neigh,
            MulticastGroup::Ipv4Route,
            MulticastGroup::Ipv6Route,
            MulticastGroup::Ipv4Ifaddr,
            MulticastGroup::Ipv6Ifaddr,
        ];
        let _guard = self.runtime.enter();
        let (connection, _handle, mut messages) = rtnetlink::new_multicast_connection(&groups)
            .map_err(|err| Error::Platform(io_error_code(&err)))?;
        let connection = self.runtime.spawn(connection);

        let (sender, receiver) = EventReceiver::bounded();
        let events = self.runtime.spawn(async move {
            while let Some((message, _addr)) = messages.next().await {
                let (_header, payload) = message.into_parts();
                let rtnetlink::packet_core::NetlinkPayload::InnerMessage(inner) = payload else {
                    continue;
                };
                if let Some(event) = route_netlink_message_to_event(inner)
                    && filter.matches(event)
                    && !sender.send(event, Event::resync_all())
                {
                    break;
                }
            }
        });

        Ok(receiver.with_subscription(LinuxWatch { connection, events }))
    }
}

/// Native async monitoring uses the backend's Tokio reactor and Netlink
/// multicast socket directly.
///
/// Unlike `net_lattice_async::from_receiver`, this implementation does not
/// place a blocking worker thread between the kernel notification source and
/// the returned stream.
#[cfg(feature = "async")]
impl TokioEventProvider for LinuxBackend {
    type Event = Event;
    type EventFilter = EventFilter;

    fn watch_tokio(&self, filter: Self::EventFilter) -> Result<TokioEventReceiver<Self::Event>> {
        let groups = [
            MulticastGroup::Link,
            MulticastGroup::Neigh,
            MulticastGroup::Ipv4Route,
            MulticastGroup::Ipv6Route,
            MulticastGroup::Ipv4Ifaddr,
            MulticastGroup::Ipv6Ifaddr,
        ];
        let _guard = self.runtime.enter();
        let (connection, _handle, mut messages) = rtnetlink::new_multicast_connection(&groups)
            .map_err(|err| Error::Platform(io_error_code(&err)))?;
        let connection = self.runtime.spawn(connection);
        let (sender, receiver) = TokioEventReceiver::bounded();
        let events = self.runtime.spawn(async move {
            while let Some((message, _addr)) = messages.next().await {
                let (_header, payload) = message.into_parts();
                let rtnetlink::packet_core::NetlinkPayload::InnerMessage(inner) = payload else {
                    continue;
                };
                if let Some(event) = route_netlink_message_to_event(inner)
                    && filter.matches(event)
                    && !sender.send(event, Event::resync_all)
                {
                    return;
                }
            }
            let _ = sender.send_error(Error::Disconnected);
        });
        Ok(receiver.with_subscription(LinuxWatch { connection, events }))
    }
}

impl DnsProvider for LinuxBackend {
    type DnsConfig = DnsConfig;

    fn dns_config(&self) -> Result<Self::DnsConfig> {
        let contents =
            std::fs::read_to_string("/etc/resolv.conf").map_err(|err| resolv_conf_error(&err))?;
        Ok(parse_resolv_conf(&contents))
    }
}

impl DnsMutator for LinuxBackend {
    type NewDnsConfig = NewDnsConfig;

    /// Replaces the active global `/etc/resolv.conf` resolver view.
    ///
    /// Only portable nameserver and search directives are rendered; other
    /// directives are not retained. Linux resolver managers can later replace
    /// the file, and this operation does not produce a DNS watcher event.
    /// Failure may leave a partially written file, so callers must re-read
    /// [`DnsProvider::dns_config`] after an error.
    fn set_dns_config(&self, config: Self::NewDnsConfig) -> Result<Self::DnsConfig> {
        write_resolv_conf(std::path::Path::new("/etc/resolv.conf"), &config)?;
        self.dns_config()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use net_lattice_ip::{Ipv4Address, Ipv4Network, Ipv4PrefixLength};
    use std::sync::{Mutex, MutexGuard, OnceLock};

    #[cfg(feature = "async")]
    fn tokio_route_event(watcher: &mut TokioEventReceiver<Event>, id: RouteId) -> bool {
        use std::pin::Pin;
        use std::task::{Context, Poll, Waker};
        use std::time::Duration;

        let waker = Waker::noop();
        let mut context = Context::from_waker(waker);
        for _ in 0..12 {
            match Pin::new(&mut *watcher).poll_recv(&mut context) {
                Poll::Ready(Some(Ok(Event::Route { id: event_id, .. }))) if event_id == id => {
                    return true;
                }
                Poll::Ready(Some(_)) | Poll::Pending => thread_sleep(Duration::from_millis(250)),
                Poll::Ready(None) => return false,
            }
        }
        false
    }

    #[cfg(feature = "async")]
    fn thread_sleep(duration: std::time::Duration) {
        std::thread::sleep(duration);
    }

    /// The kernel can reject simultaneous Netlink dumps in a shared CI
    /// network namespace with `EBUSY`. All tests that open a real Netlink
    /// socket take this guard; pure parser tests intentionally do not.
    fn kernel_test_guard() -> MutexGuard<'static, ()> {
        static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
        GUARD
            .get_or_init(|| Mutex::new(()))
            .lock()
            // A failed kernel assertion must not hide every later test behind
            // `PoisonError`; they should each report their own OS failure.
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Exercises a real round trip through Netlink, no privilege required:
    /// `RTM_GETROUTE` dumps are readable by any user. This is the one test
    /// in this module that runs by default and actually proves the backend
    /// talks to the kernel, rather than only exercising conversion logic.
    #[test]
    fn routes_reads_the_real_kernel_routing_table() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let routes = backend
            .routes()
            .expect("RTM_GETROUTE dump should not require privilege");
        // Not asserting on contents: the routing table of the machine
        // running this test is arbitrary (may even be empty in a minimal
        // container). Reaching here without an error is the assertion.
        let _ = routes;
    }

    /// Exercises a real round trip through Netlink, no privilege required:
    /// `RTM_GETLINK` dumps are readable by any user, and every Linux system
    /// has at least `lo`.
    #[test]
    fn interfaces_includes_the_loopback_interface() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let interfaces = backend
            .interfaces()
            .expect("RTM_GETLINK dump should not require privilege");
        assert!(
            interfaces
                .iter()
                .any(|iface| iface.name == "lo" && iface.kind == InterfaceKind::Loopback),
            "expected a `lo` interface classified as Loopback, got: {interfaces:?}"
        );
    }

    /// The advertised capabilities are the cross-platform contract exposed
    /// by this backend, rather than a claim about every Linux kernel feature.
    #[test]
    fn capabilities_match_the_implemented_provider_surface() {
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let capabilities = backend.capabilities();
        assert!(capabilities.contains(Capability::IPV6));
        assert!(capabilities.contains(Capability::MONITORING));
        assert!(capabilities.contains(Capability::DNS_MUTATION));
    }

    #[test]
    fn event_transport_covers_model_event_paths() {
        let (sender, receiver) = EventReceiver::bounded_with_capacity(1);
        assert!(sender.send(Event::resync_all(), Event::resync_all()));
        assert!(sender.send(Event::resync_all(), Event::resync_all()));
        assert!(sender.send(Event::resync_all(), Event::resync_all()));
        assert!(receiver.recv().is_ok());
        assert!(sender.send(Event::resync_all(), Event::resync_all()));
        assert!(receiver.recv().is_ok());
        drop(receiver);
        assert!(!sender.send(Event::resync_all(), Event::resync_all()));
        let (sender, receiver) = EventReceiver::<Event>::bounded();
        drop(sender);
        assert!(receiver.recv().is_err());

        #[cfg(feature = "async")]
        {
            use std::pin::Pin;
            use std::task::{Context, Poll, Waker};

            let (sender, mut receiver) = TokioEventReceiver::<Event>::bounded();
            for _ in 0..256 {
                assert!(sender.send(Event::resync_all(), Event::resync_all));
            }
            assert!(sender.send(Event::resync_all(), Event::resync_all));
            assert!(sender.send(Event::resync_all(), Event::resync_all));
            let waker = Waker::noop();
            let mut cx = Context::from_waker(waker);
            for _ in 0..256 {
                assert!(matches!(
                    Pin::new(&mut receiver).poll_recv(&mut cx),
                    Poll::Ready(_)
                ));
            }
            assert!(sender.send(Event::resync_all(), Event::resync_all));
            assert!(matches!(
                Pin::new(&mut receiver).poll_recv(&mut cx),
                Poll::Ready(_)
            ));
            assert!(matches!(
                Pin::new(&mut receiver).poll_recv(&mut cx),
                Poll::Ready(_)
            ));
            drop(sender);
            assert!(matches!(
                Pin::new(&mut receiver).poll_recv(&mut cx),
                Poll::Ready(None)
            ));

            let (sender, receiver) = TokioEventReceiver::bounded();
            drop(receiver);
            assert!(!sender.send(Event::resync_all(), Event::resync_all));
            assert!(!sender.send_error(Error::Disconnected));

            let (sender, mut receiver) = TokioEventReceiver::<Event>::bounded();
            assert!(sender.send_error(Error::InvalidState));
            drop(sender);
            assert!(matches!(
                Pin::new(&mut receiver).poll_recv(&mut cx),
                Poll::Ready(Some(Err(Error::InvalidState)))
            ));
        }
    }

    /// Exercises a real round trip through Netlink, no privilege required:
    /// `RTM_GETADDR` dumps are readable by any user, and every Linux system
    /// has at least `lo`'s `127.0.0.1/8`.
    #[test]
    fn addresses_includes_loopbacks_address() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let addresses = backend
            .addresses()
            .expect("RTM_GETADDR dump should not require privilege");
        assert!(
            addresses.iter().any(|addr| matches!(
                addr.address,
                Network::V4(net) if net.address() == Ipv4Address::new(127, 0, 0, 1)
            )),
            "expected `127.0.0.1` among the assigned addresses, got: {addresses:?}"
        );
    }

    /// Exercises a real round trip through Netlink, no privilege required:
    /// `RTM_GETNEIGH` dumps are readable by any user.
    #[test]
    fn neighbors_reads_the_real_kernel_neighbor_table() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let neighbors = backend
            .neighbors()
            .expect("RTM_GETNEIGH dump should not require privilege");
        // Not asserting on contents: the neighbor table of the machine
        // running this test is arbitrary (may even be empty). Reaching here
        // without an error is the assertion.
        let _ = neighbors;
    }

    /// Opens a real multicast subscription without changing system state.
    /// The ignored test below verifies delivery through the same subscription
    /// by adding and removing a temporary route.
    #[test]
    fn watch_opens_a_real_netlink_subscription() {
        use std::time::Duration;

        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        assert!(backend.capabilities().contains(Capability::MONITORING));
        let watcher = backend
            .watch()
            .expect("failed to subscribe to Netlink multicast groups");
        assert!(watcher.recv_timeout(Duration::from_millis(1)).is_ok());
        let filtered = backend
            .watch_filtered(EventFilter::none())
            .expect("failed to subscribe to filtered Netlink events");
        assert_eq!(
            filtered.recv_timeout(Duration::from_millis(1)).unwrap(),
            None
        );
    }

    /// The feature-gated provider opens the same native Netlink multicast
    /// subscription, but delivers it through the Tokio-aware transport used
    /// by `Lattice::watch_async`.
    #[cfg(feature = "async")]
    #[test]
    fn watch_tokio_opens_a_real_netlink_subscription() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let watcher = backend
            .watch_tokio(EventFilter::none())
            .expect("failed to subscribe to Netlink multicast groups");
        drop(watcher);
    }

    #[test]
    fn parse_resolv_conf_reads_nameservers_and_search_domains() {
        let contents = "# comment\n\
                         nameserver 1.1.1.1\n\
                         nameserver 2606:4700:4700::1111\n\
                         search example.com corp.example.com\n";
        let config = parse_resolv_conf(contents);
        assert_eq!(
            config.nameservers,
            vec![
                IpAddress::from(Ipv4Address::new(1, 1, 1, 1)),
                std_ip_to_ip_address("2606:4700:4700::1111".parse().unwrap()),
            ]
        );
        assert_eq!(
            config.search_domains,
            vec!["example.com".to_string(), "corp.example.com".to_string()]
        );
    }

    #[test]
    fn render_resolv_conf_preserves_requested_order() {
        let config = NewDnsConfig::with(
            vec![
                IpAddress::from(Ipv4Address::new(1, 1, 1, 1)),
                IpAddress::from(Ipv4Address::new(8, 8, 8, 8)),
            ],
            vec!["example.test".to_string(), "corp.test".to_string()],
        );
        assert_eq!(
            render_resolv_conf(&config),
            "nameserver 1.1.1.1\nnameserver 8.8.8.8\nsearch example.test corp.test\n"
        );
    }

    #[test]
    fn resolver_parser_ignores_nonportable_directives_and_renderer_handles_empty_config() {
        let config =
            parse_resolv_conf("options rotate\ninvalid 192.0.2.1\nnameserver invalid\nsearch\n");
        assert!(config.nameservers.is_empty());
        assert!(config.search_domains.is_empty());
        assert_eq!(render_resolv_conf(&NewDnsConfig::new()), "");
    }

    #[test]
    fn ip_and_network_conversion_round_trip_both_families() {
        let ipv4 = IpAddress::from(Ipv4Address::new(192, 0, 2, 1));
        let ipv6 = std_ip_to_ip_address("2001:db8::1".parse().expect("IPv6"));
        assert_eq!(std_ip_to_ip_address(ip_address_to_std(ipv4)), ipv4);
        assert_eq!(std_ip_to_ip_address(ip_address_to_std(ipv6)), ipv6);

        let v4_network = Network::from(Ipv4Network::new(
            Ipv4Address::new(192, 0, 2, 0),
            Ipv4PrefixLength::new(24).expect("prefix"),
        ));
        let v6_network = Network::from(net_lattice_ip::Ipv6Network::new(
            net_lattice_ip::Ipv6Address::new([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]),
            net_lattice_ip::Ipv6PrefixLength::new(32).expect("prefix"),
        ));
        assert_eq!(network_to_std(v4_network).1, 24);
        assert_eq!(network_to_std(v6_network).1, 32);
    }

    #[test]
    fn netlink_message_fixtures_preserve_address_route_and_neighbor_details() {
        let mut address = AddressMessage::default();
        address.header.index = 7;
        address.header.prefix_len = 24;
        address.attributes = vec![
            AddressAttribute::Address(IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 99))),
            AddressAttribute::Local(IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 7))),
            AddressAttribute::Broadcast(std::net::Ipv4Addr::new(192, 0, 2, 255)),
        ];
        let observed = message_to_interface_address(&address).expect("valid IPv4 address");
        assert_eq!(observed.interface_index, 7);
        assert_eq!(
            observed.address,
            Network::from(Ipv4Network::new(
                Ipv4Address::new(192, 0, 2, 7),
                Ipv4PrefixLength::new(24).unwrap(),
            ))
        );
        assert_eq!(
            observed.broadcast,
            Some(IpAddress::from(Ipv4Address::new(192, 0, 2, 255)))
        );
        assert!(message_to_interface_address(&AddressMessage::default()).is_none());

        let route = RouteMessageBuilder::<std::net::Ipv4Addr>::new()
            .destination_prefix(std::net::Ipv4Addr::new(198, 51, 100, 0), 24)
            .gateway(std::net::Ipv4Addr::new(192, 0, 2, 1))
            .priority(42)
            .output_interface(7)
            .build();
        let observed = message_to_route(&route).expect("valid IPv4 route");
        assert_eq!(
            observed.gateway,
            Some(IpAddress::from(Ipv4Address::new(192, 0, 2, 1)))
        );
        assert_eq!(observed.metric, Some(42));
        assert_eq!(observed.interface_index, Some(7));
        assert!(message_to_route(&RouteMessage::default()).is_none());

        let mut neighbor = NeighbourMessage::default();
        neighbor.header.ifindex = 7;
        neighbor.header.state = RtNeighbourState::Reachable;
        neighbor.attributes = vec![
            NeighbourAttribute::Destination(NeighbourAddress::Inet(std::net::Ipv4Addr::new(
                192, 0, 2, 1,
            ))),
            NeighbourAttribute::LinkLayerAddress(vec![0, 1, 2, 3, 4, 5]),
        ];
        let observed = message_to_neighbor(&neighbor).expect("valid IPv4 neighbour");
        assert_eq!(observed.interface_index, 7);
        assert_eq!(observed.state, NeighborState::Reachable);
        assert_eq!(observed.mac, Some(MacAddress::new([0, 1, 2, 3, 4, 5])));
        assert!(message_to_neighbor(&NeighbourMessage::default()).is_none());
    }

    #[test]
    fn netlink_error_and_state_mappings_are_stable() {
        assert_eq!(
            io_error_code(&std::io::Error::from_raw_os_error(13)),
            PlatformErrorCode::Linux(13)
        );
        assert_eq!(
            io_error_code(&std::io::Error::other("no OS error")),
            PlatformErrorCode::Linux(0)
        );
        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Failed),
            NeighborState::Failed
        );
        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Reachable),
            NeighborState::Reachable
        );
    }

    #[test]
    fn netlink_interface_and_neighbor_mappings_cover_all_known_states() {
        assert_eq!(
            link_layer_type_to_kind(LinkLayerType::Ether),
            InterfaceKind::Ethernet
        );
        assert_eq!(
            link_layer_type_to_kind(LinkLayerType::Loopback),
            InterfaceKind::Loopback
        );
        assert_eq!(
            link_layer_type_to_kind(LinkLayerType::Ppp),
            InterfaceKind::PointToPoint
        );
        assert_eq!(
            link_layer_type_to_kind(LinkLayerType::Ieee80211),
            InterfaceKind::Wireless
        );
        assert_eq!(
            link_layer_type_to_kind(LinkLayerType::Ieee80211Prism),
            InterfaceKind::Wireless
        );
        assert_eq!(
            link_layer_type_to_kind(LinkLayerType::Ieee80211Radiotap),
            InterfaceKind::Wireless
        );
        assert!(matches!(
            link_layer_type_to_kind(LinkLayerType::Netrom),
            InterfaceKind::Other(_)
        ));

        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Incomplete),
            NeighborState::Incomplete
        );
        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Stale),
            NeighborState::Stale
        );
        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Delay),
            NeighborState::Delay
        );
        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Probe),
            NeighborState::Probe
        );
        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Permanent),
            NeighborState::Permanent
        );
        assert_eq!(
            neighbour_state_to_state(RtNeighbourState::Noarp),
            NeighborState::Unknown
        );
    }

    #[test]
    fn netlink_event_mapper_covers_every_supported_domain_and_change_kind() {
        let route = RouteMessageBuilder::<std::net::Ipv4Addr>::new()
            .destination_prefix(std::net::Ipv4Addr::new(198, 51, 100, 0), 24)
            .build();
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::NewRoute(route.clone())),
            Some(Event::Route {
                kind: ChangeKind::Changed,
                ..
            })
        ));
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::DelRoute(route)),
            Some(Event::Route {
                kind: ChangeKind::Removed,
                ..
            })
        ));

        let mut link = LinkMessage::default();
        link.header.index = 7;
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::NewLink(link.clone())),
            Some(Event::Interface { id, kind: ChangeKind::Changed }) if id == Id::new(7)
        ));
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::DelLink(link)),
            Some(Event::Interface { id, kind: ChangeKind::Removed }) if id == Id::new(7)
        ));

        let mut address = AddressMessage::default();
        address.header.index = 7;
        address.header.prefix_len = 24;
        address.attributes.push(AddressAttribute::Local(IpAddr::V4(
            std::net::Ipv4Addr::new(192, 0, 2, 7),
        )));
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::NewAddress(address.clone())),
            Some(Event::Address {
                kind: ChangeKind::Changed,
                ..
            })
        ));
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::DelAddress(address)),
            Some(Event::Address {
                kind: ChangeKind::Removed,
                ..
            })
        ));

        let mut neighbor = NeighbourMessage::default();
        neighbor.header.ifindex = 7;
        neighbor
            .attributes
            .push(NeighbourAttribute::Destination(NeighbourAddress::Inet(
                std::net::Ipv4Addr::new(192, 0, 2, 1),
            )));
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::NewNeighbour(neighbor.clone())),
            Some(Event::Neighbor {
                kind: ChangeKind::Changed,
                ..
            })
        ));
        assert!(matches!(
            route_netlink_message_to_event(RouteNetlinkMessage::DelNeighbour(neighbor)),
            Some(Event::Neighbor {
                kind: ChangeKind::Removed,
                ..
            })
        ));
    }

    #[test]
    fn mutation_validation_and_resolver_errors_are_explicit() {
        assert!(matches!(
            resolv_conf_error(&std::io::Error::from(std::io::ErrorKind::NotFound)),
            Error::NotFound
        ));
        assert!(matches!(
            resolv_conf_error(&std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
            Error::PermissionDenied
        ));
        assert!(matches!(
            resolv_conf_error(&std::io::Error::other("resolver failure")),
            Error::Platform(PlatformErrorCode::Linux(_))
        ));

        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let ipv6 = Network::from(net_lattice_ip::Ipv6Network::new(
            net_lattice_ip::Ipv6Address::new([0x2001, 0xdb8, 0, 0, 0, 0, 0, 1]),
            net_lattice_ip::Ipv6PrefixLength::new(64).unwrap(),
        ));
        let request = NewInterfaceAddress::new(Id::new(1), ipv6)
            .with_broadcast(Ipv4Address::new(192, 0, 2, 255));
        assert!(matches!(
            backend.add_address(request),
            Err(Error::InvalidState)
        ));
    }

    /// Reads the real `/etc/resolv.conf` present on this test environment.
    /// Every Linux system has one (even if empty/symlinked to
    /// systemd-resolved's stub), so this exercises the real filesystem read
    /// without requiring any specific content.
    #[test]
    fn dns_config_reads_the_real_resolv_conf() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let config = backend
            .dns_config()
            .expect("/etc/resolv.conf should be readable");
        let _ = config;
    }

    #[test]
    #[ignore = "requires a working Netlink socket; run with the privileged backend coverage job"]
    fn invalid_mutations_exercise_kernel_error_paths() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let network = Network::from(Ipv4Network::new(
            Ipv4Address::new(203, 0, 113, 250),
            Ipv4PrefixLength::new(32).expect("valid prefix"),
        ));
        let requested = NewInterfaceAddress::new(Id::new(u64::from(u32::MAX)), network);
        assert!(backend.add_address(requested).is_err());

        let missing = InterfaceAddress::new(Id::new(u64::MAX), u32::MAX, network);
        assert!(backend.remove_address(missing).is_err());

        let route = Route::new(RouteId::new(0), network).with_interface_index(u32::MAX);
        assert!(backend.add_route(route.clone()).is_err());
        assert!(backend.remove_route(route).is_err());
    }

    fn loopback_interface_index(backend: &LinuxBackend) -> u32 {
        backend
            .runtime
            .block_on(async {
                let mut links = backend
                    .handle
                    .link()
                    .get()
                    .match_name("lo".into())
                    .execute();
                links
                    .try_next()
                    .await
                    .ok()
                    .flatten()
                    .map(|link| link.header.index)
            })
            .expect("this test environment has no `lo` interface")
    }

    /// Requires `CAP_NET_ADMIN` (root, or `sudo -E cargo test -- --ignored`
    /// in this crate). Not run by default because most development and CI
    /// environments — including the one this crate was originally written
    /// in — don't grant it, and this test would otherwise fail with
    /// `PermissionDenied` rather than being skipped.
    ///
    /// Uses a documentation-only prefix (RFC 5737 `203.0.113.0/24`,
    /// TEST-NET-3) on `lo` so it can't collide with or disrupt real
    /// routing, and removes what it added regardless of assertion outcome.
    #[test]
    #[ignore = "requires CAP_NET_ADMIN; run with `sudo -E cargo test -p net-lattice-backend-linux -- --ignored`"]
    fn add_then_remove_route_round_trips_through_the_kernel() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let interface_index = loopback_interface_index(&backend);

        let destination = Network::from(Ipv4Network::new(
            Ipv4Address::new(203, 0, 113, 0),
            Ipv4PrefixLength::new(24).unwrap(),
        ));
        let route = Route::new(RouteId::new(0), destination).with_interface_index(interface_index);

        let add_result = backend.add_route(route.clone());
        if matches!(
            add_result,
            Err(Error::PermissionDenied) | Err(Error::Platform(_))
        ) {
            // Best effort even under #[ignore]: if it's run without the
            // capability after all, fail loudly rather than silently
            // passing on a no-op.
            add_result.expect("add_route failed - are you running with CAP_NET_ADMIN?");
        }

        let routes = backend
            .routes()
            .expect("routes() failed after add_route succeeded");
        let found = routes
            .iter()
            .any(|r| r.destination == destination && r.interface_index == Some(interface_index));

        // Clean up before asserting, so a failed assertion doesn't leave
        // the test route behind on the machine that ran this.
        let _ = backend.remove_route(route);

        assert!(found, "added route was not present in routes() afterward");

        let routes_after_removal = backend
            .routes()
            .expect("routes() failed after remove_route");
        assert!(
            !routes_after_removal
                .iter()
                .any(|r| r.destination == destination && r.interface_index == Some(interface_index)),
            "removed route was still present in routes() afterward"
        );
    }

    /// Exercises the complete address-mutation path against the real
    /// kernel: create an IPv4 address on `lo`, read the canonical observed
    /// record, then remove that exact record. TEST-NET-1 is reserved for
    /// documentation and is distinct from the route tests' prefixes.
    #[test]
    #[ignore = "requires CAP_NET_ADMIN; run with `sudo -E cargo test -p net-lattice-backend-linux add_then_remove_address_round_trips_through_the_kernel -- --ignored`"]
    fn add_then_remove_address_round_trips_through_the_kernel() {
        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        let interface_index = loopback_interface_index(&backend);
        let network = Network::from(Ipv4Network::new(
            Ipv4Address::new(192, 0, 2, 9),
            Ipv4PrefixLength::new(24).unwrap(),
        ));
        let requested = NewInterfaceAddress::new(Id::new(interface_index as u64), network);

        // A prior interrupted ignored-test run must not turn this run into a
        // false duplicate. The address range is test-only and cleanup is
        // deliberately best-effort before the actual assertion path.
        if let Some(existing) = backend
            .addresses()
            .expect("addresses() failed before add_address")
            .into_iter()
            .find(|address| {
                address.interface_index == interface_index && address.address == network
            })
        {
            let _ = backend.remove_address(existing);
        }

        let observed = backend
            .add_address(requested)
            .expect("add_address failed - are you running with CAP_NET_ADMIN?");
        let present = backend
            .addresses()
            .expect("addresses() failed after add_address")
            .into_iter()
            .any(|address| address.id == observed.id);

        backend
            .remove_address(observed.clone())
            .expect("remove_address failed after successful add_address");
        let absent = !backend
            .addresses()
            .expect("addresses() failed after remove_address")
            .into_iter()
            .any(|address| address.id == observed.id);

        assert!(
            present,
            "added address was not present in addresses() afterward"
        );
        assert!(
            absent,
            "removed address was still present in addresses() afterward"
        );
    }

    /// End-to-end monitoring verification: a route mutation must travel from
    /// the kernel's Netlink multicast group through `watch()` to the caller.
    /// It is ignored by default because creating the route requires
    /// `CAP_NET_ADMIN`.
    #[test]
    #[ignore = "requires CAP_NET_ADMIN; run with `sudo -E cargo test -p net-lattice-backend-linux watch_observes_route_changes -- --ignored`"]
    fn watch_observes_route_changes() {
        use std::time::Duration;

        let _guard = kernel_test_guard();
        let backend = LinuxBackend::new().expect("failed to open a Netlink connection");
        assert!(backend.capabilities().contains(Capability::MONITORING));
        let watcher = backend
            .watch()
            .expect("failed to subscribe to Netlink events");
        #[cfg(feature = "async")]
        let mut async_watcher = backend
            .watch_tokio(EventFilter::none().routes())
            .expect("failed to subscribe to async Netlink events");
        let interface_index = loopback_interface_index(&backend);
        let destination = Network::from(Ipv4Network::new(
            Ipv4Address::new(198, 51, 100, 0),
            Ipv4PrefixLength::new(24).unwrap(),
        ));
        let route = Route::new(RouteId::new(0), destination).with_interface_index(interface_index);

        // Recover from an interrupted prior run before attempting the add.
        // The test route is deliberately isolated to TEST-NET-2.
        let _ = backend.remove_route(route.clone());
        backend
            .add_route(route.clone())
            .expect("failed to add monitoring test route");
        // Obtain the identity from the notification itself. A concurrent
        // RTM_GETROUTE dump can be rejected with EBUSY while the multicast
        // sockets are active, whereas the notification is the authoritative
        // identity source for this monitoring test.
        let watched_id = (0..12)
            .find_map(|_| match watcher.recv_timeout(Duration::from_millis(250)) {
                Ok(Some(Event::Route { id, .. })) => Some(id),
                _ => None,
            })
            .expect("watch() did not report the route addition");
        let observed = true;
        #[cfg(feature = "async")]
        let async_observed = tokio_route_event(&mut async_watcher, watched_id);
        let selected_watcher = backend
            .watch_filtered(EventFilter::none().route(watched_id))
            .expect("failed to subscribe to selected Netlink route events");
        #[cfg(feature = "async")]
        let mut selected_async_watcher = backend
            .watch_tokio(EventFilter::none().route(watched_id))
            .expect("failed to subscribe to selected async Netlink route events");
        let _ = backend.remove_route(route);
        let selected_observed = (0..12).any(|_| {
            matches!(
                selected_watcher.recv_timeout(Duration::from_millis(250)),
                Ok(Some(Event::Route { id, kind: ChangeKind::Removed })) if id == watched_id
            )
        });
        #[cfg(feature = "async")]
        let selected_async_observed = tokio_route_event(&mut selected_async_watcher, watched_id);
        assert!(observed, "watch() did not report the route mutation");
        assert!(
            selected_observed,
            "object route filter did not report removal"
        );
        #[cfg(feature = "async")]
        assert!(
            async_observed,
            "watch_tokio() did not report the route mutation"
        );
        #[cfg(feature = "async")]
        assert!(
            selected_async_observed,
            "async object route filter did not report removal"
        );
    }
}