1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use std::fs::File;
use std::io::prelude::*;
use std::error::Error;
#[allow(dead_code)]
fn read_file(file_path: &str) -> Result<String, Box<Error>> {
let mut fd = File::open(file_path)?;
let mut content = String::new();
fd.read_to_string(&mut content)?;
Ok(content.trim().to_string())
}
#[cfg(target_os="linux")]
pub mod machine_id {
use ::read_file;
use std::error::Error;
const DBUS_PATH: &str = "/var/lib/dbus/machine-id";
const DBUS_PATH_ETC: &str = "/etc/machine-id";
pub fn get_machine_id() -> Result<String, Box<Error>> {
match read_file(DBUS_PATH) {
Ok(machine_id) => Ok(machine_id),
Err(_) => Ok(read_file(DBUS_PATH_ETC)?)
}
}
}
#[cfg(any(target_os="freebsd", target_os="dragonfly", target_os="openbsd", target_os="netbsd"))]
pub mod machine_id {
use ::read_file;
use std::process::Command;
use std::error::Error;
const HOST_ID_PATH: &str = "/etc/hostid";
pub fn get_machine_id() -> Result<String, Box<Error>> {
match read_file(HOST_ID_PATH) {
Ok(machine_id) => Ok(machine_id),
Err(_) => Ok(read_from_kenv()?)
}
}
fn read_from_kenv() -> Result<String, Box<Error>> {
let output = Command::new("kenv")
.args(&["-q", "smbios.system.uuid"])
.output()?;
let content = String::from_utf8_lossy(&output.stdout);
Ok(content.trim().to_string())
}
}
#[cfg(target_os="macos")]
mod machine_id {
use std::process::Command;
use std::error::Error;
pub fn get_machine_id() -> Result<String, Box<Error>> {
let output = Command::new("ioreg")
.args(&["-rd1", "-c", "IOPlatformExpertDevice"])
.output()?;
let content = String::from_utf8_lossy(&output.stdout);
extract_id(&content)
}
fn extract_id(content: &str) -> Result<String, Box<Error>> {
let lines = content.split('\n');
for line in lines {
if line.contains("IOPlatformUUID") {
let k: Vec<&str> = line.rsplitn(2, '=').collect();
let id = k[0].trim_matches(|c: char| c == '"' || c.is_whitespace());
return Ok(id.to_string());
}
}
Err(From::from("No matching IOPlatformUUID in `ioreg -rd1 -c IOPlatformExpertDevice` command."))
}
}
pub use machine_id::get_machine_id as get;