#[cfg(not(windows))]
use std::fs;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};
use flareapp_otlp::KeyValue;
const DISCARD_PORT: u16 = 9;
#[derive(Debug, Default, PartialEq)]
struct Os {
name: Option<String>,
version: Option<String>,
description: Option<String>,
}
pub(super) fn attributes() -> Vec<KeyValue> {
let mut attributes = Vec::new();
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
}
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(),
)
})
}
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)
}
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()),
}
}
#[cfg(not(any(target_os = "macos", windows)))]
fn detect_os() -> Os {
["/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()
}
#[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"),
}
}
#[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))
}
#[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('\''))
})
}
#[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
}
#[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()
}
#[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,
}
}
#[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())
}
#[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,
}
);
}
}