snip-sync 0.2.0

gRPC sync server for snp snippet manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Process helpers used by stop/restart and the croncheck maintenance lock.
//!
//! The kernel-backed server lock is the current owner record. This module
//! only parses old PID files as a bounded upgrade fallback and provides
//! process-identity checks before a signal is sent.

use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct PidRecord {
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,
    pub pid: u32,
    #[serde(default)]
    pub start_token: Option<String>,
    #[serde(default)]
    pub nonce: Option<String>,
}

fn default_schema_version() -> u32 {
    1
}

/// PID-file formats retained only for upgrades from older releases.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsedPidFile {
    Structured(PidRecord),
    LegacyPid(u32),
    Empty,
    Malformed(String),
}

pub fn parse_pid_file(path: &Path) -> ParsedPidFile {
    let raw = match fs::read_to_string(path) {
        Ok(raw) => raw,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return ParsedPidFile::Empty;
        }
        Err(_) => return ParsedPidFile::Empty,
    };
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return ParsedPidFile::Empty;
    }
    if let Ok(pid) = trimmed.parse::<u32>() {
        return if pid == 0 {
            ParsedPidFile::Malformed("PID must be nonzero".to_string())
        } else {
            ParsedPidFile::LegacyPid(pid)
        };
    }
    match toml::from_str::<PidRecord>(trimmed) {
        Ok(record) if record.pid != 0 => ParsedPidFile::Structured(record),
        Ok(_) => ParsedPidFile::Malformed("PID must be nonzero".to_string()),
        Err(error) => ParsedPidFile::Malformed(error.to_string()),
    }
}

/// Remove an old PID file only when it still contains the record the caller
/// inspected. Current servers never create this file.
#[doc(hidden)]
pub fn remove_pid_if_unchanged(expected: &ParsedPidFile) {
    let path = crate::paths::pid_path();
    let matches = match (expected, parse_pid_file(&path)) {
        (ParsedPidFile::LegacyPid(expected), ParsedPidFile::LegacyPid(current)) => {
            expected == &current
        }
        (ParsedPidFile::Structured(expected), ParsedPidFile::Structured(current)) => {
            expected == &current
        }
        _ => false,
    };
    if matches {
        let _ = fs::remove_file(path);
    }
}

pub fn read_pid() -> Option<u32> {
    match parse_pid_file(&crate::paths::pid_path()) {
        ParsedPidFile::Structured(record) => Some(record.pid),
        ParsedPidFile::LegacyPid(pid) => Some(pid),
        _ => None,
    }
}

#[cfg(unix)]
pub fn is_running(pid: u32) -> bool {
    if pid == 0 {
        return false;
    }
    let Ok(pid) = i32::try_from(pid) else {
        return false;
    };
    let result = unsafe { libc::kill(pid, 0) };
    result == 0
        || !matches!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::ESRCH)
        )
}

#[cfg(windows)]
pub fn is_running(pid: u32) -> bool {
    if pid == 0 {
        return false;
    }
    unsafe {
        use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
        use windows_sys::Win32::System::Threading::{
            GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
        };
        let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
        if handle.is_null() {
            return false;
        }
        let mut exit_code = 0;
        let ok = GetExitCodeProcess(handle, &mut exit_code);
        CloseHandle(handle);
        ok != 0 && exit_code == STILL_ACTIVE as u32
    }
}

#[cfg(not(any(unix, windows)))]
pub fn is_running(_pid: u32) -> bool {
    false
}

pub fn record_still_matches(record: &PidRecord) -> bool {
    if !is_running(record.pid) {
        return false;
    }
    let Some(expected) = &record.start_token else {
        return true;
    };
    get_process_start_token(record.pid).is_none_or(|observed| observed == *expected)
}

#[cfg(unix)]
pub fn validate_process_name(pid: u32) -> bool {
    let output = std::process::Command::new("ps")
        .args(["-p", &pid.to_string(), "-o", "comm="])
        .output();
    match output {
        Ok(output) => is_snip_sync_process_name(String::from_utf8_lossy(&output.stdout).trim()),
        Err(_) => false,
    }
}

fn is_snip_sync_process_name(name: &str) -> bool {
    name == "snip-sync"
}

#[cfg(not(unix))]
pub fn validate_process_name(_pid: u32) -> bool {
    false
}

