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
use crate::IpType;
use crate::{Error, Result};
use libc;
#[cfg(windows)]
use log::error;
use log::{debug, trace};
use std::ffi::CStr;
use std::mem;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::ptr;
#[cfg(unix)]
use std::str::FromStr;
#[cfg(windows)]
use winapi::{
    shared::{
        minwindef::{DWORD, LPVOID, ULONG},
        winerror, ws2def,
        ws2def::{SOCKADDR, SOCKADDR_IN},
        ws2ipdef::SOCKADDR_IN6,
    },
    um::{
        heapapi::{GetProcessHeap, HeapAlloc, HeapFree},
        iphlpapi::GetAdaptersAddresses,
        iptypes::{
            GAA_FLAG_INCLUDE_PREFIX, GAA_FLAG_SKIP_DNS_SERVER, GAA_FLAG_SKIP_MULTICAST,
            IP_ADAPTER_ADDRESSES, IP_ADAPTER_ANYCAST_ADDRESS, IP_ADAPTER_UNICAST_ADDRESS,
        },
    },
};
#[cfg(windows)]
const INITIAL_ALLOC_SIZE: ULONG = 15000;
#[cfg(windows)]
const MAX_TRIES: usize = 5;

/// Fail with errno
macro_rules! fail_os_err {
    () => {
        Err(Error::IoError(std::io::Error::last_os_error()))
    };
}

/// Get an address of an interface
#[cfg(unix)]
unsafe fn get_addr_for_ifa_unix(addr: libc::ifaddrs, ip_type: Option<IpType>) -> Result<IpAddr> {
    let sockaddr = addr.ifa_addr;
    assert!(!sockaddr.is_null());
    let family = libc::c_int::from((*sockaddr).sa_family);
    // Has a IP family filter
    if let Some(ip_type) = ip_type {
        if (ip_type == IpType::Ipv4 && family != libc::AF_INET)
            || (ip_type == IpType::Ipv6 && family != libc::AF_INET6)
        {
            trace!("Short-circuiting NoAddress: addr family does not match requested type");
            return Err(Error::NoAddress);
        }
    } else if family != libc::AF_INET && family != libc::AF_INET6 {
        trace!(
            "Short-circuiting NoAddress: family type {:?} not address",
            family
        );
        return Err(Error::NoAddress);
    }
    // Length for `getnameinfo`
    let socklen = match family {
        libc::AF_INET => mem::size_of::<libc::sockaddr_in>(),
        libc::AF_INET6 => mem::size_of::<libc::sockaddr_in6>(),
        _ => unreachable!(),
    } as libc::socklen_t;
    // Allocating on stack, so only when necessary
    {
        const MAXHOST: usize = libc::NI_MAXHOST as usize;
        let mut host: [libc::c_char; MAXHOST] = [0; MAXHOST];
        if libc::getnameinfo(
            sockaddr,
            socklen,
            host.as_mut_ptr(),
            libc::NI_MAXHOST,
            ptr::null_mut(),
            0,
            libc::NI_NUMERICHOST,
        ) == 0
        {
            let address = CStr::from_ptr(host.as_ptr()).to_bytes();
            let address = std::str::from_utf8_unchecked(address);
            Ok(match family {
                libc::AF_INET => IpAddr::V4(Ipv4Addr::from_str(address)?),
                libc::AF_INET6 => IpAddr::V6(Ipv6Addr::from_str(address)?),
                _ => unreachable!(),
            })
        } else {
            fail_os_err!()
        }
    }
}

