1use serde::{Deserialize, Serialize};
24use std::fs::{File, OpenOptions};
25use std::io::{Seek, Write};
26#[cfg(unix)]
27use std::os::unix::fs::PermissionsExt;
28use std::path::{Path, PathBuf};
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct ServerLockIdentity {
35 pub schema_version: u32,
37 pub pid: u32,
39 #[serde(default)]
41 pub start_token: Option<String>,
42 pub nonce: String,
44 pub acquired_at_unix_ms: u64,
46}
47
48const SERVER_LOCK_NAME: &str = "snip-sync.server.lock";
49const SERVER_LOCK_SCHEMA_VERSION: u32 = 1;
50const LEGACY_PID_FILE_NAME: &str = "snip-sync.pid";
53
54#[derive(Debug)]
56pub enum ServerLockError {
57 Busy {
59 owner: Option<ServerLockIdentity>,
61 },
62 Io(std::io::Error),
64 UnsupportedPlatform,
66}
67
68impl std::fmt::Display for ServerLockError {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 match self {
71 Self::Busy { owner } => match owner {
72 Some(id) => write!(
73 f,
74 "snip-sync server already running (pid={}, nonce={})",
75 id.pid, id.nonce
76 ),
77 None => write!(f, "snip-sync server already running"),
78 },
79 Self::Io(e) => write!(f, "server lock io error: {e}"),
80 Self::UnsupportedPlatform => write!(
81 f,
82 "server lock is not supported on this platform; refusing to weaken exclusion"
83 ),
84 }
85 }
86}
87
88impl std::error::Error for ServerLockError {}
89
90impl From<std::io::Error> for ServerLockError {
91 fn from(e: std::io::Error) -> Self {
92 Self::Io(e)
93 }
94}
95
96#[derive(Debug)]
98pub struct ServerLock {
99 file: Option<File>,
100 path: PathBuf,
101 identity: ServerLockIdentity,
102}
103
104impl ServerLock {
105 pub fn path(&self) -> &Path {
107 &self.path
108 }
109
110 pub fn identity(&self) -> &ServerLockIdentity {
112 &self.identity
113 }
114
115 pub fn nonce(&self) -> &str {
117 &self.identity.nonce
118 }
119}
120
121impl Drop for ServerLock {
122 fn drop(&mut self) {
123 #[cfg(unix)]
124 release_unix_lock(self.file.as_ref());
125 #[cfg(windows)]
126 release_windows_lock(self.file.as_ref());
127 self.file = None;
128 }
129}
130
131#[cfg(unix)]
132fn release_unix_lock(file: Option<&File>) {
133 if let Some(file) = file {
134 use std::os::fd::AsRawFd;
135 unsafe {
136 libc::flock(file.as_raw_fd(), libc::LOCK_UN);
137 }
138 }
139}
140
141#[cfg(windows)]
142fn release_windows_lock(file: Option<&File>) {
143 if let Some(file) = file {
144 use std::os::windows::io::AsRawHandle;
145 use windows_sys::Win32::Storage::FileSystem::UnlockFileEx;
146 let handle = file.as_raw_handle();
147 let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
148 unsafe { std::mem::zeroed() };
149 overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
150 overlapped.Anonymous.Anonymous.OffsetHigh = 0;
151 unsafe {
152 UnlockFileEx(handle, 0, LOCKED_BYTE_COUNT, 0, &mut overlapped);
153 }
154 }
155}
156
157#[cfg(windows)]
158const LOCKED_BYTE_COUNT: u32 = 1;
159#[cfg(windows)]
164const LOCKED_BYTE_OFFSET: u32 = u32::MAX;
165
166pub fn server_lock_path(state_dir: &Path) -> PathBuf {
168 state_dir.join(SERVER_LOCK_NAME)
169}
170
171fn server_owner_path(lock_path: &Path) -> PathBuf {
178 let mut name = lock_path
179 .file_name()
180 .map(|name| name.to_os_string())
181 .unwrap_or_default();
182 name.push(".owner");
183 lock_path.with_file_name(name)
184}
185
186#[cfg(unix)]
189fn is_retryable_lock_error(error: &std::io::Error) -> bool {
190 error.raw_os_error() == Some(libc::EINTR)
191}
192
193#[cfg(not(unix))]
194fn is_retryable_lock_error(_error: &std::io::Error) -> bool {
195 false
196}
197
198#[cfg(unix)]
205fn acquire_unix_lock(file: &File) -> std::io::Result<bool> {
206 use std::os::fd::AsRawFd;
207 loop {
208 let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
209 if rc == 0 {
210 return Ok(true);
211 }
212 let error = std::io::Error::last_os_error();
213 if is_retryable_lock_error(&error) {
214 continue;
215 }
216 if matches!(error.raw_os_error(), Some(libc::EWOULDBLOCK)) {
217 return Ok(false);
218 }
219 return Err(error);
220 }
221}
222
223impl ServerLock {
224 pub fn try_acquire(state_dir: &Path) -> Result<Self, ServerLockError> {
226 let path = server_lock_path(state_dir);
227 if let Some(parent) = path.parent() {
228 std::fs::create_dir_all(parent)?;
229 }
230
231 let mut file = OpenOptions::new()
232 .read(true)
233 .write(true)
234 .create(true)
235 .truncate(false)
236 .open(&path)?;
237
238 #[cfg(unix)]
239 {
240 match acquire_unix_lock(&file) {
241 Ok(true) => {}
242 Ok(false) => {
243 let owner = busy_owner(state_dir, &path);
244 return Err(ServerLockError::Busy { owner });
245 }
246 Err(error) => return Err(ServerLockError::Io(error)),
247 }
248 }
249
250 #[cfg(windows)]
251 {
252 use std::os::windows::io::AsRawHandle;
253 use windows_sys::Win32::Storage::FileSystem::{
254 LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx,
255 };
256 let handle = file.as_raw_handle();
257 let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
258 unsafe { std::mem::zeroed() };
259 overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
260 overlapped.Anonymous.Anonymous.OffsetHigh = 0;
261 let ok = unsafe {
262 LockFileEx(
263 handle,
264 LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
265 0,
266 LOCKED_BYTE_COUNT,
267 0,
268 &mut overlapped,
269 )
270 };
271 if ok == 0 {
272 let err = std::io::Error::last_os_error();
273 if matches!(err.raw_os_error(), Some(33) | Some(32)) {
274 let owner = busy_owner(state_dir, &path);
275 return Err(ServerLockError::Busy { owner });
276 }
277 return Err(ServerLockError::Io(err));
278 }
279 }
280
281 #[cfg(not(any(unix, windows)))]
282 {
283 let _ = file;
284 return Err(ServerLockError::UnsupportedPlatform);
285 }
286
287 let identity = ServerLockIdentity {
288 schema_version: SERVER_LOCK_SCHEMA_VERSION,
289 pid: std::process::id(),
290 start_token: current_start_token(),
291 nonce: generate_nonce(),
292 acquired_at_unix_ms: unix_now_ms(),
293 };
294
295 #[cfg(unix)]
296 {
297 if let Ok(meta) = std::fs::metadata(&path) {
298 let mut perms = meta.permissions();
299 perms.set_mode(0o600);
300 let _ = std::fs::set_permissions(&path, perms);
301 }
302 }
303
304 if let Err(e) = publish_identity(&path, &mut file, &identity) {
305 #[cfg(unix)]
306 release_unix_lock(Some(&file));
307 #[cfg(windows)]
308 release_windows_lock(Some(&file));
309 return Err(ServerLockError::Io(e));
310 }
311
312 Ok(ServerLock {
313 file: Some(file),
314 path,
315 identity,
316 })
317 }
318}
319
320fn publish_identity(
327 lock_path: &Path,
328 file: &mut File,
329 identity: &ServerLockIdentity,
330) -> std::io::Result<()> {
331 let serialized = toml::to_string_pretty(identity)
332 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
333
334 publish_owner_sidecar(&server_owner_path(lock_path), serialized.as_bytes())?;
335
336 file.set_len(0)?;
337 file.seek(std::io::SeekFrom::Start(0))?;
338 file.write_all(serialized.as_bytes())?;
339 file.sync_all()?;
340 Ok(())
341}
342
343fn publish_owner_sidecar(owner_path: &Path, contents: &[u8]) -> std::io::Result<()> {
346 let parent = owner_path.parent().unwrap_or_else(|| Path::new("."));
347 let file_name = owner_path
348 .file_name()
349 .map(|name| name.to_string_lossy().into_owned())
350 .unwrap_or_else(|| format!("{SERVER_LOCK_NAME}.owner"));
351 let temp_path = parent.join(format!("{file_name}.tmp-{}", uuid::Uuid::new_v4()));
352
353 let write_result = (|| -> std::io::Result<()> {
354 let mut temp = {
355 #[cfg(unix)]
356 {
357 use std::os::unix::fs::OpenOptionsExt;
360 let mut options = OpenOptions::new();
361 options.write(true).create_new(true).mode(0o600);
362 options.open(&temp_path)
363 }
364 #[cfg(not(unix))]
365 {
366 OpenOptions::new()
367 .write(true)
368 .create_new(true)
369 .open(&temp_path)
370 }
371 }?;
372 temp.write_all(contents)?;
373 temp.sync_all()?;
374 Ok(())
375 })();
376 if let Err(error) = write_result {
377 let _ = std::fs::remove_file(&temp_path);
378 return Err(error);
379 }
380
381 if let Err(error) = std::fs::rename(&temp_path, owner_path) {
382 let _ = std::fs::remove_file(&temp_path);
383 return Err(error);
384 }
385
386 if let Ok(directory) = File::open(parent) {
388 let _ = directory.sync_all();
389 }
390 Ok(())
391}
392
393pub fn read_owner(path: &Path) -> Option<ServerLockIdentity> {
399 if let Some(identity) = read_identity_file(&server_owner_path(path)) {
400 return Some(identity);
401 }
402 read_identity_file(path)
403}
404
405fn read_identity_file(path: &Path) -> Option<ServerLockIdentity> {
406 let raw = std::fs::read_to_string(path).ok()?;
407 if raw.trim().is_empty() {
408 return None;
409 }
410 toml::from_str(&raw).ok()
411}
412
413fn busy_owner(state_dir: &Path, lock_path: &Path) -> Option<ServerLockIdentity> {
420 read_owner(lock_path).or_else(|| legacy_pid_owner(state_dir))
421}
422
423fn legacy_pid_owner(state_dir: &Path) -> Option<ServerLockIdentity> {
425 let pid_path = state_dir.join(LEGACY_PID_FILE_NAME);
426 let (pid, start_token) = match crate::process::parse_pid_file(&pid_path) {
427 crate::process::ParsedPidFile::Structured(record) => (record.pid, record.start_token),
428 crate::process::ParsedPidFile::LegacyPid(pid) => (pid, None),
429 crate::process::ParsedPidFile::Empty | crate::process::ParsedPidFile::Malformed(_) => {
430 return None;
431 }
432 };
433 Some(ServerLockIdentity {
434 schema_version: SERVER_LOCK_SCHEMA_VERSION,
435 pid,
436 start_token,
437 nonce: format!("legacy-pid-{pid}"),
438 acquired_at_unix_ms: unix_now_ms(),
441 })
442}
443
444fn unix_now_ms() -> u64 {
445 std::time::SystemTime::now()
446 .duration_since(std::time::SystemTime::UNIX_EPOCH)
447 .map(|d| d.as_millis() as u64)
448 .unwrap_or(0)
449}
450
451fn generate_nonce() -> String {
452 use std::sync::atomic::{AtomicU64, Ordering};
453 static COUNTER: AtomicU64 = AtomicU64::new(0);
454 let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
455 let nanos = std::time::SystemTime::now()
456 .duration_since(std::time::SystemTime::UNIX_EPOCH)
457 .map(|d| d.as_nanos())
458 .unwrap_or(0);
459 format!("{:x}-{:x}-{:x}", std::process::id(), nanos, seq)
460}
461
462fn current_start_token() -> Option<String> {
463 #[cfg(target_os = "linux")]
464 {
465 let pid = std::process::id();
466 let stat_path = format!("/proc/{pid}/stat");
467 let content = std::fs::read_to_string(&stat_path).ok()?;
468 parse_linux_proc_start_token(&content)
469 }
470 #[cfg(target_os = "macos")]
471 {
472 use libc::{PROC_PIDTBSDINFO, c_int, proc_bsdinfo, proc_pidinfo};
473 let pid = std::process::id();
474 let mut info: proc_bsdinfo = unsafe { std::mem::zeroed() };
475 let ret = unsafe {
476 proc_pidinfo(
477 pid as c_int,
478 PROC_PIDTBSDINFO,
479 0,
480 &mut info as *mut _ as *mut _,
481 std::mem::size_of::<proc_bsdinfo>() as i32,
482 )
483 };
484 if ret <= 0 {
485 return None;
486 }
487 Some(format!(
488 "{}.{:06}",
489 info.pbi_start_tvsec, info.pbi_start_tvusec
490 ))
491 }
492 #[cfg(windows)]
493 {
494 use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
495 use windows_sys::Win32::System::Threading::{
496 GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
497 };
498 unsafe {
499 let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, std::process::id());
500 if handle.is_null() {
501 return None;
502 }
503 let mut creation: FILETIME = std::mem::zeroed();
504 let mut exit_time: FILETIME = std::mem::zeroed();
505 let mut kernel_time: FILETIME = std::mem::zeroed();
506 let mut user_time: FILETIME = std::mem::zeroed();
507 let ok = GetProcessTimes(
508 handle,
509 &mut creation,
510 &mut exit_time,
511 &mut kernel_time,
512 &mut user_time,
513 );
514 CloseHandle(handle);
515 if ok == 0 {
516 return None;
517 }
518 let creation =
519 ((creation.dwHighDateTime as u64) << 32) | (creation.dwLowDateTime as u64);
520 Some(creation.to_string())
521 }
522 }
523 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
524 {
525 let _ = std::process::id();
526 None
527 }
528}
529
530#[cfg(target_os = "linux")]
531fn parse_linux_proc_start_token(stat: &str) -> Option<String> {
532 let after_comm = stat.rfind(')')?;
533 let fields: Vec<&str> = stat.get(after_comm + 2..)?.split_whitespace().collect();
534 fields.get(19).map(|value| (*value).to_owned())
535}
536
537#[cfg(test)]
538mod tests {
539 use super::*;
540
541 #[cfg(target_os = "linux")]
542 #[test]
543 fn linux_start_token_parser_reads_field_22() {
544 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";
545 assert_eq!(parse_linux_proc_start_token(stat), Some("START22".into()));
546 assert_ne!(parse_linux_proc_start_token(stat), Some("FIELD21".into()));
547 assert_eq!(parse_linux_proc_start_token("1 (short) S f3"), None);
548 }
549
550 #[test]
551 fn first_acquisition_succeeds() {
552 let dir = tempfile::TempDir::new().unwrap();
553 let guard = ServerLock::try_acquire(dir.path()).unwrap();
554 assert_eq!(guard.identity().pid, std::process::id());
555 assert!(!guard.identity().nonce.is_empty());
556 }
557
558 #[test]
559 fn second_acquisition_in_same_process_returns_busy() {
560 let dir = tempfile::TempDir::new().unwrap();
561 let _first = ServerLock::try_acquire(dir.path()).unwrap();
562 let second = ServerLock::try_acquire(dir.path());
563 match second {
564 Err(ServerLockError::Busy { owner }) => {
565 assert!(owner.is_some());
566 }
567 other => panic!("expected Busy, got {other:?}"),
568 }
569 }
570
571 #[test]
572 fn drop_allows_later_acquisition() {
573 let dir = tempfile::TempDir::new().unwrap();
574 let first = ServerLock::try_acquire(dir.path()).unwrap();
575 let nonce1 = first.nonce().to_string();
576 drop(first);
577 let second = ServerLock::try_acquire(dir.path()).unwrap();
578 assert_ne!(second.nonce(), nonce1);
579 }
580
581 #[test]
582 fn canonical_file_persists_after_release() {
583 let dir = tempfile::TempDir::new().unwrap();
584 {
585 let _g = ServerLock::try_acquire(dir.path()).unwrap();
586 }
587 assert!(server_lock_path(dir.path()).exists());
588 }
589
590 #[test]
591 fn empty_metadata_does_not_block_acquisition_when_lock_free() {
592 let dir = tempfile::TempDir::new().unwrap();
593 let path = server_lock_path(dir.path());
594 std::fs::write(&path, "").unwrap();
595 let guard = ServerLock::try_acquire(dir.path()).unwrap();
596 let observed = read_owner(&path).unwrap();
597 assert_eq!(observed.nonce, guard.nonce());
598 }
599
600 #[test]
601 fn malformed_metadata_does_not_block_acquisition_when_lock_free() {
602 let dir = tempfile::TempDir::new().unwrap();
603 let path = server_lock_path(dir.path());
604 std::fs::write(&path, "not valid toml").unwrap();
605 let guard = ServerLock::try_acquire(dir.path()).unwrap();
606 let observed = read_owner(&path).unwrap();
607 assert_eq!(observed.nonce, guard.nonce());
608 }
609
610 #[test]
611 fn identity_roundtrip() {
612 let id = ServerLockIdentity {
613 schema_version: 1,
614 pid: 12345,
615 start_token: Some("tok".to_string()),
616 nonce: "nonce".to_string(),
617 acquired_at_unix_ms: 999,
618 };
619 let s = toml::to_string_pretty(&id).unwrap();
620 let back: ServerLockIdentity = toml::from_str(&s).unwrap();
621 assert_eq!(id, back);
622 }
623
624 #[test]
625 fn busy_path_recovers_the_owner_when_the_lock_file_record_is_torn() {
626 let dir = tempfile::TempDir::new().unwrap();
627 let guard = ServerLock::try_acquire(dir.path()).unwrap();
628 let path = server_lock_path(dir.path());
629 std::fs::write(&path, "").unwrap();
632
633 match ServerLock::try_acquire(dir.path()) {
634 Err(ServerLockError::Busy { owner }) => {
635 let owner = owner.expect("the busy path must resolve an owner");
636 assert_eq!(owner.pid, std::process::id());
637 assert_eq!(owner.nonce, guard.nonce());
638 }
639 other => panic!("expected Busy, got {other:?}"),
640 }
641 }
642
643 #[test]
644 fn busy_path_falls_back_to_the_legacy_pid_file() {
645 let dir = tempfile::TempDir::new().unwrap();
646 let _guard = ServerLock::try_acquire(dir.path()).unwrap();
647 let path = server_lock_path(dir.path());
648 std::fs::write(&path, "").unwrap();
651 std::fs::remove_file(server_owner_path(&path)).unwrap();
652 std::fs::write(
653 dir.path().join(LEGACY_PID_FILE_NAME),
654 format!("{}\n", std::process::id()),
655 )
656 .unwrap();
657
658 match ServerLock::try_acquire(dir.path()) {
659 Err(ServerLockError::Busy { owner }) => {
660 let owner = owner.expect("the legacy PID file must resolve an owner");
661 assert_eq!(owner.pid, std::process::id());
662 }
663 other => panic!("expected Busy, got {other:?}"),
664 }
665 }
666
667 #[cfg(unix)]
668 #[test]
669 fn retryable_lock_error_is_only_eintr() {
670 let interrupted = std::io::Error::from_raw_os_error(libc::EINTR);
671 assert!(is_retryable_lock_error(&interrupted));
672
673 let would_block = std::io::Error::from_raw_os_error(libc::EAGAIN);
674 assert!(!is_retryable_lock_error(&would_block));
675
676 let other = std::io::Error::other("not an errno");
677 assert!(!is_retryable_lock_error(&other));
678 }
679}