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
//! The two text files a resolver reads on Linux, a line at a time:
//! `resolv.conf` and `hosts`. Nothing here opens a file.

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

use super::Config;

const DNS_PORT: u16 = 53;

/// The words of a line, without what follows a comment character.
fn words<'a>(line: &'a [u8], comments: &[u8]) -> impl Iterator<Item = &'a [u8]> + use<'a> {
    let end = line
        .iter()
        .position(|byte| comments.contains(byte))
        .unwrap_or(line.len());
    line[..end]
        .split(|byte| byte.is_ascii_whitespace())
        .filter(|word| !word.is_empty())
}

/// An address as these files write one: with, for IPv6, an optional `%`
/// and the number of an interface. The name of an interface is not
/// taken: `None`.
fn address(word: &[u8]) -> Option<(IpAddr, u32)> {
    let text = core::str::from_utf8(word).ok()?;
    match text.split_once('%') {
        None => Some((text.parse().ok()?, 0)),
        Some((addr, scope)) => Some((
            IpAddr::V6(addr.parse::<Ipv6Addr>().ok()?),
            scope.parse().ok()?,
        )),
    }
}

/// A number after a prefix, as the options have it (`ndots:2`).
fn option(word: &[u8], prefix: &[u8]) -> Option<u8> {
    let digits = core::str::from_utf8(word.strip_prefix(prefix)?).ok()?;
    // Any number is taken, and brought to what the option allows.
    Some(digits.parse::<u32>().ok()?.min(255) as u8)
}

/// Applies a line of `resolv.conf` to `config`. A comment starts a line,
/// with `#` or `;`.
pub(crate) fn resolv_line(line: &[u8], config: &mut Config) {
    let trimmed = line.trim_ascii_start();
    if trimmed.starts_with(b"#") || trimmed.starts_with(b";") {
        return;
    }
    let mut words = words(line, b"");
    match words.next() {
        Some(b"nameserver") => {
            if let Some((addr, scope)) = words.next().and_then(address) {
                config.push_server(match addr {
                    IpAddr::V4(_) => SocketAddr::new(addr, DNS_PORT),
                    IpAddr::V6(addr) => SocketAddr::V6(SocketAddrV6::new(addr, DNS_PORT, 0, scope)),
                });
            }
        }
        // The last of the two kinds of line wins; `domain` is a search
        // list of one.
        Some(b"search") => config.replace_search(words),
        Some(b"domain") => config.replace_search(words.take(1)),
        Some(b"options") => {
            for word in words {
                if let Some(ndots) = option(word, b"ndots:") {
                    *config = config.clone().with_ndots(ndots);
                } else if let Some(seconds) = option(word, b"timeout:") {
                    // Zero is not a time to wait: glibc makes it one too.
                    let seconds = u64::from(seconds.max(1));
                    *config = config.clone().with_timeout(Duration::from_secs(seconds));
                } else if let Some(attempts) = option(word, b"attempts:") {
                    *config = config.clone().with_attempts(attempts);
                }
            }
        }
        _ => {}
    }
}

/// A line of `hosts`: an address, and the names it has. `None` for a line
/// that says nothing: empty, a comment, or not an address. The number of
/// an interface after `%` is not kept.
#[cfg_attr(
    not(any(target_os = "linux", target_os = "fullrust")),
    allow(dead_code)
)]
pub(crate) fn hosts_line(line: &[u8]) -> Option<(IpAddr, impl Iterator<Item = &[u8]>)> {
    let mut words = words(line, b"#");
    let (addr, _) = address(words.next()?)?;
    Some((addr, words))
}

/// Whether a name of `hosts` is the name asked for: the case of letters
/// does not count, nor does a last dot.
#[cfg_attr(
    not(any(target_os = "linux", target_os = "fullrust")),
    allow(dead_code)
)]
pub(crate) fn same_host(a: &[u8], b: &[u8]) -> bool {
    let a = a.strip_suffix(b".").unwrap_or(a);
    let b = b.strip_suffix(b".").unwrap_or(b);
    a.eq_ignore_ascii_case(b)
}

/// Whether `host` is `localhost` or a name under it, which are this
/// machine whatever any file or server says (RFC 6761).
#[cfg_attr(
    not(any(target_os = "linux", target_os = "fullrust")),
    allow(dead_code)
)]
pub(crate) fn is_localhost(host: &[u8]) -> bool {
    let host = host.strip_suffix(b".").unwrap_or(host);
    let dot = host.len().checked_sub(b".localhost".len());
    host.eq_ignore_ascii_case(b"localhost")
        || dot.is_some_and(|dot| host[dot..].eq_ignore_ascii_case(b".localhost"))
}

#[cfg(test)]
mod tests {
    use super::*;

    extern crate std;
    use std::vec::Vec;