/// Get all assigned ip addresses of the specified type on the specified interface
/// Both parameters can be None, in which case that filter is not applied.
#[cfg(unix)]
pub fn get_iface_addrs(ip_type: Option<IpType>, iface_name: Option<&str>) -> Result<Vec<IpAddr>> {
    // Hold all found addresses
    let mut result: Vec<IpAddr> = Vec::new();
    unsafe {
        // Save for freeifaddrs()
        let mut save_addrs: *mut libc::ifaddrs = mem::zeroed();
        if libc::getifaddrs(&mut save_addrs) != 0 {
            return fail_os_err!();
        }
        let mut addrs = save_addrs;
        // Walk through the linked list
        while !addrs.is_null() {
            let addr = *addrs;
            // Interface name
            let ifa_name = addr.ifa_name as *const libc::c_char;
            let ifa_name = CStr::from_ptr(ifa_name).to_bytes();
            let ifa_name = std::str::from_utf8_unchecked(ifa_name);
            trace!("Got interface {:?}", ifa_name);
            // Filter iface name
            let address = iface_name.map_or_else(
                || get_addr_for_ifa_unix(addr, ip_type),
                |expected_ifa_name| {
                    if ifa_name == expected_ifa_name {
                        get_addr_for_ifa_unix(addr, ip_type)
                    } else {
                        Err(Error::NoAddress)
                    }
                },
            );
            if let Ok(address) = address {
                trace!(
                    "Found good addresses of type {:?} for interface {:?}: {:?}",
                    ip_type,
                    iface_name,
                    address
                );
                result.push(address);
            }
            addrs = addr.ifa_next;
        }
        libc::freeifaddrs(save_addrs);
    }
    if result.is_empty() {
        debug!("No address becase none of the interfaces has a matching one");
        Err(Error::NoAddress)
    } else {
        Ok(result)
    }
}

/// Convert pointer to a `SOCKADDR` to Rust IpAddr
/// `raw_addr` must not be NULL
#[cfg(windows)]
unsafe fn sockaddr_to_ipaddr(raw_addr: *mut SOCKADDR) -> IpAddr {
    if (*raw_addr).sa_family as i32 == ws2def::AF_INET {
        let saddr_in = raw_addr as *mut SOCKADDR_IN;
        let saddr_in_addr = (*saddr_in).sin_addr.S_un.S_addr();
        IpAddr::V4(Ipv4Addr::from(*saddr_in_addr))
    } else {
        let saddr_in = raw_addr as *mut SOCKADDR_IN6;
        let saddr_in_addr = (*saddr_in).sin6_addr.u.Byte();
        IpAddr::V6(Ipv6Addr::from(*saddr_in_addr))
    }
}

/// Extract all addresses from an adapter
/// `adapter` must not be NULL
#[cfg(windows)]
unsafe fn extract_addresses(adapter: *mut IP_ADAPTER_ADDRESSES) -> Vec<IpAddr> {
    let mut addresses: Vec<IpAddr> = Vec::new();
    let mut cur_unicast: *mut IP_ADAPTER_UNICAST_ADDRESS = (*adapter).FirstUnicastAddress;
    while !cur_unicast.is_null() {
        let raw_addr = (*cur_unicast).Address.lpSockaddr;
        assert!(!raw_addr.is_null());
        let ipaddr = sockaddr_to_ipaddr(raw_addr);
        debug!(
            "Found good unicast address on adapter {:?}: {:?}",
            (*adapter).FriendlyName,
            ipaddr
        );
        addresses.push(ipaddr);
        cur_unicast = (*cur_unicast).Next;
    }
    let mut cur_anycast: *mut IP_ADAPTER_ANYCAST_ADDRESS = (*adapter).FirstAnycastAddress;
    while !cur_anycast.is_null() {
        let raw_addr = (*cur_anycast).Address.lpSockaddr;
        assert!(!raw_addr.is_null());
        let ipaddr = sockaddr_to_ipaddr(raw_addr);
        debug!(
            "Found good anycast address on adapter {:?}: {:?}",
            (*adapter).FriendlyName,
            ipaddr
        );
        addresses.push(ipaddr);
        cur_anycast = (*cur_anycast).Next;
    }
    addresses
}

