microsandbox-agentd 0.5.6

Guest init process and agent daemon for microsandbox microVMs.
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
//! Guest-side network configuration from `MSB_NET*` environment variables.
//!
//! Configures the guest network interface using ioctls and netlink, following
//! the parameters from host.

use std::net::{Ipv4Addr, Ipv6Addr};

use crate::config::NetConfig;
use crate::error::AgentdResult;

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

/// Set the guest hostname and provision `/etc/hosts`. Each argument is
/// optional; omitted pieces are skipped.
///
/// # Arguments
///
/// * `hostname` - Guest hostname. When set, calls `sethostname()` and writes
///   `/etc/hostname`.
/// * `host_alias` - DNS name the guest uses to reach the sandbox host
///   (typically `host.microsandbox.internal`). Written to `/etc/hosts`
///   alongside whichever gateway IPs are present.
/// * `gateway_ipv4` - Gateway IPv4 the alias points at.
/// * `gateway_ipv6` - Gateway IPv6 the alias points at.
///
/// # Errors
///
/// Returns [`AgentdError::Init`][crate::error::AgentdError::Init] when `/etc`
/// cannot be created, `/etc/hosts` or `/etc/hostname` cannot be written, or
/// `sethostname(2)` fails.
pub(crate) fn apply_hostname(
    hostname: Option<&str>,
    host_alias: Option<&str>,
    gateway_ipv4: Option<Ipv4Addr>,
    gateway_ipv6: Option<Ipv6Addr>,
) -> AgentdResult<()> {
    linux::write_hosts_file(hostname, host_alias, gateway_ipv4, gateway_ipv6)?;

    if let Some(name) = hostname {
        linux::set_hostname(name)?;
    }

    Ok(())
}

/// Apply the guest-side network configuration.
///
/// Always provisions loopback first so the guest has a working `lo` interface
/// even when the sandbox was booted with networking disabled. When `cfg.net`
/// is `None`, nothing further is configured.
///
/// # Arguments
///
/// * `cfg` - Parsed `MSB_NET*` specs bundled by
///   [`BootParams::network`][crate::config::BootParams::network]: interface
///   name/MAC/MTU plus optional IPv4 and IPv6 addressing.
///
/// # Errors
///
/// Returns [`AgentdError::Init`][crate::error::AgentdError::Init] when bringing
/// up `lo` fails, or any of the interface ioctls / netlink messages for the
/// main interface fail.
pub(crate) fn apply_network_config(cfg: NetConfig<'_>) -> AgentdResult<()> {
    linux::configure_loopback()?;

    let Some(net) = cfg.net else {
        return Ok(());
    };

    linux::configure_interface(net, cfg.ipv4, cfg.ipv6)
}

/// Render the `/etc/hosts` contents.
///
/// # Arguments
///
/// * `hostname` - Guest hostname; when `Some`, appended as an alias on the
///   `127.0.0.1` and `::1` lines.
/// * `host_alias` - Name like `host.microsandbox.internal`; when `Some` and a
///   gateway IP is set for the matching family, emits `<gw>\t<alias>` lines.
/// * `gateway_ipv4` - IPv4 the alias resolves to. The IPv4 alias line is
///   skipped when `None` (or when `host_alias` is `None`).
/// * `gateway_ipv6` - IPv6 the alias resolves to. The IPv6 alias line is
///   skipped when `None` (or when `host_alias` is `None`).
fn hosts_file_contents(
    hostname: Option<&str>,
    host_alias: Option<&str>,
    gateway_ipv4: Option<Ipv4Addr>,
    gateway_ipv6: Option<Ipv6Addr>,
) -> String {
    let mut s = String::new();

    // Localhost entries — always include hostname aliases when set.
    if let Some(name) = hostname {
        s.push_str(&format!("127.0.0.1\tlocalhost {name}\n"));
        s.push_str(&format!(
            "::1\tlocalhost ip6-localhost ip6-loopback {name}\n"
        ));
    } else {
        s.push_str("127.0.0.1\tlocalhost\n");
        s.push_str("::1\tlocalhost ip6-localhost ip6-loopback\n");
    }

    // `<host_alias>` → gateway IP mapping. Emits both address families
    // so v4-only and v6-only resolvers find the alias.
    if let Some(alias) = host_alias {
        if let Some(gw_v4) = gateway_ipv4 {
            s.push_str(&format!("{gw_v4}\t{alias}\n"));
        }
        if let Some(gw_v6) = gateway_ipv6 {
            s.push_str(&format!("{gw_v6}\t{alias}\n"));
        }
    }

    s.push_str("fe00::\tip6-localnet\n");
    s.push_str("ff00::\tip6-mcastprefix\n");
    s.push_str("ff02::1\tip6-allnodes\n");
    s.push_str("ff02::2\tip6-allrouters\n");

    s
}

