nlink 0.15.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
//! Protocol state types for strongly-typed connections.
//!
//! This module provides the type-level protocol distinction that enables
//! compile-time safety for protocol-specific operations on [`Connection`].
//!
//! # Design
//!
//! Each netlink protocol (Route, Generic, etc.) has an associated state type
//! that may carry protocol-specific data:
//!
//! - [`Route`]: Zero-sized, no additional state needed
//! - [`Generic`]: Contains a family ID cache for efficient lookups
//!
//! The [`ProtocolState`] trait is sealed to prevent external implementations.
//!
//! # Example
//!
//! ```ignore
//! use nlink::netlink::{Connection, Route, Generic};
//!
//! // Route connection for interface/address/route/TC operations
//! let route = Connection::<Route>::new()?;
//! route.get_links().await?;
//!
//! // Generic connection for WireGuard/MACsec configuration
//! let genl = Connection::<Generic>::new()?;
//! genl.get_family("wireguard").await?;
//! ```

use std::{collections::HashMap, sync::RwLock};

use super::{
    error::Result,
    genl::FamilyInfo,
    socket::{NetlinkSocket, Protocol},
};

/// Sealed trait module to prevent external implementations.
mod private {
    pub trait Sealed {}
}

/// Protocol state trait for typed connections.
///
/// This trait is sealed and cannot be implemented outside this crate.
/// Each implementation provides:
/// - The underlying netlink protocol constant
/// - Protocol-specific state (if any)
///
/// Types that implement `Default` can use the generic `Connection::new()`.
/// Types that require special initialization should provide their own constructor.
pub trait ProtocolState: private::Sealed {
    /// The netlink protocol for this state type.
    const PROTOCOL: Protocol;
}

/// Async initialization trait for protocols requiring async setup.
///
/// GENL protocols (WireGuard, MACsec, MPTCP, Ethtool, nl80211, Devlink) need
/// to resolve their family ID asynchronously after the socket is created.
/// This trait enables `namespace::connection_for_async()` to create connections
/// in foreign namespaces for these protocols.
///
/// This trait is sealed and cannot be implemented outside this crate.
pub trait AsyncProtocolInit: ProtocolState {
    /// Resolve protocol-specific state from an already-connected socket.
    ///
    /// The socket has already been created in the target namespace.
    /// This method performs the async GENL family resolution through that socket.
    fn resolve_async(
        socket: &NetlinkSocket,
    ) -> impl std::future::Future<Output = Result<Self>> + Send
    where
        Self: Sized;
}

/// Route protocol state (RTNetlink).
///
/// Used for interface, address, route, neighbor, and traffic control operations.
/// This is a zero-sized type with no additional state.
#[derive(Debug, Default, Clone, Copy)]
pub struct Route;

impl private::Sealed for Route {}

impl ProtocolState for Route {
    const PROTOCOL: Protocol = Protocol::Route;
}

/// Socket diagnostics protocol state.
///
/// Used for querying socket information (TCP, UDP, Unix, etc.).
/// This is a zero-sized type with no additional state.
#[derive(Debug, Default, Clone, Copy)]
pub struct SockDiag;

impl private::Sealed for SockDiag {}

impl ProtocolState for SockDiag {
    const PROTOCOL: Protocol = Protocol::SockDiag;
}

/// Generic netlink protocol state.
///
/// Used for family-based protocols like WireGuard and MACsec.
/// Contains a cache of resolved family IDs for efficient lookups.
pub struct Generic {
    /// Cache of family name -> family info mappings.
    pub(crate) cache: RwLock<HashMap<String, FamilyInfo>>,
}

impl Default for Generic {
    fn default() -> Self {
        Self {
            cache: RwLock::new(HashMap::new()),
        }
    }
}

impl std::fmt::Debug for Generic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Generic")
            .field(
                "cache_size",
                &self.cache.read().map(|c| c.len()).unwrap_or(0),
            )
            .finish()
    }
}

impl private::Sealed for Generic {}

impl ProtocolState for Generic {
    const PROTOCOL: Protocol = Protocol::Generic;
}

/// WireGuard protocol state.
///
/// Used for WireGuard device configuration via Generic Netlink.
/// Contains the resolved WireGuard family ID.
///
/// Construct with `Connection::<Wireguard>::new_async().await?`, not `Connection::new()`.
#[derive(Debug, Default)]
pub struct Wireguard {
    /// Resolved WireGuard GENL family ID.
    pub(crate) family_id: u16,
}

impl private::Sealed for Wireguard {}

impl ProtocolState for Wireguard {
    const PROTOCOL: Protocol = Protocol::Generic;
}

