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
use std::{
    collections::HashMap,
    net::{IpAddr, SocketAddr},
    str::FromStr,
};

use super::cerr;

pub fn interfaces() -> std::io::Result<HashMap<InterfaceName, InterfaceData>> {
    let mut elements = HashMap::default();

    for data in InterfaceIterator::new()? {
        let current: &mut InterfaceData = elements.entry(data.name).or_default();

        current.socket_addrs.extend(data.socket_addr);
        assert!(!(current.mac.is_some() && data.mac.is_some()));
        current.mac = current.mac.or(data.mac);
    }

    Ok(elements)
}

#[derive(Default, Debug)]
pub struct InterfaceData {
    socket_addrs: Vec<SocketAddr>,
    mac: Option<[u8; 6]>,
}

impl InterfaceData {
    pub fn has_ip_addr(&self, address: IpAddr) -> bool {
        self.socket_addrs
            .iter()
            .any(|socket_addr| socket_addr.ip() == address)
    }

    pub fn mac(&self) -> Option<[u8; 6]> {
        self.mac
    }
}

struct InterfaceIterator {
    base: *mut libc::ifaddrs,
    next: *mut libc::ifaddrs,
}

impl InterfaceIterator {
    pub fn new() -> std::io::Result<Self> {
        let mut addrs: *mut libc::ifaddrs = std::ptr::null_mut();

        unsafe {
            cerr(libc::getifaddrs(&mut addrs))?;

            assert!(!addrs.is_null());

            Ok(Self {
                base: addrs,
                next: addrs,
            })
        }
    }
}

impl Drop for InterfaceIterator {
    fn drop(&mut self) {
        unsafe { libc::freeifaddrs(self.base) };
    }
}

struct InterfaceDataInternal {
    name: InterfaceName,
    mac: Option<[u8; 6]>,
    socket_addr: Option<SocketAddr>,
}

impl Iterator for InterfaceIterator {
    type Item = InterfaceDataInternal;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        let ifaddr = unsafe { self.next.as_ref() }?;

        self.next = ifaddr.ifa_next;

        let ifname = unsafe { std::ffi::CStr::from_ptr(ifaddr.ifa_name) };
        let name = match std::str::from_utf8(ifname.to_bytes()) {
            Err(_) => unreachable!("interface names must be ascii"),
            Ok(name) => InterfaceName::from_str(name).expect("name from os"),
        };

        let family = unsafe { (*ifaddr.ifa_addr).sa_family };

        let mac = if family as i32 == libc::AF_PACKET {
            let sockaddr_ll: libc::sockaddr_ll =
                unsafe { std::ptr::read_unaligned(ifaddr.ifa_addr as *const _) };

            Some([
                sockaddr_ll.sll_addr[0],
                sockaddr_ll.sll_addr[1],
                sockaddr_ll.sll_addr[2],
                sockaddr_ll.sll_addr[3],
                sockaddr_ll.sll_addr[4],
                sockaddr_ll.sll_addr[5],
            ])
        } else {
            None
        };

        let socket_addr = unsafe { sockaddr_to_socket_addr(ifaddr.ifa_addr) };

        let data = InterfaceDataInternal {
            name,
            mac,
            socket_addr,
        };

        Some(data)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct InterfaceName {
    bytes: [u8; libc::IFNAMSIZ],
}

impl InterfaceName {
    #[cfg(test)]
    pub const LOOPBACK: Self = Self {
        bytes: *b"lo\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
    };

    #[cfg(test)]
    pub const INVALID: Self = Self {
        bytes: *b"123412341234123\0",
    };

    pub fn as_str(&self) -> &str {
        std::str::from_utf8(self.bytes.as_slice())
            .unwrap_or_default()
            .trim_end_matches('\0')
    }

    pub fn as_cstr(&self) -> &std::ffi::CStr {
        // TODO: in rust 1.69.0, use
        // std::ffi::CStr::from_bytes_until_nul(&self.bytes[..]).unwrap()

        // it is an invariant of InterfaceName that the bytes are null-terminated
        let first_null = self.bytes.iter().position(|b| *b == 0).unwrap();
        std::ffi::CStr::from_bytes_with_nul(&self.bytes[..=first_null]).unwrap()
    }

    pub fn to_ifr_name(self) -> [libc::c_char; libc::IFNAMSIZ] {
        let mut it = self.bytes.iter().copied();
        [0; libc::IFNAMSIZ].map(|_| it.next().unwrap_or(0) as libc::c_char)
    }

    pub fn from_socket_addr(local_addr: SocketAddr) -> std::io::Result<Option<Self>> {
        let matches_inferface = |interface: &InterfaceDataInternal| match interface.socket_addr {
            None => false,
            Some(address) => address.ip() == local_addr.ip(),
        };

        match InterfaceIterator::new()?.find(matches_inferface) {
            Some(interface) => Ok(Some(interface.name)),
            None => Ok(None),
        }
    }

    pub fn get_index(&self) -> Option<libc::c_uint> {
        // # SAFETY
        //
        // The pointer is valid and null-terminated
        match unsafe { libc::if_nametoindex(self.as_cstr().as_ptr()) } {
            0 => None,
            n => Some(n),
        }
    }
}

impl std::fmt::Debug for InterfaceName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("InterfaceName")
            .field(&self.as_str())
            .finish()
    }
}

impl std::fmt::Display for InterfaceName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.as_str().fmt(f)
    }
}

impl std::str::FromStr for InterfaceName {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut bytes = [0; libc::IFNAMSIZ];

        // >= so that we always retain a NUL byte at the end
        if s.len() >= bytes.len() {
            return Err(());
        }

