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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//! Provides the means for for detecting the existence of an OS from an unmounted device, or path.
//!
//! ```rust,no_run
//! extern crate os_detect;
//!
//! use os_detect::detect_os_from_device;
//! use std::path::Path;
//!
//! pub fn main() {
//!     let device_path = &Path::new("/dev/sda3");
//!     let fs = "ext4";
//!     if let Some(os) = detect_os_from_device(device_path, fs) {
//!         println!("{:#?}", os);
//!     }
//! }
//! ```

#[macro_use]
extern crate log;
extern crate os_release;
extern crate partition_identity;
extern crate sys_mount;
extern crate tempdir;

use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;
use tempdir::TempDir;
use os_release::OsRelease;
use std::path::PathBuf;
use partition_identity::PartitionID;
use sys_mount::*;

/// Describes the OS found on a partition.
#[derive(Debug, Clone)]
pub enum OS {
    Windows(String),
    Linux {
        info: OsRelease,
        partitions: Vec<PartitionID>,
        targets: Vec<PathBuf>,
    },
    MacOs(String)
}

/// Mounts the partition to a temporary directory and checks for the existence of an
/// installed operating system.
///
/// If the installed operating system is Linux, it will also report back the location
/// of the home partition.
pub fn detect_os_from_device<'a, F: Into<FilesystemType<'a>>>(device: &Path, fs: F) -> Option<OS> {
    // Create a temporary directoy where we will mount the FS.
    TempDir::new("distinst").ok().and_then(|tempdir| {
        // Mount the FS to the temporary directory
        let base = tempdir.path();
        Mount::new(device, base, fs, MountFlags::empty(), None)
            .map(|m| m.into_unmount_drop(UnmountFlags::DETACH))
            .ok()
            .and_then(|_mount| detect_os_from_path(base))
    })
}

/// Detects the existence of an OS at a defined path.
///
/// This function is called by `detect_os_from_device`, after having temporarily mounted it.
pub fn detect_os_from_path(base: &Path) -> Option<OS> {
    detect_linux(base)
        .or_else(|| detect_windows(base))
        .or_else(|| detect_macos(base))
}

/// Detect if Linux is installed at the given path.
pub fn detect_linux(base: &Path) -> Option<OS> {
    let path = base.join("etc/os-release");
    if path.exists() {
        if let Ok(info) = OsRelease::new_from(path) {
            let (partitions, targets) = find_linux_parts(base);
            return Some(OS::Linux { info, partitions, targets });
        }
    }

    None
}

/// Detect if Mac OS is installed at the given path.
pub fn detect_macos(base: &Path) -> Option<OS> {
    open(base.join("etc/os-release"))
        .ok()
        .and_then(|file| {
            parse_plist(BufReader::new(file))
                .or_else(|| Some("Mac OS (Unknown)".into()))
                .map(OS::MacOs)
        })
}

/// Detect if Windows is installed at the given path.
pub fn detect_windows(base: &Path) -> Option<OS> {
    // TODO: More advanced version-specific detection is possible.
    base.join("Windows/System32/ntoskrnl.exe")
        .exists()
        .map(|| OS::Windows("Windows".into()))
}

fn find_linux_parts(base: &Path) -> (Vec<PartitionID>, Vec<PathBuf>) {
    let mut partitions = Vec::new();
    let mut targets = Vec::new();

    if let Ok(fstab) = open(base.join("etc/fstab")) {
        for entry in BufReader::new(fstab).lines() {
            if let Ok(entry) = entry {
                let entry = entry.trim();
                if entry.starts_with('#') || entry.is_empty() {
                    continue;
                }

                let mut fields = entry.split_whitespace();
                let source = fields.next();
                let target = fields.next();

                if let Some(target) = target {
                    if let Some(Ok(path)) = source.map(|s| s.parse::<PartitionID>()) {
                        partitions.push(path);
                        targets.push(PathBuf::from(String::from(target)));
                    }
                }
            }
        }
    }

    (partitions, targets)
}

fn parse_plist<R: BufRead>(file: R) -> Option<String> {
    // The plist is an XML file, but we don't need complex XML parsing for this.
    let mut product_name: Option<String> = None;
    let mut version: Option<String> = None;
    let mut flags = 0;

    for entry in file.lines().flat_map(|line| line) {
        let entry = entry.trim();
        match flags {
            0 => match entry {
                "<key>ProductUserVisibleVersion</key>" => flags = 1,
                "<key>ProductName</key>" => flags = 2,
                _ => (),
            },
            1 => {
                if entry.len() < 10 {
                    return None;
                }
                version = Some(entry[8..entry.len() - 9].into());
                flags = 0;
            }
            2 => {
                if entry.len() < 10 {
                    return None;
                }
                product_name = Some(entry[8..entry.len() - 9].into());
                flags = 0;
            }
            _ => unreachable!(),
        }
        if product_name.is_some() && version.is_some() {
            break;
        }
    }

    if let (Some(name), Some(version)) = (product_name, version) {
        Some(format!("{} ({})", name, version))
    } else {
        None
    }
}

fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
    File::open(&path).map_err(|why| io::Error::new(
        io::ErrorKind::Other,
        format!("unable to open file at {:?}: {}", path.as_ref(), why)
    ))
}

/// Adds a new map method for boolean types.
pub(crate) trait BoolExt {
    fn map<T, F: Fn() -> T>(&self, action: F) -> Option<T>;
}

impl BoolExt for bool {
    fn map<T, F: Fn() -> T>(&self, action: F) -> Option<T> {
        if *self {
            Some(action())
        } else {
            None
        }
    }
}

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

    const MAC_PLIST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "Apple Stuff">
<plist version="1.0">
<dict>
    <key>ProductBuildVersion</key>
    <string>10C540</string>
    <key>ProductName</key>
    <string>Mac OS X</string>
    <key>ProductUserVisibleVersion</key>
    <string>10.6.2</string>
    <key>ProductVersion</key>
    <string>10.6.2</string>
</dict>
</plist>"#;

    #[test]
    fn mac_plist_parsing() {
        assert_eq!(
            parse_plist(Cursor::new(MAC_PLIST)),
            Some("Mac OS X (10.6.2)".into())
        );
    }
}