//--------------------------------------------------------------------------------------------------
// Modules
//--------------------------------------------------------------------------------------------------

mod linux {
    use std::net::{Ipv4Addr, Ipv6Addr};
    use std::{fs, io, mem, ptr};

    use nix::unistd;

    use crate::config::{NetIpv4Spec, NetIpv6Spec, NetSpec};
    use crate::error::{AgentdError, AgentdResult};

    //----------------------------------------------------------------------------------------------
    // Types
    //----------------------------------------------------------------------------------------------

    // Alpine's musl-target libc crate does not expose the Linux netlink
    // ifaddrmsg/rtmsg definitions, so we define the kernel-layout structs we
    // need locally and continue using libc only for constants and syscalls.
    #[repr(C)]
    struct IfAddrMsg {
        ifa_family: u8,
        ifa_prefixlen: u8,
        ifa_flags: u8,
        ifa_scope: u8,
        ifa_index: u32,
    }

    #[repr(C)]
    struct RtMsg {
        rtm_family: u8,
        rtm_dst_len: u8,
        rtm_src_len: u8,
        rtm_tos: u8,
        rtm_table: u8,
        rtm_protocol: u8,
        rtm_scope: u8,
        rtm_type: u8,
        rtm_flags: u32,
    }

    /// Configures the guest network interface using ioctls and netlink.
    ///
    /// Operations (in order):
    /// 1. Set MAC address via `ioctl(SIOCSIFHWADDR)`
    /// 2. Set MTU via `ioctl(SIOCSIFMTU)`
    /// 3. Assign IPv4 address via netlink `RTM_NEWADDR`
    /// 4. Assign IPv6 address via netlink `RTM_NEWADDR`
    /// 5. Bring interface up via `ioctl(SIOCSIFFLAGS)` with `IFF_UP`
    /// 6. Add IPv4 default route via netlink `RTM_NEWROUTE`
    /// 7. Add IPv6 default route via netlink `RTM_NEWROUTE`
    /// 8. Write `/etc/resolv.conf`
    pub fn configure_interface(
        net: &NetSpec,
        ipv4: Option<&NetIpv4Spec>,
        ipv6: Option<&NetIpv6Spec>,
    ) -> AgentdResult<()> {
        let ifindex = get_ifindex(&net.iface)?;

        set_mac_address(&net.iface, &net.mac)?;
        set_mtu(&net.iface, net.mtu)?;

        if let Some(v4) = ipv4 {
            add_address_v4(ifindex, v4.address, v4.prefix_len)?;
        }
        if let Some(v6) = ipv6 {
            add_address_v6(ifindex, v6.address, v6.prefix_len)?;
        }

        bring_interface_up(&net.iface)?;

        if let Some(v4) = ipv4 {
            add_default_route_v4(v4.gateway)?;
        }
        if let Some(v6) = ipv6 {
            add_default_route_v6(v6.gateway)?;
        }

        write_resolv_conf(ipv4.and_then(|v| v.dns), ipv6.and_then(|v| v.dns))?;

        Ok(())
    }

    /// Brings up the loopback interface and makes sure localhost addresses exist.
    pub fn configure_loopback() -> AgentdResult<()> {
        let ifindex = get_ifindex("lo")?;

        bring_interface_up("lo")?;
        add_address_v4_if_missing(ifindex, Ipv4Addr::LOCALHOST, 8)?;
        add_address_v6_if_missing(ifindex, Ipv6Addr::LOCALHOST, 128)?;

        Ok(())
    }

