running-process 4.5.5

Subprocess and PTY runtime for the running-process project
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Process identity verification for backend handles.

use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use crate::broker::backend_lifecycle::identity::{self, DaemonProcess};
use crate::broker::host_identity;

/// Verify a daemon process identity and return an OS liveness handle.
pub fn verify_daemon_process(expected: &DaemonProcess) -> Result<ProcessHandle, VerifyPidError> {
    if expected.pid == 0 {
        return Err(VerifyPidError::InvalidPid(expected.pid));
    }

    let current_boot_id = host_identity::current().boot_id;
    if !expected.boot_id.is_empty()
        && !current_boot_id.is_empty()
        && expected.boot_id != current_boot_id
    {
        return Err(VerifyPidError::BootIdMismatch {
            expected: expected.boot_id.clone(),
            actual: current_boot_id,
        });
    }

    let handle = ProcessHandle::open(expected.pid)?;
    let exe_path = process_exe_path(expected.pid).map_err(|source| VerifyPidError::ExePath {
        pid: expected.pid,
        source,
    })?;
    if !same_exe_path(&exe_path, &expected.exe_path) {
        return Err(VerifyPidError::ExePathMismatch {
            pid: expected.pid,
            expected: expected.exe_path.clone(),
            actual: exe_path,
        });
    }

    let actual_sha256 =
        identity::sha256_file(&exe_path).map_err(|source| VerifyPidError::ExeHash {
            pid: expected.pid,
            path: exe_path.clone(),
            source,
        })?;
    if actual_sha256 != expected.exe_sha256 {
        return Err(VerifyPidError::ExeSha256Mismatch { pid: expected.pid });
    }

    Ok(handle)
}

/// Return whether a process ID currently resolves to a live process.
pub fn process_is_alive(pid: u32) -> bool {
    ProcessHandle::open(pid)
        .map(|handle| handle.is_alive())
        .unwrap_or(false)
}

/// Send a graceful terminate signal where the platform has one.
pub fn signal_terminate(pid: u32) -> Result<(), VerifyPidError> {
    platform_signal_terminate(pid)
}

/// Force-kill a process ID.
pub fn force_kill_pid(pid: u32) -> Result<(), VerifyPidError> {
    platform_force_kill(pid)
}

/// Errors returned while verifying a daemon process.
#[derive(Debug, thiserror::Error)]
pub enum VerifyPidError {
    /// PID zero or a value outside the native PID range is never valid.
    #[error("invalid daemon pid: {0}")]
    InvalidPid(u32),
    /// The process is not currently alive.
    #[error("process not found: {pid}")]
    NotFound {
        /// Process ID that could not be opened.
        pid: u32,
    },
    /// The manifest was written during a prior host boot.
    #[error("daemon boot id mismatch: expected {expected}, current {actual}")]
    BootIdMismatch {
        /// Boot ID stored with the daemon identity.
        expected: String,
        /// Current host boot ID.
        actual: String,
    },
    /// The executable could not be hashed.
    #[error("failed to hash executable for pid {pid} at {path:?}: {source}")]
    ExeHash {
        /// Process ID being verified.
        pid: u32,
        /// Executable path selected for hashing.
        path: PathBuf,
        /// Underlying I/O error.
        source: io::Error,
    },
    /// The executable path for the process could not be read.
    #[error("failed to resolve executable path for pid {pid}: {source}")]
    ExePath {
        /// Process ID being verified.
        pid: u32,
        /// Underlying platform error.
        source: io::Error,
    },
    /// The executable path did not match the manifest identity.
    #[error(
        "daemon executable path mismatch for pid {pid}: expected {expected:?}, actual {actual:?}"
    )]
    ExePathMismatch {
        /// Process ID being verified.
        pid: u32,
        /// Executable path stored with the daemon identity.
        expected: PathBuf,
        /// Executable path reported by the operating system.
        actual: PathBuf,
    },
    /// The executable hash did not match the manifest identity.
    #[error("daemon executable sha256 mismatch for pid {pid}")]
    ExeSha256Mismatch {
        /// Process ID being verified.
        pid: u32,
    },
    /// A platform process-handle operation failed.
    #[error("process handle operation failed for pid {pid}: {source}")]
    Handle {
        /// Process ID being opened or signalled.
        pid: u32,
        /// Underlying platform error.
        source: io::Error,
    },
    /// The platform has no graceful shutdown primitive in this foundation.
    #[error("graceful terminate is unsupported on this platform")]
    GracefulTerminateUnsupported,
}

