1use 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#[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#[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#[cfg(not(any(unix, windows)))]
64pub struct Listener(std::convert::Infallible);
65#[cfg(not(any(unix, windows)))]
66pub struct Stream(std::convert::Infallible);
67
68pub 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
84pub 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
100pub 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#[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
145pub 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 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#[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 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#[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#[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 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 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}