    #[test]
    fn resolv_conf() {
        let config = Config::from_resolv_conf(
            b"# a comment\n\
              ; another\n\
              nameserver 192.0.2.1\n\
              \tnameserver   2001:db8::53  \n\
              nameserver fe80::1%3\n\
              nameserver 192.0.2.4\n\
              domain ignored.example\n\
              search example.com sub.example.org.  \n\
              options ndots:2 rotate timeout:3 attempts:4 edns0\n\
              sortlist 130.155.160.0/255.255.240.0\n\
              nonsense\n",
        );
        let servers: Vec<_> = config.servers().to_vec();
        assert_eq!(
            servers,
            [
                "192.0.2.1:53".parse::<SocketAddr>().unwrap(),
                "[2001:db8::53]:53".parse().unwrap(),
                "[fe80::1%3]:53".parse().unwrap(),
            ]
        );
        assert!(config.search().eq(["example.com", "sub.example.org"]));
        assert_eq!(config.ndots(), 2);
        assert_eq!(config.timeout(), Duration::from_secs(3));
        assert_eq!(config.attempts(), 4);
        let text = std::format!("{config:?}");
        assert!(text.contains("192.0.2.1:53") && text.contains("sub.example.org"));

        // Nothing: the defaults, and the server of the machine itself.
        for text in [&b""[..], b"\n\n# nameserver 192.0.2.1\n", b"nameserver\n"] {
            let config = Config::from_resolv_conf(text);
            assert_eq!(config.servers(), ["127.0.0.1:53".parse().unwrap()]);
            assert_eq!(config.search().count(), 0);
            assert_eq!(config.ndots(), 1);
            assert_eq!(config.timeout(), Duration::from_secs(5));
            assert_eq!(config.attempts(), 2);
        }

        // What cannot be read is left out, and the limits hold.
        let config = Config::from_resolv_conf(
            b"nameserver 192.0.2.300\n\
              nameserver fe80::1%eth0\n\
              nameserver 192.0.2.9 trailing\n\
              search a.example\n\
              domain b.example c.example\n\
              options ndots:99 timeout:0 attempts:0\n\
              options timeout:999 attempts:77 ndots:x\n",
        );
        assert_eq!(config.servers(), ["192.0.2.9:53".parse().unwrap()]);
        assert!(config.search().eq(["b.example"]));
        assert_eq!(config.ndots(), 15);
        assert_eq!(config.timeout(), Duration::from_secs(30));
        assert_eq!(config.attempts(), 5);

        // Six domains, and 255 characters.
        let config = Config::from_resolv_conf(b"search a.x b.x c.x d.x bad/name e.x f.x g.x h.x\n");
        assert!(config.search().eq(["a.x", "b.x", "c.x", "d.x", "e.x"]));
        let mut text = b"search".to_vec();
        for _ in 0..5 {
            text.push(b' ');
            text.extend_from_slice(&[b'a'; 60]);
        }
        let config = Config::from_resolv_conf(&text);
        assert_eq!(config.search().count(), 4);
    }

    #[test]
    fn config() {
        let server = "192.0.2.1:5353".parse().unwrap();
        assert!(Config::new(&[]).is_err());
        assert!(Config::new(&[server; 4]).is_err());
        let config = Config::new(&[server; 3]).unwrap();
        assert_eq!(config.servers(), [server; 3]);
        let config = config
            .with_ndots(200)
            .with_attempts(0)
            .with_timeout(Duration::ZERO)
            .with_search(&["example.com", "example.org."])
            .unwrap();
        assert_eq!(config.ndots(), 15);
        assert_eq!(config.attempts(), 1);
        assert_eq!(config.timeout(), Duration::from_millis(1));
        assert!(config.search().eq(["example.com", "example.org"]));
        assert!(config.clone().with_search(&["a"; 7]).is_err());
        assert!(config.clone().with_search(&["not a name"]).is_err());
        assert!(config.clone().with_search(&[""]).is_err());
        let config = config.with_search(&[]).unwrap();
        assert_eq!(config.search().count(), 0);
    }

    #[test]
    fn hosts() {
        let line = |text: &'static str| {
            hosts_line(text.as_bytes()).map(|(addr, names)| (addr, names.collect::<Vec<_>>()))
        };
        assert_eq!(
            line("127.0.0.1\tlocalhost localhost.localdomain  # this machine"),
            Some((
                "127.0.0.1".parse().unwrap(),
                [&b"localhost"[..], b"localhost.localdomain"].to_vec()
            ))
        );
        assert_eq!(
            line("  ::1 ip6-localhost"),
            Some(("::1".parse().unwrap(), [&b"ip6-localhost"[..]].to_vec()))
        );
        assert_eq!(
            line("fe80::1%2 router"),
            Some(("fe80::1".parse().unwrap(), [&b"router"[..]].to_vec()))
        );
        assert_eq!(
            line("192.0.2.1"),
            Some(("192.0.2.1".parse().unwrap(), Vec::new()))
        );
        for nothing in [
            "",
            "   ",
            "# 127.0.0.1 x",
            "localhost 127.0.0.1",
            "1.2.3 x",
            "\u{e9} x",
        ] {
            assert_eq!(line(nothing), None, "{nothing:?}");
        }
        assert!(same_host(b"LocalHost", b"localhost."));
        assert!(!same_host(b"localhost", b"localhost.example"));

        for name in ["localhost", "LOCALHOST.", "a.localhost", "a.b.LocalHost."] {
            assert!(is_localhost(name.as_bytes()), "{name}");
        }
        for name in [
            "",
            "localhost.example",
            "notlocalhost",
            "local",
            ".localhos",
        ] {
            assert!(!is_localhost(name.as_bytes()), "{name}");
        }
    }
}