veilid-tools 0.5.6

A collection of baseline tools for Rust development use by Veilid and Veilid-enabled Rust applications
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
#![cfg(any(target_os = "macos", target_os = "ios"))]
#![allow(non_camel_case_types)]
use super::*;

use libc::{
    close, freeifaddrs, getifaddrs, ifaddrs, ioctl, pid_t, sockaddr, sockaddr_dl, sockaddr_in6,
    socket, sysctl, time_t, AF_INET6, AF_LINK, CTL_NET, IFF_BROADCAST, IFF_LOOPBACK,
    IFF_POINTOPOINT, IFF_RUNNING, IFNAMSIZ, NET_RT_FLAGS, PF_ROUTE, RTAX_DST, RTAX_GATEWAY,
    RTAX_MAX, RTA_DST, RTA_GATEWAY, RTF_GATEWAY, SOCK_DGRAM,
};
use sockaddr_tools::SockAddr;
use std::ffi::CStr;
use std::io;
use std::os::raw::{c_int, c_uchar, c_ulong, c_ushort, c_void};

// xnu bsd/netinet6/in6_var.h IN6_IFF_* flags and address-info ioctls
/// Get IPv6 address flags
const SIOCGIFAFLAG_IN6: c_ulong = 0xC1206949;
/// Get IPv6 address lifetime (preferred/valid/expire)
const SIOCGIFALIFETIME_IN6: c_ulong = 0xC1206951;
/// Address is undergoing duplicate-address detection
const IN6_IFF_TENTATIVE: c_ushort = 0x0002;
/// Address has been detected as a duplicate
const IN6_IFF_DUPLICATED: c_ushort = 0x0004;
/// Network interface link is detached
const IN6_IFF_DETACHED: c_ushort = 0x0008;
/// Address has reached the end of its preferred lifetime (still valid but discouraged)
const IN6_IFF_DEPRECATED: c_ushort = 0x0010;
/// Address was assigned via IPv6 stateless auto-configuration (SLAAC)
const IN6_IFF_AUTOCONF: c_ushort = 0x0040;
/// RFC 4941 privacy / temporary address (rotates)
const IN6_IFF_TEMPORARY: c_ushort = 0x0080;
/// Address was assigned dynamically (e.g. via DHCPv6)
const IN6_IFF_DYNAMIC: c_ushort = 0x0100;
/// RFC 7217 stable secured SLAAC; currently unused — kept for documentation
#[allow(dead_code)]
const IN6_IFF_SECURED: c_ushort = 0x0400;
/// CLAT46 synthesized address for RFC 6877 IPv4-as-a-Service over IPv6 (cellular)
const IN6_IFF_CLAT46: c_ushort = 0x1000;

macro_rules! set_name {
    ($name_field:expr, $name_str:expr) => {{
        let name_c = &::std::ffi::CString::new($name_str.to_owned()).map_err(|_| {
            ::std::io::Error::new(
                ::std::io::ErrorKind::InvalidInput,
                "malformed interface name",
            )
        })?;
        let name_slice = name_c.as_bytes_with_nul();
        if name_slice.len() > IFNAMSIZ {
            return Err(io::Error::new(::std::io::ErrorKind::InvalidInput, ""));
        }
        $name_field[..name_slice.len()].clone_from_slice(name_slice);

        Ok(())
    }};
}

macro_rules! round_up {
    ($a:expr) => {
        if $a > 0 {
            1 + (($a - 1) | 3)
        } else {
            4
        }
    };
}

#[derive(Clone, Copy, Debug)]
#[repr(C)]
struct rt_msghdr {
    rtm_msglen: c_ushort,
    rtm_version: c_uchar,
    rtm_type: c_uchar,
    rtm_index: c_ushort,
    rtm_flags: c_int,
    rtm_addrs: c_int,
    rtm_pid: pid_t,
    rtm_seq: c_int,
    rtm_errno: c_int,
    rtm_use: c_int,
    rtm_inits: u32,
    rtm_rmx: rt_metrics,
}

