1use std::fs;
8use std::path::{Path, PathBuf};
9use std::time::{Duration, Instant};
10
11#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
12pub struct PidRecord {
13 #[serde(default = "default_schema_version")]
14 pub schema_version: u32,
15 pub pid: u32,
16 #[serde(default)]
17 pub start_token: Option<String>,
18 #[serde(default)]
19 pub nonce: Option<String>,
20}
21
22fn default_schema_version() -> u32 {
23 1
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ParsedPidFile {
29 Structured(PidRecord),
30 LegacyPid(u32),
31 Empty,
32 Malformed(String),
33}
34
35pub fn parse_pid_file(path: &Path) -> ParsedPidFile {
36 let raw = match fs::read_to_string(path) {
37 Ok(raw) => raw,
38 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
39 return ParsedPidFile::Empty;
40 }
41 Err(_) => return ParsedPidFile::Empty,
42 };
43 let trimmed = raw.trim();
44 if trimmed.is_empty() {
45 return ParsedPidFile::Empty;
46 }
47 if let Ok(pid) = trimmed.parse::<u32>() {
48 return if pid == 0 {
49 ParsedPidFile::Malformed("PID must be nonzero".to_string())
50 } else {
51 ParsedPidFile::LegacyPid(pid)
52 };
53 }
54 match toml::from_str::<PidRecord>(trimmed) {
55 Ok(record) if record.pid != 0 => ParsedPidFile::Structured(record),
56 Ok(_) => ParsedPidFile::Malformed("PID must be nonzero".to_string()),
57 Err(error) => ParsedPidFile::Malformed(error.to_string()),
58 }
59}
60
61#[doc(hidden)]
64pub fn remove_pid_if_unchanged(expected: &ParsedPidFile) {
65 let path = crate::paths::pid_path();
66 let matches = match (expected, parse_pid_file(&path)) {
67 (ParsedPidFile::LegacyPid(expected), ParsedPidFile::LegacyPid(current)) => {
68 expected == ¤t
69 }
70 (ParsedPidFile::Structured(expected), ParsedPidFile::Structured(current)) => {
71 expected == ¤t
72 }
73 _ => false,
74 };
75 if matches {
76 let _ = fs::remove_file(path);
77 }
78}
79
80pub fn read_pid() -> Option<u32> {
81 match parse_pid_file(&crate::paths::pid_path()) {
82 ParsedPidFile::Structured(record) => Some(record.pid),
83 ParsedPidFile::LegacyPid(pid) => Some(pid),
84 _ => None,
85 }
86}
87
88#[cfg(unix)]
89pub fn is_running(pid: u32) -> bool {
90 if pid == 0 {
91 return false;
92 }
93 let Ok(pid) = i32::try_from(pid) else {
94 return false;
95 };
96 let result = unsafe { libc::kill(pid, 0) };
97 result == 0
98 || !matches!(
99 std::io::Error::last_os_error().raw_os_error(),
100 Some(libc::ESRCH)
101 )
102}
103
104#[cfg(windows)]
105pub fn is_running(pid: u32) -> bool {
106 if pid == 0 {
107 return false;
108 }
109 unsafe {
110 use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
111 use windows_sys::Win32::System::Threading::{
112 GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
113 };
114 let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
115 if handle.is_null() {
116 return false;
117 }
118 let mut exit_code = 0;
119 let ok = GetExitCodeProcess(handle, &mut exit_code);
120 CloseHandle(handle);
121 ok != 0 && exit_code == STILL_ACTIVE as u32
122 }
123}
124
125#[cfg(not(any(unix, windows)))]
126pub fn is_running(_pid: u32) -> bool {
127 false
128}
129
130pub fn record_still_matches(record: &PidRecord) -> bool {
131 if !is_running(record.pid) {
132 return false;
133 }
134 let Some(expected) = &record.start_token else {
135 return true;
136 };
137 get_process_start_token(record.pid).is_none_or(|observed| observed == *expected)
138}
139
140#[cfg(unix)]
141pub fn validate_process_name(pid: u32) -> bool {
142 let output = std::process::Command::new("ps")
143 .args(["-p", &pid.to_string(), "-o", "comm="])
144 .output();
145 match output {
146 Ok(output) => is_snip_sync_process_name(String::from_utf8_lossy(&output.stdout).trim()),
147 Err(_) => false,
148 }
149}
150
151fn is_snip_sync_process_name(name: &str) -> bool {
152 name == "snip-sync"
153}
154
155#[cfg(not(unix))]
156pub fn validate_process_name(_pid: u32) -> bool {
157 false
158}
159
160pub fn wait_for_exit(pid: u32, timeout: Duration) -> Result<(), String> {
161 let deadline = Instant::now() + timeout;
162 loop {
163 if !is_running(pid) {
164 return Ok(());
165 }
166 if Instant::now() >= deadline {
167 return Err(format!(
168 "Process {} did not exit within {}s",
169 pid,
170 timeout.as_secs()
171 ));
172 }
173 std::thread::sleep(Duration::from_millis(200));
174 }
175}
176
177pub struct LockGuard {
179 #[allow(dead_code)]
183 file: fs::File,
184 path: PathBuf,
185 remove_on_drop: bool,
186}
187
188impl Drop for LockGuard {
189 fn drop(&mut self) {
190 #[cfg(windows)]
191 {
192 use std::os::windows::io::AsRawHandle;
193 use windows_sys::Win32::Storage::FileSystem::UnlockFileEx;
194 let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
195 unsafe { std::mem::zeroed() };
196 overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
197 unsafe {
198 UnlockFileEx(
199 self.file.as_raw_handle(),
200 0,
201 LOCKED_BYTE_COUNT,
202 0,
203 &mut overlapped,
204 );
205 }
206 }
207 if self.remove_on_drop {
208 let _ = fs::remove_file(&self.path);
209 }
210 }
211}
212
213pub fn try_lock(path: &Path) -> Result<Option<LockGuard>, String> {
214 if let Some(parent) = path.parent() {
215 fs::create_dir_all(parent)
216 .map_err(|error| format!("Failed to create lock directory: {error}"))?;
217 }
218
219 #[cfg(unix)]
220 {
221 use std::os::fd::AsRawFd;
222 let file = fs::OpenOptions::new()
223 .write(true)
224 .create(true)
225 .truncate(false)
226 .open(path)
227 .map_err(|error| format!("Failed to open lock file {}: {error}", path.display()))?;
228 let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
229 if result == 0 {
230 return Ok(Some(LockGuard {
231 file,
232 path: path.to_path_buf(),
233 remove_on_drop: false,
234 }));
235 }
236 if std::io::Error::last_os_error().kind() == std::io::ErrorKind::WouldBlock {
237 return Ok(None);
238 }
239 Err(format!(
240 "Failed to lock {}: {}",
241 path.display(),
242 std::io::Error::last_os_error()
243 ))
244 }
245
246 #[cfg(not(unix))]
247 {
248 #[cfg(windows)]
249 {
250 use std::os::windows::io::AsRawHandle;
251 use windows_sys::Win32::Storage::FileSystem::{
252 LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx,
253 };
254 let file = fs::OpenOptions::new()
255 .read(true)
256 .write(true)
257 .create(true)
258 .truncate(false)
259 .open(path)
260 .map_err(|error| format!("Failed to open lock file {}: {error}", path.display()))?;
261 let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
262 unsafe { std::mem::zeroed() };
263 overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
264 let ok = unsafe {
265 LockFileEx(
266 file.as_raw_handle(),
267 LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
268 0,
269 LOCKED_BYTE_COUNT,
270 0,
271 &mut overlapped,
272 )
273 };
274 if ok == 0 {
275 let error = std::io::Error::last_os_error();
276 if matches!(error.raw_os_error(), Some(32) | Some(33)) {
277 return Ok(None);
278 }
279 return Err(format!("Failed to lock {}: {error}", path.display()));
280 }
281 return Ok(Some(LockGuard {
282 file,
283 path: path.to_path_buf(),
284 remove_on_drop: false,
285 }));
286 }
287
288 #[cfg(not(windows))]
289 match fs::OpenOptions::new()
290 .write(true)
291 .create_new(true)
292 .open(path)
293 {
294 Ok(file) => Ok(Some(LockGuard {
295 file,
296 path: path.to_path_buf(),
297 remove_on_drop: true,
298 })),
299 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(None),
300 Err(error) => Err(format!("Failed to lock {}: {error}", path.display())),
301 }
302 }
303}
304
305#[cfg(windows)]
306const LOCKED_BYTE_COUNT: u32 = 1;
307
308#[cfg(windows)]
309const LOCKED_BYTE_OFFSET: u32 = u32::MAX;
310
311#[cfg(windows)]
312pub fn terminate_process(pid: u32, timeout: Duration) -> Result<(), String> {
313 use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0, WAIT_TIMEOUT};
314 use windows_sys::Win32::System::Threading::{
315 OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject,
316 };
317
318 let handle = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, 0, pid) };
319 if handle.is_null() {
320 return Err(format!(
321 "failed to open recorded server process {pid}: {}",
322 std::io::Error::last_os_error()
323 ));
324 }
325 let terminated = unsafe { TerminateProcess(handle, 1) } != 0;
326 if !terminated {
327 let error = std::io::Error::last_os_error();
328 unsafe { CloseHandle(handle) };
329 return Err(format!(
330 "failed to terminate recorded server process {pid}: {error}"
331 ));
332 }
333 let wait_ms = timeout.as_millis().min(u32::MAX as u128) as u32;
334 let result = unsafe { WaitForSingleObject(handle, wait_ms) };
335 unsafe { CloseHandle(handle) };
336 match result {
337 WAIT_OBJECT_0 => Ok(()),
338 WAIT_TIMEOUT => Err(format!(
339 "process {pid} did not exit within {}s",
340 timeout.as_secs()
341 )),
342 _ => Err(format!(
343 "failed waiting for process {pid}: {}",
344 std::io::Error::last_os_error()
345 )),
346 }
347}
348
349#[cfg(target_os = "linux")]
350pub fn get_process_start_token(pid: u32) -> Option<String> {
351 let content = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
352 parse_linux_proc_start_token(&content)
353}
354
355#[cfg(target_os = "linux")]
356fn parse_linux_proc_start_token(stat: &str) -> Option<String> {
357 let after_comm = stat.rfind(')')?;
358 stat.get(after_comm + 2..)?
359 .split_whitespace()
360 .nth(19)
361 .map(str::to_owned)
362}
363
364#[cfg(target_os = "macos")]
365pub fn get_process_start_token(pid: u32) -> Option<String> {
366 use libc::{PROC_PIDTBSDINFO, proc_bsdinfo, proc_pidinfo};
367 let pid = i32::try_from(pid).ok()?;
368 let mut info: proc_bsdinfo = unsafe { std::mem::zeroed() };
369 let result = unsafe {
370 proc_pidinfo(
371 pid,
372 PROC_PIDTBSDINFO,
373 0,
374 &mut info as *mut _ as *mut _,
375 std::mem::size_of::<proc_bsdinfo>() as i32,
376 )
377 };
378 (result > 0).then(|| format!("{}.{:06}", info.pbi_start_tvsec, info.pbi_start_tvusec))
379}
380
381#[cfg(windows)]
382pub fn get_process_start_token(pid: u32) -> Option<String> {
383 use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
384 use windows_sys::Win32::System::Threading::{
385 GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
386 };
387 unsafe {
388 let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
389 if handle.is_null() {
390 return None;
391 }
392 let mut creation: FILETIME = std::mem::zeroed();
393 let mut exit: FILETIME = std::mem::zeroed();
394 let mut kernel: FILETIME = std::mem::zeroed();
395 let mut user: FILETIME = std::mem::zeroed();
396 let ok = GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user);
397 CloseHandle(handle);
398 (ok != 0).then(|| {
399 (((creation.dwHighDateTime as u64) << 32) | creation.dwLowDateTime as u64).to_string()
400 })
401 }
402}
403
404#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
405pub fn get_process_start_token(_pid: u32) -> Option<String> {
406 None
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 #[test]
414 fn process_name_requires_exact_match() {
415 assert!(is_snip_sync_process_name("snip-sync"));
416 assert!(!is_snip_sync_process_name("snip-sync-dev"));
417 assert!(!is_snip_sync_process_name("not-snip-sync"));
418 }
419
420 #[cfg(target_os = "linux")]
421 #[test]
422 fn linux_start_token_parser_reads_field_22() {
423 let stat = "42 (name with ) parens) S f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 FIELD21 START22";
424 assert_eq!(parse_linux_proc_start_token(stat), Some("START22".into()));
425 assert_eq!(parse_linux_proc_start_token("1 (short) S f3"), None);
426 }
427
428 #[test]
429 fn test_parse_pid_file_legacy_numeric() {
430 let temp = tempfile::tempdir().unwrap();
431 let path = temp.path().join("snip-sync.pid");
432 fs::write(&path, "1234\n").unwrap();
433 assert_eq!(parse_pid_file(&path), ParsedPidFile::LegacyPid(1234));
434 }
435
436 #[test]
437 fn test_parse_pid_file_rejects_zero() {
438 let temp = tempfile::tempdir().unwrap();
439 let path = temp.path().join("snip-sync.pid");
440 fs::write(&path, "0\n").unwrap();
441 assert!(matches!(parse_pid_file(&path), ParsedPidFile::Malformed(_)));
442 }
443
444 #[test]
445 fn test_remove_legacy_pid_only_when_unchanged() {
446 let temp = tempfile::tempdir().unwrap();
447 let path = temp.path().join("snip-sync.pid");
448 fs::write(&path, "1234\n").unwrap();
449 remove_pid_if_unchanged_at(&path, &ParsedPidFile::LegacyPid(9999));
450 assert!(path.exists());
451 remove_pid_if_unchanged_at(&path, &ParsedPidFile::LegacyPid(1234));
452 assert!(!path.exists());
453 }
454
455 #[cfg(windows)]
456 #[test]
457 fn stale_on_disk_lock_file_does_not_block_kernel_lock() {
458 let temp = tempfile::tempdir().unwrap();
459 let path = temp.path().join("croncheck.lock");
460 fs::write(&path, "stale").unwrap();
461 let guard = try_lock(&path)
462 .unwrap()
463 .expect("stale file must not own lock");
464 drop(guard);
465 assert!(
466 path.exists(),
467 "kernel lock release must not depend on unlinking"
468 );
469 }
470
471 fn remove_pid_if_unchanged_at(path: &Path, expected: &ParsedPidFile) {
472 let matches = match (expected, parse_pid_file(path)) {
473 (ParsedPidFile::LegacyPid(expected), ParsedPidFile::LegacyPid(current)) => {
474 expected == ¤t
475 }
476 _ => false,
477 };
478 if matches {
479 let _ = fs::remove_file(path);
480 }
481 }
482}