Skip to main content

git_policy_cli/
index_lock_holders.rs

1//! What:
2//!  Processes holding a lock file open,
3//!  found by device and inode:
4//!  `/proc/<pid>/fd` on
5//!       Linux,
6//!  `lsof` on macOS,
7//!  the Restart Manager on Windows.
8//! Why:
9//!  An open descriptor proves a live owner.
10//!  Matching by device and inode,
11//!  never by path text,
12//!      means bind mounts and renamed paths cannot fake or hide a holder.
13//!  Processes the scan
14//!      cannot read are partial evidence (`src/index-lock/index-lock-holders-linux.ts`,
15//!      `-darwin.ts`,
16//!  `-win32.ts`).
17//!
18//! In TS you'd write (pseudocode):
19//! ```ts
20//! const evidence = await scanPlatformHolders({ lockPath, lock });
21//! ```
22
23/// `Path`/`PathBuf` are borrowed/owned filesystem paths.
24use std::path::Path;
25/// `PathBuf` is an owned filesystem path,
26///  used by the Unix proc scan.
27#[cfg(unix)]
28use std::path::PathBuf;
29
30/// The incumbent's Restart Manager script,
31///  byte for byte.
32pub const RESTART_MANAGER_SCRIPT: &str = include_str!("index_lock_restart_manager.ps1");
33
34/// Partial-evidence note every unprivileged macOS scan carries.
35pub const SILENT_DENIAL_NOTE: &str = "lsof omits other users' processes on macOS without reporting it";
36
37/// What:
38///  One process holding the lock open.
39/// Why:
40///   `LockHolderProcess`.
41///
42/// In TS you'd write (pseudocode):
43/// ```ts
44/// type LockHolderProcess = { pid: number; command?: string };
45/// ```
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct Holder {
48    /// Holder process ID.
49    pub pid: i64,
50    /// Holder command name when readable.
51    pub command: Option<String>,
52}
53
54/// What:
55///  The scan mechanism,
56///  its holders,
57///  and what it could not see.
58/// Why:
59///   `LockHolderEvidence`.
60///
61/// In TS you'd write (pseudocode):
62/// ```ts
63/// type LockHolderEvidence = { method: 'proc-fd' | 'lsof' | 'restart-manager' | 'unsupported'; holders; partial };
64/// ```
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct HolderEvidence {
67    /// Scan mechanism name.
68    pub method: &'static str,
69    /// Processes holding the lock open.
70    pub holders: Vec<Holder>,
71    /// Reasons the scan could not see everything.
72    pub partial: Vec<String>,
73}
74
75/// What:
76///  Whether a directory name is a decimal PID.
77/// Why:
78///   `/proc` also holds `self`,
79///  `sys` and others.
80///
81/// In TS you'd write (pseudocode):
82/// ```ts
83/// name.length > 0 && isAsciiDigits(name)
84/// ```
85#[cfg(unix)]
86fn is_pid_name(name: &str) -> bool {
87    return !name.is_empty() && name.bytes().all(is_digit);
88}
89
90/// What:
91///  Whether a byte is an ASCII digit.
92/// Why:
93///   A named predicate keeps the scans free of closures.
94///
95/// In TS you'd write (pseudocode):
96/// ```ts
97/// (byte: number) => byte >= 0x30 && byte <= 0x39
98/// ```
99#[cfg(unix)]
100fn is_digit(byte: u8) -> bool {
101    return byte.is_ascii_digit();
102}
103
104/// What:
105///  Whether an error means the process exited during the scan.
106/// Why:
107///   `ENOENT` and `ESRCH` are expected races,
108///  never partial evidence.
109///
110/// In TS you'd write (pseudocode):
111/// ```ts
112/// ['ENOENT', 'ESRCH'].includes(error.code)
113/// ```
114#[cfg(unix)]
115fn exited(error: &std::io::Error) -> bool {
116    if error.kind() == std::io::ErrorKind::NotFound {
117        return true;
118    }
119    #[cfg(unix)]
120    {
121        return error.raw_os_error() == Some(libc::ESRCH);
122    }
123    #[cfg(not(unix))]
124    {
125        return false;
126    }
127}
128
129/// What:
130///  The device and inode a path names after following links,
131///  as numbers.
132/// Why:
133///   A descriptor link resolves to the open file itself.
134///
135/// In TS you'd write (pseudocode):
136/// ```ts
137/// const { dev, ino } = await stat(path, { bigint: true });
138/// ```
139#[cfg(unix)]
140fn followed_identity(path: &Path) -> std::io::Result<(u64, u64)> {
141    /// The Unix metadata accessors,
142    ///  for the device and inode.
143    use std::os::unix::fs::MetadataExt;
144    let metadata: std::fs::Metadata = std::fs::metadata(path)?;
145    return Ok((metadata.dev(), metadata.ino()));
146}
147
148/// What:
149///  Whether one process holds the file open,
150///  and why its descriptors were unreadable.
151/// Why:
152///   `scanProcess`:
153///  the first unreadable descriptor's reason is kept.
154///
155/// In TS you'd write (pseudocode):
156/// ```ts
157/// async function scanProcess({ procRoot, pid, device, inode }): Promise<{ holds: boolean; partial?: string }>;
158/// ```
159#[cfg(unix)]
160fn scan_process(proc_root: &Path, pid: &str, device: u64, inode: u64) -> (bool, Option<String>) {
161    let fd_directory: PathBuf = proc_root.join(pid).join("fd");
162    let listing: std::fs::ReadDir = match std::fs::read_dir(&fd_directory) {
163        Ok(found) => found,
164        Err(error) if exited(&error) => return (false, None),
165        Err(error) => return (false, Some(format!("PID {pid}: {error}"))),
166    };
167    let mut holds: bool = false;
168    let mut partial: Option<String> = None;
169    for item in listing {
170        let Ok(entry) = item else {
171            continue;
172        };
173        match followed_identity(entry.path().as_path()) {
174            Ok((found_device, found_inode)) => {
175                if found_device == device && found_inode == inode {
176                    holds = true;
177                }
178            }
179            Err(error) if exited(&error) => {}
180            Err(error) => {
181                if partial.is_none() {
182                    partial = Some(format!(
183                        "PID {pid} fd {}: {error}",
184                        entry.file_name().to_string_lossy()
185                    ));
186                }
187            }
188        }
189    }
190    return (holds, partial);
191}
192
193/// What:
194///  Every process other than this one holding a file open,
195///  by device and inode,
196///  through a
197///       proc root.
198/// Why:
199///   `scanProcFdHolders`;
200///  processes are scanned one after another (the incumbent runs 16 at
201///       once;
202///  the result is the same set).
203///
204/// In TS you'd write (pseudocode):
205/// ```ts
206/// async function scanProcFdHolders({ device, inode, procRoot, selfPid }): Promise<LockHolderEvidence>;
207/// ```
208#[cfg(unix)]
209pub fn scan_proc_fd_holders(proc_root: &Path, device: u64, inode: u64, self_pid: u32) -> HolderEvidence {
210    let mut evidence: HolderEvidence = HolderEvidence {
211        method: "proc-fd",
212        holders: Vec::new(),
213        partial: Vec::new(),
214    };
215    let listing: std::fs::ReadDir = match std::fs::read_dir(proc_root) {
216        Ok(found) => found,
217        Err(error) => {
218            evidence.partial.push(format!("{}: {error}", proc_root.display()));
219            return evidence;
220        }
221    };
222    let own: String = self_pid.to_string();
223    let mut pids: Vec<String> = Vec::new();
224    for item in listing.flatten() {
225        let name: String = item.file_name().to_string_lossy().into_owned();
226        if is_pid_name(name.as_str()) && name != own {
227            pids.push(name);
228        }
229    }
230    for pid in &pids {
231        let (holds, partial) = scan_process(proc_root, pid.as_str(), device, inode);
232        if holds && let Ok(number) = pid.parse::<i64>() {
233            let command: Option<String> = std::fs::read_to_string(proc_root.join(pid).join("comm"))
234                .ok()
235                .map(trimmed);
236            evidence.holders.push(Holder { pid: number, command });
237        }
238        if let Some(reason) = partial {
239            evidence.partial.push(reason);
240        }
241    }
242    super::diagnostic_log::debug(
243        "scanProcFdHolders",
244        format!(
245            "scanned {} processes: {} holders, {} unreadable",
246            pids.len(),
247            evidence.holders.len(),
248            evidence.partial.len()
249        )
250        .as_str(),
251    );
252    return evidence;
253}
254
255/// What:
256///  Text without surrounding whitespace.
257/// Why:
258///   A named function keeps `map` free of closures.
259///
260/// In TS you'd write (pseudocode):
261/// ```ts
262/// (text: string) => text.trim()
263/// ```
264#[cfg(unix)]
265fn trimmed(text: String) -> String {
266    return String::from(super::js_text::trim_javascript(text.as_str()));
267}
268
269/// What:
270///  Scan for open holders with the host's mechanism.
271/// Why:
272///   `scanPlatformHolders`.
273///
274/// In TS you'd write (pseudocode):
275/// ```ts
276/// async function scanPlatformHolders({ lockPath, lock }): Promise<LockHolderEvidence>;
277/// ```
278pub fn scan_platform_holders(lock_path: &Path, device: u64, inode: u64) -> HolderEvidence {
279    #[cfg(target_os = "linux")]
280    {
281        let _ = lock_path;
282        return scan_proc_fd_holders(Path::new("/proc"), device, inode, std::process::id());
283    }
284    #[cfg(target_os = "macos")]
285    {
286        return scan_lsof_holders(lock_path, device, inode);
287    }
288    #[cfg(windows)]
289    {
290        let _ = (device, inode);
291        return scan_restart_manager_holders(lock_path);
292    }
293    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
294    {
295        let _ = (lock_path, device, inode);
296        return HolderEvidence {
297            method: "unsupported",
298            holders: Vec::new(),
299            partial: vec![String::from("no open-holder scan on this platform")],
300        };
301    }
302}
303
304/// What:
305///  Holders through `lsof -n -P -w -F pcDi -- <lock>`;
306///  exit 1 with output means "no match".
307/// Why:
308///   `scanLsofHolders`;
309///  an unprivileged scan always notes that macOS hides other users.
310///
311/// In TS you'd write (pseudocode):
312/// ```ts
313/// async function scanLsofHolders({ lockPath, device, inode }): Promise<LockHolderEvidence>;
314/// ```
315#[cfg(target_os = "macos")]
316fn scan_lsof_holders(lock_path: &Path, device: u64, inode: u64) -> HolderEvidence {
317    let output: std::io::Result<std::process::Output> = std::process::Command::new("lsof")
318        .args(["-n", "-P", "-w", "-F", "pcDi", "--"])
319        .arg(lock_path)
320        .env("LC_ALL", "C")
321        .stdin(std::process::Stdio::null())
322        .output();
323    let stdout: String = match output {
324        Ok(finished) if finished.status.success() || finished.status.code() == Some(1) => {
325            String::from_utf8_lossy(finished.stdout.as_slice()).into_owned()
326        }
327        Ok(finished) => {
328            return HolderEvidence {
329                method: "lsof",
330                holders: Vec::new(),
331                partial: vec![format!("lsof failed: exit {:?}", finished.status.code())],
332            };
333        }
334        Err(error) => {
335            return HolderEvidence {
336                method: "lsof",
337                holders: Vec::new(),
338                partial: vec![format!("lsof failed: {error}")],
339            };
340        }
341    };
342    // SAFETY: `getuid` has no preconditions.
343    let root: bool = unsafe { libc::getuid() } == 0;
344    return HolderEvidence {
345        method: "lsof",
346        holders: matching_holders(parse_lsof_fields(stdout.as_str()).as_slice(), device, inode),
347        partial: if root { Vec::new() } else { vec![String::from(SILENT_DENIAL_NOTE)] },
348    };
349}
350
351/// What:
352///  Holders through the Restart Manager script,
353///  the path passed in `CLI_GIT_RM_TARGET`.
354/// Why:
355///   `scanRestartManagerHolders`.
356///
357/// In TS you'd write (pseudocode):
358/// ```ts
359/// async function scanRestartManagerHolders(lockPath: string): Promise<LockHolderEvidence>;
360/// ```
361#[cfg(windows)]
362fn scan_restart_manager_holders(lock_path: &Path) -> HolderEvidence {
363    let output: std::io::Result<std::process::Output> = std::process::Command::new("powershell.exe")
364        .args(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", RESTART_MANAGER_SCRIPT])
365        .env("CLI_GIT_RM_TARGET", lock_path)
366        .stdin(std::process::Stdio::null())
367        .output();
368    match output {
369        Ok(finished) if finished.status.success() => {
370            return HolderEvidence {
371                method: "restart-manager",
372                holders: parse_restart_manager_output(String::from_utf8_lossy(finished.stdout.as_slice()).as_ref()),
373                partial: Vec::new(),
374            };
375        }
376        Ok(finished) => {
377            return HolderEvidence {
378                method: "restart-manager",
379                holders: Vec::new(),
380                partial: vec![format!("Restart Manager query failed: exit {:?}", finished.status.code())],
381            };
382        }
383        Err(error) => {
384            return HolderEvidence {
385                method: "restart-manager",
386                holders: Vec::new(),
387                partial: vec![format!("Restart Manager query failed: {error}")],
388            };
389        }
390    }
391}
392
393/// Holders found by the parsers,
394///  re-exported for the scans and their controls.
395pub use super::index_lock_holder_parsers::{LsofProcess, matching_holders, parse_lsof_fields, parse_lsof_number, parse_restart_manager_output};
396
397/// Holder-scan controls stay out of the release executable.
398#[cfg(test)]
399#[path = "index_lock_holders_tests.rs"]
400mod tests;