#[derive(Clone, Copy, Debug)]
#[repr(C)]
struct rt_metrics {
    rmx_locks: u32,
    rmx_mtu: u32,
    rmx_hopcount: u32,
    rmx_expire: i32,
    rmx_recvpipe: u32,
    rmx_sendpipe: u32,
    rmx_ssthresh: u32,
    rmx_rtt: u32,
    rmx_rttvar: u32,
    rmx_pksent: u32,
    rmx_state: u32,
    rmx_filler: [u32; 3],
}

#[derive(Clone, Copy, Debug)]
#[repr(C)]
struct in6_addrlifetime {
    ia6t_expire: time_t,
    ia6t_preferred: time_t,
    ia6t_vltime: u32,
    ia6t_pltime: u32,
}

#[derive(Clone, Copy, Debug)]
#[repr(C)]
struct in6_ifstat {
    ifs6_in_receive: u64,
    ifs6_in_hdrerr: u64,
    ifs6_in_toobig: u64,
    ifs6_in_noroute: u64,
    ifs6_in_addrerr: u64,
    ifs6_in_protounknown: u64,
    ifs6_in_truncated: u64,
    ifs6_in_discard: u64,
    ifs6_in_deliver: u64,
    ifs6_out_forward: u64,
    ifs6_out_request: u64,
    ifs6_out_discard: u64,
    ifs6_out_fragok: u64,
    ifs6_out_fragfail: u64,
    ifs6_out_fragcreat: u64,
    ifs6_reass_reqd: u64,
    ifs6_reass_ok: u64,
    ifs6_atmfrag_rcvd: u64,
    ifs6_reass_fail: u64,
    ifs6_in_mcast: u64,
    ifs6_out_mcast: u64,
    ifs6_cantfoward_icmp6: u64,
    ifs6_addr_expiry_cnt: u64,
    ifs6_pfx_expiry_cnt: u64,
    ifs6_defrtr_expiry_cnt: u64,
}

#[derive(Clone, Copy, Debug)]
#[repr(C)]
struct icmp6_ifstat {
    ifs6_in_msg: u64,
    ifs6_in_error: u64,
    ifs6_in_dstunreach: u64,
    ifs6_in_adminprohib: u64,
    ifs6_in_timeexceed: u64,
    ifs6_in_paramprob: u64,
    ifs6_in_pkttoobig: u64,
    ifs6_in_echo: u64,
    ifs6_in_echoreply: u64,
    ifs6_in_routersolicit: u64,
    ifs6_in_routeradvert: u64,
    ifs6_in_neighborsolicit: u64,
    ifs6_in_neighboradvert: u64,
    ifs6_in_redirect: u64,
    ifs6_in_mldquery: u64,
    ifs6_in_mldreport: u64,
    ifs6_in_mlddone: u64,
    ifs6_out_msg: u64,
    ifs6_out_error: u64,
    ifs6_out_dstunreach: u64,
    ifs6_out_adminprohib: u64,
    ifs6_out_timeexceed: u64,
    ifs6_out_paramprob: u64,
    ifs6_out_pkttoobig: u64,
    ifs6_out_echo: u64,
    ifs6_out_echoreply: u64,
    ifs6_out_routersolicit: u64,
    ifs6_out_routeradvert: u64,
    ifs6_out_neighborsolicit: u64,
    ifs6_out_neighboradvert: u64,
    ifs6_out_redirect: u64,
    ifs6_out_mldquery: u64,
    ifs6_out_mldreport: u64,
    ifs6_out_mlddone: u64,
}

#[derive(Clone, Copy)]
#[repr(C)]
union IfrIfru {
    ifru_addr: sockaddr_in6,
    ifru_dstaddr: sockaddr_in6,
    ifru_flags: c_int,
    ifru_flags6: c_int,
    ifru_metric: c_int,
    ifru_intval: c_int,
    ifru_data: *mut c_uchar, // caddr_t
    ifru_lifetime: in6_addrlifetime,
    ifru_stat: in6_ifstat,
    ifru_icmp6stat: icmp6_ifstat,
    ifru_scope_id: [u32; 16],
}

#[derive(Clone)]
#[repr(C)]
struct in6_ifreq {
    ifr_name: [c_uchar; IFNAMSIZ],
    ifr_ifru: IfrIfru,
}

