flareapp-core 0.3.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! Detects the host details that the `host-details` feature adds to the
//! resource: `host.ip`, `os.name`, `os.version` and `os.description`.
//!
//! Detection reads a system file (the registry on Windows) and asks the operating
//! system which route a packet takes. Detection sends nothing over the network
//! and does not block. When a value cannot be found, its attribute is left out.

#[cfg(not(windows))]
use std::fs;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};

use flareapp_otlp::KeyValue;

/// The port of the discard service (RFC 863), which throws away all data that it
/// receives. [`source_address`] sends no data, so any port works. This port shows
/// that no data goes out.
const DISCARD_PORT: u16 = 9;

/// The operating system, as the `os.*` attributes describe it. Each field is
/// `None` when its value cannot be found.
#[derive(Debug, Default, PartialEq)]
struct Os {
    name: Option<String>,
    version: Option<String>,
    description: Option<String>,
}

/// Returns the host details that were found, as resource attributes.
pub(super) fn attributes() -> Vec<KeyValue> {
    let mut attributes = Vec::new();

    // Send one string, not the `string[]` of the semantic conventions, because
    // Flare's error format expects `host.ip` to be a string. See section 4.4 of
    // `docs/design.md`.
    if let Some(ip) = host_ip() {
        attributes.push(KeyValue::new("host.ip", ip.to_string()));
    }

    let os = detect_os();
    let fields = [
        ("os.name", os.name),
        ("os.version", os.version),
        ("os.description", os.description),
    ];
    for (key, value) in fields {
        if let Some(value) = value.filter(|value| !value.trim().is_empty()) {
            attributes.push(KeyValue::new(key, value));
        }
    }

    attributes
}

/// Returns the IP address of the network interface with the default route.
///
/// Tries IPv4 first, then IPv6. Returns `None` when the machine has no usable
/// address, for example without a network.
fn host_ip() -> Option<IpAddr> {
    let ipv4 = source_address(
        Ipv4Addr::UNSPECIFIED.into(),
        Ipv4Addr::new(192, 0, 2, 1).into(),
    );

    ipv4.or_else(|| {
        source_address(
            Ipv6Addr::UNSPECIFIED.into(),
            Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).into(),
        )
    })
}

/// Returns the source address that the operating system picks to reach `target`.
///
/// Connecting a UDP socket sends no packets: the OS only picks a route and a
/// source address. `target` is a documentation address (RFC 5737 and RFC 3849),
/// which no real host has, so the OS picks the default route.
fn source_address(bind: IpAddr, target: IpAddr) -> Option<IpAddr> {
    let socket = UdpSocket::bind(SocketAddr::new(bind, 0)).ok()?;
    socket.connect(SocketAddr::new(target, DISCARD_PORT)).ok()?;
    let ip = socket.local_addr().ok()?.ip();

    is_usable(ip).then_some(ip)
}

/// Returns `true` when `ip` can identify the host on a network: it is not a
/// loopback, link-local or unspecified address.
fn is_usable(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => !(ip.is_loopback() || ip.is_link_local() || ip.is_unspecified()),
        IpAddr::V6(ip) => !(ip.is_loopback() || ip.is_unicast_link_local() || ip.is_unspecified()),
    }
}

/// Reads the OS from the os-release file, which Linux distributions have.
///
/// This does not use the `os_info` crate, because on Linux it first runs
/// `lsb_release`, which takes about 100 ms on Ubuntu 22.04.
#[cfg(not(any(target_os = "macos", windows)))]
fn detect_os() -> Os {
    // `os-release(5)` asks to read `/usr/lib/os-release` when `/etc/os-release`
    // does not exist.
    ["/etc/os-release", "/usr/lib/os-release"]
        .iter()
        .find_map(|path| fs::read_to_string(path).ok())
        .map(|contents| os_from_os_release(&contents))
        .unwrap_or_default()
}

/// Reads the OS from the contents of an os-release file.
///
/// `NAME` is like `Ubuntu`, `VERSION_ID` like `24.04` and `PRETTY_NAME` like
/// `Ubuntu 24.04.1 LTS`.
#[cfg(not(any(target_os = "macos", windows)))]
fn os_from_os_release(contents: &str) -> Os {
    Os {
        name: os_release_value(contents, "NAME"),
        version: os_release_value(contents, "VERSION_ID"),
        description: os_release_value(contents, "PRETTY_NAME"),
    }
}

/// Returns the value of `key` in the contents of an os-release file.
///
/// Each line is `KEY=value`. A value can be in double or single quotes, and a
/// backslash escapes the character after it, like in a shell.
#[cfg(not(any(target_os = "macos", windows)))]
fn os_release_value(contents: &str, key: &str) -> Option<String> {
    let value = contents
        .lines()
        .find_map(|line| line.trim().strip_prefix(key)?.strip_prefix('='))?
        .trim();

    Some(unquote(value).map_or_else(|| value.to_owned(), unescape))
}

/// Returns `value` without its double or single quotes, or `None` when `value`
/// is not in quotes.
#[cfg(not(any(target_os = "macos", windows)))]
fn unquote(value: &str) -> Option<&str> {
    value
        .strip_prefix('"')
        .and_then(|value| value.strip_suffix('"'))
        .or_else(|| {
            value
                .strip_prefix('\'')
                .and_then(|value| value.strip_suffix('\''))
        })
}

