Skip to main content

tilo_socket/
lib.rs

1//! Local (Unix-domain) sockets named by a path of any length. The kernel takes a
2//! socket's path in a fixed buffer (`sun_path`: 108 bytes on Linux, 104 on macOS), so a
3//! socket in a deep enough directory cannot be bound or reached by its path at all; a
4//! path that does not fit is reached through its directory, opened first and named by
5//! its descriptor (`/proc/self/fd/<fd>/<name>`), so only the socket's own name has to
6//! fit. A path that fits is used as it is. Elsewhere than Linux and Android a path that
7//! does not fit is refused with [`io::ErrorKind::InvalidInput`] naming the limit, never
8//! silently.
9//!
10//! Windows names a local service with a named pipe instead (`windows`): the same
11//! [`bind`], [`connect`], [`Listener`] and [`Stream`], kept to this account by the
12//! pipe's DACL and a check of the peer's token. [`tokio`] is the same for an async
13//! caller.
14//!
15//! On Unix the crate adds nothing to std but libc for one call: three bytes of a
16//! peek, so a server can tell a client that left from one still there. The
17//! `tilo_files::native::socket` re-export and a tool that must stay small to start
18//! quickly (the `cargo desktop` launcher) bind and connect through the same code
19//! without taking on a dependency graph.
20
21use std::io;
22#[cfg(unix)]
23use std::os::unix::net::{UnixListener, UnixStream};
24use std::path::Path;
25
26pub use datagram::Datagram;
27pub use descriptor::Descriptor;
28
29#[cfg(windows)]
30pub mod account;
31pub mod datagram;
32pub mod descriptor;
33#[cfg(feature = "tokio")]
34pub mod tokio;
35#[cfg(windows)]
36mod windows;
37#[cfg(windows)]
38pub use windows::{Listener, MAX_PATH, SocketAddr, Stream, link};
39
40/// The longest socket path the kernel takes, without its terminating NUL.
41#[cfg(any(target_os = "linux", target_os = "android"))]
42pub const MAX_PATH: usize = 107;
43#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
44pub const MAX_PATH: usize = 103;
45/// A page has no local socket: no length of a path fits.
46#[cfg(not(any(unix, windows)))]
47pub const MAX_PATH: usize = 0;
48
49#[cfg(unix)]
50pub type Listener = UnixListener;
51#[cfg(unix)]
52pub type Stream = UnixStream;
53#[cfg(unix)]
54pub use std::os::unix::net::SocketAddr;
55/// A page has no local socket: nothing produces one.
56#[cfg(not(any(unix, windows)))]
57pub struct Listener(std::convert::Infallible);
58#[cfg(not(any(unix, windows)))]
59pub struct Stream(std::convert::Infallible);
60
61/// Listens on a new socket at `path`, whatever its length.
62pub fn bind(path: &Path) -> io::Result<Listener> {
63    #[cfg(unix)]
64    {
65        reach(path, |short| UnixListener::bind(short))
66    }
67    #[cfg(windows)]
68    {
69        windows::bind(path)
70    }
71    #[cfg(not(any(unix, windows)))]
72    {
73        Err(no_socket(path))
74    }
75}
76
77/// Connects to the socket at `path`, whatever its length.
78pub fn connect(path: &Path) -> io::Result<Stream> {
79    #[cfg(unix)]
80    {
81        reach(path, |short| UnixStream::connect(short))
82    }
83    #[cfg(windows)]
84    {
85        windows::connect(path)
86    }
87    #[cfg(not(any(unix, windows)))]
88    {
89        Err(no_socket(path))
90    }
91}
92
93/// Two connected ends, both in this process: one is handed to another process or thread, as a
94/// connection made without a listener. A Unix stream pair; on Windows a pipe only this process
95/// joined ([`link::pair`]), which reads as a byte stream as a socket does.
96///
97/// # Errors
98/// The system's error making the pair.
99pub fn pair() -> io::Result<(Stream, Stream)> {
100    #[cfg(unix)]
101    {
102        UnixStream::pair()
103    }
104    #[cfg(windows)]
105    {
106        link::pair()
107    }
108    #[cfg(not(any(unix, windows)))]
109    {
110        Err(io::Error::new(
111            io::ErrorKind::Unsupported,
112            "a page has no local socket",
113        ))
114    }
115}
116
117/// Whether something is bound at `path` now, without connecting to it: a
118/// socket file on Unix, a pipe with an instance on Windows. One a run left
119/// behind on Unix still reads as bound; [`connect`] says whether it answers.
120#[must_use]
121pub fn is_bound(path: &Path) -> bool {
122    #[cfg(unix)]
123    {
124        use std::os::unix::fs::FileTypeExt as _;
125        std::fs::symlink_metadata(path).is_ok_and(|found| found.file_type().is_socket())
126    }
127    #[cfg(windows)]
128    {
129        windows::is_bound(path)
130    }
131    #[cfg(not(any(unix, windows)))]
132    {
133        let _ = path;
134        false
135    }
136}
137
138/// What the peer at the other end of `stream` has sent so far, up to `buffer`'s length, without
139/// consuming it: the next read gets the same bytes. Waits up to `within` for the first of them;
140/// `0` when the peer sent nothing by then, or closed.
141///
142/// # Errors
143/// The connection fails while it is looked at.
144pub fn peek(stream: &Stream, buffer: &mut [u8], within: std::time::Duration) -> io::Result<usize> {
145    #[cfg(unix)]
146    {
147        use std::os::fd::AsRawFd as _;
148        stream.set_read_timeout(Some(within))?;
149        // SAFETY: a peek into `buffer`, a live local of the length given, on a descriptor
150        // `stream` owns for the whole call; `MSG_PEEK` leaves the bytes for the next read.
151        let read = unsafe {
152            libc::recv(
153                stream.as_raw_fd(),
154                buffer.as_mut_ptr().cast(),
155                buffer.len(),
156                libc::MSG_PEEK,
157            )
158        };
159        let error = io::Error::last_os_error();
160        stream.set_read_timeout(None)?;
161        match usize::try_from(read) {
162            Ok(read) => Ok(read),
163            Err(_)
164                if matches!(
165                    error.kind(),
166                    io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
167                ) =>
168            {
169                Ok(0)
170            }
171            Err(_) => Err(error),
172        }
173    }
174    #[cfg(windows)]
175    {
176        windows::peek(stream, buffer, within)
177    }
178    #[cfg(not(any(unix, windows)))]
179    {
180        let _ = (stream, buffer, within);
181        Ok(0)
182    }
183}
184
185/// Whether the peer at the other end of `stream` is still connected, without consuming what it
186/// sent: a peek that finds the connection over says it is not, and one that finds bytes waiting
187/// or nothing yet says it is.
188#[must_use]
189pub fn connected(stream: &Stream) -> bool {
190    #[cfg(unix)]
191    {
192        use std::os::fd::AsRawFd as _;
193        let mut byte = 0_u8;
194        // SAFETY: a one-byte peek into a live local, on a descriptor `stream` owns for the whole
195        // call; `MSG_PEEK` leaves the bytes for the next read.
196        let read = unsafe {
197            libc::recv(
198                stream.as_raw_fd(),
199                (&raw mut byte).cast(),
200                1,
201                libc::MSG_PEEK | libc::MSG_DONTWAIT,
202            )
203        };
204        match read {
205            0 => false,
206            read if read > 0 => true,
207            _ => matches!(
208                io::Error::last_os_error().kind(),
209                io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
210            ),
211        }
212    }
213    #[cfg(windows)]
214    {
215        windows::connected(stream)
216    }
217    #[cfg(not(any(unix, windows)))]
218    {
219        let _ = stream;
220        false
221    }
222}
223
224/// The refusal a page reaches: it has no local socket to reach.
225#[cfg(not(any(unix, windows)))]
226fn no_socket(_path: &Path) -> io::Error {
227    io::Error::new(io::ErrorKind::Unsupported, "a page has no local socket")
228}
229
230/// Calls `act` with a name for `path` that fits the kernel's buffer, valid for as long as `act` runs.
231#[cfg(unix)]
232fn reach<T>(path: &Path, act: impl FnOnce(&Path) -> io::Result<T>) -> io::Result<T> {
233    if path.as_os_str().len() <= MAX_PATH {
234        return act(path);
235    }
236    through_directory(path, act)
237}
238
239#[cfg(any(target_os = "linux", target_os = "android"))]
240fn through_directory<T>(path: &Path, act: impl FnOnce(&Path) -> io::Result<T>) -> io::Result<T> {
241    use std::os::fd::AsRawFd as _;
242
243    let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
244        return Err(too_long(path));
245    };
246    let parent = if parent.as_os_str().is_empty() {
247        Path::new(".")
248    } else {
249        parent
250    };
251    // The directory is held open read-only while the socket call runs, so the
252    // kernel resolves `/proc/self/fd/<fd>` to it and only the socket's own name
253    // has to fit.
254    let directory = std::fs::File::open(parent).map_err(|error| {
255        let kind = error.kind();
256        io::Error::new(kind, format!("{}: {error}", parent.display()))
257    })?;
258    let short = Path::new("/proc/self/fd")
259        .join(directory.as_raw_fd().to_string())
260        .join(name);
261    if short.as_os_str().len() > MAX_PATH {
262        return Err(too_long(path));
263    }
264    act(&short)
265}
266
267#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
268fn through_directory<T>(path: &Path, _act: impl FnOnce(&Path) -> io::Result<T>) -> io::Result<T> {
269    Err(too_long(path))
270}
271
272#[cfg(unix)]
273fn too_long(path: &Path) -> io::Error {
274    io::Error::new(
275        io::ErrorKind::InvalidInput,
276        format!(
277            "{}: a socket's name must be at most {MAX_PATH} bytes",
278            path.display()
279        ),
280    )
281}
282
283#[cfg(test)]
284#[expect(
285    clippy::mixed_attributes_style,
286    reason = "the module is a test module, whose panics the lint rules exempt, that binds a Unix socket"
287)]
288mod tests {
289    #![cfg(unix)]
290
291    use super::*;
292    use std::io::{Read as _, Write as _};
293
294    /// A directory whose sockets' paths are longer than the kernel takes.
295    fn deep() -> (tempfile::TempDir, std::path::PathBuf) {
296        let root = tempfile::tempdir().unwrap();
297        let dir = root.path().join("a".repeat(60)).join("b".repeat(60));
298        std::fs::create_dir_all(&dir).unwrap();
299        (root, dir)
300    }
301
302    tilo_test_env::scenario! {
303        fn a_socket_binds_and_connects_however_deep_its_directory;
304
305        phase a_socket_in_a_deep_directory_binds_and_answers;
306        {
307            let (_root, dir) = deep();
308            let path = dir.join("files.sock");
309            assert!(path.as_os_str().len() > MAX_PATH);
310            let listener = bind(&path).unwrap();
311            assert!(path.exists(), "the socket is named where it was asked for");
312            let mut client = connect(&path).unwrap();
313            client.write_all(b"hi").unwrap();
314            let (mut served, _) = listener.accept().unwrap();
315            let mut got = [0; 2];
316            served.read_exact(&mut got).unwrap();
317            assert_eq!(&got, b"hi");
318        }
319
320        phase nothing_bound_in_a_deep_directory_is_not_found;
321        {
322            let (_root, dir) = deep();
323            let error = connect(&dir.join("files.sock")).unwrap_err();
324            assert_eq!(error.kind(), io::ErrorKind::NotFound);
325        }
326
327        phase a_short_path_is_used_as_it_is;
328        {
329            let root = tempfile::tempdir().unwrap();
330            let path = root.path().join("s");
331            let listener = bind(&path).unwrap();
332            assert_eq!(
333                listener.local_addr().unwrap().as_pathname(),
334                Some(path.as_path())
335            );
336            connect(&path).unwrap();
337        }
338    }
339}