1use std::io::{self, Read, Write};
10use std::path::Path;
11use std::time::Duration;
12
13pub struct Rendezvous(backend::Rendezvous);
14
15pub enum Joined {
16 Owner(Ownership),
17 Peer(Connection),
18}
19
20pub struct Ownership(backend::Ownership);
22
23pub struct Listener(backend::Listener);
26
27pub struct Connection(backend::Connection);
28
29impl Rendezvous {
30 pub fn beside(resource: &Path) -> io::Result<Self> {
38 backend::Rendezvous::beside(resource).map(Self)
39 }
40
41 pub fn join(
45 &self,
46 timeout: Duration,
47 mut greet: impl FnMut(&Connection) -> io::Result<()>,
48 ) -> io::Result<Joined> {
49 let started = tilo_clock::now();
50 loop {
51 if let Ok(connection) = self.0.connect().map(Connection)
52 && greet(&connection).is_ok()
53 {
54 return Ok(Joined::Peer(connection));
55 }
56 if let Some(ownership) = self.0.try_own()? {
57 return Ok(Joined::Owner(Ownership(ownership)));
58 }
59 if started.elapsed() >= timeout {
60 return Err(io::Error::new(
61 io::ErrorKind::TimedOut,
62 "the process that owns this resource did not answer",
63 ));
64 }
65 std::thread::sleep(Duration::from_millis(25));
66 }
67 }
68}
69
70impl Ownership {
71 pub fn listen(&self) -> io::Result<Listener> {
72 self.0.listen().map(Listener)
73 }
74
75 pub fn hold_with(&self, command: &mut std::process::Command) {
78 self.0.hold_with(command);
79 }
80}
81
82impl Listener {
83 pub fn accept_within(&self, wait: Duration) -> io::Result<Option<Connection>> {
84 Ok(self.0.accept_within(wait)?.map(Connection))
85 }
86
87 pub fn close(&self) {
90 self.0.close();
91 }
92}
93
94impl Connection {
95 pub fn try_clone(&self) -> io::Result<Self> {
96 self.0.try_clone().map(Self)
97 }
98
99 pub fn close(&self) {
100 self.0.close();
101 }
102
103 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
105 self.0.set_read_timeout(timeout)
106 }
107}
108
109impl Read for &Connection {
110 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
111 self.0.read(buf)
112 }
113}
114
115impl Write for &Connection {
116 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
117 self.0.write(buf)
118 }
119
120 fn flush(&mut self) -> io::Result<()> {
121 self.0.flush()
122 }
123}
124
125impl Read for Connection {
126 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
127 let mut shared: &Self = self;
128 shared.read(buf)
129 }
130}
131
132impl Write for Connection {
133 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
134 let mut shared: &Self = self;
135 shared.write(buf)
136 }
137
138 fn flush(&mut self) -> io::Result<()> {
139 let mut shared: &Self = self;
140 shared.flush()
141 }
142}
143
144#[cfg(unix)]
145mod backend {
146 use std::io::{self, Read, Write};
147 use std::net::Shutdown;
148 use std::os::fd::AsRawFd;
149 use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
150 use std::os::unix::net::{SocketAddr, UnixListener, UnixStream};
151 use std::path::{Path, PathBuf};
152 use std::sync::Arc;
153 use std::time::Duration;
154
155 pub struct Rendezvous {
156 socket: PathBuf,
157 address: Arc<Address>,
158 lock: PathBuf,
159 }
160
161 pub struct Ownership {
162 socket: PathBuf,
163 address: Arc<Address>,
164 lock: advisory_lock::FileLock,
165 }
166
167 enum Address {
172 Path(PathBuf),
173 Beside {
174 directory: relative::Directory,
175 name: PathBuf,
176 },
177 }
178
179 impl Address {
180 fn new(socket: &Path) -> io::Result<Self> {
181 if SocketAddr::from_pathname(socket).is_ok() {
182 return Ok(Self::Path(socket.to_owned()));
183 }
184 let too_long = || {
185 io::Error::new(
186 io::ErrorKind::InvalidInput,
187 format!(
188 "the socket path {} is too long for a local socket",
189 socket.display()
190 ),
191 )
192 };
193 let (Some(parent), Some(name)) = (socket.parent(), socket.file_name()) else {
194 return Err(too_long());
195 };
196 let name = PathBuf::from(name);
197 if SocketAddr::from_pathname(&name).is_err() {
198 return Err(too_long());
199 }
200 Ok(Self::Beside {
201 directory: relative::Directory::open(parent)?,
202 name,
203 })
204 }
205
206 fn bind(&self) -> io::Result<UnixListener> {
207 match self {
208 Self::Path(path) => tilo_files::native::socket::bind(path),
209 Self::Beside { directory, name } => relative::bind(directory, name),
210 }
211 }
212
213 fn connect(&self) -> io::Result<UnixStream> {
214 match self {
215 Self::Path(path) => tilo_files::native::socket::connect(path),
216 Self::Beside { directory, name } => relative::connect(directory, name),
217 }
218 }
219 }
220
221 #[cfg(not(target_vendor = "apple"))]
224 mod relative {
225 use std::io;
226 use std::os::fd::{AsRawFd, OwnedFd};
227 use std::os::unix::fs::OpenOptionsExt;
228 use std::os::unix::net::{UnixListener, UnixStream};
229 use std::path::{Path, PathBuf};
230
231 pub struct Directory(OwnedFd);
232
233 impl Directory {
234 pub fn open(path: &Path) -> io::Result<Self> {
235 let directory = std::fs::OpenOptions::new()
236 .read(true)
237 .custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC)
238 .open(path)?;
239 Ok(Self(directory.into()))
240 }
241
242 fn through(&self, name: &Path) -> PathBuf {
243 PathBuf::from(format!("/proc/self/fd/{}", self.0.as_raw_fd())).join(name)
244 }
245 }
246
247 pub fn bind(directory: &Directory, name: &Path) -> io::Result<UnixListener> {
248 tilo_files::native::socket::bind(&directory.through(name))
249 }
250
251 pub fn connect(directory: &Directory, name: &Path) -> io::Result<UnixStream> {
252 tilo_files::native::socket::connect(&directory.through(name))
253 }
254 }
255
256 #[cfg(target_vendor = "apple")]
260 mod relative {
261 use std::ffi::{CString, OsString};
262 use std::io;
263 use std::os::unix::ffi::OsStringExt;
264 use std::os::unix::net::{UnixListener, UnixStream};
265 use std::path::{Path, PathBuf};
266
267 pub struct Directory(PathBuf);
268
269 impl Directory {
270 pub fn open(path: &Path) -> io::Result<Self> {
271 path.canonicalize().map(Self)
272 }
273
274 fn through<T>(
275 &self,
276 name: &Path,
277 call: impl FnOnce(PathBuf) -> io::Result<T>,
278 ) -> io::Result<T> {
279 let template = CString::new("/tmp/tilo-socket-XXXXXX").map_err(io::Error::other)?;
280 let mut template = template.into_bytes_with_nul();
281 let made = unsafe { libc::mkdtemp(template.as_mut_ptr().cast()) };
283 if made.is_null() {
284 return Err(io::Error::last_os_error());
285 }
286 template.pop();
287 let short = PathBuf::from(OsString::from_vec(template));
288 let link = short.join("d");
289 let result =
290 std::os::unix::fs::symlink(&self.0, &link).and_then(|()| call(link.join(name)));
291 let _ = std::fs::remove_file(&link);
292 let _ = std::fs::remove_dir(&short);
293 result
294 }
295 }
296
297 pub fn bind(directory: &Directory, name: &Path) -> io::Result<UnixListener> {
298 directory.through(name, |short| tilo_files::native::socket::bind(&short))
299 }
300
301 pub fn connect(directory: &Directory, name: &Path) -> io::Result<UnixStream> {
302 directory.through(name, |short| tilo_files::native::socket::connect(&short))
303 }
304 }
305
306 pub struct Listener {
307 socket: PathBuf,
308 identity: (u64, u64),
309 bound: UnixListener,
310 }
311
312 pub struct Connection(UnixStream);
313
314 fn identity(metadata: &std::fs::Metadata) -> (u64, u64) {
315 (metadata.dev(), metadata.ino())
316 }
317
318 impl Rendezvous {
319 pub fn beside(resource: &Path) -> io::Result<Self> {
320 let resource = resource.canonicalize()?;
321 let (Some(parent), Some(name)) = (resource.parent(), resource.file_name()) else {
322 return Err(io::Error::new(
323 io::ErrorKind::InvalidInput,
324 "a resource at the filesystem root has no place beside it",
325 ));
326 };
327 let sibling = |suffix: &str| {
328 let mut file = name.to_os_string();
329 file.push(suffix);
330 parent.join(file)
331 };
332 let socket = sibling(".sock");
333 let address = Arc::new(Address::new(&socket)?);
334 Ok(Self {
335 socket,
336 address,
337 lock: sibling(".lock"),
338 })
339 }
340
341 pub fn connect(&self) -> io::Result<Connection> {
342 self.address.connect().map(Connection)
343 }
344
345 pub fn try_own(&self) -> io::Result<Option<Ownership>> {
346 let file = std::fs::OpenOptions::new()
347 .read(true)
348 .write(true)
349 .create(true)
350 .truncate(false)
351 .mode(0o600)
352 .open(&self.lock)?;
353 let lock = match advisory_lock::FileLock::try_exclusive(file) {
354 Ok(lock) => lock,
355 Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
356 Err(std::fs::TryLockError::Error(error)) => return Err(error),
357 };
358 let held = lock.metadata()?;
361 if !std::fs::metadata(&self.lock).is_ok_and(|path| identity(&path) == identity(&held)) {
362 return Ok(None);
363 }
364 match std::fs::remove_file(&self.socket) {
365 Ok(()) => {}
366 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
367 Err(error) => return Err(error),
368 }
369 Ok(Some(Ownership {
370 socket: self.socket.clone(),
371 address: self.address.clone(),
372 lock,
373 }))
374 }
375 }
376
377 impl Ownership {
378 pub fn listen(&self) -> io::Result<Listener> {
379 let listener = self.address.bind()?;
380 let secured = listener
381 .set_nonblocking(true)
382 .and_then(|()| {
383 std::fs::set_permissions(&self.socket, std::fs::Permissions::from_mode(0o600))
384 })
385 .and_then(|()| std::fs::symlink_metadata(&self.socket));
386 match secured {
387 Ok(metadata) => Ok(Listener {
388 socket: self.socket.clone(),
389 identity: identity(&metadata),
390 bound: listener,
391 }),
392 Err(error) => {
393 let _ = std::fs::remove_file(&self.socket);
394 Err(error)
395 }
396 }
397 }
398
399 pub fn hold_with(&self, command: &mut std::process::Command) {
400 use std::os::unix::process::CommandExt;
401 let fd = self.lock.as_raw_fd();
402 unsafe {
407 command.pre_exec(move || {
408 if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
409 return Err(io::Error::last_os_error());
410 }
411 Ok(())
412 });
413 }
414 }
415 }
416
417 impl Listener {
418 pub fn accept_within(&self, wait: Duration) -> io::Result<Option<Connection>> {
419 let mut poll = libc::pollfd {
420 fd: self.bound.as_raw_fd(),
421 events: libc::POLLIN,
422 revents: 0,
423 };
424 let millis = libc::c_int::try_from(wait.as_millis()).unwrap_or(libc::c_int::MAX);
425 let ready = unsafe { libc::poll(&raw mut poll, 1, millis) };
427 if ready < 0 {
428 let error = io::Error::last_os_error();
429 return if error.kind() == io::ErrorKind::Interrupted {
430 Ok(None)
431 } else {
432 Err(error)
433 };
434 }
435 if ready == 0 {
436 return Ok(None);
437 }
438 match self.bound.accept() {
439 Ok((stream, _)) => {
440 stream.set_nonblocking(false)?;
442 Ok(Some(Connection(stream)))
443 }
444 Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None),
445 Err(error) => Err(error),
446 }
447 }
448
449 pub fn close(&self) {
450 if std::fs::symlink_metadata(&self.socket)
452 .is_ok_and(|metadata| identity(&metadata) == self.identity)
453 {
454 let _ = std::fs::remove_file(&self.socket);
455 }
456 }
457 }
458
459 impl Drop for Listener {
460 fn drop(&mut self) {
461 self.close();
462 }
463 }
464
465 impl Connection {
466 pub fn try_clone(&self) -> io::Result<Self> {
467 self.0.try_clone().map(Self)
468 }
469
470 pub fn close(&self) {
471 let _ = self.0.shutdown(Shutdown::Both);
472 }
473
474 pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
475 self.0.set_read_timeout(timeout)
476 }
477
478 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
479 (&self.0).read(buf)
480 }
481
482 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
483 (&self.0).write(buf)
484 }
485
486 pub fn flush(&self) -> io::Result<()> {
487 (&self.0).flush()
488 }
489 }
490}
491
492#[cfg(not(unix))]
493mod backend {
494 use std::io;
495 use std::path::Path;
496 use std::time::Duration;
497
498 pub enum Never {}
499
500 pub struct Rendezvous(Never);
501 pub struct Ownership(Never);
502 pub struct Listener(Never);
503 pub struct Connection(Never);
504
505 impl Rendezvous {
506 pub fn beside(_: &Path) -> io::Result<Self> {
507 Err(io::Error::new(
508 io::ErrorKind::Unsupported,
509 "local sockets are not available on this platform",
510 ))
511 }
512
513 pub fn connect(&self) -> io::Result<Connection> {
514 match self.0 {}
515 }
516
517 pub fn try_own(&self) -> io::Result<Option<Ownership>> {
518 match self.0 {}
519 }
520 }
521
522 impl Ownership {
523 pub fn listen(&self) -> io::Result<Listener> {
524 match self.0 {}
525 }
526
527 pub fn hold_with(&self, _: &mut std::process::Command) {
528 match self.0 {}
529 }
530 }
531
532 impl Listener {
533 pub fn accept_within(&self, _: Duration) -> io::Result<Option<Connection>> {
534 match self.0 {}
535 }
536
537 pub fn close(&self) {
538 match self.0 {}
539 }
540 }
541
542 impl Connection {
543 pub fn try_clone(&self) -> io::Result<Self> {
544 match self.0 {}
545 }
546
547 pub fn close(&self) {
548 match self.0 {}
549 }
550
551 pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
552 match self.0 {}
553 }
554
555 pub fn read(&self, _: &mut [u8]) -> io::Result<usize> {
556 match self.0 {}
557 }
558
559 pub fn write(&self, _: &[u8]) -> io::Result<usize> {
560 match self.0 {}
561 }
562
563 pub fn flush(&self) -> io::Result<()> {
564 match self.0 {}
565 }
566 }
567}
568
569#[cfg(test)]
570#[cfg(unix)]
571mod tests {
572 use super::*;
573
574 #[allow(
575 clippy::unnecessary_wraps,
576 reason = "the signature `Rendezvous::join` requires of a greeting"
577 )]
578 fn greet(_: &Connection) -> io::Result<()> {
579 Ok(())
580 }
581
582 #[test]
583 fn the_first_process_owns_and_the_next_connects() {
584 let dir = tempfile::tempdir().unwrap();
585 let resource = dir.path().join("profile");
586 std::fs::create_dir(&resource).unwrap();
587 let rendezvous = Rendezvous::beside(&resource).unwrap();
588 let Joined::Owner(owner) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
589 else {
590 panic!("nobody owned the resource");
591 };
592 let listener = owner.listen().unwrap();
593 let socket = dir.path().canonicalize().unwrap().join("profile.sock");
594 assert!(socket.exists());
595 let Joined::Peer(peer) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
596 else {
597 panic!("the owner was not reached");
598 };
599 let accepted = listener
600 .accept_within(tilo_test_env::hang_bound())
601 .unwrap()
602 .unwrap();
603 (&peer).write_all(b"hello").unwrap();
604 let mut read = [0; 5];
605 (&accepted).read_exact(&mut read).unwrap();
606 assert_eq!(&read, b"hello");
607 assert!(
608 listener
609 .accept_within(Duration::from_millis(10))
610 .unwrap()
611 .is_none()
612 );
613 listener.close();
614 assert!(!socket.exists());
615 drop(owner);
616 }
617
618 tilo_test_env::scenario! {
619 fn a_rendezvous_replaces_a_dead_owner_meets_deep_resources_and_refuses_long_paths;
620
621 phase a_dead_owners_socket_is_replaced_and_a_busy_lock_times_out;
622 {
623 let dir = tempfile::tempdir().unwrap();
624 let resource = dir.path().join("profile");
625 std::fs::create_dir(&resource).unwrap();
626 let socket = dir.path().canonicalize().unwrap().join("profile.sock");
627 drop(std::os::unix::net::UnixListener::bind(&socket).unwrap());
628 let rendezvous = Rendezvous::beside(&resource).unwrap();
629 let Joined::Owner(owner) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
630 else {
631 panic!("a dead owner's socket answered");
632 };
633 assert!(!socket.exists(), "the stale socket is removed");
634 let error = rendezvous
635 .join(Duration::from_millis(100), greet)
636 .err()
637 .unwrap();
638 assert_eq!(error.kind(), io::ErrorKind::TimedOut);
639 drop(owner);
640 assert!(matches!(
641 rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap(),
642 Joined::Owner(_)
643 ));
644 }
645
646 phase a_resource_deeper_than_a_socket_address_still_meets;
647 {
648 let dir = tempfile::tempdir().unwrap();
649 let deep = dir.path().join("d".repeat(60)).join("e".repeat(60));
650 std::fs::create_dir_all(&deep).unwrap();
651 let resource = deep.join("profile");
652 std::fs::create_dir(&resource).unwrap();
653 let socket = deep.canonicalize().unwrap().join("profile.sock");
654 assert!(std::os::unix::net::SocketAddr::from_pathname(&socket).is_err());
655 let rendezvous = Rendezvous::beside(&resource).unwrap();
656 let Joined::Owner(owner) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
657 else {
658 panic!("nobody owned the resource");
659 };
660 let listener = owner.listen().unwrap();
661 assert!(socket.exists(), "the socket is bound beside the resource");
662 let Joined::Peer(peer) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
663 else {
664 panic!("the owner was not reached");
665 };
666 let accepted = listener
667 .accept_within(tilo_test_env::hang_bound())
668 .unwrap()
669 .unwrap();
670 (&peer).write_all(b"hello").unwrap();
671 let mut read = [0; 5];
672 (&accepted).read_exact(&mut read).unwrap();
673 assert_eq!(&read, b"hello");
674 listener.close();
675 assert!(!socket.exists());
676 drop(owner);
677 }
678
679 phase a_socket_path_too_long_is_refused;
680 {
681 let dir = tempfile::tempdir().unwrap();
682 let resource = dir.path().join("x".repeat(120));
683 std::fs::create_dir(&resource).unwrap();
684 let error = Rendezvous::beside(&resource).err().unwrap();
685 assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
686 }
687 }
688}