/// Kobject uevent protocol state.
///
/// Used for receiving kernel object events (device hotplug, like udev).
/// This is a zero-sized type with no additional state.
///
/// Note: Does not implement `Default` because connections require
/// multicast group subscription. Use `Connection::<KobjectUevent>::new()`.
#[derive(Debug, Clone, Copy)]
pub struct KobjectUevent;

impl private::Sealed for KobjectUevent {}

impl ProtocolState for KobjectUevent {
    const PROTOCOL: Protocol = Protocol::KobjectUevent;
}

/// Connector protocol state.
///
/// Used for kernel connector events, primarily process events (fork/exec/exit).
/// This is a zero-sized type with no additional state.
///
/// Note: Does not implement `Default` because connections require
/// registration with the kernel. Use `Connection::<Connector>::new()`.
#[derive(Debug, Clone, Copy)]
pub struct Connector;

impl private::Sealed for Connector {}

impl ProtocolState for Connector {
    const PROTOCOL: Protocol = Protocol::Connector;
}

/// Netfilter protocol state.
///
/// Used for netfilter operations, primarily connection tracking (conntrack).
/// This is a zero-sized type with no additional state.
#[derive(Debug, Default, Clone, Copy)]
pub struct Netfilter;

impl private::Sealed for Netfilter {}

impl ProtocolState for Netfilter {
    const PROTOCOL: Protocol = Protocol::Netfilter;
}

/// XFRM protocol state.
///
/// Used for IPsec Security Association (SA) and Security Policy (SP) management.
/// This is a zero-sized type with no additional state.
#[derive(Debug, Default, Clone, Copy)]
pub struct Xfrm;

impl private::Sealed for Xfrm {}

impl ProtocolState for Xfrm {
    const PROTOCOL: Protocol = Protocol::Xfrm;
}

/// FIB lookup protocol state.
///
/// Used for performing FIB (Forwarding Information Base) route lookups.
/// This is a zero-sized type with no additional state.
#[derive(Debug, Clone, Copy)]
pub struct FibLookup;

impl private::Sealed for FibLookup {}

impl ProtocolState for FibLookup {
    const PROTOCOL: Protocol = Protocol::FibLookup;
}

/// SELinux protocol state.
///
/// Used for receiving SELinux event notifications (setenforce, policyload).
/// This is a zero-sized type with no additional state.
///
/// Note: Does not implement `Default` because connections require
/// multicast group subscription. Use `Connection::<SELinux>::new()`.
#[derive(Debug, Clone, Copy)]
pub struct SELinux;

impl private::Sealed for SELinux {}

impl ProtocolState for SELinux {
    const PROTOCOL: Protocol = Protocol::SELinux;
}

/// Audit protocol state.
///
/// Used for interacting with the Linux Audit subsystem.
/// This is a zero-sized type with no additional state.
#[derive(Debug, Clone, Copy)]
pub struct Audit;

impl private::Sealed for Audit {}

impl ProtocolState for Audit {
    const PROTOCOL: Protocol = Protocol::Audit;
}

/// MACsec protocol state.
///
/// Used for MACsec (IEEE 802.1AE) device configuration via Generic Netlink.
/// Contains the resolved MACsec family ID.
///
/// Construct with `Connection::<Macsec>::new_async().await?`, not `Connection::new()`.
#[derive(Debug, Default)]
pub struct Macsec {
    /// Resolved MACsec GENL family ID.
    pub(crate) family_id: u16,
}

impl private::Sealed for Macsec {}

impl ProtocolState for Macsec {
    const PROTOCOL: Protocol = Protocol::Generic;
}

/// MPTCP protocol state.
///
/// Used for MPTCP (Multipath TCP) endpoint configuration via Generic Netlink.
/// Contains the resolved MPTCP Path Manager family ID.
///
/// Construct with `Connection::<Mptcp>::new_async().await?`, not `Connection::new()`.
#[derive(Debug, Default)]
pub struct Mptcp {
    /// Resolved MPTCP PM GENL family ID.
    pub(crate) family_id: u16,
}

impl private::Sealed for Mptcp {}

impl ProtocolState for Mptcp {
    const PROTOCOL: Protocol = Protocol::Generic;
}

/// Devlink protocol state.
///
/// Used for querying hardware device management via Generic Netlink.
/// Contains the resolved devlink family ID.
///
/// Construct with `Connection::<Devlink>::new_async().await?`, not `Connection::new()`.
#[derive(Debug, Default)]
pub struct Devlink {
    /// Resolved devlink GENL family ID.
    pub(crate) family_id: u16,
    /// Multicast group ID for event notifications.
    pub(crate) monitor_group_id: Option<u32>,
}

