Skip to main content

tilo_socket/
peer.rs

1//! The process at the other end of a local connection, pinned: held so that it names that one
2//! process for as long as it is kept, never another that later runs under the same pid.
3//!
4//! Each platform pins it its own way, and every pin answers the same questions: which process
5//! it is ([`Pinned::pid`]), whether it still runs ([`Pinned::alive`]), whether a pid and start
6//! another part of the system names are it ([`Pinned::is`]), and, for a tokio caller, when it
7//! ends ([`Pinned::exited`]).
8//!
9//! - Linux: the pidfd the kernel hands for the socket's peer (`SO_PEERPIDFD`), which refers to
10//!   that task alone and becomes readable when it exits.
11//! - macOS: the peer's pid (`LOCAL_PEERPID`), with its start time read before and after a
12//!   kqueue `NOTE_EXIT` watch is set on it: the same start on both sides means the watch is on
13//!   the process that connected, not one that took its pid after it.
14//! - Windows: the pipe's client process (`GetNamedPipeClientProcessId`), opened as a handle and
15//!   then checked against the pipe: while the pipe is still connected the process holding its end
16//!   runs, so the handle is that process and not one that reused its pid.
17//! - Android, whose kernel pins no process behind a socket: only this process, which runs while it
18//!   asks. A peer that is any other process is pinned by nothing.
19
20use std::io;
21use std::sync::Arc;
22
23/// A process pinned at the other end of a connection. Clones share the one pin.
24#[derive(Clone, Debug)]
25pub struct Pinned(Arc<imp::Pin>);
26
27impl Pinned {
28    /// The process at the other end of `stream`, pinned as it is now.
29    ///
30    /// # Errors
31    /// The system names no process for the peer, or it ended while it was being pinned.
32    pub fn of(stream: &crate::Stream) -> io::Result<Self> {
33        #[cfg(unix)]
34        let pin = imp::Pin::of(std::os::fd::AsFd::as_fd(stream));
35        #[cfg(windows)]
36        let pin = imp::Pin::of(
37            std::os::windows::io::AsRawHandle::as_raw_handle(stream),
38            stream.is_server_end(),
39        );
40        pin.map(|pin| Self(Arc::new(pin)))
41    }
42
43    /// [`Pinned::of`] for a stream on the tokio runtime.
44    ///
45    /// # Errors
46    /// As [`Pinned::of`].
47    #[cfg(feature = "tokio")]
48    pub fn of_tokio(stream: &crate::tokio::Stream) -> io::Result<Self> {
49        #[cfg(unix)]
50        let pin = imp::Pin::of(std::os::fd::AsFd::as_fd(stream));
51        #[cfg(windows)]
52        let pin = {
53            let (pipe, server_end) = stream.raw_end();
54            imp::Pin::of(pipe, server_end)
55        };
56        pin.map(|pin| Self(Arc::new(pin)))
57    }
58
59    /// The process `pidfd` refers to, as a launcher that pinned it hands it over.
60    ///
61    /// # Errors
62    /// The process has already ended.
63    #[cfg(target_os = "linux")]
64    pub fn from_pidfd(pidfd: std::os::fd::OwnedFd) -> io::Result<Self> {
65        imp::Pin::from_pidfd(pidfd).map(|pin| Self(Arc::new(pin)))
66    }
67
68    /// The pidfd pinning the process, to hand over to another process.
69    #[cfg(target_os = "linux")]
70    #[must_use]
71    pub fn pidfd(&self) -> std::os::fd::BorrowedFd<'_> {
72        std::os::fd::AsFd::as_fd(&*self.0.pidfd)
73    }
74
75    /// The pinned process's pid.
76    #[must_use]
77    pub fn pid(&self) -> u32 {
78        self.0.pid
79    }
80
81    /// Whether the pinned process still runs.
82    #[must_use]
83    pub fn alive(&self) -> bool {
84        self.0.alive()
85    }
86
87    /// Whether the process another part of the system names by `pid` and `start` (its start
88    /// time as this platform counts it: clock ticks since boot on Linux, microseconds since the
89    /// epoch on macOS, the creation `FILETIME` on Windows) is the pinned one, still running.
90    #[must_use]
91    pub fn is(&self, pid: u32, start: u64) -> bool {
92        self.0.pid == pid && imp::start_of(pid) == Some(start) && self.0.is_started(start)
93    }
94
95    /// Resolves once the pinned process has ended, or at once when its end cannot be watched:
96    /// a process this cannot watch is treated as gone, never as running forever.
97    #[cfg(feature = "tokio")]
98    pub async fn exited(&self) {
99        self.0.exited().await;
100    }
101}
102
103/// Whether `fd` has nothing to read now: a pidfd, or a kqueue watching an exit, is readable once
104/// its process has ended.
105#[cfg(any(target_os = "linux", target_os = "macos"))]
106fn quiet(fd: std::os::fd::BorrowedFd<'_>) -> bool {
107    use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
108    poll(&mut [PollFd::new(fd, PollFlags::POLLIN)], PollTimeout::ZERO) == Ok(0)
109}
110
111/// Resolves once `fd` turns readable, or at once when it cannot be watched.
112#[cfg(all(feature = "tokio", any(target_os = "linux", target_os = "macos")))]
113async fn readable(fd: &std::sync::Arc<std::os::fd::OwnedFd>) {
114    #[derive(Debug)]
115    struct Watched(std::sync::Arc<std::os::fd::OwnedFd>);
116    impl std::os::fd::AsRawFd for Watched {
117        fn as_raw_fd(&self) -> std::os::fd::RawFd {
118            self.0.as_raw_fd()
119        }
120    }
121    // SAFETY: the AsyncFd owns `Watched` and so one strong reference to the descriptor, which
122    // keeps it open until the AsyncFd deregisters it on drop.
123    if let Ok(watched) = unsafe {
124        tokio::io::unix::AsyncFd::register_with_interest(
125            Watched(std::sync::Arc::clone(fd)),
126            tokio::io::Interest::READABLE,
127        )
128    } {
129        let _ = watched.readable().await;
130    }
131}
132
133#[cfg(target_os = "linux")]
134mod imp {
135    use std::io;
136    use std::os::fd::{AsFd as _, AsRawFd as _, BorrowedFd, OwnedFd};
137    use std::sync::Arc;
138
139    #[derive(Debug)]
140    pub(super) struct Pin {
141        pub(super) pidfd: Arc<OwnedFd>,
142        pub(super) pid: u32,
143    }
144
145    impl Pin {
146        pub(super) fn of(socket: BorrowedFd<'_>) -> io::Result<Self> {
147            Self::from_pidfd(nix::sys::socket::getsockopt(
148                &socket,
149                nix::sys::socket::sockopt::PeerPidfd,
150            )?)
151        }
152
153        pub(super) fn from_pidfd(pidfd: OwnedFd) -> io::Result<Self> {
154            let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", pidfd.as_raw_fd()))?;
155            // A pidfd whose process has ended reads `Pid: -1`, which parses as no pid.
156            let pid = info
157                .lines()
158                .find_map(|line| line.strip_prefix("Pid:"))
159                .and_then(|pid| pid.trim().parse::<u32>().ok());
160            match pid {
161                Some(pid) if super::quiet(pidfd.as_fd()) => Ok(Self {
162                    pidfd: Arc::new(pidfd),
163                    pid,
164                }),
165                _ => Err(io::Error::other("the pinned process has already ended")),
166            }
167        }
168
169        pub(super) fn alive(&self) -> bool {
170            super::quiet(self.pidfd.as_fd())
171        }
172
173        /// The pidfd pins the task itself: a start read for its pid while it runs is its own.
174        pub(super) fn is_started(&self, _: u64) -> bool {
175            self.alive()
176        }
177
178        #[cfg(feature = "tokio")]
179        pub(super) async fn exited(&self) {
180            super::readable(&self.pidfd).await;
181        }
182    }
183
184    /// The start of the process `pid` now, in clock ticks since boot (`/proc/<pid>/stat`'s 22nd
185    /// field).
186    pub(super) fn start_of(pid: u32) -> Option<u64> {
187        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
188        let (_, fields) = stat.rsplit_once(") ")?;
189        fields.split_whitespace().nth(19)?.parse().ok()
190    }
191}
192
193#[cfg(target_os = "macos")]
194mod imp {
195    use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent, Kqueue};
196    use std::io;
197    use std::os::fd::{AsFd as _, BorrowedFd, OwnedFd};
198    use std::sync::Arc;
199
200    #[derive(Debug)]
201    pub(super) struct Pin {
202        pub(super) pid: u32,
203        start: u64,
204        /// A kqueue watching the process's exit: readable once it has ended.
205        exit: Arc<OwnedFd>,
206    }
207
208    impl Pin {
209        pub(super) fn of(socket: BorrowedFd<'_>) -> io::Result<Self> {
210            let pid =
211                nix::sys::socket::getsockopt(&socket, nix::sys::socket::sockopt::LocalPeerPid)?;
212            let pid = u32::try_from(pid)
213                .ok()
214                .filter(|pid| *pid > 0)
215                .ok_or_else(|| io::Error::other("the system named no process for the peer"))?;
216            let ended = || io::Error::other("the peer's process ended while it was pinned");
217            let start = start_of(pid).ok_or_else(ended)?;
218            let exit = Kqueue::new()?;
219            let watch = KEvent::new(
220                usize::try_from(pid).map_err(io::Error::other)?,
221                EventFilter::EVFILT_PROC,
222                EvFlags::EV_ADD | EvFlags::EV_CLEAR,
223                FilterFlag::NOTE_EXIT,
224                0,
225                0,
226            );
227            exit.kevent(&[watch], &mut [], None)?;
228            // The watch is set on whatever runs as `pid` now: the same start as before it means
229            // that is the process that connected.
230            if start_of(pid) != Some(start) {
231                return Err(ended());
232            }
233            Ok(Self {
234                pid,
235                start,
236                exit: Arc::new(exit.into()),
237            })
238        }
239
240        pub(super) fn alive(&self) -> bool {
241            super::quiet(self.exit.as_fd())
242        }
243
244        pub(super) fn is_started(&self, start: u64) -> bool {
245            self.start == start && self.alive()
246        }
247
248        #[cfg(feature = "tokio")]
249        pub(super) async fn exited(&self) {
250            super::readable(&self.exit).await;
251        }
252    }
253
254    /// The start of the process `pid` now, in microseconds since the epoch. Nothing in the
255    /// platform crates wraps `proc_pidinfo`, so it is called here.
256    pub(super) fn start_of(pid: u32) -> Option<u64> {
257        // SAFETY: proc_bsdinfo is plain integers and arrays of them, for which zero is valid.
258        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
259        let size = libc::c_int::try_from(size_of::<libc::proc_bsdinfo>()).ok()?;
260        // SAFETY: a writable buffer of `size` bytes for the flavour that fills a proc_bsdinfo.
261        let read = unsafe {
262            libc::proc_pidinfo(
263                libc::c_int::try_from(pid).ok()?,
264                libc::PROC_PIDTBSDINFO,
265                0,
266                (&raw mut info).cast(),
267                size,
268            )
269        };
270        (read == size).then(|| {
271            info.pbi_start_tvsec
272                .saturating_mul(1_000_000)
273                .saturating_add(info.pbi_start_tvusec)
274        })
275    }
276}
277
278#[cfg(windows)]
279mod imp {
280    use std::io;
281    use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle, RawHandle};
282    use windows_sys::Win32::Foundation::{FILETIME, WAIT_TIMEOUT};
283    use windows_sys::Win32::System::Threading::{
284        GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
285        WaitForSingleObject,
286    };
287
288    #[derive(Debug)]
289    pub(super) struct Pin {
290        pub(super) pid: u32,
291        start: u64,
292        process: OwnedHandle,
293    }
294
295    impl Pin {
296        pub(super) fn of(pipe: RawHandle, server_end: bool) -> io::Result<Self> {
297            let pid = crate::windows::peer_pid(pipe, server_end)?;
298            // SAFETY: opens a handle the OwnedHandle takes; a null one is the failure.
299            let process = unsafe {
300                OpenProcess(
301                    PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
302                    0,
303                    pid,
304                )
305            };
306            if process.is_null() {
307                return Err(io::Error::last_os_error());
308            }
309            // SAFETY: a fresh process handle this call owns.
310            let process = unsafe { OwnedHandle::from_raw_handle(process) };
311            // While the pipe is connected the process holding its other end runs: the handle
312            // opened for its pid is that process, not one that took the pid after it.
313            if !crate::windows::pipe_connected(pipe) {
314                return Err(io::Error::other(
315                    "the peer's process ended while it was pinned",
316                ));
317            }
318            let start = created(process.as_raw_handle())
319                .ok_or_else(|| io::Error::other("the system names no start for the peer"))?;
320            Ok(Self {
321                pid,
322                start,
323                process,
324            })
325        }
326
327        pub(super) fn alive(&self) -> bool {
328            // SAFETY: a live process handle, without waiting.
329            unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) == WAIT_TIMEOUT }
330        }
331
332        pub(super) fn is_started(&self, start: u64) -> bool {
333            self.start == start && self.alive()
334        }
335
336        /// A wait on a duplicate of the handle, on the runtime's blocking pool: one the caller
337        /// stops awaiting keeps its thread until the process ends.
338        #[cfg(feature = "tokio")]
339        pub(super) async fn exited(&self) {
340            let Ok(process) = self.process.try_clone() else {
341                return;
342            };
343            let _ = tokio::task::spawn_blocking(move || {
344                // SAFETY: a live process handle the closure owns.
345                unsafe {
346                    WaitForSingleObject(
347                        process.as_raw_handle(),
348                        windows_sys::Win32::System::Threading::INFINITE,
349                    )
350                }
351            })
352            .await;
353        }
354    }
355
356    /// The creation time of the process `process` handles, as a `FILETIME`'s 100 ns since 1601.
357    fn created(process: RawHandle) -> Option<u64> {
358        let mut times = [FILETIME {
359            dwLowDateTime: 0,
360            dwHighDateTime: 0,
361        }; 4];
362        let [creation, exit, kernel, user] = &mut times;
363        // SAFETY: a live process handle and four writable FILETIMEs.
364        let read = unsafe { GetProcessTimes(process, creation, exit, kernel, user) };
365        (read != 0)
366            .then(|| (u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime))
367    }
368
369    /// The creation time of the process `pid` now.
370    pub(super) fn start_of(pid: u32) -> Option<u64> {
371        // SAFETY: opens a handle the OwnedHandle takes; a null one is the failure.
372        let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
373        if process.is_null() {
374            return None;
375        }
376        // SAFETY: a fresh process handle this call owns.
377        let process = unsafe { OwnedHandle::from_raw_handle(process) };
378        created(process.as_raw_handle())
379    }
380}
381
382/// A phone's kernel, which pins no process behind a socket: only this process, which runs while
383/// it asks.
384#[cfg(target_os = "android")]
385mod imp {
386    use std::io;
387
388    #[derive(Debug)]
389    pub(super) struct Pin {
390        pub(super) pid: u32,
391    }
392
393    impl Pin {
394        pub(super) fn of(socket: std::os::fd::BorrowedFd<'_>) -> io::Result<Self> {
395            let peer =
396                nix::sys::socket::getsockopt(&socket, nix::sys::socket::sockopt::PeerCredentials)?;
397            let pid = u32::try_from(peer.pid())
398                .map_err(|_| io::Error::other("the system named no process for the peer"))?;
399            if pid == std::process::id() {
400                Ok(Self { pid })
401            } else {
402                Err(io::Error::other(
403                    "this kernel pins no process behind a socket but this one",
404                ))
405            }
406        }
407
408        #[expect(
409            clippy::unused_self,
410            reason = "this process runs while it asks; the other platforms read their pin"
411        )]
412        pub(super) const fn alive(&self) -> bool {
413            true
414        }
415
416        pub(super) fn is_started(&self, _: u64) -> bool {
417            self.alive()
418        }
419
420        #[cfg(feature = "tokio")]
421        pub(super) async fn exited(&self) {
422            std::future::pending::<()>().await;
423        }
424    }
425
426    /// No start of a process is read here: a caller's pid and start never match.
427    pub(super) const fn start_of(_: u32) -> Option<u64> {
428        None
429    }
430}
431
432#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))]
433#[path = "peer_tests.rs"]
434mod tests;