1use std::error::Error;
2use std::net::IpAddr;
3use std::process::{Command, Output};
4use std::str;
5use std::str::FromStr;
6
7use hmac_sha256::HMAC;
8use uuid::Uuid;
9
10use crate::error::NetzworkApiError;
11
12const APP_DOMAIN: &[u8; 12] = b"netzwork.tbd";
14
15#[cfg(target_os = "linux")]
16fn get_machine_id() -> Result<Uuid, Box<dyn Error>> {
17 let machine_id = std::fs::read_to_string("/etc/machine-id")?
18 .trim()
19 .to_string();
20 Ok(Uuid::from_str(&machine_id)?)
21}
22
23#[cfg(target_os = "macos")]
24fn get_machine_id() -> Result<Uuid, Box<dyn Error>> {
25 let output: Output = Command::new("system_profiler")
26 .arg("SPHardwareDataType")
27 .output()?;
28
29 let hardware_uuid = str::from_utf8(&output.stdout)?
30 .lines()
31 .find(|line| line.contains("Hardware UUID"))
32 .and_then(|line| line.split_whitespace().nth(2))
33 .map(str::to_string)
34 .ok_or("Failed to retrieve Hardware UUID")?
35 .trim()
36 .to_string();
37
38 Ok(Uuid::from_str(&hardware_uuid)?)
39}
40
41fn get_secure_machine_id(app_id_opt: Option<Uuid>) -> Result<Uuid, Box<dyn Error>> {
44 let app_id = match app_id_opt {
45 Some(u) => u,
46 None => Uuid::new_v5(&Uuid::NAMESPACE_DNS, APP_DOMAIN),
47 };
48 let hmac = HMAC::mac(app_id, get_machine_id()?);
49 let mut id = Uuid::from_slice(&hmac[0..16])?.into_bytes();
50 id[6] = (id[6] & 0x0F) | 0x40;
53 id[8] = (id[8] & 0x3F) | 0x80;
55 Ok(Uuid::from_bytes(id))
56}
57
58pub fn host_uuid() -> Result<Uuid, NetzworkApiError> {
59 match get_secure_machine_id(None) {
60 Ok(uuid) => Ok(uuid),
61 Err(_err) => Err(NetzworkApiError::HostIdentityError(
62 "get_secure_machine_id call failed".to_string(),
63 )),
64 }
65}
66
67pub fn agent_uuid(host_uuid: &Uuid, name: &String) -> Uuid {
68 Uuid::new_v5(host_uuid, name.as_bytes())
69}
70
71pub fn interface_uuid(host_uuid: &Uuid, mac_addr: &[u8]) -> Uuid {
72 Uuid::new_v5(host_uuid, mac_addr)
73}
74
75pub fn interface_addr_uuid(iface_uuid: &Uuid, ip_addr: IpAddr) -> Uuid {
76 Uuid::new_v5(iface_uuid, ip_addr.to_string().as_bytes())
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn test_machineid() {
85 assert_ne!(get_machine_id().unwrap(), Uuid::nil());
86 }
87 #[test]
88 fn test_secure_machineid() {
89 assert_ne!(get_secure_machine_id(None).unwrap(), Uuid::nil());
90 }
91}