zlayer-overlay 0.12.8

Encrypted overlay networking for containers using boringtun userspace WireGuard
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
#![cfg(target_os = "linux")]

//! Rust netlink helpers that replace shell-outs to `ip` for overlay TUN
//! transport setup.
//!
//! This module is the Linux-only counterpart to the shell-outs previously
//! used by [`crate::transport`] to configure the boringtun-created TUN
//! device:
//!
//! - `ip link show <iface>`           → [`link_exists`]
//! - `ip link delete <iface>`         → [`delete_link_by_name`]
//! - `ip addr add <cidr> dev <iface>` → [`add_address_to_link`]
//! - `ip link set dev <iface> up`     → [`set_link_up_by_name`]
//! - `ip route add <net> dev <iface>` → [`add_route_via_dev`]
//!
//! All helpers talk RTNETLINK directly via the `rtnetlink` crate (async,
//! tokio-backed). The module is compiled on Linux only — the macOS branch
//! of `transport.rs` uses a completely different path (utun + ifconfig +
//! route) and never touches these helpers.

use std::net::IpAddr;

use thiserror::Error;

/// Errors returned by the netlink helpers in this module.
#[derive(Debug, Error)]
pub enum NetlinkError {
    /// Failed to open or access a file.
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    /// The requested link was not found in the current network namespace.
    #[error("link '{0}' not found")]
    NotFound(String),

    /// A netlink operation failed.
    #[error("netlink operation failed: {0}")]
    Netlink(String),
}

/// Returns `Ok(true)` if the named link exists in the current netns,
/// `Ok(false)` if it does not, and an error for any other RTNETLINK
/// failure (permission denied, etc.).
///
/// Replaces the shell-out:
///   ip link show `<name>`
///
/// Used by the stale-interface cleanup in
/// [`crate::transport::OverlayTransport::create_interface`] to detect
/// a leaked TUN device from a previously crashed `boringtun` instance.
///
/// # Errors
///
/// Returns [`NetlinkError::Netlink`] if the RTNETLINK connection fails
/// to initialize or the lookup returns an error other than
/// `ENODEV` / "No such device" (which are mapped to `Ok(false)`).
pub async fn link_exists(name: &str) -> Result<bool, NetlinkError> {
    use futures_util::stream::TryStreamExt;

    let (connection, handle, _) = rtnetlink::new_connection()
        .map_err(|e| NetlinkError::Netlink(format!("new_connection failed: {e}")))?;
    tokio::spawn(connection);

    let lookup = handle
        .link()
        .get()
        .match_name(name.to_string())
        .execute()
        .try_next()
        .await;

    match lookup {
        Ok(Some(_)) => Ok(true),
        Ok(None) => Ok(false),
        Err(rtnetlink::Error::NetlinkError(err)) => {
            let msg = err.to_string();
            // libc::ENODEV == 19 on Linux. Avoid a libc dep by hard-coding.
            let is_enodev = err.code.is_some_and(|c| c.get().unsigned_abs() == 19);
            if is_enodev || msg.contains("No such device") {
                Ok(false)
            } else {
                Err(NetlinkError::Netlink(format!(
                    "link lookup failed for {name}: {msg}"
                )))
            }
        }
        Err(e) => {
            let msg = e.to_string();
            if msg.contains("No such device") {
                Ok(false)
            } else {
                Err(NetlinkError::Netlink(format!(
                    "link lookup failed for {name}: {msg}"
                )))
            }
        }
    }
}

/// Delete the link by name. Idempotent: returns `Ok(())` if the link
/// does not exist.
///
/// Replaces the shell-out:
///   ip link delete `<name>`
///
/// Currently unused at runtime (the boot-time stale-interface sweep in
/// `bin/zlayer/src/commands/serve.rs::cleanup_stale_daemon` uses `ip link
/// delete` directly). Kept as a tested netlink helper for any future
/// caller-driven cleanup that wants to avoid the shell hop.
///
/// # Errors
///
/// Returns [`NetlinkError::Netlink`] if RTNETLINK reports a failure
/// other than `ENODEV` / "No such device" (which are treated as
/// success so this is safe to call unconditionally).
#[allow(dead_code)]
pub async fn delete_link_by_name(name: &str) -> Result<(), NetlinkError> {
    use futures_util::stream::TryStreamExt;

    let (connection, handle, _) = rtnetlink::new_connection()
        .map_err(|e| NetlinkError::Netlink(format!("new_connection failed: {e}")))?;
    tokio::spawn(connection);

    let lookup = handle
        .link()
        .get()
        .match_name(name.to_string())
        .execute()
        .try_next()
        .await;

    let link = match lookup {
        Ok(Some(link)) => link,
        Ok(None) => return Ok(()),
        Err(rtnetlink::Error::NetlinkError(err)) => {
            let msg = err.to_string();
            // libc::ENODEV == 19 on Linux. Avoid a libc dep by hard-coding.
            let is_enodev = err.code.is_some_and(|c| c.get().unsigned_abs() == 19);
            if is_enodev || msg.contains("No such device") {
                return Ok(());
            }
            return Err(NetlinkError::Netlink(format!(
                "link lookup failed for {name}: {msg}"
            )));
        }
        Err(e) => {
            let msg = e.to_string();
            if msg.contains("No such device") {
                return Ok(());
            }
            return Err(NetlinkError::Netlink(format!(
                "link lookup failed for {name}: {msg}"
            )));
        }
    };

    let index = link.header.index;

    handle
        .link()
        .del(index)
        .execute()
        .await
        .map_err(|e| NetlinkError::Netlink(format!("link delete failed for {name}: {e}")))
}