pub fn wait_for_exit(pid: u32, timeout: Duration) -> Result<(), String> {
    let deadline = Instant::now() + timeout;
    loop {
        if !is_running(pid) {
            return Ok(());
        }
        if Instant::now() >= deadline {
            return Err(format!(
                "Process {} did not exit within {}s",
                pid,
                timeout.as_secs()
            ));
        }
        std::thread::sleep(Duration::from_millis(200));
    }
}

/// Try to acquire an advisory lock for a short-lived maintenance command.
pub struct LockGuard {
    // Retained: the advisory lock lives on this descriptor, so it must stay
    // open for the whole guard. The handle is only *read* on Windows
    // (`UnlockFileEx` in `Drop`), hence the suppression.
    #[allow(dead_code)]
    file: fs::File,
    path: PathBuf,
    remove_on_drop: bool,
}

impl Drop for LockGuard {
    fn drop(&mut self) {
        #[cfg(windows)]
        {
            use std::os::windows::io::AsRawHandle;
            use windows_sys::Win32::Storage::FileSystem::UnlockFileEx;
            let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
                unsafe { std::mem::zeroed() };
            overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
            unsafe {
                UnlockFileEx(
                    self.file.as_raw_handle(),
                    0,
                    LOCKED_BYTE_COUNT,
                    0,
                    &mut overlapped,
                );
            }
        }
        if self.remove_on_drop {
            let _ = fs::remove_file(&self.path);
        }
    }
}

pub fn try_lock(path: &Path) -> Result<Option<LockGuard>, String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|error| format!("Failed to create lock directory: {error}"))?;
    }

    #[cfg(unix)]
    {
        use std::os::fd::AsRawFd;
        let file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .open(path)
            .map_err(|error| format!("Failed to open lock file {}: {error}", path.display()))?;
        let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
        if result == 0 {
            return Ok(Some(LockGuard {
                file,
                path: path.to_path_buf(),
                remove_on_drop: false,
            }));
        }
        if std::io::Error::last_os_error().kind() == std::io::ErrorKind::WouldBlock {
            return Ok(None);
        }
        Err(format!(
            "Failed to lock {}: {}",
            path.display(),
            std::io::Error::last_os_error()
        ))
    }

    #[cfg(not(unix))]
    {
        #[cfg(windows)]
        {
            use std::os::windows::io::AsRawHandle;
            use windows_sys::Win32::Storage::FileSystem::{
                LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx,
            };
            let file = fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(path)
                .map_err(|error| format!("Failed to open lock file {}: {error}", path.display()))?;
            let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED =
                unsafe { std::mem::zeroed() };
            overlapped.Anonymous.Anonymous.Offset = LOCKED_BYTE_OFFSET;
            let ok = unsafe {
                LockFileEx(
                    file.as_raw_handle(),
                    LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
                    0,
                    LOCKED_BYTE_COUNT,
                    0,
                    &mut overlapped,
                )
            };
            if ok == 0 {
                let error = std::io::Error::last_os_error();
                if matches!(error.raw_os_error(), Some(32) | Some(33)) {
                    return Ok(None);
                }
                return Err(format!("Failed to lock {}: {error}", path.display()));
            }
            return Ok(Some(LockGuard {
                file,
                path: path.to_path_buf(),
                remove_on_drop: false,
            }));
        }

        #[cfg(not(windows))]
        match fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)
        {
            Ok(file) => Ok(Some(LockGuard {
                file,
                path: path.to_path_buf(),
                remove_on_drop: true,
            })),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(None),
            Err(error) => Err(format!("Failed to lock {}: {error}", path.display())),
        }
    }
}

#[cfg(windows)]
const LOCKED_BYTE_COUNT: u32 = 1;

#[cfg(windows)]
const LOCKED_BYTE_OFFSET: u32 = u32::MAX;

#[cfg(windows)]
pub fn terminate_process(pid: u32, timeout: Duration) -> Result<(), String> {
    use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0, WAIT_TIMEOUT};
    use windows_sys::Win32::System::Threading::{
        OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject,
    };

    let handle = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, 0, pid) };
    if handle.is_null() {
        return Err(format!(
            "failed to open recorded server process {pid}: {}",
            std::io::Error::last_os_error()
        ));
    }
    let terminated = unsafe { TerminateProcess(handle, 1) } != 0;
    if !terminated {
        let error = std::io::Error::last_os_error();
        unsafe { CloseHandle(handle) };
        return Err(format!(
            "failed to terminate recorded server process {pid}: {error}"
        ));
    }
    let wait_ms = timeout.as_millis().min(u32::MAX as u128) as u32;
    let result = unsafe { WaitForSingleObject(handle, wait_ms) };
    unsafe { CloseHandle(handle) };
    match result {
        WAIT_OBJECT_0 => Ok(()),
        WAIT_TIMEOUT => Err(format!(
            "process {pid} did not exit within {}s",
            timeout.as_secs()
        )),
        _ => Err(format!(
            "failed waiting for process {pid}: {}",
            std::io::Error::last_os_error()
        )),
    }
}

