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 Linux, where the kernel has none: `/etc/hosts`, then
//! the name servers of `/etc/resolv.conf`, asked by `net::dns`.
//!
//! This is what a C library does when `/etc/nsswitch.conf` says `files
//! dns`, which is its default; the file itself is not read.

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

use crate::net::dns::{self, Config, conf};
use crate::net::{Family, IpVersion, Protocol, Type};
use crate::sys::{errno, syscall};
use crate::{ErrorKind, Result};

const AT_FDCWD: i32 = -100;
const O_RDONLY: usize = 0;
/// The same on every architecture oscall supports.
const O_CLOEXEC: usize = 0o2000000;

/// Calls `f` with each line of the file at `path`, without its end of
/// line, until `f` says to stop. A line longer than the buffer is left
/// out: no line of these files that means something is.
fn lines(path: &CStr, mut f: impl FnMut(&[u8]) -> bool) -> Result<()> {
    // SAFETY: the path is NUL-terminated, and opening a file for reading
    // has no effect on the process but the descriptor returned.
    let fd = unsafe { syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_RDONLY | O_CLOEXEC, 0) }?;
    let mut buf = [0u8; 4096];
    let mut filled = 0;
    // Inside a line that did not fit: what is read belongs to it until
    // its end.
    let mut skipping = false;
    let result = 'file: loop {
        // SAFETY: the destination is the unfilled end of `buf`, which is
        // never empty here.
        let read = unsafe { syscall!(READ, fd, buf.as_mut_ptr().add(filled), buf.len() - filled) };
        let read = match read {
            Ok(read) => read,
            // Reading a file is not a wait a signal should end.
            Err(error) if error.raw_os_error() == errno::EINTR => continue,
            Err(error) => break Err(error),
        };
        if read == 0 {
            // The last line may have no end.
            if filled != 0 && !skipping {
                f(&buf[..filled]);
            }
            break Ok(());
        }
        filled += read;
        let mut start = 0;
        while let Some(len) = buf[start..filled].iter().position(|&byte| byte == b'\n') {
            if !skipping && !f(&buf[start..start + len]) {
                break 'file Ok(());
            }
            skipping = false;
            start += len + 1;
        }
        buf.copy_within(start..filled, 0);
        filled -= start;
        if filled == buf.len() {
            skipping = true;
            filled = 0;
        }
    };
    // SAFETY: `fd` was opened above and is used by nothing else.
    unsafe { crate::sys::close(fd as i32) };
    result
}

pub(crate) fn config() -> Result<Config> {
    let mut config = Config::empty();
    let read = lines(c"/etc/resolv.conf", |line| {
        conf::resolv_line(line, &mut config);
        true
    });
    match read {
        Ok(()) => {}
        // No file: the defaults, as for a C library.
        Err(error) if error.kind() == ErrorKind::NotFound => {}
        Err(error) => return Err(error),
    }
    Ok(config.or_local())
}

fn wanted(version: IpVersion, addr: &IpAddr) -> bool {
    match version {
        IpVersion::Any => true,
        IpVersion::V4 => addr.is_ipv4(),
        IpVersion::V6 => addr.is_ipv6(),
    }
}

/// Whether the machine has a way to send to `addr`: what connecting a
/// datagram socket finds out, without sending anything.
fn routable(addr: &SocketAddr) -> bool {
    let family = if addr.is_ipv4() {
        Family::Ipv4
    } else {
        Family::Ipv6
    };
    // Port 0 is not one to connect to: any other does for a route.
    let mut addr = *addr;
    if addr.port() == 0 {
        addr.set_port(53);
    }
    crate::net::socket(family, Type::Datagram, Protocol::Default)
        .and_then(|socket| crate::net::connect(&socket, &addr.into()))
        .is_ok()
}

/// The order `net::resolve` says: IPv6 first, and what cannot be reached
/// last. With addresses of one kind only there is nothing to choose
/// between, and nothing is asked of the kernel.
fn order(addrs: &mut [SocketAddr]) {
    dns::v6_first(addrs);
    let mixed = addrs.iter().any(SocketAddr::is_ipv4) && addrs.iter().any(SocketAddr::is_ipv6);
    if mixed {
        dns::partition(addrs, routable);
    }
}

pub(crate) fn resolve(
    host: &str,
    port: u16,
    version: IpVersion,
    addrs: &mut [SocketAddr],
) -> Result<usize> {
    let name = host.as_bytes();
    // How many addresses were written, and whether there was any to
    // write: with nowhere to write, the name is known all the same.
    let mut count = 0;
    let mut known = false;
    let mut push = |count: &mut usize, addr: IpAddr| {
        if wanted(version, &addr) {
            known = true;
            if let Some(slot) = addrs.get_mut(*count) {
                *slot = SocketAddr::new(addr, port);
                *count += 1;
            }
        }
    };
    // A file that is not there, or cannot be read, knows no name.
    let _ = lines(c"/etc/hosts", |line| {
        if let Some((addr, mut names)) = conf::hosts_line(line)
            && names.any(|known| conf::same_host(known, name))
        {
            push(&mut count, addr);
        }
        true
    });
    if count == 0 && conf::is_localhost(name) {
        push(&mut count, IpAddr::V6(Ipv6Addr::LOCALHOST));
        push(&mut count, IpAddr::V4(Ipv4Addr::LOCALHOST));
    }
    if !known {
        // A name `/etc/hosts` has, with no address of the kind asked for,
        // is still asked of the servers: so does glibc.
        count = config()?.resolve(host, port, version, addrs)?;
    }
    let found = addrs.get_mut(..count).ok_or(ErrorKind::Other)?;
    order(found);
    Ok(count)
}

pub(crate) fn reverse(addr: IpAddr, buf: &mut [u8]) -> Result<usize> {
    let mut found = None;
    let _ = lines(c"/etc/hosts", |line| {
        if let Some((known, mut names)) = conf::hosts_line(line)
            && known == addr
            && let Some(name) = names.next()
        {
            found = Some(match buf.get_mut(..name.len()) {
                Some(slot) => {
                    slot.copy_from_slice(name);
                    Ok(name.len())
                }
                None => Err(ErrorKind::BufferTooSmall.into()),
            });
            return false;
        }
        true
    });
    match found {
        Some(result) => result,
        None => Ok(config()?.reverse(addr, buf)?.len()),
    }
}