/// Set the link identified by `name` to the "up" administrative state.
///
/// Replaces the shell-out:
///   ip link set dev `<name>` up
///
/// # Errors
///
/// Returns [`NetlinkError::NotFound`] if no link with the given name
/// exists in the current netns. Returns [`NetlinkError::Netlink`] for
/// any other RTNETLINK failure (permission denied, etc.).
pub async fn set_link_up_by_name(name: &str) -> Result<(), NetlinkError> {
    use futures_util::stream::TryStreamExt;

    let (connection, handle, _) = rtnetlink::new_connection()
        .map_err(|e| NetlinkError::Netlink(format!("new_connection failed: {e}")))?;
    tokio::spawn(connection);

    let link = handle
        .link()
        .get()
        .match_name(name.to_string())
        .execute()
        .try_next()
        .await
        .map_err(|e| {
            let msg = e.to_string();
            if msg.contains("No such device") {
                NetlinkError::NotFound(name.to_string())
            } else {
                NetlinkError::Netlink(format!("link lookup failed for {name}: {msg}"))
            }
        })?
        .ok_or_else(|| NetlinkError::NotFound(name.to_string()))?;

    let index = link.header.index;

    handle
        .link()
        .set(index)
        .up()
        .execute()
        .await
        .map_err(|e| NetlinkError::Netlink(format!("link set up failed for {name}: {e}")))
}

/// Set the MTU on the link identified by `name`.
///
/// Replaces the shell-out:
///   ip link set dev `<name>` mtu `<mtu>`
///
/// The overlay TUN device is WireGuard-in-WireGuard over a mesh, so the
/// effective payload budget is smaller than the physical link MTU. An
/// un-tuned MTU silently blackholes oversized packets, so the caller
/// drives this explicitly from `OverlayConfig.mtu`.
///
/// # Errors
///
/// Returns [`NetlinkError::NotFound`] if no link with the given name
/// exists in the current netns. Returns [`NetlinkError::Netlink`] for
/// any other RTNETLINK failure (permission denied, etc.).
pub async fn set_link_mtu_by_name(name: &str, mtu: u32) -> Result<(), NetlinkError> {
    use futures_util::stream::TryStreamExt;

    let (connection, handle, _) = rtnetlink::new_connection()
        .map_err(|e| NetlinkError::Netlink(format!("new_connection failed: {e}")))?;
    tokio::spawn(connection);

    let link = handle
        .link()
        .get()
        .match_name(name.to_string())
        .execute()
        .try_next()
        .await
        .map_err(|e| {
            let msg = e.to_string();
            if msg.contains("No such device") {
                NetlinkError::NotFound(name.to_string())
            } else {
                NetlinkError::Netlink(format!("link lookup failed for {name}: {msg}"))
            }
        })?
        .ok_or_else(|| NetlinkError::NotFound(name.to_string()))?;

    let index = link.header.index;

    handle
        .link()
        .set(index)
        .mtu(mtu)
        .execute()
        .await
        .map_err(|e| NetlinkError::Netlink(format!("link set mtu failed for {name}: {e}")))
}