#[cfg(unix)]
mod platform {
    use std::io;

    #[cfg(target_os = "macos")]
    use std::ptr;

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
    #[cfg(target_os = "macos")]
    use std::sync::atomic::{AtomicBool, Ordering};

    use super::VerifyPidError;

    /// Platform liveness handle for a backend process.
    pub struct ProcessHandle {
        pid: u32,
        #[cfg(target_os = "linux")]
        pid_fd: Option<OwnedFd>,
        #[cfg(target_os = "macos")]
        exit_kqueue: OwnedFd,
        #[cfg(target_os = "macos")]
        exited: AtomicBool,
    }

    impl ProcessHandle {
        pub(crate) fn open(pid: u32) -> Result<Self, VerifyPidError> {
            validate_pid(pid)?;
            #[cfg(target_os = "macos")]
            {
                Ok(Self {
                    pid,
                    exit_kqueue: open_exit_kqueue(pid)?,
                    exited: AtomicBool::new(false),
                })
            }

            #[cfg(target_os = "linux")]
            {
                if !process_exists(pid) {
                    return Err(VerifyPidError::NotFound { pid });
                }
                Ok(Self {
                    pid,
                    pid_fd: try_pidfd_open(pid)?,
                })
            }

            #[cfg(all(not(target_os = "linux"), not(target_os = "macos")))]
            {
                if !process_exists(pid) {
                    return Err(VerifyPidError::NotFound { pid });
                }
                Ok(Self { pid })
            }
        }

        /// Process ID associated with this handle.
        pub fn pid(&self) -> u32 {
            self.pid
        }

        /// Return whether the process represented by this handle is alive.
        pub fn is_alive(&self) -> bool {
            #[cfg(target_os = "linux")]
            {
                if let Some(pid_fd) = self.pid_fd.as_ref() {
                    return pidfd_is_alive(pid_fd);
                }
                process_exists(self.pid)
            }

            #[cfg(target_os = "macos")]
            {
                !self.exited.load(Ordering::Relaxed)
                    && kqueue_process_is_alive(&self.exit_kqueue, &self.exited)
            }

            #[cfg(all(not(target_os = "linux"), not(target_os = "macos")))]
            {
                process_exists(self.pid)
            }
        }
    }

    #[cfg(not(target_os = "macos"))]
    pub(crate) fn process_exists(pid: u32) -> bool {
        let Ok(native_pid) = validate_pid(pid) else {
            return false;
        };
        let rc = unsafe { libc::kill(native_pid, 0) };
        if rc == 0 {
            return true;
        }
        matches!(io::Error::last_os_error().raw_os_error(), Some(libc::EPERM))
    }

    pub(crate) fn platform_signal_terminate(pid: u32) -> Result<(), VerifyPidError> {
        let native_pid = validate_pid(pid)?;
        let rc = unsafe { libc::kill(native_pid, libc::SIGTERM) };
        if rc == 0 {
            Ok(())
        } else {
            Err(VerifyPidError::Handle {
                pid,
                source: io::Error::last_os_error(),
            })
        }
    }