    // ── ioctl helpers ──────────────────────────────────────────────────

    /// Gets the interface index for a given interface name.
    fn get_ifindex(ifname: &str) -> AgentdResult<u32> {
        unsafe {
            let mut ifr: libc::ifreq = mem::zeroed();
            copy_ifname(&mut ifr, ifname)?;

            let sock = socket_fd()?;
            if libc::ioctl(sock, libc::SIOCGIFINDEX as _, &mut ifr) < 0 {
                libc::close(sock);
                return Err(AgentdError::Init(format!(
                    "SIOCGIFINDEX failed for {ifname}: {}",
                    io::Error::last_os_error()
                )));
            }
            libc::close(sock);

            Ok(ifr.ifr_ifru.ifru_ifindex as u32)
        }
    }

    /// Sets the MAC address on an interface.
    fn set_mac_address(ifname: &str, mac: &[u8; 6]) -> AgentdResult<()> {
        unsafe {
            let mut ifr: libc::ifreq = mem::zeroed();
            copy_ifname(&mut ifr, ifname)?;

            ifr.ifr_ifru.ifru_hwaddr.sa_family = libc::ARPHRD_ETHER;
            ifr.ifr_ifru.ifru_hwaddr.sa_data[..6].copy_from_slice(&mac.map(|b| b as libc::c_char));

            let sock = socket_fd()?;
            if libc::ioctl(sock, libc::SIOCSIFHWADDR as _, &ifr) < 0 {
                libc::close(sock);
                return Err(AgentdError::Init(format!(
                    "SIOCSIFHWADDR failed for {ifname}: {}",
                    io::Error::last_os_error()
                )));
            }
            libc::close(sock);
        }
        Ok(())
    }

    /// Sets the MTU on an interface.
    fn set_mtu(ifname: &str, mtu: u16) -> AgentdResult<()> {
        unsafe {
            let mut ifr: libc::ifreq = mem::zeroed();
            copy_ifname(&mut ifr, ifname)?;
            ifr.ifr_ifru.ifru_mtu = mtu as libc::c_int;

            let sock = socket_fd()?;
            if libc::ioctl(sock, libc::SIOCSIFMTU as _, &ifr) < 0 {
                libc::close(sock);
                return Err(AgentdError::Init(format!(
                    "SIOCSIFMTU failed for {ifname}: {}",
                    io::Error::last_os_error()
                )));
            }
            libc::close(sock);
        }
        Ok(())
    }

    /// Brings an interface up.
    fn bring_interface_up(ifname: &str) -> AgentdResult<()> {
        unsafe {
            let mut ifr: libc::ifreq = mem::zeroed();
            copy_ifname(&mut ifr, ifname)?;

            let sock = socket_fd()?;

            // Get current flags.
            if libc::ioctl(sock, libc::SIOCGIFFLAGS as _, &mut ifr) < 0 {
                libc::close(sock);
                return Err(AgentdError::Init(format!(
                    "SIOCGIFFLAGS failed for {ifname}: {}",
                    io::Error::last_os_error()
                )));
            }

            // Set IFF_UP.
            ifr.ifr_ifru.ifru_flags |= libc::IFF_UP as libc::c_short;

            if libc::ioctl(sock, libc::SIOCSIFFLAGS as _, &ifr) < 0 {
                libc::close(sock);
                return Err(AgentdError::Init(format!(
                    "SIOCSIFFLAGS (UP) failed for {ifname}: {}",
                    io::Error::last_os_error()
                )));
            }
            libc::close(sock);
        }
        Ok(())
    }

    // ── netlink helpers ────────────────────────────────────────────────

    /// Adds an IPv4 address to an interface via netlink RTM_NEWADDR.
    fn add_address_v4(ifindex: u32, addr: Ipv4Addr, prefix_len: u8) -> AgentdResult<()> {
        let addr_bytes = addr.octets();
        netlink_newaddr(ifindex, libc::AF_INET as u8, prefix_len, &addr_bytes).map_err(|e| {
            AgentdError::Init(format!(
                "failed to add IPv4 address {addr}/{prefix_len}: {e}"
            ))
        })
    }