impl in6_ifreq {
    pub fn from_name(name: &str) -> io::Result<Self> {
        let mut req: in6_ifreq = unsafe { mem::zeroed() };
        req.set_name(name)?;
        Ok(req)
    }
    pub fn set_name(&mut self, name: &str) -> io::Result<()> {
        set_name!(self.ifr_name, name)
    }
    pub fn set_addr(&mut self, addr: sockaddr_in6) {
        self.ifr_ifru.ifru_addr = addr;
    }
    pub fn get_flags6(&self) -> c_ushort {
        unsafe { self.ifr_ifru.ifru_flags6 as c_ushort }
    }
    pub fn get_ia6t_expire(&self) -> time_t {
        unsafe { self.ifr_ifru.ifru_lifetime.ia6t_expire as time_t }
    }
}

pub fn do_broadcast(ifaddr: &ifaddrs) -> Option<IpAddr> {
    sockaddr_tools::to_ipaddr(ifaddr.ifa_dstaddr)
}

///////////////////////////////////////////////////

pub struct IfAddrs {
    inner: *mut ifaddrs,
}

impl IfAddrs {
    pub fn new() -> io::Result<Self> {
        let mut ifaddrs = mem::MaybeUninit::uninit();

        unsafe {
            if -1 == getifaddrs(ifaddrs.as_mut_ptr()) {
                return Err(io::Error::last_os_error());
            }
            Ok(Self {
                inner: ifaddrs.assume_init(),
            })
        }
    }

    pub fn iter(&self) -> IfAddrsIterator {
        IfAddrsIterator { next: self.inner }
    }
}

impl Drop for IfAddrs {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        unsafe {
            freeifaddrs(self.inner);
        }
    }
}

pub struct IfAddrsIterator {
    next: *mut ifaddrs,
}

impl Iterator for IfAddrsIterator {
    type Item = ifaddrs;

    #[allow(unsafe_code)]
    fn next(&mut self) -> Option<Self::Item> {
        if self.next.is_null() {
            return None;
        };

        Some(unsafe {
            let result = *self.next;
            self.next = (*self.next).ifa_next;

            result
        })
    }
}

///////////////////////////////////////////////////

pub struct PlatformSupportApple {
    gateways: BTreeMap<u32, BTreeSet<IpAddr>>,
}

impl PlatformSupportApple {
    pub fn new() -> Self {
        PlatformSupportApple {
            gateways: BTreeMap::new(),
        }
    }