        if s.is_empty() {
            // this causes problems down the line when giving the interface name to tokio
            return Err(());
        }

        let mut it = s.bytes();
        bytes = bytes.map(|_| it.next().unwrap_or_default());

        Ok(Self { bytes })
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for InterfaceName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        FromStr::from_str(&s).map_err(|_| serde::de::Error::custom("invalid interface name"))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinuxNetworkMode {
    Ipv4,
    Ipv6,
}

impl LinuxNetworkMode {
    pub fn unspecified_ip_addr(&self) -> IpAddr {
        match self {
            LinuxNetworkMode::Ipv4 => IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
            LinuxNetworkMode::Ipv6 => IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED),
        }
    }
}

/// Convert a libc::sockaddr to a rust std::net::SocketAddr
///
/// # Safety
///
/// According to the posix standard, `sockaddr` does not have a defined size:
/// the size depends on the value of the `ss_family` field. We assume this to be
/// correct.
///
/// In practice, types in rust/c need a statically-known stack size, so they
/// pick some value. In practice it can be (and is) larger than the
/// `sizeof<libc::sockaddr>` value.
unsafe fn sockaddr_to_socket_addr(sockaddr: *const libc::sockaddr) -> Option<SocketAddr> {
    // Most (but not all) of the fields in a socket addr are in network byte
    // ordering. As such, when doing conversions here, we should start from the
    // NATIVE byte representation, as this will actualy be the big-endian
    // representation of the underlying value regardless of platform.
    match unsafe { (*sockaddr).sa_family as libc::c_int } {
        libc::AF_INET => {
            // SAFETY: we cast from a libc::sockaddr (alignment 2) to a libc::sockaddr_in (alignment 4)
            // that means that the pointer is now potentially unaligned. We must used read_unaligned!
            let inaddr: libc::sockaddr_in =
                unsafe { std::ptr::read_unaligned(sockaddr as *const libc::sockaddr_in) };

            let socketaddr = std::net::SocketAddrV4::new(
                std::net::Ipv4Addr::from(inaddr.sin_addr.s_addr.to_ne_bytes()),
                u16::from_be_bytes(inaddr.sin_port.to_ne_bytes()),
            );

            Some(std::net::SocketAddr::V4(socketaddr))
        }
        libc::AF_INET6 => {
            // SAFETY: we cast from a libc::sockaddr (alignment 2) to a libc::sockaddr_in6 (alignment 4)
            // that means that the pointer is now potentially unaligned. We must used read_unaligned!
            let inaddr: libc::sockaddr_in6 =
                unsafe { std::ptr::read_unaligned(sockaddr as *const libc::sockaddr_in6) };

            let sin_addr = inaddr.sin6_addr.s6_addr;
            let segment_bytes: [u8; 16] =
                unsafe { std::ptr::read_unaligned(&sin_addr as *const _ as *const _) };

            let socketaddr = std::net::SocketAddrV6::new(
                std::net::Ipv6Addr::from(segment_bytes),
                u16::from_be_bytes(inaddr.sin6_port.to_ne_bytes()),
                inaddr.sin6_flowinfo, /* NOTE: Despite network byte order, no conversion is needed (see https://github.com/rust-lang/rust/issues/101605) */
                inaddr.sin6_scope_id,
            );

            Some(std::net::SocketAddr::V6(socketaddr))
        }
        _ => None,
    }
}

pub fn sockaddr_storage_to_socket_addr(
    sockaddr_storage: &libc::sockaddr_storage,
) -> Option<SocketAddr> {
    // Safety:
    //
    // sockaddr_storage always has enough space to store either a sockaddr_in or
    // sockaddr_in6
    unsafe { sockaddr_to_socket_addr(sockaddr_storage as *const _ as *const libc::sockaddr) }
}

#[cfg(test)]
mod tests {
    use std::net::Ipv4Addr;

    use super::*;

    #[test]
    fn interface_name_from_string() {
        assert!(InterfaceName::from_str("").is_err());
        assert!(InterfaceName::from_str("a string that is too long").is_err());

        let input = "enp0s31f6";
        assert_eq!(InterfaceName::from_str(input).unwrap().as_str(), input);

        let ifr_name = (*b"enp0s31f6\0\0\0\0\0\0\0").map(|b| b as libc::c_char);
        assert_eq!(
            InterfaceName::from_str(input).unwrap().to_ifr_name(),
            ifr_name
        );
    }

    #[test]
    fn test_mac_address_iterator() {
        let v: Vec<_> = InterfaceIterator::new()
            .unwrap()
            .filter_map(|d| d.mac)
            .collect();

        assert!(!v.is_empty());
    }

    #[test]
    fn test_interface_name_iterator() {
        let v: Vec<_> = InterfaceIterator::new().unwrap().map(|d| d.name).collect();

        assert!(v.contains(&InterfaceName::LOOPBACK));
    }

    #[test]
    fn test_socket_addr_iterator() {
        let v: Vec<_> = InterfaceIterator::new()
            .unwrap()
            .filter_map(|d| d.socket_addr)
            .collect();

        let localhost_0 = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));

        assert!(v.contains(&localhost_0));
    }

    #[test]
    fn interface_index_ipv4() {
        assert!(InterfaceName::LOOPBACK.get_index().is_some());
    }

    #[test]
    fn interface_index_ipv6() {
        assert!(InterfaceName::LOOPBACK.get_index().is_some());
    }

    #[test]
    fn interface_index_invalid() {
        assert!(InterfaceName::INVALID.get_index().is_none());
    }
}