liarsping 0.1.0

A ping server which attempts to manipulate the ping times seen by the client
Documentation
use std::path::Path;

const SYSCTL_PATH: &str = "/proc/sys/net/ipv4/icmp_echo_ignore_all";
const WARNING: &str = "warning: net.ipv4.icmp_echo_ignore_all is 0; the kernel will also reply to echo requests, causing DUP! responses. Run: sudo sysctl -w net.ipv4.icmp_echo_ignore_all=1";

/// Returns the warning string if the kernel will also reply, otherwise None.
/// Reads the sysctl from the given path so tests can fake it.
pub fn check_at(path: &Path) -> Option<&'static str> {
    let raw = std::fs::read_to_string(path).ok()?;
    if raw.trim() == "0" { Some(WARNING) } else { None }
}

/// Production wrapper: reads the real sysctl and writes any warning to stderr.
pub fn check_and_warn() {
    if let Some(msg) = check_at(Path::new(SYSCTL_PATH)) {
        eprintln!("{msg}");
    }
}

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

    fn write_tmp(contents: &str) -> tempfile::NamedTempFile {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "{contents}").unwrap();
        f
    }

    #[test]
    fn warns_when_zero() {
        let f = write_tmp("0\n");
        assert!(check_at(f.path()).is_some());
    }

    #[test]
    fn silent_when_one() {
        let f = write_tmp("1\n");
        assert!(check_at(f.path()).is_none());
    }

    #[test]
    fn silent_when_unreadable() {
        let p = Path::new("/proc/sys/this/does/not/exist");
        assert!(check_at(p).is_none());
    }
}