oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Name resolution on Windows: `GetAddrInfoW` and `GetNameInfoW`, which
//! ask the DNS client service.

use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6};

use crate::net::IpVersion;
use crate::path::{wide_to_wtf8, with_wide};
use crate::sys::dll;
use crate::{Error, ErrorKind, Result};

const AF_UNSPEC: i32 = 0;
const AF_INET: i32 = 2;
const AF_INET6: i32 = 23;
const SOCK_STREAM: i32 = 1;
/// Fail rather than print the address when it has no name.
const NI_NAMEREQD: i32 = 4;
/// `NI_MAXHOST`.
const MAX_HOST: usize = 1025;

/// `ADDRINFOW`.
#[repr(C)]
struct AddrInfo {
    flags: i32,
    family: i32,
    socktype: i32,
    protocol: i32,
    addrlen: usize,
    canonname: *mut u16,
    addr: *const u8,
    next: *mut AddrInfo,
}

dll!("ws2_32.dll" {
    fn GetAddrInfoW(
        node: *const u16,
        service: *const u16,
        hints: *const AddrInfo,
        result: *mut *mut AddrInfo,
    ) -> i32;
    fn FreeAddrInfoW(list: *mut AddrInfo);
    fn GetNameInfoW(
        addr: *const u8,
        addrlen: i32,
        host: *mut u16,
        hostlen: u32,
        service: *mut u16,
        servicelen: u32,
        flags: i32,
    ) -> i32;
});

/// `SOCKADDR_IN` is 16 bytes and `SOCKADDR_IN6` 28: the family, the port,
/// and the address (after four bytes of flow for IPv6, and before four of
/// scope).
fn decode(addr: &[u8], port: u16) -> Option<SocketAddr> {
    let family = u16::from_ne_bytes(<[u8; 2]>::try_from(addr.get(..2)?).ok()?);
    match i32::from(family) {
        AF_INET => {
            let octets = <[u8; 4]>::try_from(addr.get(4..8)?).ok()?;
            Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::from(octets)), port))
        }
        AF_INET6 => {
            let octets = <[u8; 16]>::try_from(addr.get(8..24)?).ok()?;
            let scope = u32::from_ne_bytes(<[u8; 4]>::try_from(addr.get(24..28)?).ok()?);
            Some(SocketAddr::V6(SocketAddrV6::new(
                Ipv6Addr::from(octets),
                port,
                0,
                scope,
            )))
        }
        _ => None,
    }
}

pub(crate) fn resolve(
    host: &str,
    port: u16,
    version: IpVersion,
    addrs: &mut [SocketAddr],
) -> Result<usize> {
    crate::sys::net::startup()?;
    let hints = AddrInfo {
        flags: 0,
        family: match version {
            IpVersion::Any => AF_UNSPEC,
            IpVersion::V4 => AF_INET,
            IpVersion::V6 => AF_INET6,
        },
        // One kind of socket, or every address comes once per kind.
        socktype: SOCK_STREAM,
        protocol: 0,
        addrlen: 0,
        canonname: core::ptr::null_mut(),
        addr: core::ptr::null(),
        next: core::ptr::null_mut(),
    };
    with_wide(host.as_bytes(), |host| {
        let mut list = core::ptr::null_mut();
        // SAFETY: the name is NUL-terminated, the hints are a whole
        // structure, and the function writes the list to `list`.
        let code = unsafe {
            GetAddrInfoW(
                host.as_ptr(),
                core::ptr::null(),
                &raw const hints,
                &raw mut list,
            )
        };
        if code != 0 {
            // The function returns its error, a Winsock code.
            return Err(Error::from_raw_os_error(code));
        }
        let mut count = 0;
        let mut entry = list.cast_const();
        // SAFETY: on success the list is entries that each point to the
        // next, the last to nothing, and to an address of the length
        // they say; it is freed once, after its last use.
        unsafe {
            while let Some(info) = entry.as_ref() {
                if !info.addr.is_null()
                    && let Some(addr) =
                        decode(core::slice::from_raw_parts(info.addr, info.addrlen), port)
                    && let Some(slot) = addrs.get_mut(count)
                {
                    *slot = addr;
                    count += 1;
                }
                entry = info.next;
            }
            FreeAddrInfoW(list);
        }
        if count == 0 && !addrs.is_empty() {
            return Err(ErrorKind::NotFound.into());
        }
        Ok(count)
    })
}

pub(crate) fn reverse(addr: IpAddr, buf: &mut [u8]) -> Result<usize> {
    crate::sys::net::startup()?;
    let mut raw = [0u8; 28];
    let len = match addr {
        IpAddr::V4(addr) => {
            raw[..2].copy_from_slice(&(AF_INET as u16).to_ne_bytes());
            raw[4..8].copy_from_slice(&addr.octets());
            16
        }
        IpAddr::V6(addr) => {
            raw[..2].copy_from_slice(&(AF_INET6 as u16).to_ne_bytes());
            raw[8..24].copy_from_slice(&addr.octets());
            28
        }
    };
    let mut host = [0u16; MAX_HOST];
    // SAFETY: the address is a whole `SOCKADDR` of the length given, and
    // the function writes at most the size of `host`, NUL included.
    let code = unsafe {
        GetNameInfoW(
            raw.as_ptr(),
            len,
            host.as_mut_ptr(),
            MAX_HOST as u32,
            core::ptr::null_mut(),
            0,
            NI_NAMEREQD,
        )
    };
    if code != 0 {
        return Err(Error::from_raw_os_error(code));
    }
    let len = host.iter().position(|&unit| unit == 0).unwrap_or(MAX_HOST);
    wide_to_wtf8(&host[..len], buf).ok_or_else(|| ErrorKind::BufferTooSmall.into())
}