Debian Codegraph @

src/helpers.rs

raw
1 use std::io::Read;
2
3 pub(crate) fn is_flatpak() -> bool {
4 std::path::PathBuf::from("/.flatpak-info").exists()
5 }
6
7 pub(crate) fn is_snap() -> bool {
8 let pid = std::process::id();
9 let path = format!("/proc/{pid}/cgroup");
10 let mut file = match std::fs::File::open(path) {
11 Ok(file) => file,
12 Err(_) => return false,
13 };
14
15 let mut buffer = String::new();
16 match file.read_to_string(&mut buffer) {
17 Ok(_) => cgroup_v2_is_snap(&buffer),
18 Err(_) => false,
19 }
20 }
21
22 fn cgroup_v2_is_snap(cgroups: &str) -> bool {
23 cgroups
24 .lines()
25 .map(|line| {
26 let (n, rest) = line.split_once(':')?;
27 // Check that n is a number.
28 n.parse::<u32>().ok()?;
29 let unit = match rest.split_once(':') {
30 Some(("", unit)) => Some(unit),
31 Some(("freezer", unit)) => Some(unit),
32 Some(("name=systemd", unit)) => Some(unit),
33 _ => None,
34 }?;
35 let scope = std::path::Path::new(unit).file_name()?.to_str()?;
36
37 Some(scope.starts_with("snap."))
38 })
39 .any(|x| x.unwrap_or(false))
40 }
41
42 #[cfg(test)]
43 mod tests {
44 use super::*;
45
46 #[test]
47 fn test_cgroup_v2_is_snap() {
48 let data =
49 "0::/user.slice/user-1000.slice/[email protected]/apps.slice/snap.something.scope\n";
50 assert!(cgroup_v2_is_snap(data));
51
52 let data = "0::/user.slice/user-1000.slice/[email protected]/apps.slice\n";
53 assert!(!cgroup_v2_is_snap(data));
54
55 let data = "12:pids:/user.slice/user-1000.slice/[email protected]
56 11:perf_event:/
57 10:net_cls,net_prio:/
58 9:cpuset:/
59 8:memory:/user.slice/user-1000.slice/[email protected]/apps.slice/apps-org.gnome.Terminal.slice/vte-spawn-228ae109-a869-4533-8988-65ea4c10b492.scope
60 7:rdma:/
61 6:devices:/user.slice
62 5:blkio:/user.slice
63 4:hugetlb:/
64 3:freezer:/snap.portal-test
65 2:cpu,cpuacct:/user.slice
66 1:name=systemd:/user.slice/user-1000.slice/[email protected]/apps.slice/apps-org.gnome.Terminal.slice/vte-spawn-228ae109-a869-4533-8988-65ea4c10b492.scope
67 0::/user.slice/user-1000.slice/[email protected]/apps.slice/apps-org.gnome.Terminal.slice/vte-spawn-228ae109-a869-4533-8988-65ea4c10b492.scope\n";
68 assert!(cgroup_v2_is_snap(data));
69 }
70 }