    /// Adds an IPv6 address to an interface via netlink RTM_NEWADDR.
    fn add_address_v6(ifindex: u32, addr: Ipv6Addr, prefix_len: u8) -> AgentdResult<()> {
        let addr_bytes = addr.octets();
        netlink_newaddr(ifindex, libc::AF_INET6 as u8, prefix_len, &addr_bytes).map_err(|e| {
            AgentdError::Init(format!(
                "failed to add IPv6 address {addr}/{prefix_len}: {e}"
            ))
        })
    }

    /// Adds an IPv4 address unless it already exists.
    fn add_address_v4_if_missing(ifindex: u32, addr: Ipv4Addr, prefix_len: u8) -> AgentdResult<()> {
        let addr_bytes = addr.octets();
        match netlink_newaddr(ifindex, libc::AF_INET as u8, prefix_len, &addr_bytes) {
            Ok(()) => Ok(()),
            Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()),
            Err(e) => Err(AgentdError::Init(format!(
                "failed to add IPv4 address {addr}/{prefix_len}: {e}"
            ))),
        }
    }

    /// Adds an IPv6 address unless it already exists.
    fn add_address_v6_if_missing(ifindex: u32, addr: Ipv6Addr, prefix_len: u8) -> AgentdResult<()> {
        let addr_bytes = addr.octets();
        match netlink_newaddr(ifindex, libc::AF_INET6 as u8, prefix_len, &addr_bytes) {
            Ok(()) => Ok(()),
            Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()),
            Err(e) => Err(AgentdError::Init(format!(
                "failed to add IPv6 address {addr}/{prefix_len}: {e}"
            ))),
        }
    }

    /// Adds an IPv4 default route via netlink RTM_NEWROUTE.
    fn add_default_route_v4(gateway: Ipv4Addr) -> AgentdResult<()> {
        let gw_bytes = gateway.octets();
        netlink_newroute(libc::AF_INET as u8, &gw_bytes).map_err(|e| {
            AgentdError::Init(format!(
                "failed to add IPv4 default route via {gateway}: {e}"
            ))
        })
    }

    /// Adds an IPv6 default route via netlink RTM_NEWROUTE.
    fn add_default_route_v6(gateway: Ipv6Addr) -> AgentdResult<()> {
        let gw_bytes = gateway.octets();
        netlink_newroute(libc::AF_INET6 as u8, &gw_bytes).map_err(|e| {
            AgentdError::Init(format!(
                "failed to add IPv6 default route via {gateway}: {e}"
            ))
        })
    }

    /// Sends a netlink RTM_NEWADDR message.
    ///
    /// For IPv4: emits both `IFA_ADDRESS` and `IFA_LOCAL` (kernel expects both).
    /// For IPv6: emits only `IFA_ADDRESS` (no `IFA_LOCAL` semantics for IPv6).
    fn netlink_newaddr(ifindex: u32, family: u8, prefix_len: u8, addr: &[u8]) -> io::Result<()> {
        let addr_len = addr.len();
        let is_ipv4 = family == libc::AF_INET as u8;

        // IPv4 needs two RTAs (IFA_ADDRESS + IFA_LOCAL), IPv6 needs one (IFA_ADDRESS).
        let num_rtas = if is_ipv4 { 2 } else { 1 };
        let rtas_len = rta_space(addr_len) * num_rtas;
        let msg_len = NLMSG_HDRLEN + IFADDRMSG_LEN + rtas_len;
        let mut buf = vec![0u8; nlmsg_align(msg_len)];

        // nlmsghdr
        let nlh = buf.as_mut_ptr().cast::<libc::nlmsghdr>();
        unsafe {
            (*nlh).nlmsg_len = msg_len as u32;
            (*nlh).nlmsg_type = libc::RTM_NEWADDR;
            (*nlh).nlmsg_flags =
                (libc::NLM_F_REQUEST | libc::NLM_F_ACK | libc::NLM_F_CREATE | libc::NLM_F_EXCL)
                    as u16;
            (*nlh).nlmsg_seq = 1;
        }

        // ifaddrmsg
        let ifa = unsafe { buf.as_mut_ptr().add(NLMSG_HDRLEN).cast::<IfAddrMsg>() };
        unsafe {
            (*ifa).ifa_family = family;
            (*ifa).ifa_prefixlen = prefix_len;
            (*ifa).ifa_flags = 0;
            (*ifa).ifa_index = ifindex;
            (*ifa).ifa_scope = libc::RT_SCOPE_UNIVERSE;
        }

        // RTA attributes
        let mut rta_offset = NLMSG_HDRLEN + IFADDRMSG_LEN;
        write_rta(&mut buf[rta_offset..], libc::IFA_ADDRESS, addr);
        rta_offset += rta_space(addr_len);

        if is_ipv4 {
            write_rta(&mut buf[rta_offset..], libc::IFA_LOCAL, addr);
        }

        netlink_send(&buf)
    }

    /// Sends a netlink RTM_NEWROUTE message for a default route.
    fn netlink_newroute(family: u8, gateway: &[u8]) -> io::Result<()> {
        let gw_len = gateway.len();

        // nlmsghdr + rtmsg + RTA_GATEWAY(rta_header + addr)
        let rta_len = rta_space(gw_len);
        let msg_len = NLMSG_HDRLEN + RTMSG_LEN + rta_len;
        let mut buf = vec![0u8; nlmsg_align(msg_len)];

        // nlmsghdr
        let nlh = buf.as_mut_ptr().cast::<libc::nlmsghdr>();
        unsafe {
            (*nlh).nlmsg_len = msg_len as u32;
            (*nlh).nlmsg_type = libc::RTM_NEWROUTE;
            (*nlh).nlmsg_flags =
                (libc::NLM_F_REQUEST | libc::NLM_F_ACK | libc::NLM_F_CREATE | libc::NLM_F_EXCL)
                    as u16;
            (*nlh).nlmsg_seq = 2;
        }

        // rtmsg
        let rtm = unsafe { buf.as_mut_ptr().add(NLMSG_HDRLEN).cast::<RtMsg>() };
        unsafe {
            (*rtm).rtm_family = family;
            (*rtm).rtm_dst_len = 0; // default route
            (*rtm).rtm_src_len = 0;
            (*rtm).rtm_tos = 0;
            (*rtm).rtm_table = libc::RT_TABLE_MAIN;
            (*rtm).rtm_protocol = libc::RTPROT_BOOT;
            (*rtm).rtm_scope = libc::RT_SCOPE_UNIVERSE;
            (*rtm).rtm_type = libc::RTN_UNICAST;
            (*rtm).rtm_flags = 0;
        }

        // RTA_GATEWAY attribute
        let rta_offset = NLMSG_HDRLEN + RTMSG_LEN;
        write_rta(&mut buf[rta_offset..], libc::RTA_GATEWAY, gateway);

        netlink_send(&buf)
    }

    /// Opens a netlink socket, sends a message, and waits for the ACK.
    fn netlink_send(msg: &[u8]) -> io::Result<()> {
        unsafe {
            let sock = libc::socket(libc::AF_NETLINK, libc::SOCK_DGRAM, libc::NETLINK_ROUTE);
            if sock < 0 {
                return Err(io::Error::last_os_error());
            }

            // Bind to kernel.
            let mut sa: libc::sockaddr_nl = mem::zeroed();
            sa.nl_family = libc::AF_NETLINK as u16;
            if libc::bind(
                sock,
                (&sa as *const libc::sockaddr_nl).cast(),
                mem::size_of::<libc::sockaddr_nl>() as u32,
            ) < 0
            {
                libc::close(sock);
                return Err(io::Error::last_os_error());
            }

            // Send.
            if libc::send(sock, msg.as_ptr().cast(), msg.len(), 0) < 0 {
                libc::close(sock);
                return Err(io::Error::last_os_error());
            }

            // Read ACK.
            let mut ack_buf = [0u8; 1024];
            let n = libc::recv(sock, ack_buf.as_mut_ptr().cast(), ack_buf.len(), 0);
            libc::close(sock);

            if n < 0 {
                return Err(io::Error::last_os_error());
            }

            // Check for error in the ACK (using from_ne_bytes to avoid
            // unaligned pointer dereference on the stack buffer).
            if (n as usize) >= NLMSG_HDRLEN + 4 {
                let nlh = ack_buf.as_ptr().cast::<libc::nlmsghdr>();
                if (*nlh).nlmsg_type == libc::NLMSG_ERROR as u16 {
                    let err = i32::from_ne_bytes(
                        ack_buf[NLMSG_HDRLEN..NLMSG_HDRLEN + 4].try_into().unwrap(),
                    );
                    if err < 0 {
                        return Err(io::Error::from_raw_os_error(-err));
                    }
                }
            }

            Ok(())
        }
    }

    // ── hostname + hosts + resolv.conf ──────────────────────────────────

    /// Sets the kernel hostname via `sethostname()` and writes `/etc/hostname`.
    pub fn set_hostname(name: &str) -> AgentdResult<()> {
        unistd::sethostname(name)
            .map_err(|e| AgentdError::Init(format!("sethostname({name}): {e}")))?;

        fs::create_dir_all("/etc")
            .map_err(|e| AgentdError::Init(format!("failed to create /etc: {e}")))?;
        fs::write("/etc/hostname", format!("{name}\n"))
            .map_err(|e| AgentdError::Init(format!("failed to write /etc/hostname: {e}")))?;

        Ok(())
    }

    /// Writes `/etc/hosts` with localhost aliases and an optional hostname entry.
    pub fn write_hosts_file(
        hostname: Option<&str>,
        host_alias: Option<&str>,
        gateway_ipv4: Option<Ipv4Addr>,
        gateway_ipv6: Option<Ipv6Addr>,
    ) -> AgentdResult<()> {
        fs::create_dir_all("/etc")
            .map_err(|e| AgentdError::Init(format!("failed to create /etc: {e}")))?;
        fs::write(
            "/etc/hosts",
            super::hosts_file_contents(hostname, host_alias, gateway_ipv4, gateway_ipv6),
        )
        .map_err(|e| AgentdError::Init(format!("failed to write /etc/hosts: {e}")))?;
        Ok(())
    }

    /// Writes `/etc/resolv.conf` with the configured DNS servers.
    fn write_resolv_conf(dns_v4: Option<Ipv4Addr>, dns_v6: Option<Ipv6Addr>) -> AgentdResult<()> {
        if dns_v4.is_none() && dns_v6.is_none() {
            return Ok(());
        }

        let mut content = String::new();
        if let Some(dns) = dns_v4 {
            content.push_str(&format!("nameserver {dns}\n"));
        }
        if let Some(dns) = dns_v6 {
            content.push_str(&format!("nameserver {dns}\n"));
        }

        fs::write("/etc/resolv.conf", &content)
            .map_err(|e| AgentdError::Init(format!("failed to write /etc/resolv.conf: {e}")))?;

        Ok(())
    }

    // ── low-level helpers ──────────────────────────────────────────────

    /// Creates a UDP socket for ioctl operations.
    fn socket_fd() -> AgentdResult<libc::c_int> {
        let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) };
        if fd < 0 {
            return Err(AgentdError::Init(format!(
                "failed to create socket: {}",
                io::Error::last_os_error()
            )));
        }
        Ok(fd)
    }

    /// Copies an interface name into an ifreq struct.
    fn copy_ifname(ifr: &mut libc::ifreq, ifname: &str) -> AgentdResult<()> {
        let bytes = ifname.as_bytes();
        if bytes.len() >= libc::IFNAMSIZ {
            return Err(AgentdError::Init(format!(
                "interface name too long: {ifname}"
            )));
        }
        unsafe {
            ptr::copy_nonoverlapping(
                bytes.as_ptr(),
                ifr.ifr_name.as_mut_ptr().cast(),
                bytes.len(),
            );
        }
        Ok(())
    }

    // ── netlink constants and helpers ──────────────────────────────────

    const NLMSG_HDRLEN: usize = 16;
    const IFADDRMSG_LEN: usize = 8;
    const RTMSG_LEN: usize = 12;
    const RTA_HDRLEN: usize = 4;

    // Compile-time assertions: catch layout mismatches across platforms.
    const _: () = assert!(mem::size_of::<libc::nlmsghdr>() == NLMSG_HDRLEN);
    const _: () = assert!(mem::size_of::<IfAddrMsg>() == IFADDRMSG_LEN);
    const _: () = assert!(mem::size_of::<RtMsg>() == RTMSG_LEN);

    fn nlmsg_align(len: usize) -> usize {
        (len + 3) & !3
    }

    fn rta_space(data_len: usize) -> usize {
        nlmsg_align(RTA_HDRLEN + data_len)
    }

    /// Writes an rtattr (type + data) into the buffer.
    fn write_rta(buf: &mut [u8], rta_type: u16, data: &[u8]) {
        let rta_len = (RTA_HDRLEN + data.len()) as u16;
        buf[0..2].copy_from_slice(&rta_len.to_ne_bytes());
        buf[2..4].copy_from_slice(&rta_type.to_ne_bytes());
        buf[RTA_HDRLEN..RTA_HDRLEN + data.len()].copy_from_slice(data);
    }
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

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

    #[test]
    fn test_hosts_file_without_hostname() {
        assert_eq!(
            hosts_file_contents(None, None, None, None),
            concat!(
                "127.0.0.1\tlocalhost\n",
                "::1\tlocalhost ip6-localhost ip6-loopback\n",
                "fe00::\tip6-localnet\n",
                "ff00::\tip6-mcastprefix\n",
                "ff02::1\tip6-allnodes\n",
                "ff02::2\tip6-allrouters\n",
            )
        );
    }

    #[test]
    fn test_hosts_file_with_hostname() {
        assert_eq!(
            hosts_file_contents(Some("worker-01"), None, None, None),
            concat!(
                "127.0.0.1\tlocalhost worker-01\n",
                "::1\tlocalhost ip6-localhost ip6-loopback worker-01\n",
                "fe00::\tip6-localnet\n",
                "ff00::\tip6-mcastprefix\n",
                "ff02::1\tip6-allnodes\n",
                "ff02::2\tip6-allrouters\n",
            )
        );
    }

    #[test]
    fn test_hosts_file_with_host_alias_both_families() {
        assert_eq!(
            hosts_file_contents(
                Some("worker-01"),
                Some("host.microsandbox.internal"),
                Some(Ipv4Addr::new(100, 96, 0, 1)),
                Some("fd42:6d73:62::1".parse().unwrap()),
            ),
            concat!(
                "127.0.0.1\tlocalhost worker-01\n",
                "::1\tlocalhost ip6-localhost ip6-loopback worker-01\n",
                "100.96.0.1\thost.microsandbox.internal\n",
                "fd42:6d73:62::1\thost.microsandbox.internal\n",
                "fe00::\tip6-localnet\n",
                "ff00::\tip6-mcastprefix\n",
                "ff02::1\tip6-allnodes\n",
                "ff02::2\tip6-allrouters\n",
            )
        );
    }

    #[test]
    fn test_hosts_file_with_host_alias_v4_only() {
        let out = hosts_file_contents(
            None,
            Some("host.microsandbox.internal"),
            Some(Ipv4Addr::new(100, 96, 0, 1)),
            None,
        );
        assert!(out.contains("100.96.0.1\thost.microsandbox.internal\n"));
        assert!(!out.contains("fd42"));
    }

    #[test]
    fn test_hosts_file_omits_alias_when_name_missing() {
        let out = hosts_file_contents(
            None,
            None,
            Some(Ipv4Addr::new(100, 96, 0, 1)),
            Some("fd42:6d73:62::1".parse().unwrap()),
        );
        assert!(!out.contains("host.microsandbox.internal"));
        assert!(!out.contains("100.96.0.1"));
        assert!(!out.contains("fd42"));
    }
}