impl private::Sealed for Devlink {}

impl ProtocolState for Devlink {
    const PROTOCOL: Protocol = Protocol::Generic;
}

/// Nftables protocol state.
///
/// Used for nftables firewall management via NETLINK_NETFILTER.
/// This is a zero-sized type with no additional state.
#[derive(Debug, Default, Clone, Copy)]
pub struct Nftables;

impl private::Sealed for Nftables {}

impl ProtocolState for Nftables {
    const PROTOCOL: Protocol = Protocol::Netfilter;
}

/// nl80211 protocol state.
///
/// Used for WiFi configuration via Generic Netlink.
/// Contains the resolved nl80211 family ID.
///
/// Construct with `Connection::<Nl80211>::new_async().await?`, not `Connection::new()`.
#[derive(Debug, Default)]
pub struct Nl80211 {
    /// Resolved nl80211 GENL family ID.
    pub(crate) family_id: u16,
    /// Multicast group IDs for event monitoring.
    pub(crate) scan_group_id: Option<u32>,
    pub(crate) mlme_group_id: Option<u32>,
    pub(crate) regulatory_group_id: Option<u32>,
    pub(crate) config_group_id: Option<u32>,
}

impl private::Sealed for Nl80211 {}

impl ProtocolState for Nl80211 {
    const PROTOCOL: Protocol = Protocol::Generic;
}

/// Ethtool protocol state.
///
/// Used for querying and configuring network device settings via Generic Netlink.
/// Contains the resolved ethtool family ID and monitor group ID.
///
/// Construct with `Connection::<Ethtool>::new_async().await?`, not `Connection::new()`.
#[derive(Debug, Default)]
pub struct Ethtool {
    /// Resolved ethtool GENL family ID.
    pub(crate) family_id: u16,
    /// Monitor multicast group ID (for event notifications).
    pub(crate) monitor_group_id: Option<u32>,
}

impl private::Sealed for Ethtool {}

impl ProtocolState for Ethtool {
    const PROTOCOL: Protocol = Protocol::Generic;
}

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

    #[test]
    fn route_is_zero_sized() {
        assert_eq!(std::mem::size_of::<Route>(), 0);
    }

    #[test]
    fn sockdiag_is_zero_sized() {
        assert_eq!(std::mem::size_of::<SockDiag>(), 0);
    }

    #[test]
    fn generic_has_cache() {
        let g = Generic::default();
        assert!(g.cache.read().unwrap().is_empty());
    }

    #[test]
    fn protocol_constants() {
        assert_eq!(Route::PROTOCOL, Protocol::Route);
        assert_eq!(SockDiag::PROTOCOL, Protocol::SockDiag);
        assert_eq!(Generic::PROTOCOL, Protocol::Generic);
        assert_eq!(Wireguard::PROTOCOL, Protocol::Generic);
        assert_eq!(Macsec::PROTOCOL, Protocol::Generic);
        assert_eq!(Mptcp::PROTOCOL, Protocol::Generic);
        assert_eq!(Ethtool::PROTOCOL, Protocol::Generic);
        assert_eq!(Nl80211::PROTOCOL, Protocol::Generic);
        assert_eq!(KobjectUevent::PROTOCOL, Protocol::KobjectUevent);
        assert_eq!(Connector::PROTOCOL, Protocol::Connector);
        assert_eq!(Netfilter::PROTOCOL, Protocol::Netfilter);
        assert_eq!(Nftables::PROTOCOL, Protocol::Netfilter);
        assert_eq!(Xfrm::PROTOCOL, Protocol::Xfrm);
        assert_eq!(FibLookup::PROTOCOL, Protocol::FibLookup);
        assert_eq!(SELinux::PROTOCOL, Protocol::SELinux);
        assert_eq!(Audit::PROTOCOL, Protocol::Audit);
    }

    #[test]
    fn new_types_are_zero_sized() {
        assert_eq!(std::mem::size_of::<KobjectUevent>(), 0);
        assert_eq!(std::mem::size_of::<Connector>(), 0);
        assert_eq!(std::mem::size_of::<Netfilter>(), 0);
        assert_eq!(std::mem::size_of::<Xfrm>(), 0);
        assert_eq!(std::mem::size_of::<FibLookup>(), 0);
        assert_eq!(std::mem::size_of::<SELinux>(), 0);
        assert_eq!(std::mem::size_of::<Audit>(), 0);
        assert_eq!(std::mem::size_of::<Nftables>(), 0);
    }
}