    pub(crate) fn platform_force_kill(pid: u32) -> Result<(), VerifyPidError> {
        let native_pid = validate_pid(pid)?;
        let rc = unsafe { libc::kill(native_pid, libc::SIGKILL) };
        if rc == 0 {
            Ok(())
        } else {
            Err(VerifyPidError::Handle {
                pid,
                source: io::Error::last_os_error(),
            })
        }
    }

    fn validate_pid(pid: u32) -> Result<libc::pid_t, VerifyPidError> {
        if pid == 0 || pid > libc::pid_t::MAX as u32 {
            Err(VerifyPidError::InvalidPid(pid))
        } else {
            Ok(pid as libc::pid_t)
        }
    }

    #[cfg(target_os = "macos")]
    fn open_exit_kqueue(pid: u32) -> Result<OwnedFd, VerifyPidError> {
        let native_pid = validate_pid(pid)?;
        let raw_fd = unsafe { libc::kqueue() };
        if raw_fd < 0 {
            return Err(VerifyPidError::Handle {
                pid,
                source: io::Error::last_os_error(),
            });
        }

        let kqueue_fd = unsafe { OwnedFd::from_raw_fd(raw_fd) };
        let change = libc::kevent {
            ident: native_pid as libc::uintptr_t,
            filter: libc::EVFILT_PROC,
            flags: libc::EV_ADD | libc::EV_CLEAR,
            fflags: libc::NOTE_EXIT,
            data: 0,
            udata: ptr::null_mut(),
        };
        let rc = unsafe {
            libc::kevent(
                kqueue_fd.as_raw_fd(),
                &change,
                1,
                ptr::null_mut(),
                0,
                ptr::null(),
            )
        };
        if rc == 0 {
            return Ok(kqueue_fd);
        }

        let source = io::Error::last_os_error();
        if matches!(source.raw_os_error(), Some(libc::ESRCH)) {
            Err(VerifyPidError::NotFound { pid })
        } else {
            Err(VerifyPidError::Handle { pid, source })
        }
    }

    #[cfg(target_os = "macos")]
    fn kqueue_process_is_alive(kqueue_fd: &OwnedFd, exited: &AtomicBool) -> bool {
        let mut event = std::mem::MaybeUninit::<libc::kevent>::uninit();
        let timeout = libc::timespec {
            tv_sec: 0,
            tv_nsec: 0,
        };
        let rc = unsafe {
            libc::kevent(
                kqueue_fd.as_raw_fd(),
                ptr::null(),
                0,
                event.as_mut_ptr(),
                1,
                &timeout,
            )
        };
        if rc == 0 {
            return true;
        }

        exited.store(true, Ordering::Relaxed);
        false
    }

    #[cfg(target_os = "linux")]
    fn try_pidfd_open(pid: u32) -> Result<Option<OwnedFd>, VerifyPidError> {
        let raw = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as libc::pid_t, 0_u32) };
        if raw >= 0 {
            let fd = unsafe { OwnedFd::from_raw_fd(raw as i32) };
            return Ok(Some(fd));
        }

        let err = io::Error::last_os_error();
        match err.raw_os_error() {
            Some(libc::ENOSYS | libc::EINVAL | libc::EPERM) => Ok(None),
            Some(libc::ESRCH) => Err(VerifyPidError::NotFound { pid }),
            _ => Ok(None),
        }
    }

    #[cfg(target_os = "linux")]
    fn pidfd_is_alive(pid_fd: &OwnedFd) -> bool {
        let mut poll_fd = libc::pollfd {
            fd: pid_fd.as_raw_fd(),
            events: libc::POLLIN,
            revents: 0,
        };
        let rc = unsafe { libc::poll(&mut poll_fd, 1, 0) };
        rc == 0
    }
}

#[cfg(windows)]
mod platform {
    use std::io;

    use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
    use windows_sys::Win32::System::Threading::{
        GetExitCodeProcess, OpenProcess, TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION,
        PROCESS_TERMINATE,
    };

    use super::VerifyPidError;

    const STILL_ACTIVE: u32 = 259;