/// Add an IP address (v4 or v6) to the link identified by `name` in
/// the current network namespace.
///
/// Replaces the shell-out:
///   ip addr add `<addr>/<prefix_len>` dev `<name>`
///
/// `addr` may be v4 or v6. `prefix_len` is the CIDR prefix length
/// (24 for a `/24`, 64 for a `/64`, etc.).
///
/// # Errors
///
/// Returns [`NetlinkError::NotFound`] if the link is missing. Returns
/// [`NetlinkError::Netlink`] for any other rtnetlink failure. EEXIST
/// is NOT treated as success here — the caller (transport.rs) already
/// swallows duplicate-address errors at the call site to preserve the
/// original shell-out's idempotency.
pub async fn add_address_to_link(
    name: &str,
    addr: IpAddr,
    prefix_len: u8,
) -> Result<(), NetlinkError> {
    use futures_util::stream::TryStreamExt;

    let (connection, handle, _) = rtnetlink::new_connection()
        .map_err(|e| NetlinkError::Netlink(format!("new_connection failed: {e}")))?;
    tokio::spawn(connection);

    let link = handle
        .link()
        .get()
        .match_name(name.to_string())
        .execute()
        .try_next()
        .await
        .map_err(|e| {
            let msg = e.to_string();
            if msg.contains("No such device") {
                NetlinkError::NotFound(name.to_string())
            } else {
                NetlinkError::Netlink(format!("link lookup failed for {name}: {msg}"))
            }
        })?
        .ok_or_else(|| NetlinkError::NotFound(name.to_string()))?;

    let index = link.header.index;

    handle
        .address()
        .add(index, addr, prefix_len)
        .execute()
        .await
        .map_err(|e| {
            NetlinkError::Netlink(format!(
                "address add failed for {name} ({addr}/{prefix_len}): {e}"
            ))
        })
}

/// Add a route to a subnet via a device name, with link scope
/// (direct, no gateway).
///
/// Replaces the shell-outs:
///   ip route add `<dest>/<prefix_len>` dev `<dev_name>`
///   ip -6 route add `<dest>/<prefix_len>` dev `<dev_name>`
///
/// Uses plain `add` semantics (not replace) to preserve the original
/// shell-out behavior — the caller is expected to swallow EEXIST at
/// the call site for idempotency.
///
/// The route is installed with link scope (direct-via-dev, no
/// gateway) which is the correct form for a point-to-point TUN
/// interface where the overlay subnet is reachable directly.
///
/// # Errors
///
/// Returns [`NetlinkError::NotFound`] if `dev_name` does not exist in
/// the current netns. Returns [`NetlinkError::Netlink`] for any other
/// RTNETLINK failure, including EEXIST (caller swallows it).
pub async fn add_route_via_dev(
    dest: IpAddr,
    prefix_len: u8,
    dev_name: &str,
) -> Result<(), NetlinkError> {
    use futures_util::stream::TryStreamExt;
    use netlink_packet_route::route::RouteScope;

    let (connection, handle, _) = rtnetlink::new_connection()
        .map_err(|e| NetlinkError::Netlink(format!("new_connection failed: {e}")))?;
    tokio::spawn(connection);

    let link = handle
        .link()
        .get()
        .match_name(dev_name.to_string())
        .execute()
        .try_next()
        .await
        .map_err(|e| {
            let msg = e.to_string();
            if msg.contains("No such device") {
                NetlinkError::NotFound(dev_name.to_string())
            } else {
                NetlinkError::Netlink(format!("link lookup failed for {dev_name}: {msg}"))
            }
        })?
        .ok_or_else(|| NetlinkError::NotFound(dev_name.to_string()))?;

    let oif_idx = link.header.index;

    match dest {
        IpAddr::V4(d) => handle
            .route()
            .add()
            .v4()
            .destination_prefix(d, prefix_len)
            .output_interface(oif_idx)
            .scope(RouteScope::Link)
            .execute()
            .await
            .map_err(|e| {
                NetlinkError::Netlink(format!(
                    "route add v4 {d}/{prefix_len} dev {dev_name} failed: {e}"
                ))
            }),
        IpAddr::V6(d) => handle
            .route()
            .add()
            .v6()
            .destination_prefix(d, prefix_len)
            .output_interface(oif_idx)
            .scope(RouteScope::Link)
            .execute()
            .await
            .map_err(|e| {
                NetlinkError::Netlink(format!(
                    "route add v6 {d}/{prefix_len} dev {dev_name} failed: {e}"
                ))
            }),
    }
}

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

    /// `set_link_mtu_by_name` against a guaranteed-nonexistent interface
    /// must error cleanly (never panic). In a privileged netns the lookup
    /// resolves to `NotFound`; in a sandboxed / unprivileged environment
    /// the RTNETLINK connection or lookup may fail for other reasons —
    /// either way we accept the error and skip gracefully, mirroring the
    /// egress.rs graceful-skip pattern.
    #[tokio::test]
    async fn set_mtu_on_missing_link_errors_cleanly() {
        let name = "zl-no-such-iface-xyz";
        match set_link_mtu_by_name(name, 1420).await {
            Ok(()) => panic!("setting MTU on a nonexistent link should not succeed"),
            Err(NetlinkError::NotFound(n)) => assert_eq!(n, name),
            Err(e) => {
                // Unprivileged / sandboxed: RTNETLINK refused before the
                // lookup could distinguish ENODEV. Accept and skip.
                eprintln!("skipping: RTNETLINK unavailable in this environment: {e}");
            }
        }
    }
}