/// Get all assigned ip addresses of the specified type on the specified interface
/// Both parameters can be None, in which case that filter is not applied.
///
/// See also:
/// https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
#[cfg(windows)]
pub fn get_iface_addrs(ip_type: Option<IpType>, iface_name: Option<&str>) -> Result<Vec<IpAddr>> {
    let family: u32 = match ip_type {
        Some(IpType::Ipv4) => ws2def::AF_INET,
        Some(IpType::Ipv6) => ws2def::AF_INET6,
        None => ws2def::AF_UNSPEC,
    } as u32;
    let flags: ULONG = GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_MULTICAST;
    // Allocate a 15 KB buffer to start with.
    let mut allocated_size: ULONG = INITIAL_ALLOC_SIZE;
    let mut adapter_addresses: *mut IP_ADAPTER_ADDRESSES;
    let mut return_value: DWORD = 0;
    unsafe {
        // Silence maybe uninitialized error
        adapter_addresses = mem::zeroed();
        // Try several times to query the resources as suggested by doc
        for trial in 0..MAX_TRIES {
            adapter_addresses = HeapAlloc(GetProcessHeap(), 0, allocated_size as usize)
                as *mut IP_ADAPTER_ADDRESSES;
            if adapter_addresses.is_null() {
                error!("Raw heap allocation failed");
                return fail_os_err!();
            }
            return_value = GetAdaptersAddresses(
                family,
                flags,
                ptr::null_mut(),
                adapter_addresses,
                &mut allocated_size,
            );
            debug!(
                "GetAdaptersAddresses returned {:?} on the {}th trial",
                return_value, trial
            );
            if return_value == winerror::ERROR_BUFFER_OVERFLOW {
                HeapFree(GetProcessHeap(), 0, adapter_addresses as LPVOID);
            } else {
                break;
            }
        }
    }
    let result = if return_value == winerror::NO_ERROR {
        let mut addresses: Vec<IpAddr> = Vec::new();
        let mut curr_adapter = adapter_addresses;
        while !curr_adapter.is_null() {
            unsafe {
                let adapter_name = (*curr_adapter).FriendlyName as *const libc::c_char;
                let adapter_name = CStr::from_ptr(adapter_name).to_bytes();
                let adapter_name = std::str::from_utf8_unchecked(adapter_name);
                trace!("Examining adpater {:?}", adapter_name);
                if let Some(expected_adapter_name) = iface_name {
                    if adapter_name == expected_adapter_name {
                        let mut addrs = extract_addresses(curr_adapter);
                        addresses.append(&mut addrs);
                    }
                } else {
                    let mut addrs = extract_addresses(curr_adapter);
                    addresses.append(&mut addrs);
                }
                curr_adapter = (*curr_adapter).Next;
            }
        }
        Ok(addresses)
    } else {
        // Let Rust interpret the error for me
        Err(Error::IoError(std::io::Error::from_raw_os_error(
            return_value as i32,
        )))
    };
    unsafe {
        HeapFree(GetProcessHeap(), 0, adapter_addresses as LPVOID);
    }
    result
}

#[cfg(test)]
mod test {
    use super::get_iface_addrs;
    use crate::Error;
    use crate::IpType;

    #[test]
    fn test_get_iface_addrs_ipv4() {
        // There is no reliable way to find the name of an interface
        // So `iface_name` is None.
        match get_iface_addrs(Some(IpType::Ipv4), None) {
            Ok(addresses) => {
                assert!(!addresses.is_empty(), "Addresses should not be empty");
                for address in &addresses {
                    assert!(address.is_ipv4(), "Address not IPv4: {:?}", address);
                }
            }
            Err(error) => {
                assert!(
                    matches!(error, Error::NoAddress),
                    "get_iface_addrs failed because of reasons other than NoAddress: {:?}",
                    error
                );
            }
        }
    }

    #[test]
    fn test_get_iface_addrs_ipv6() {
        match get_iface_addrs(Some(IpType::Ipv6), None) {
            Ok(addresses) => {
                assert!(!addresses.is_empty(), "Addresses should not be empty");
                for address in &addresses {
                    assert!(address.is_ipv6(), "Address not IPv6: {:?}", address);
                }
            }
            Err(error) => {
                assert!(
                    matches!(error, Error::NoAddress),
                    "get_iface_addrs failed because of reasons other than NoAddress: {:?}",
                    error
                );
            }
        }
    }

    #[test]
    fn test_get_iface_addrs_any() {
        match get_iface_addrs(None, None) {
            Ok(addresses) => {
                assert!(!addresses.is_empty(), "Addresses should not be empty");
            }
            Err(error) => {
                assert!(
                    matches!(error, Error::NoAddress),
                    "get_iface_addrs failed because of reasons other than NoAddress: {:?}",
                    error
                );
                // It does not make sense if this one if NoAddress but individual ones succeed
                assert!(
                    matches!(
                        get_iface_addrs(Some(IpType::Ipv6), None),
                        Err(Error::NoAddress)
                    ) || matches!(
                        get_iface_addrs(Some(IpType::Ipv4), None),
                        Err(Error::NoAddress)
                    ),
                    "Individual get_iface_addrs succeeded but generic one didn't"
                );
            }
        }
    }
}