    fn refresh_default_route_interfaces(&mut self) {
        loop {
            let mut mib = [CTL_NET, PF_ROUTE, 0, 0, NET_RT_FLAGS, RTF_GATEWAY];
            let mut sa_tab: [*const sockaddr; RTAX_MAX as usize] =
                [std::ptr::null(); RTAX_MAX as usize];
            let mut rt_buf_len = 0usize;

            // Get memory size for mib result
            if unsafe {
                sysctl(
                    mib.as_mut_ptr(),
                    mib.len() as u32,
                    std::ptr::null_mut(),
                    &mut rt_buf_len as *mut usize,
                    std::ptr::null_mut(),
                    0,
                )
            } < 0
            {
                error!("Unable to get memory size for routing table");
                return;
            }

            // Allocate a buffer
            let mut rt_buf = vec![0u8; rt_buf_len];

            // Get mib result
            if unsafe {
                sysctl(
                    mib.as_mut_ptr(),
                    mib.len() as u32,
                    rt_buf.as_mut_ptr() as *mut c_void,
                    &mut rt_buf_len as *mut usize,
                    std::ptr::null_mut(),
                    0,
                )
            } < 0
            {
                debug!("routing table changed length between interface checks, trying again");
                continue;
            }

            // Clear old interfaces
            self.gateways.clear();

            // Process each routing message
            let mut mib_ptr = rt_buf.as_ptr();
            let mib_end = unsafe { mib_ptr.add(rt_buf_len) };
            while mib_ptr < mib_end {
                let rt = mib_ptr as *const rt_msghdr;
                let mut sa = unsafe { rt.add(1) } as *const sockaddr;
                let rtm_addrs = unsafe { (*rt).rtm_addrs };
                let intf_index = unsafe { (*rt).rtm_index } as u32;

                // Fill in sockaddr table
                (0..(RTAX_MAX as usize)).for_each(|i| {
                    if rtm_addrs & (1 << i) != 0 {
                        sa_tab[i] = sa;
                        sa = unsafe {
                            let sa_len = (*sa).sa_len;
                            sa = ((sa as *const u8).add(round_up!(sa_len as usize)))
                                as *const sockaddr;
                            sa
                        };
                    }
                });

                // Look for gateways
                if rtm_addrs & (RTA_DST | RTA_GATEWAY) == (RTA_DST | RTA_GATEWAY) {
                    // Only interested in AF_INET and AF_INET6 address families
                    // SockAddr::new() takes care of this for us
                    let saddr_dst = match SockAddr::new(sa_tab[RTAX_DST as usize]) {
                        Some(a) => a,
                        None => continue,
                    };

                    let saddr_gateway = match SockAddr::new(sa_tab[RTAX_GATEWAY as usize]) {
                        Some(a) => a,
                        None => continue,
                    };

                    // Look for default gateways
                    let dst_ipaddr = match saddr_dst.as_ipaddr() {
                        Some(a) => a,
                        None => continue,
                    };
                    let gateway_ipaddr = match saddr_gateway.as_ipaddr() {
                        Some(a) => a,
                        None => continue,
                    };

                    if dst_ipaddr.is_unspecified() {
                        self.gateways
                            .entry(intf_index)
                            .or_default()
                            .insert(gateway_ipaddr);
                    }
                }

                mib_ptr = unsafe { mib_ptr.add((*rt).rtm_msglen.into()) };
            }

            break;
        }
    }

    fn get_interface_flags(&self, flags: c_int) -> InterfaceFlags {
        InterfaceFlags {
            is_loopback: (flags & IFF_LOOPBACK) != 0,
            is_running: (flags & IFF_RUNNING) != 0,
            is_point_to_point: (flags & IFF_POINTOPOINT) != 0,
            // macOS/iOS surface CLAT at the address level via IN6_IFF_CLAT46, not as an interface flag
            is_clat: false,
        }
    }

    fn get_address_flags(ifname: &str, addr: sockaddr_in6) -> io::Result<AddressFlags> {
        let sock = unsafe { socket(AF_INET6, SOCK_DGRAM, 0) };
        if sock < 0 {
            return Err(io::Error::last_os_error());
        }

        let mut req = in6_ifreq::from_name(ifname).unwrap_or_log();
        req.set_addr(addr);

        let res = unsafe { ioctl(sock, SIOCGIFAFLAG_IN6, &mut req) };
        if res < 0 {
            unsafe { close(sock) };
            return Err(io::Error::last_os_error());
        }
        let flags = req.get_flags6();

        let mut req = in6_ifreq::from_name(ifname).unwrap_or_log();
        req.set_addr(addr);

        let res = unsafe { ioctl(sock, SIOCGIFALIFETIME_IN6, &mut req) };
        unsafe { close(sock) };
        if res < 0 {
            return Err(io::Error::last_os_error());
        }
        let expire = req.get_ia6t_expire();

        // RFC 4941 privacy address only; RFC 7217 secured SLAAC also has a non-zero
        // RA lifetime but is stable, so it must not be conflated
        let is_temporary = (flags & IN6_IFF_TEMPORARY) != 0;
        let is_dynamic = (flags & (IN6_IFF_DYNAMIC | IN6_IFF_AUTOCONF)) != 0;
        let is_preferred = (flags
            & (IN6_IFF_TENTATIVE | IN6_IFF_DUPLICATED | IN6_IFF_DETACHED | IN6_IFF_DEPRECATED))
            == 0;
        let is_clat = (flags & IN6_IFF_CLAT46) != 0;
        let expiration_secs = if expire == 0 {
            None
        } else {
            Some(expire as u64)
        };

        Ok(AddressFlags {
            is_temporary,
            is_dynamic,
            is_preferred,
            is_clat,
            expiration_secs,
        })
    }

