tilo-process 0.5.0

The current process and, later, child processes: one API on Linux, macOS and the web, where there are none.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! One owner process per resource; every other process connects to it.
//!
//! A [`Rendezvous`] beside the resource elects the owner with an advisory lock
//! (`<name>.lock`) and lets every other process reach it over a local socket
//! (`<name>.sock`). The owner keeps its [`Ownership`] while it uses the resource, and
//! the lock is released when that drops, so the next process can take over even when
//! the owner died.

use std::io::{self, Read, Write};
use std::path::Path;
use std::time::Duration;

pub struct Rendezvous(backend::Rendezvous);

pub enum Joined {
    Owner(Ownership),
    Peer(Connection),
}

/// The right to use the resource, held until dropped.
pub struct Ownership(backend::Ownership);

/// The owner's end of the socket. [`Listener::close`] (or drop) removes the
/// socket so no process connects to an owner that stopped serving.
pub struct Listener(backend::Listener);

pub struct Connection(backend::Connection);

impl Rendezvous {
    /// The rendezvous for `resource`: `<resource>.sock` and `<resource>.lock` beside it,
    /// named after the resource's canonical path.
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidInput`] when the socket's file name alone is too long for a
    /// local socket address.
    pub fn beside(resource: &Path) -> io::Result<Self> {
        backend::Rendezvous::beside(resource).map(Self)
    }

    /// Connects to the owner, or becomes the owner when there is none. `greet` checks a new
    /// connection before it counts as a peer, and an owner that is shutting down refuses
    /// there.
    pub fn join(
        &self,
        timeout: Duration,
        mut greet: impl FnMut(&Connection) -> io::Result<()>,
    ) -> io::Result<Joined> {
        let started = tilo_clock::now();
        loop {
            if let Ok(connection) = self.0.connect().map(Connection)
                && greet(&connection).is_ok()
            {
                return Ok(Joined::Peer(connection));
            }
            if let Some(ownership) = self.0.try_own()? {
                return Ok(Joined::Owner(Ownership(ownership)));
            }
            if started.elapsed() >= timeout {
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "the process that owns this resource did not answer",
                ));
            }
            std::thread::sleep(Duration::from_millis(25));
        }
    }
}

impl Ownership {
    pub fn listen(&self) -> io::Result<Listener> {
        self.0.listen().map(Listener)
    }

    /// Gives the resource's lock to the program `command` starts, which holds the resource
    /// for as long as it runs, even when this process exits without letting go first.
    pub fn hold_with(&self, command: &mut std::process::Command) {
        self.0.hold_with(command);
    }
}

impl Listener {
    pub fn accept_within(&self, wait: Duration) -> io::Result<Option<Connection>> {
        Ok(self.0.accept_within(wait)?.map(Connection))
    }

    /// Removes the socket, so no other process connects to this owner any
    /// more. Connections already accepted are unaffected.
    pub fn close(&self) {
        self.0.close();
    }
}

impl Connection {
    pub fn try_clone(&self) -> io::Result<Self> {
        self.0.try_clone().map(Self)
    }

    pub fn close(&self) {
        self.0.close();
    }

    /// Bounds how long a read waits; `None` waits indefinitely.
    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        self.0.set_read_timeout(timeout)
    }
}

impl Read for &Connection {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl Write for &Connection {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

impl Read for Connection {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let mut shared: &Self = self;
        shared.read(buf)
    }
}

impl Write for Connection {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let mut shared: &Self = self;
        shared.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        let mut shared: &Self = self;
        shared.flush()
    }
}

#[cfg(unix)]
mod backend {
    use std::io::{self, Read, Write};
    use std::net::Shutdown;
    use std::os::fd::AsRawFd;
    use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
    use std::os::unix::net::{SocketAddr, UnixListener, UnixStream};
    use std::path::{Path, PathBuf};
    use std::sync::Arc;
    use std::time::Duration;

    pub struct Rendezvous {
        socket: PathBuf,
        address: Arc<Address>,
        lock: PathBuf,
    }

    pub struct Ownership {
        socket: PathBuf,
        address: Arc<Address>,
        lock: advisory_lock::FileLock,
    }

    /// How the socket is bound and reached. A local socket address holds a path of about a
    /// hundred bytes, and a resource may lie deeper, as a private browser profile in macOS's
    /// temporary directory does; such a socket is reached by its name relative to its
    /// directory.
    enum Address {
        Path(PathBuf),
        Beside {
            directory: relative::Directory,
            name: PathBuf,
        },
    }

    impl Address {
        fn new(socket: &Path) -> io::Result<Self> {
            if SocketAddr::from_pathname(socket).is_ok() {
                return Ok(Self::Path(socket.to_owned()));
            }
            let too_long = || {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!(
                        "the socket path {} is too long for a local socket",
                        socket.display()
                    ),
                )
            };
            let (Some(parent), Some(name)) = (socket.parent(), socket.file_name()) else {
                return Err(too_long());
            };
            let name = PathBuf::from(name);
            if SocketAddr::from_pathname(&name).is_err() {
                return Err(too_long());
            }
            Ok(Self::Beside {
                directory: relative::Directory::open(parent)?,
                name,
            })
        }

        fn bind(&self) -> io::Result<UnixListener> {
            match self {
                Self::Path(path) => tilo_files::native::socket::bind(path),
                Self::Beside { directory, name } => relative::bind(directory, name),
            }
        }

        fn connect(&self) -> io::Result<UnixStream> {
            match self {
                Self::Path(path) => tilo_files::native::socket::connect(path),
                Self::Beside { directory, name } => relative::connect(directory, name),
            }
        }
    }

    /// Linux names an open directory in a short path, `/proc/self/fd/<n>`,
    /// that the kernel resolves to the directory itself.
    #[cfg(not(target_vendor = "apple"))]
    mod relative {
        use std::io;
        use std::os::fd::{AsRawFd, OwnedFd};
        use std::os::unix::fs::OpenOptionsExt;
        use std::os::unix::net::{UnixListener, UnixStream};
        use std::path::{Path, PathBuf};

        pub struct Directory(OwnedFd);

        impl Directory {
            pub fn open(path: &Path) -> io::Result<Self> {
                let directory = std::fs::OpenOptions::new()
                    .read(true)
                    .custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC)
                    .open(path)?;
                Ok(Self(directory.into()))
            }

            fn through(&self, name: &Path) -> PathBuf {
                PathBuf::from(format!("/proc/self/fd/{}", self.0.as_raw_fd())).join(name)
            }
        }

        pub fn bind(directory: &Directory, name: &Path) -> io::Result<UnixListener> {
            tilo_files::native::socket::bind(&directory.through(name))
        }

        pub fn connect(directory: &Directory, name: &Path) -> io::Result<UnixStream> {
            tilo_files::native::socket::connect(&directory.through(name))
        }
    }

    /// macOS has no `/proc/self/fd` path and no `bindat`: the socket's directory is reached
    /// through a symbolic link in a fresh private temporary directory (`mkdtemp`, mode
    /// 0700) in `/tmp`, made for the one call and removed after it.
    #[cfg(target_vendor = "apple")]
    mod relative {
        use std::ffi::{CString, OsString};
        use std::io;
        use std::os::unix::ffi::OsStringExt;
        use std::os::unix::net::{UnixListener, UnixStream};
        use std::path::{Path, PathBuf};

        pub struct Directory(PathBuf);

        impl Directory {
            pub fn open(path: &Path) -> io::Result<Self> {
                path.canonicalize().map(Self)
            }

            fn through<T>(
                &self,
                name: &Path,
                call: impl FnOnce(PathBuf) -> io::Result<T>,
            ) -> io::Result<T> {
                let template = CString::new("/tmp/tilo-socket-XXXXXX").map_err(io::Error::other)?;
                let mut template = template.into_bytes_with_nul();
                // SAFETY: a writable, NUL-terminated template mkdtemp fills in.
                let made = unsafe { libc::mkdtemp(template.as_mut_ptr().cast()) };
                if made.is_null() {
                    return Err(io::Error::last_os_error());
                }
                template.pop();
                let short = PathBuf::from(OsString::from_vec(template));
                let link = short.join("d");
                let result =
                    std::os::unix::fs::symlink(&self.0, &link).and_then(|()| call(link.join(name)));
                let _ = std::fs::remove_file(&link);
                let _ = std::fs::remove_dir(&short);
                result
            }
        }

        pub fn bind(directory: &Directory, name: &Path) -> io::Result<UnixListener> {
            directory.through(name, |short| tilo_files::native::socket::bind(&short))
        }

        pub fn connect(directory: &Directory, name: &Path) -> io::Result<UnixStream> {
            directory.through(name, |short| tilo_files::native::socket::connect(&short))
        }
    }

    pub struct Listener {
        socket: PathBuf,
        identity: (u64, u64),
        bound: UnixListener,
    }

    pub struct Connection(UnixStream);

    fn identity(metadata: &std::fs::Metadata) -> (u64, u64) {
        (metadata.dev(), metadata.ino())
    }

    impl Rendezvous {
        pub fn beside(resource: &Path) -> io::Result<Self> {
            let resource = resource.canonicalize()?;
            let (Some(parent), Some(name)) = (resource.parent(), resource.file_name()) else {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "a resource at the filesystem root has no place beside it",
                ));
            };
            let sibling = |suffix: &str| {
                let mut file = name.to_os_string();
                file.push(suffix);
                parent.join(file)
            };
            let socket = sibling(".sock");
            let address = Arc::new(Address::new(&socket)?);
            Ok(Self {
                socket,
                address,
                lock: sibling(".lock"),
            })
        }

        pub fn connect(&self) -> io::Result<Connection> {
            self.address.connect().map(Connection)
        }

        pub fn try_own(&self) -> io::Result<Option<Ownership>> {
            let file = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .mode(0o600)
                .open(&self.lock)?;
            let lock = match advisory_lock::FileLock::try_exclusive(file) {
                Ok(lock) => lock,
                Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
                Err(std::fs::TryLockError::Error(error)) => return Err(error),
            };
            // The previous owner may have removed the lock file, with its directory, after this
            // process opened it: a lock on a file that is gone owns nothing.
            let held = lock.metadata()?;
            if !std::fs::metadata(&self.lock).is_ok_and(|path| identity(&path) == identity(&held)) {
                return Ok(None);
            }
            match std::fs::remove_file(&self.socket) {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
            Ok(Some(Ownership {
                socket: self.socket.clone(),
                address: self.address.clone(),
                lock,
            }))
        }
    }

    impl Ownership {
        pub fn listen(&self) -> io::Result<Listener> {
            let listener = self.address.bind()?;
            let secured = listener
                .set_nonblocking(true)
                .and_then(|()| {
                    std::fs::set_permissions(&self.socket, std::fs::Permissions::from_mode(0o600))
                })
                .and_then(|()| std::fs::symlink_metadata(&self.socket));
            match secured {
                Ok(metadata) => Ok(Listener {
                    socket: self.socket.clone(),
                    identity: identity(&metadata),
                    bound: listener,
                }),
                Err(error) => {
                    let _ = std::fs::remove_file(&self.socket);
                    Err(error)
                }
            }
        }

        pub fn hold_with(&self, command: &mut std::process::Command) {
            use std::os::unix::process::CommandExt;
            let fd = self.lock.as_raw_fd();
            // SAFETY: one async-signal-safe `fcntl` on a descriptor this
            // ownership keeps open until the child has been spawned. Clearing
            // close-on-exec in the child alone hands it the open description
            // the lock belongs to; nothing else in this process inherits it.
            unsafe {
                command.pre_exec(move || {
                    if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
                        return Err(io::Error::last_os_error());
                    }
                    Ok(())
                });
            }
        }
    }

    impl Listener {
        pub fn accept_within(&self, wait: Duration) -> io::Result<Option<Connection>> {
            let mut poll = libc::pollfd {
                fd: self.bound.as_raw_fd(),
                events: libc::POLLIN,
                revents: 0,
            };
            let millis = libc::c_int::try_from(wait.as_millis()).unwrap_or(libc::c_int::MAX);
            // SAFETY: one valid pollfd that outlives the call.
            let ready = unsafe { libc::poll(&raw mut poll, 1, millis) };
            if ready < 0 {
                let error = io::Error::last_os_error();
                return if error.kind() == io::ErrorKind::Interrupted {
                    Ok(None)
                } else {
                    Err(error)
                };
            }
            if ready == 0 {
                return Ok(None);
            }
            match self.bound.accept() {
                Ok((stream, _)) => {
                    // macOS hands accepted sockets the listener's flags.
                    stream.set_nonblocking(false)?;
                    Ok(Some(Connection(stream)))
                }
                Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None),
                Err(error) => Err(error),
            }
        }

        pub fn close(&self) {
            // Only this owner's socket: a successor may already serve its own.
            if std::fs::symlink_metadata(&self.socket)
                .is_ok_and(|metadata| identity(&metadata) == self.identity)
            {
                let _ = std::fs::remove_file(&self.socket);
            }
        }
    }

    impl Drop for Listener {
        fn drop(&mut self) {
            self.close();
        }
    }

    impl Connection {
        pub fn try_clone(&self) -> io::Result<Self> {
            self.0.try_clone().map(Self)
        }

        pub fn close(&self) {
            let _ = self.0.shutdown(Shutdown::Both);
        }

        pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
            self.0.set_read_timeout(timeout)
        }

        pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
            (&self.0).read(buf)
        }

        pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
            (&self.0).write(buf)
        }

        pub fn flush(&self) -> io::Result<()> {
            (&self.0).flush()
        }
    }
}

#[cfg(not(unix))]
mod backend {
    use std::io;
    use std::path::Path;
    use std::time::Duration;

    pub enum Never {}

    pub struct Rendezvous(Never);
    pub struct Ownership(Never);
    pub struct Listener(Never);
    pub struct Connection(Never);

    impl Rendezvous {
        pub fn beside(_: &Path) -> io::Result<Self> {
            Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "local sockets are not available on this platform",
            ))
        }

        pub fn connect(&self) -> io::Result<Connection> {
            match self.0 {}
        }

        pub fn try_own(&self) -> io::Result<Option<Ownership>> {
            match self.0 {}
        }
    }

    impl Ownership {
        pub fn listen(&self) -> io::Result<Listener> {
            match self.0 {}
        }

        pub fn hold_with(&self, _: &mut std::process::Command) {
            match self.0 {}
        }
    }

    impl Listener {
        pub fn accept_within(&self, _: Duration) -> io::Result<Option<Connection>> {
            match self.0 {}
        }

        pub fn close(&self) {
            match self.0 {}
        }
    }

    impl Connection {
        pub fn try_clone(&self) -> io::Result<Self> {
            match self.0 {}
        }

        pub fn close(&self) {
            match self.0 {}
        }

        pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
            match self.0 {}
        }

        pub fn read(&self, _: &mut [u8]) -> io::Result<usize> {
            match self.0 {}
        }

        pub fn write(&self, _: &[u8]) -> io::Result<usize> {
            match self.0 {}
        }

        pub fn flush(&self) -> io::Result<()> {
            match self.0 {}
        }
    }
}

#[cfg(test)]
#[cfg(unix)]
mod tests {
    use super::*;

    #[allow(
        clippy::unnecessary_wraps,
        reason = "the signature `Rendezvous::join` requires of a greeting"
    )]
    fn greet(_: &Connection) -> io::Result<()> {
        Ok(())
    }

    #[test]
    fn the_first_process_owns_and_the_next_connects() {
        let dir = tempfile::tempdir().unwrap();
        let resource = dir.path().join("profile");
        std::fs::create_dir(&resource).unwrap();
        let rendezvous = Rendezvous::beside(&resource).unwrap();
        let Joined::Owner(owner) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
        else {
            panic!("nobody owned the resource");
        };
        let listener = owner.listen().unwrap();
        let socket = dir.path().canonicalize().unwrap().join("profile.sock");
        assert!(socket.exists());
        let Joined::Peer(peer) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
        else {
            panic!("the owner was not reached");
        };
        let accepted = listener
            .accept_within(tilo_test_env::hang_bound())
            .unwrap()
            .unwrap();
        (&peer).write_all(b"hello").unwrap();
        let mut read = [0; 5];
        (&accepted).read_exact(&mut read).unwrap();
        assert_eq!(&read, b"hello");
        assert!(
            listener
                .accept_within(Duration::from_millis(10))
                .unwrap()
                .is_none()
        );
        listener.close();
        assert!(!socket.exists());
        drop(owner);
    }

    tilo_test_env::scenario! {
        fn a_rendezvous_replaces_a_dead_owner_meets_deep_resources_and_refuses_long_paths;

        phase a_dead_owners_socket_is_replaced_and_a_busy_lock_times_out;
        {
            let dir = tempfile::tempdir().unwrap();
            let resource = dir.path().join("profile");
            std::fs::create_dir(&resource).unwrap();
            let socket = dir.path().canonicalize().unwrap().join("profile.sock");
            drop(std::os::unix::net::UnixListener::bind(&socket).unwrap());
            let rendezvous = Rendezvous::beside(&resource).unwrap();
            let Joined::Owner(owner) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
            else {
                panic!("a dead owner's socket answered");
            };
            assert!(!socket.exists(), "the stale socket is removed");
            let error = rendezvous
                .join(Duration::from_millis(100), greet)
                .err()
                .unwrap();
            assert_eq!(error.kind(), io::ErrorKind::TimedOut);
            drop(owner);
            assert!(matches!(
                rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap(),
                Joined::Owner(_)
            ));
        }

        phase a_resource_deeper_than_a_socket_address_still_meets;
        {
            let dir = tempfile::tempdir().unwrap();
            let deep = dir.path().join("d".repeat(60)).join("e".repeat(60));
            std::fs::create_dir_all(&deep).unwrap();
            let resource = deep.join("profile");
            std::fs::create_dir(&resource).unwrap();
            let socket = deep.canonicalize().unwrap().join("profile.sock");
            assert!(std::os::unix::net::SocketAddr::from_pathname(&socket).is_err());
            let rendezvous = Rendezvous::beside(&resource).unwrap();
            let Joined::Owner(owner) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
            else {
                panic!("nobody owned the resource");
            };
            let listener = owner.listen().unwrap();
            assert!(socket.exists(), "the socket is bound beside the resource");
            let Joined::Peer(peer) = rendezvous.join(tilo_test_env::hang_bound(), greet).unwrap()
            else {
                panic!("the owner was not reached");
            };
            let accepted = listener
                .accept_within(tilo_test_env::hang_bound())
                .unwrap()
                .unwrap();
            (&peer).write_all(b"hello").unwrap();
            let mut read = [0; 5];
            (&accepted).read_exact(&mut read).unwrap();
            assert_eq!(&read, b"hello");
            listener.close();
            assert!(!socket.exists());
            drop(owner);
        }

        phase a_socket_path_too_long_is_refused;
        {
            let dir = tempfile::tempdir().unwrap();
            let resource = dir.path().join("x".repeat(120));
            std::fs::create_dir(&resource).unwrap();
            let error = Rendezvous::beside(&resource).err().unwrap();
            assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        }
    }
}