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 macOS: `getaddrinfo` and `getnameinfo`, which ask
//! the system's resolver (`mDNSResponder`).

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

use crate::net::IpVersion;
use crate::path::with_cstr;
use crate::sys::{errno, last_error};
use crate::{Error, ErrorKind, Result};

const AF_UNSPEC: c_int = 0;
const AF_INET: c_int = 2;
const AF_INET6: c_int = 30;
const SOCK_STREAM: c_int = 1;

// netdb.h
const EAI_AGAIN: c_int = 2;
const EAI_MEMORY: c_int = 6;
const EAI_NODATA: c_int = 7;
const EAI_NONAME: c_int = 8;
const EAI_SYSTEM: c_int = 11;
const EAI_OVERFLOW: c_int = 14;
/// Fail rather than print the address when it has no name.
const NI_NAMEREQD: c_int = 4;
/// `NI_MAXHOST`.
const MAX_HOST: usize = 1025;

/// `struct addrinfo`, in the order macOS has its members.
#[repr(C)]
struct AddrInfo {
    flags: c_int,
    family: c_int,
    socktype: c_int,
    protocol: c_int,
    addrlen: u32,
    canonname: *mut c_char,
    addr: *const u8,
    next: *mut AddrInfo,
}

unsafe extern "C" {
    fn getaddrinfo(
        node: *const c_char,
        service: *const c_char,
        hints: *const AddrInfo,
        result: *mut *mut AddrInfo,
    ) -> c_int;
    fn freeaddrinfo(list: *mut AddrInfo);
    fn getnameinfo(
        addr: *const u8,
        addrlen: u32,
        host: *mut c_char,
        hostlen: u32,
        service: *mut c_char,
        servicelen: u32,
        flags: c_int,
    ) -> c_int;
}

/// The two functions have error numbers of their own, which mean other
/// things as system errors: each becomes the system error that says the
/// same.
fn error(code: c_int) -> Error {
    match code {
        EAI_NONAME | EAI_NODATA => ErrorKind::NotFound.into(),
        EAI_AGAIN => ErrorKind::TimedOut.into(),
        EAI_MEMORY => ErrorKind::OutOfMemory.into(),
        EAI_OVERFLOW => ErrorKind::BufferTooSmall.into(),
        EAI_SYSTEM => last_error(),
        _ => Error::from_raw_os_error(errno::EIO),
    }
}

/// `sockaddr_in` is 16 bytes and `sockaddr_in6` 28: a length, 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> {
    match c_int::from(*addr.get(1)?) {
        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> {
    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_cstr(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 {
            getaddrinfo(
                host.as_ptr(),
                core::ptr::null(),
                &raw const hints,
                &raw mut list,
            )
        };
        if code != 0 {
            return Err(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 as usize),
                        port,
                    )
                    && let Some(slot) = addrs.get_mut(count)
                {
                    *slot = addr;
                    count += 1;
                }
                entry = info.next;
            }
            freeaddrinfo(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> {
    let mut raw = [0u8; 28];
    let len = match addr {
        IpAddr::V4(addr) => {
            raw[0] = 16;
            raw[1] = AF_INET as u8;
            raw[4..8].copy_from_slice(&addr.octets());
            16
        }
        IpAddr::V6(addr) => {
            raw[0] = 28;
            raw[1] = AF_INET6 as u8;
            raw[8..24].copy_from_slice(&addr.octets());
            28
        }
    };
    let mut host = [0u8; 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 {
        getnameinfo(
            raw.as_ptr(),
            len,
            host.as_mut_ptr().cast(),
            MAX_HOST as u32,
            core::ptr::null_mut(),
            0,
            NI_NAMEREQD,
        )
    };
    if code != 0 {
        return Err(error(code));
    }
    let len = host.iter().position(|&byte| byte == 0).unwrap_or(MAX_HOST);
    buf.get_mut(..len)
        .ok_or(ErrorKind::BufferTooSmall)?
        .copy_from_slice(&host[..len]);
    Ok(len)
}