    #[expect(clippy::unused_async)]
    pub async fn get_interfaces(
        &mut self,
        interfaces: &mut BTreeMap<String, NetworkInterface>,
    ) -> io::Result<()> {
        self.refresh_default_route_interfaces();

        // Ask for all the addresses we have
        let ifaddrs = IfAddrs::new()?;

        // Determine all the name to index mappings
        let mut name_to_index = BTreeMap::<String, u32>::new();
        for ifaddr in ifaddrs.iter() {
            if !ifaddr.ifa_addr.is_null()
                && unsafe { (*ifaddr.ifa_addr).sa_family } == AF_LINK as u8
            {
                // Get the interface name
                let ifname = unsafe { CStr::from_ptr(ifaddr.ifa_name) }
                    .to_string_lossy()
                    .into_owned();
                let sdl = unsafe { *(ifaddr.ifa_addr as *const sockaddr_dl) };
                name_to_index.insert(ifname, sdl.sdl_index as u32);
            }
        }

        // Iterate all interface addresses, pair them with their gateways and add them to the interfaces map
        for ifaddr in ifaddrs.iter() {
            // Ensure we're getting an ip address here otherwise we'll skip it
            let Some(ip_addr) = sockaddr_tools::to_ipaddr(ifaddr.ifa_addr) else {
                continue;
            };

            // Get the interface name
            let ifname = unsafe { CStr::from_ptr(ifaddr.ifa_name) }
                .to_string_lossy()
                .into_owned();

            // Get the interface index
            let Some(ifindex) = name_to_index.get(&ifname).copied() else {
                continue;
            };

            // Map the name to a NetworkInterface
            if !interfaces.contains_key(&ifname) {
                // If we have no NetworkInterface yet, make one
                let flags = self.get_interface_flags(ifaddr.ifa_flags as c_int);
                let mut net_intf = NetworkInterface::new(ifname.clone(), flags);
                // Add gateways if we have them
                if let Some(gateways) = self.gateways.get(&ifindex) {
                    for gateway in gateways {
                        net_intf.add_gateway(*gateway);
                    }
                }
                interfaces.insert(ifname.clone(), net_intf);
            }
            let intf = interfaces.get_mut(&ifname).unwrap_or_log();

            let mut address_flags = AddressFlags::default();

            let intf_addr = match ip_addr {
                IpAddr::V4(ipv4_addr) => {
                    let netmask = match sockaddr_tools::to_ipaddr(ifaddr.ifa_netmask) {
                        Some(IpAddr::V4(netmask)) => netmask,
                        _ => Ipv4Addr::new(0, 0, 0, 0),
                    };
                    let broadcast = if (ifaddr.ifa_flags & (IFF_BROADCAST as u32)) != 0 {
                        match do_broadcast(&ifaddr) {
                            Some(IpAddr::V4(broadcast)) => Some(broadcast),
                            _ => None,
                        }
                    } else {
                        None
                    };

                    IfAddr::V4(Ifv4Addr {
                        ip: ipv4_addr,
                        netmask,
                        broadcast,
                    })
                }
                IpAddr::V6(ipv6_addr) => {
                    let netmask = match sockaddr_tools::to_ipaddr(ifaddr.ifa_netmask) {
                        Some(IpAddr::V6(netmask)) => netmask,
                        _ => Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0),
                    };

                    // Get address flags for ipv6
                    address_flags = match Self::get_address_flags(
                        &ifname,
                        SockAddr::new(ifaddr.ifa_addr).unwrap_or_log().sa_in6(),
                    ) {
                        Ok(v) => v,
                        Err(e) => {
                            debug!(
                                "failed to get address flags for ifname={}, ifaddr={:?} : {}",
                                ifname, ifaddr.ifa_addr, e
                            );
                            continue;
                        }
                    };

                    IfAddr::V6(Ifv6Addr {
                        ip: ipv6_addr,
                        netmask,
                        broadcast: None,
                    })
                }
            };

            // Add to the list
            intf.add_address(InterfaceAddress::new(intf_addr, address_flags));
        }

        Ok(())
    }
}