    /// Platform liveness handle for a backend process.
    pub struct ProcessHandle {
        pid: u32,
        handle: HANDLE,
    }

    impl ProcessHandle {
        pub(crate) fn open(pid: u32) -> Result<Self, VerifyPidError> {
            let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
            if handle.is_null() {
                return Err(VerifyPidError::NotFound { pid });
            }
            Ok(Self { pid, handle })
        }

        /// Process ID associated with this handle.
        pub fn pid(&self) -> u32 {
            self.pid
        }

        /// Return whether the process represented by this handle is alive.
        pub fn is_alive(&self) -> bool {
            let mut exit_code = 0_u32;
            let ok = unsafe { GetExitCodeProcess(self.handle, &mut exit_code) };
            ok != 0 && exit_code == STILL_ACTIVE
        }
    }

    impl Drop for ProcessHandle {
        fn drop(&mut self) {
            unsafe {
                CloseHandle(self.handle);
            }
        }
    }

    pub(crate) fn platform_signal_terminate(_pid: u32) -> Result<(), VerifyPidError> {
        Err(VerifyPidError::GracefulTerminateUnsupported)
    }

    pub(crate) fn platform_force_kill(pid: u32) -> Result<(), VerifyPidError> {
        let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
        if handle.is_null() {
            return Err(VerifyPidError::NotFound { pid });
        }
        let ok = unsafe { TerminateProcess(handle, 1) };
        let source = io::Error::last_os_error();
        unsafe {
            CloseHandle(handle);
        }
        if ok == 0 {
            Err(VerifyPidError::Handle { pid, source })
        } else {
            Ok(())
        }
    }
}

pub use platform::ProcessHandle;
use platform::{platform_force_kill, platform_signal_terminate};

fn process_exe_path(pid: u32) -> Result<PathBuf, io::Error> {
    #[cfg(target_os = "linux")]
    {
        std::fs::read_link(format!("/proc/{pid}/exe"))
    }

    #[cfg(target_os = "windows")]
    {
        use windows_sys::Win32::Foundation::CloseHandle;
        use windows_sys::Win32::System::Threading::{
            OpenProcess, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION,
        };

        let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
        if handle.is_null() {
            return Err(io::Error::last_os_error());
        }

        let mut path = vec![0_u16; 32768];
        let mut len = path.len() as u32;
        let ok = unsafe { QueryFullProcessImageNameW(handle, 0, path.as_mut_ptr(), &mut len) };
        let source = io::Error::last_os_error();
        unsafe {
            CloseHandle(handle);
        }
        if ok == 0 {
            return Err(source);
        }

        path.truncate(len as usize);
        Ok(PathBuf::from(String::from_utf16_lossy(&path)))
    }

    #[cfg(all(not(target_os = "linux"), not(target_os = "windows")))]
    {
        let mut system = sysinfo::System::new_all();
        system.refresh_processes();
        if let Some(process) = system.process(sysinfo::Pid::from_u32(pid)) {
            if let Some(exe) = process.exe() {
                return Ok(exe.to_path_buf());
            }
        }
        Err(io::Error::new(
            io::ErrorKind::NotFound,
            "process executable path not found",
        ))
    }
}

fn same_exe_path(actual: &Path, expected: &Path) -> bool {
    let actual = fs::canonicalize(actual).unwrap_or_else(|_| actual.to_path_buf());
    let expected = fs::canonicalize(expected).unwrap_or_else(|_| expected.to_path_buf());

    #[cfg(windows)]
    {
        comparable_windows_path(&actual) == comparable_windows_path(&expected)
    }

    #[cfg(not(windows))]
    {
        actual == expected
    }
}

#[cfg(windows)]
fn comparable_windows_path(path: &Path) -> String {
    let path = path.to_string_lossy().replace('\\', "/");
    let path = path.strip_prefix("//?/").unwrap_or(&path);
    path.to_ascii_lowercase()
}