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(feature = "tokio")]
34pub mod tokio;
35#[cfg(windows)]
36mod windows;
37#[cfg(windows)]
38pub use windows::{Listener, MAX_PATH, SocketAddr, Stream, link};
39
40#[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#[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#[cfg(not(any(unix, windows)))]
57pub struct Listener(std::convert::Infallible);
58#[cfg(not(any(unix, windows)))]
59pub struct Stream(std::convert::Infallible);
60
61pub 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
77pub 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
93pub 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#[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
138pub 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 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#[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 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#[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#[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 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 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}