1use std::io;
21use std::sync::Arc;
22
23#[derive(Clone, Debug)]
25pub struct Pinned(Arc<imp::Pin>);
26
27impl Pinned {
28 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 #[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 #[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 #[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 #[must_use]
77 pub fn pid(&self) -> u32 {
78 self.0.pid
79 }
80
81 #[must_use]
83 pub fn alive(&self) -> bool {
84 self.0.alive()
85 }
86
87 #[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 #[cfg(feature = "tokio")]
98 pub async fn exited(&self) {
99 self.0.exited().await;
100 }
101}
102
103#[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#[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 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 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 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 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 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 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 pub(super) fn start_of(pid: u32) -> Option<u64> {
257 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 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 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 let process = unsafe { OwnedHandle::from_raw_handle(process) };
311 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 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 #[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 unsafe {
346 WaitForSingleObject(
347 process.as_raw_handle(),
348 windows_sys::Win32::System::Threading::INFINITE,
349 )
350 }
351 })
352 .await;
353 }
354 }
355
356 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 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 pub(super) fn start_of(pid: u32) -> Option<u64> {
371 let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
373 if process.is_null() {
374 return None;
375 }
376 let process = unsafe { OwnedHandle::from_raw_handle(process) };
378 created(process.as_raw_handle())
379 }
380}
381
382#[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 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;