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