1use std::path::Path;
25#[cfg(unix)]
28use std::path::PathBuf;
29
30pub const RESTART_MANAGER_SCRIPT: &str = include_str!("index_lock_restart_manager.ps1");
33
34pub const SILENT_DENIAL_NOTE: &str = "lsof omits other users' processes on macOS without reporting it";
36
37#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct Holder {
48 pub pid: i64,
50 pub command: Option<String>,
52}
53
54#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct HolderEvidence {
67 pub method: &'static str,
69 pub holders: Vec<Holder>,
71 pub partial: Vec<String>,
73}
74
75#[cfg(unix)]
86fn is_pid_name(name: &str) -> bool {
87 return !name.is_empty() && name.bytes().all(is_digit);
88}
89
90#[cfg(unix)]
100fn is_digit(byte: u8) -> bool {
101 return byte.is_ascii_digit();
102}
103
104#[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#[cfg(unix)]
140fn followed_identity(path: &Path) -> std::io::Result<(u64, u64)> {
141 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#[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#[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#[cfg(unix)]
265fn trimmed(text: String) -> String {
266 return String::from(super::js_text::trim_javascript(text.as_str()));
267}
268
269pub 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#[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 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#[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
393pub use super::index_lock_holder_parsers::{LsofProcess, matching_holders, parse_lsof_fields, parse_lsof_number, parse_restart_manager_output};
396
397#[cfg(test)]
399#[path = "index_lock_holders_tests.rs"]
400mod tests;