/// Removes each backslash and keeps the character after it, like a shell does.
#[cfg(not(any(target_os = "macos", windows)))]
fn unescape(value: &str) -> String {
    let mut unescaped = String::with_capacity(value.len());
    let mut chars = value.chars();
    while let Some(character) = chars.next() {
        match character {
            '\\' => unescaped.extend(chars.next()),
            character => unescaped.push(character),
        }
    }

    unescaped
}

/// Reads the OS from `SystemVersion.plist`, where macOS keeps its name and
/// version.
#[cfg(target_os = "macos")]
fn detect_os() -> Os {
    fs::read_to_string("/System/Library/CoreServices/SystemVersion.plist")
        .map(|plist| os_from_plist(&plist))
        .unwrap_or_default()
}

/// Reads the OS from the contents of `SystemVersion.plist`.
///
/// The description adds the build number, like `macOS 15.1 (24B83)`.
#[cfg(target_os = "macos")]
fn os_from_plist(plist: &str) -> Os {
    let name = plist_string(plist, "ProductName");
    let version = plist_string(plist, "ProductVersion");
    let build = plist_string(plist, "ProductBuildVersion");

    let description = match (&name, &version, build) {
        (Some(name), Some(version), Some(build)) => Some(format!("{name} {version} ({build})")),
        (Some(name), Some(version), None) => Some(format!("{name} {version}")),
        _ => None,
    };

    Os {
        name,
        version,
        description,
    }
}

/// Returns the string value of `key` in an XML property list.
///
/// In the file, each value follows its key: `<key>ProductName</key>` and then
/// `<string>macOS</string>`.
#[cfg(target_os = "macos")]
fn plist_string(plist: &str, key: &str) -> Option<String> {
    let (_, after_key) = plist.split_once(&format!("<key>{key}</key>"))?;
    let value = after_key.trim_start().strip_prefix("<string>")?;
    let (value, _) = value.split_once("</string>")?;

    Some(value.to_owned())
}

/// Reads the OS with the `os_info` crate. It asks Windows for its version and
/// reads the edition, like `Windows 11 Professional`, from the registry.
#[cfg(windows)]
fn detect_os() -> Os {
    let info = os_info::get();
    let version = match info.version() {
        os_info::Version::Unknown => None,
        version => Some(version.to_string()),
    };
    let description = match (info.edition(), &version) {
        (Some(edition), Some(version)) => Some(format!("{edition} {version}")),
        (Some(edition), None) => Some(edition.to_owned()),
        (None, _) => None,
    };

    Os {
        name: Some("Windows".to_owned()),
        version,
        description,
    }
}

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

    #[test]
    fn keeps_only_addresses_that_identify_the_host() {
        let usable = ["10.0.3.17", "192.168.1.150", "2001:db8::5", "fd00::2"];
        let unusable = [
            "127.0.0.1",
            "::1",
            "169.254.10.1",
            "fe80::1",
            "0.0.0.0",
            "::",
        ];

        for ip in usable {
            assert!(is_usable(ip.parse().unwrap()), "{ip} should be usable");
        }
        for ip in unusable {
            assert!(!is_usable(ip.parse().unwrap()), "{ip} should not be usable");
        }
    }

    #[cfg(not(any(target_os = "macos", windows)))]
    #[test]
    fn reads_the_os_from_os_release() {
        let contents = r#"
            PRETTY_NAME="Ubuntu 24.04.1 LTS"
            NAME="Ubuntu"
            VERSION_ID="24.04"
            ID=ubuntu
        "#;

        assert_eq!(
            os_from_os_release(contents),
            Os {
                name: Some("Ubuntu".to_owned()),
                version: Some("24.04".to_owned()),
                description: Some("Ubuntu 24.04.1 LTS".to_owned()),
            }
        );
    }

    #[cfg(not(any(target_os = "macos", windows)))]
    #[test]
    fn reads_os_release_values_in_every_quote_style() {
        let contents = "# NAME=Comment\nNAME=Alpine\nVERSION_ID='3.20'\nPRETTY_NAME=\"Say \\\"hi\\\"\"\nBUILD_ID=\n";

        assert_eq!(
            os_release_value(contents, "NAME").as_deref(),
            Some("Alpine")
        );
        assert_eq!(
            os_release_value(contents, "VERSION_ID").as_deref(),
            Some("3.20")
        );
        assert_eq!(
            os_release_value(contents, "PRETTY_NAME").as_deref(),
            Some("Say \"hi\"")
        );
        assert_eq!(os_release_value(contents, "BUILD_ID").as_deref(), Some(""));
        assert_eq!(os_release_value(contents, "VERSION"), None);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn reads_the_os_from_system_version_plist() {
        let plist = "<dict>\n\t<key>ProductBuildVersion</key>\n\t<string>24B83</string>\n\t\
            <key>ProductName</key>\n\t<string>macOS</string>\n\t\
            <key>ProductVersion</key>\n\t<string>15.1</string>\n</dict>";

        assert_eq!(
            os_from_plist(plist),
            Os {
                name: Some("macOS".to_owned()),
                version: Some("15.1".to_owned()),
                description: Some("macOS 15.1 (24B83)".to_owned()),
            }
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn leaves_out_the_description_without_a_version() {
        let plist = "<key>ProductName</key><string>macOS</string>";

        assert_eq!(
            os_from_plist(plist),
            Os {
                name: Some("macOS".to_owned()),
                version: None,
                description: None,
            }
        );
    }
}