#[cfg(target_os = "linux")]
pub fn get_process_start_token(pid: u32) -> Option<String> {
    let content = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    parse_linux_proc_start_token(&content)
}

#[cfg(target_os = "linux")]
fn parse_linux_proc_start_token(stat: &str) -> Option<String> {
    let after_comm = stat.rfind(')')?;
    stat.get(after_comm + 2..)?
        .split_whitespace()
        .nth(19)
        .map(str::to_owned)
}

#[cfg(target_os = "macos")]
pub fn get_process_start_token(pid: u32) -> Option<String> {
    use libc::{PROC_PIDTBSDINFO, proc_bsdinfo, proc_pidinfo};
    let pid = i32::try_from(pid).ok()?;
    let mut info: proc_bsdinfo = unsafe { std::mem::zeroed() };
    let result = unsafe {
        proc_pidinfo(
            pid,
            PROC_PIDTBSDINFO,
            0,
            &mut info as *mut _ as *mut _,
            std::mem::size_of::<proc_bsdinfo>() as i32,
        )
    };
    (result > 0).then(|| format!("{}.{:06}", info.pbi_start_tvsec, info.pbi_start_tvusec))
}

#[cfg(windows)]
pub fn get_process_start_token(pid: u32) -> Option<String> {
    use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
    use windows_sys::Win32::System::Threading::{
        GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
    };
    unsafe {
        let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
        if handle.is_null() {
            return None;
        }
        let mut creation: FILETIME = std::mem::zeroed();
        let mut exit: FILETIME = std::mem::zeroed();
        let mut kernel: FILETIME = std::mem::zeroed();
        let mut user: FILETIME = std::mem::zeroed();
        let ok = GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user);
        CloseHandle(handle);
        (ok != 0).then(|| {
            (((creation.dwHighDateTime as u64) << 32) | creation.dwLowDateTime as u64).to_string()
        })
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
pub fn get_process_start_token(_pid: u32) -> Option<String> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn process_name_requires_exact_match() {
        assert!(is_snip_sync_process_name("snip-sync"));
        assert!(!is_snip_sync_process_name("snip-sync-dev"));
        assert!(!is_snip_sync_process_name("not-snip-sync"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_start_token_parser_reads_field_22() {
        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";
        assert_eq!(parse_linux_proc_start_token(stat), Some("START22".into()));
        assert_eq!(parse_linux_proc_start_token("1 (short) S f3"), None);
    }

    #[test]
    fn test_parse_pid_file_legacy_numeric() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("snip-sync.pid");
        fs::write(&path, "1234\n").unwrap();
        assert_eq!(parse_pid_file(&path), ParsedPidFile::LegacyPid(1234));
    }

    #[test]
    fn test_parse_pid_file_rejects_zero() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("snip-sync.pid");
        fs::write(&path, "0\n").unwrap();
        assert!(matches!(parse_pid_file(&path), ParsedPidFile::Malformed(_)));
    }

    #[test]
    fn test_remove_legacy_pid_only_when_unchanged() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("snip-sync.pid");
        fs::write(&path, "1234\n").unwrap();
        remove_pid_if_unchanged_at(&path, &ParsedPidFile::LegacyPid(9999));
        assert!(path.exists());
        remove_pid_if_unchanged_at(&path, &ParsedPidFile::LegacyPid(1234));
        assert!(!path.exists());
    }

    #[cfg(windows)]
    #[test]
    fn stale_on_disk_lock_file_does_not_block_kernel_lock() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("croncheck.lock");
        fs::write(&path, "stale").unwrap();
        let guard = try_lock(&path)
            .unwrap()
            .expect("stale file must not own lock");
        drop(guard);
        assert!(
            path.exists(),
            "kernel lock release must not depend on unlinking"
        );
    }

    fn remove_pid_if_unchanged_at(path: &Path, expected: &ParsedPidFile) {
        let matches = match (expected, parse_pid_file(path)) {
            (ParsedPidFile::LegacyPid(expected), ParsedPidFile::LegacyPid(current)) => {
                expected == &current
            }
            _ => false,
        };
        if matches {
            let _ = fs::remove_file(path);
        }
    }
}