Skip to main content

tilo_socket/
descriptor.rs

1//! A descriptor a local connection carries: an open file, or one end of a connection.
2//!
3//! A Unix connection hands the file descriptor itself; Windows hands a handle. Both are one type
4//! here, so a protocol above this crate names it once and means the same thing on every target.
5//! Sending one beside a line is the caller's transport: `SCM_RIGHTS` on a Unix socket, and a
6//! handle duplicated into the process at the other end on Windows.
7
8use std::fs::File;
9#[cfg(any(unix, windows))]
10use std::io;
11
12/// An open file or connection, carried beside a message on a local connection.
13#[derive(Debug)]
14pub struct Descriptor(Held);
15
16#[cfg(unix)]
17type Held = std::os::fd::OwnedFd;
18#[cfg(windows)]
19type Held = windows::Held;
20#[cfg(not(any(unix, windows)))]
21type Held = std::convert::Infallible;
22
23#[cfg(windows)]
24mod windows {
25    use std::fmt;
26    use std::io;
27    use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, OwnedHandle, RawHandle};
28
29    use crate::Stream;
30
31    /// What a descriptor's handle is: a connection, or any other handle (a section).
32    pub(super) enum Held {
33        Pipe(Stream),
34        Other(OwnedHandle),
35    }
36
37    impl Held {
38        /// `handle` as what it is: a pipe, or any other handle.
39        pub(super) fn of(handle: OwnedHandle) -> io::Result<Self> {
40            // SAFETY: a live handle, only asked its type.
41            let kind = unsafe {
42                windows_sys::Win32::Storage::FileSystem::GetFileType(handle.as_raw_handle())
43            };
44            if kind == windows_sys::Win32::Storage::FileSystem::FILE_TYPE_PIPE {
45                Stream::from_handle(handle).map(Self::Pipe)
46            } else {
47                Ok(Self::Other(handle))
48            }
49        }
50
51        pub(super) fn handle(&self) -> RawHandle {
52            match self {
53                Self::Pipe(stream) => stream.as_raw_handle(),
54                Self::Other(handle) => handle.as_raw_handle(),
55            }
56        }
57    }
58
59    impl fmt::Debug for Held {
60        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61            formatter
62                .debug_struct("Held")
63                .field("handle", &self.handle())
64                .finish()
65        }
66    }
67
68    impl AsRawHandle for Held {
69        fn as_raw_handle(&self) -> RawHandle {
70            self.handle()
71        }
72    }
73
74    impl AsHandle for Held {
75        fn as_handle(&self) -> BorrowedHandle<'_> {
76            // SAFETY: the handle this descriptor owns, borrowed for as long as it lives.
77            unsafe { BorrowedHandle::borrow_raw(self.handle()) }
78        }
79    }
80
81    impl Held {
82        /// The connection, when this descriptor is one.
83        pub(super) fn stream(&self) -> io::Result<&Stream> {
84            match self {
85                Self::Pipe(stream) => Ok(stream),
86                Self::Other(_) => Err(no_pipe()),
87            }
88        }
89
90        /// The connection, owned.
91        pub(super) fn into_stream(self) -> io::Result<Stream> {
92            match self {
93                Self::Pipe(stream) => Ok(stream),
94                Self::Other(_) => Err(no_pipe()),
95            }
96        }
97
98        /// The handle, owned.
99        pub(super) fn into_handle(self) -> OwnedHandle {
100            match self {
101                Self::Pipe(stream) => stream.into_handle(),
102                Self::Other(handle) => handle,
103            }
104        }
105    }
106
107    /// What a caller that wanted a connection was handed instead.
108    pub(super) fn no_pipe() -> io::Error {
109        io::Error::new(
110            io::ErrorKind::InvalidInput,
111            "a handle handed on as a connection is no pipe",
112        )
113    }
114}
115
116impl Descriptor {
117    /// A descriptor for `held`.
118    #[cfg(any(unix, windows))]
119    #[must_use]
120    fn of(held: Held) -> Self {
121        Self(held)
122    }
123
124    /// The file this descriptor holds open.
125    ///
126    /// A connection handed as a file still opens as it, which is how a chosen folder or a section
127    /// is read: the descriptor names the thing, not how it is carried.
128    #[cfg(unix)]
129    #[must_use]
130    pub fn into_file(self) -> File {
131        File::from(self.0)
132    }
133
134    /// The file this descriptor holds open.
135    #[cfg(windows)]
136    #[must_use]
137    pub fn into_file(self) -> File {
138        File::from(match self.0 {
139            windows::Held::Pipe(stream) => stream.into_handle(),
140            windows::Held::Other(handle) => handle,
141        })
142    }
143
144    /// The file this descriptor holds open: a page carries none.
145    #[cfg(not(any(unix, windows)))]
146    #[must_use]
147    pub fn into_file(self) -> File {
148        match self.0 {}
149    }
150
151    /// The connection, owned.
152    ///
153    /// # Errors
154    /// `InvalidInput` for a descriptor that is no connection.
155    #[cfg(unix)]
156    pub fn into_stream(self) -> io::Result<crate::Stream> {
157        Ok(crate::Stream::from(self.0))
158    }
159
160    /// The connection, owned.
161    ///
162    /// # Errors
163    /// `InvalidInput` for a descriptor that is no connection.
164    #[cfg(windows)]
165    pub fn into_stream(self) -> io::Result<crate::Stream> {
166        self.0.into_stream()
167    }
168
169    /// The connection, when this descriptor is one.
170    ///
171    /// # Errors
172    /// `InvalidInput` for a descriptor that is no connection.
173    #[cfg(windows)]
174    pub fn stream(&self) -> io::Result<&crate::Stream> {
175        self.0.stream()
176    }
177}
178
179#[cfg(unix)]
180impl From<std::os::fd::OwnedFd> for Descriptor {
181    fn from(fd: std::os::fd::OwnedFd) -> Self {
182        Self::of(fd)
183    }
184}
185
186#[cfg(unix)]
187impl From<Descriptor> for std::os::fd::OwnedFd {
188    fn from(descriptor: Descriptor) -> Self {
189        descriptor.0
190    }
191}
192
193#[cfg(unix)]
194impl std::os::fd::IntoRawFd for Descriptor {
195    fn into_raw_fd(self) -> std::os::fd::RawFd {
196        std::os::fd::IntoRawFd::into_raw_fd(self.0)
197    }
198}
199
200#[cfg(unix)]
201impl From<Descriptor> for crate::Stream {
202    fn from(descriptor: Descriptor) -> Self {
203        Self::from(descriptor.0)
204    }
205}
206
207#[cfg(unix)]
208impl From<crate::Stream> for Descriptor {
209    fn from(stream: crate::Stream) -> Self {
210        Self::of(stream.into())
211    }
212}
213
214#[cfg(unix)]
215impl std::os::fd::AsRawFd for Descriptor {
216    fn as_raw_fd(&self) -> std::os::fd::RawFd {
217        self.0.as_raw_fd()
218    }
219}
220
221#[cfg(unix)]
222impl std::os::fd::AsFd for Descriptor {
223    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
224        self.0.as_fd()
225    }
226}
227
228#[cfg(unix)]
229impl std::os::fd::FromRawFd for Descriptor {
230    /// # Safety
231    /// `fd` is an open descriptor nothing else owns.
232    unsafe fn from_raw_fd(fd: std::os::fd::RawFd) -> Self {
233        // SAFETY: the caller hands over an open descriptor nothing else owns.
234        Self::of(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) })
235    }
236}
237
238#[cfg(windows)]
239impl Descriptor {
240    /// A connection that carries no handles.
241    #[must_use]
242    pub fn new(stream: crate::Stream) -> Self {
243        Self::of(windows::Held::Pipe(stream))
244    }
245
246    /// `handle`, to hand on in a message: a pipe is a connection, anything else is handed as it
247    /// is.
248    ///
249    /// # Errors
250    /// The system's error asking which kind of handle it is.
251    pub fn from_handle(handle: std::os::windows::io::OwnedHandle) -> io::Result<Self> {
252        windows::Held::of(handle).map(Self::of)
253    }
254
255    /// The handle, owned.
256    #[must_use]
257    pub fn into_handle(self) -> std::os::windows::io::OwnedHandle {
258        self.0.into_handle()
259    }
260}
261
262#[cfg(windows)]
263impl From<crate::Stream> for Descriptor {
264    fn from(stream: crate::Stream) -> Self {
265        Self::of(windows::Held::Pipe(stream))
266    }
267}
268
269#[cfg(windows)]
270impl std::os::windows::io::AsRawHandle for Descriptor {
271    fn as_raw_handle(&self) -> std::os::windows::io::RawHandle {
272        self.0.as_raw_handle()
273    }
274}
275
276#[cfg(windows)]
277impl std::os::windows::io::AsHandle for Descriptor {
278    fn as_handle(&self) -> std::os::windows::io::BorrowedHandle<'_> {
279        self.0.as_handle()
280    }
281}
282
283impl Descriptor {
284    /// A second descriptor on the same open file or connection.
285    ///
286    /// # Errors
287    /// The system's error duplicating it.
288    #[cfg(unix)]
289    pub fn try_clone(&self) -> io::Result<Self> {
290        Ok(Self::of(self.0.try_clone()?))
291    }
292
293    /// A second descriptor on the same open file or connection.
294    ///
295    /// # Errors
296    /// The system's error duplicating it.
297    #[cfg(windows)]
298    pub fn try_clone(&self) -> io::Result<Self> {
299        Ok(Self::of(match &self.0 {
300            windows::Held::Pipe(stream) => windows::Held::Pipe(stream.try_clone()?),
301            windows::Held::Other(handle) => windows::Held::Other(handle.try_clone()?),
302        }))
303    }
304}