orbit-core 0.5.3

Fleet-aware shared-memory rings over POSIX shared memory.
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! POSIX shared-memory helpers — V1 substrate for cross-process rings.
//!
//! Wraps `shm_open` / `ftruncate` / `mmap` / `munmap` / `shm_unlink`
//! into a small, RAII-friendly API. Unix-only; Windows support is
//! a separate concern (Win32 named file mapping) that can land later.
//!
//! ## Naming
//!
//! Segments are named `/orbit-{fleet}-{kind}-{uid}` — fleet name from
//! the embedder, KIND from `OrbitTyped::KIND`, UID from `geteuid()`.
//! UID-scoping avoids the `/dev/shm` sticky-bit cross-user collision
//! problem (a stale segment owned by one user blocks another from
//! `shm_unlink`-ing it on next boot).
//!
//! Rings that require a process-recoverable writer lock also open a
//! companion `orbit-{fleet}-{kind}-{uid}.lock` file. It carries no
//! ring data or state; it only supplies a regular-file inode for `flock`,
//! because advisory locking on a POSIX SHM descriptor is not uniformly
//! supported across the Unix targets Orbit serves. An unlocked stale
//! companion file is safe to reuse.
//!
//! Those files live in a per-uid directory — `$XDG_RUNTIME_DIR/orbit-{uid}`
//! where the session provides one, `/tmp/orbit-{uid}` otherwise — created
//! `0700` and checked on every lock. They were once in `/tmp` directly, which
//! made them squattable: see [`lock_dir`].
//!
//! ## Lifetime
//!
//! [`ShmRegion`] owns the mapped pointer and unmaps on drop. It does
//! NOT `shm_unlink` on drop — the segment lives until an explicit
//! [`ShmRegion::unlink`] call. This matches POSIX convention: a
//! segment with mapped users is not removed; `shm_unlink` only
//! prevents *new* opens, the current mapping stays valid until the
//! last process unmaps.

#![cfg(unix)]

use std::ffi::CString;
use std::fs::OpenOptions;
use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::ptr::NonNull;

/// Namespace used by Orbit POSIX shared-memory objects.
pub const SHM_NAMESPACE: &str = "orbit";

/// Maximum POSIX access allowed for one SHM object, independent of its layout.
///
/// New objects are owned by the effective uid. On macOS, the selected group
/// must be the creator's effective gid and the requested mode is passed directly
/// to `shm_open` (with the platform's native creation-mask semantics).
/// Other Unix targets create privately, then set the requested group and exact
/// group-sharing mode. `OwnerOnly` uses the existing `shm_open(..., 0600)` path.
/// Orbit never changes `umask` or process credentials, or chmods/chowns an
/// existing object. This does not
/// isolate processes running under the same uid.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ShmAccessPolicy {
    /// Owner read/write, no group or other access (`0600`).
    #[default]
    OwnerOnly,
    /// Owner read/write and selected group read (`0640`).
    GroupRead { gid: u32 },
    /// Owner and selected group read/write (`0660`). Trust every group writer.
    GroupReadWrite { gid: u32 }
}

impl ShmAccessPolicy {
    pub const fn mode(self) -> u32 {
        match self {
            Self::OwnerOnly => 0o600,
            Self::GroupRead { .. } => 0o640,
            Self::GroupReadWrite { .. } => 0o660
        }
    }

    pub const fn gid(self) -> Option<u32> {
        match self {
            Self::OwnerOnly => None,
            Self::GroupRead { gid } | Self::GroupReadWrite { gid } => Some(gid)
        }
    }
}

/// Result of physically validating an existing POSIX SHM object.
///
/// This check is deliberately below ring semantics: it verifies that the
/// named object satisfies the access policy and is large enough for the requested mapping,
/// but it does not inspect an owning data structure's magic, version, or
/// geometry header.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ShmValidation {
    /// No object currently exists under the requested name.
    Missing,
    /// The object exists and can safely back at least the requested mapping.
    Valid { actual_size: usize }
}

/// A mapped POSIX SHM region. Drop unmaps; `unlink` removes the
/// underlying name and any companion lock file (only the *creator*
/// should call it on shutdown).
pub struct ShmRegion {
    name: CString,
    lock_path: PathBuf,
    /// Whether this region uses the companion file for ordered writes.
    ///
    /// The descriptor itself is deliberately not retained: every critical
    /// section opens its own file description so a later fork does not inherit
    /// an idle descriptor that can keep a future `flock` alive.
    process_lock: bool,
    ptr: NonNull<u8>,
    len: usize,
    /// True when this handle was the one that *created* the segment
    /// (so it knows to `shm_unlink` if asked). Other attachers see
    /// `false`.
    created: bool
}

impl ShmRegion {
    /// Validate an existing shared-memory object without creating, mapping,
    /// resetting, or unlinking it.
    ///
    /// Returns [`ShmValidation::Missing`] when the name does not exist. A
    /// present object must be at least `minimum_size` bytes; larger objects
    /// are accepted because some platforms report page-rounded SHM sizes.
    /// The owning ring or table remains responsible for validating its own
    /// persisted ABI header after mapping.
    /// The expected owner is the effective uid and the policy is `OwnerOnly`.
    pub fn validate_existing(
        name: &str,
        minimum_size: usize
    ) -> io::Result<ShmValidation> {
        Self::validate_existing_with_policy(
            name,
            minimum_size,
            unsafe { libc::geteuid() },
            ShmAccessPolicy::default()
        )
    }

    /// Validate size, expected owner and maximum permissions without mutation.
    /// `owner_uid` is trusted configuration, not metadata read from the object.
    pub fn validate_existing_with_policy(
        name: &str,
        minimum_size: usize,
        owner_uid: u32,
        policy: ShmAccessPolicy
    ) -> io::Result<ShmValidation> {
        let cname = CString::new(name)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "shm name has nul byte"))?;
        let raw_fd = loop {
            // SAFETY: passing a valid C string and well-known POSIX flags.
            // macOS `shm_open` rejects `O_CLOEXEC` with EINVAL. The descriptor
            // is scoped to this validation call and closes before return.
            let fd = unsafe { libc::shm_open(cname.as_ptr(), libc::O_RDONLY, 0o600) };
            if fd >= 0 {
                break fd;
            }
            let error = io::Error::last_os_error();
            if error.kind() == io::ErrorKind::Interrupted {
                continue;
            }
            if error.raw_os_error() == Some(libc::ENOENT) {
                return Ok(ShmValidation::Missing);
            }
            return Err(error);
        };
        // SAFETY: `raw_fd` was returned by `shm_open` and is now uniquely
        // owned by this scope.
        let fd = unsafe { OwnedFd::from_raw_fd(raw_fd) };
        let actual_size = shm_object_size(&fd, name, owner_uid, policy)?;
        validate_minimum_size(name, actual_size, minimum_size)?;
        Ok(ShmValidation::Valid { actual_size })
    }

    /// Map an existing shared-memory object read-only.
    ///
    /// This path never creates, sizes, locks, resets, or unlinks the object.
    /// It is kept crate-private so callers receive a capability such as a
    /// read-only ring view rather than a [`ShmRegion`] that also exposes
    /// lifecycle and writable-pointer operations.
    pub(crate) fn open_existing_read_only(
        name: &str,
        minimum_size: usize,
        owner_uid: u32,
        policy: ShmAccessPolicy
    ) -> io::Result<Self> {
        let cname = CString::new(name)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "shm name has nul byte"))?;
        let raw_fd = loop {
            // SAFETY: passing a valid C string and read-only POSIX flags.
            // macOS `shm_open` rejects `O_CLOEXEC` with EINVAL. This
            // descriptor closes immediately after `mmap`, before the view is
            // returned, so it cannot leak across a later exec.
            let fd = unsafe { libc::shm_open(cname.as_ptr(), libc::O_RDONLY, 0o600) };
            if fd >= 0 {
                break fd;
            }
            let error = io::Error::last_os_error();
            if error.kind() == io::ErrorKind::Interrupted {
                continue;
            }
            return Err(error);
        };
        // SAFETY: `raw_fd` was returned by `shm_open` and is now uniquely
        // owned by this scope.
        let fd = unsafe { OwnedFd::from_raw_fd(raw_fd) };
        let actual_size = shm_object_size(&fd, name, owner_uid, policy)?;
        validate_minimum_size(name, actual_size, minimum_size)?;

        // Map the complete object so its persisted header can describe the
        // geometry without the observer reproducing the producer's layout.
        // SAFETY: fd is valid, actual_size is positive after minimum
        // validation, and the mapping is read-only.
        let ptr = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                actual_size,
                libc::PROT_READ,
                libc::MAP_SHARED,
                fd.as_raw_fd(),
                0
            )
        };
        if ptr == libc::MAP_FAILED {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: mmap returned a non-null pointer (checked above).
        let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returned non-null on success");

        Ok(Self {
            lock_path: lock_file_path(name),
            name: cname,
            process_lock: false,
            ptr,
            len: actual_size,
            created: false
        })
    }

    /// Open or create a shared-memory segment of `size` bytes,
    /// memory-mapped read/write. Idempotent: if the segment already
    /// exists with the same name and enough mapped bytes, it is reused
    /// (`created = false`). First creation does `ftruncate(size)`;
    /// later opens verify the existing object before mapping it. Some
    /// platforms report a page-rounded SHM size, so a larger `st_size`
    /// is valid; the owning data structure must verify its own header.
    /// Existing objects must belong to the effective uid and satisfy `OwnerOnly`.
    pub fn open_or_create(
        name: &str,
        size: usize
    ) -> io::Result<Self> {
        Self::open_or_create_with_policy(name, size, ShmAccessPolicy::default())
    }

    /// Open or create using an explicit access policy. Existing objects must
    /// belong to the effective uid and pass the policy before being mapped.
    /// Rejection never resizes, chmods, chowns or unlinks an existing object.
    pub fn open_or_create_with_policy(
        name: &str,
        size: usize,
        policy: ShmAccessPolicy
    ) -> io::Result<Self> {
        let (region, initialization_lock) = Self::open_or_create_inner(name, size, false, policy)?;
        debug_assert!(initialization_lock.is_none());
        Ok(region)
    }

    /// Open or create a region while holding its process lock through caller
    /// initialization. This prevents a peer from observing the interval
    /// between `shm_open` and the owning data structure's initialized header.
    pub fn open_or_create_locked(
        name: &str,
        size: usize
    ) -> io::Result<(Self, ShmRegionLock)> {
        Self::open_or_create_locked_with_policy(name, size, ShmAccessPolicy::default())
    }

    /// Policy-aware creation with the existing owner-local initialization lock.
    /// Group permissions do not make that lock or fleet membership cross-user.
    pub fn open_or_create_locked_with_policy(
        name: &str,
        size: usize,
        policy: ShmAccessPolicy
    ) -> io::Result<(Self, ShmRegionLock)> {
        let (region, initialization_lock) = Self::open_or_create_inner(name, size, true, policy)?;
        Ok((
            region,
            initialization_lock.expect("locked SHM open must return its initialization lock")
        ))
    }

    fn open_or_create_inner(
        name: &str,
        size: usize,
        process_lock: bool,
        policy: ShmAccessPolicy
    ) -> io::Result<(Self, Option<ShmRegionLock>)> {
        let cname = CString::new(name)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "shm name has nul byte"))?;
        let lock_path = lock_file_path(name);
        let initialization_lock =
            if process_lock { Some(lock_path_exclusive(&lock_path)?) } else { None };

        // Darwin cannot fchmod/fchown a POSIX SHM descriptor. Grant only the
        // intended group at creation; attaching a matching existing object is OK.
        #[cfg(target_os = "macos")]
        let can_create = policy.gid().is_none_or(|gid| gid == unsafe { libc::getegid() });
        #[cfg(target_os = "macos")]
        let creation_mode = policy.mode();
        // Elsewhere, don't expose the object to its initial group before chown.
        #[cfg(not(target_os = "macos"))]
        let (can_create, creation_mode) = (true, 0o600u32);
        // Try create-exclusive first; if it already exists, open.
        let (raw_fd, created) = unsafe {
            // SAFETY: passing a valid C string and well-known POSIX flags.
            let fd = if can_create {
                libc::shm_open(
                    cname.as_ptr(),
                    libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
                    creation_mode
                )
            } else {
                libc::shm_open(cname.as_ptr(), libc::O_RDWR, 0)
            };
            if fd >= 0 {
                (fd, can_create)
            } else {
                // Could be EEXIST (already created by a peer) or another error.
                let err = io::Error::last_os_error();
                if !can_create && err.raw_os_error() == Some(libc::ENOENT) {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "creating group-shared SHM requires the selected effective gid"
                    ));
                }
                if err.raw_os_error() != Some(libc::EEXIST) {
                    return Err(err);
                }
                let fd = libc::shm_open(cname.as_ptr(), libc::O_RDWR, 0o600);
                if fd < 0 {
                    return Err(io::Error::last_os_error());
                }
                (fd, false)
            }
        };
        // SAFETY: `raw_fd` was returned by `shm_open` and is now uniquely
        // owned by this scope.
        let fd = unsafe { OwnedFd::from_raw_fd(raw_fd) };

        #[cfg(not(target_os = "macos"))]
        if created && let Err(error) = configure_new_shm(&fd, policy) {
            let _ = unsafe { libc::shm_unlink(cname.as_ptr()) };
            return Err(error);
        }

        // Verify ownership and permissions before ftruncate or mmap. Only a
        // newly created object is ours to unlink on initialization failure.
        let owner_uid = unsafe { libc::geteuid() };
        if let Err(error) = shm_object_size(&fd, name, owner_uid, policy) {
            if created {
                let _ = unsafe { libc::shm_unlink(cname.as_ptr()) };
            }
            return Err(error);
        }

        // Size the segment on first creation.
        if created {
            // SAFETY: fd is a valid POSIX fd we just received.
            let rc = unsafe { libc::ftruncate(fd.as_raw_fd(), size as libc::off_t) };
            if rc != 0 {
                let err = io::Error::last_os_error();
                let _ = unsafe { libc::shm_unlink(cname.as_ptr()) };
                return Err(err);
            }
        }

        // Never mmap beyond the real SHM object: access past it can raise
        // SIGBUS. A larger reported size is valid on platforms (notably
        // macOS) that page-round POSIX SHM objects; callers verify their
        // own ABI metadata after mapping.
        let actual_size = match shm_object_size(&fd, name, owner_uid, policy) {
            Ok(actual_size) => actual_size,
            Err(error) => {
                if created {
                    let _ = unsafe { libc::shm_unlink(cname.as_ptr()) };
                }
                return Err(error);
            }
        };
        if let Err(error) = validate_minimum_size(name, actual_size, size) {
            if created {
                let _ = unsafe { libc::shm_unlink(cname.as_ptr()) };
            }
            return Err(error);
        }

        // Memory-map the segment.
        // SAFETY: fd valid, size positive, flags well-known.
        let ptr = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                size,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_SHARED,
                fd.as_raw_fd(),
                0
            )
        };

        if ptr == libc::MAP_FAILED {
            let err = io::Error::last_os_error();
            if created {
                let _ = unsafe { libc::shm_unlink(cname.as_ptr()) };
            }
            return Err(err);
        }

        // SAFETY: mmap returned a non-null pointer (we just checked).
        let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returned non-null on success");

        Ok((
            Self { name: cname, lock_path, process_lock, ptr, len: size, created },
            initialization_lock
        ))
    }

    /// Raw mapped pointer to the start of the region.
    pub fn as_ptr(&self) -> *mut u8 {
        self.ptr.as_ptr()
    }

    /// Length of the mapped region (the `size` passed to `open_or_create`).
    pub fn len(&self) -> usize {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// True when this handle was the one that created the segment.
    /// Useful for picking which process performs first-time
    /// initialization of the header.
    pub fn created(&self) -> bool {
        self.created
    }

    /// Acquire an exclusive cross-process lock tied to this SHM name.
    ///
    /// `flock` ownership is held by the kernel and is released when a process
    /// exits or the descriptor closes, including abnormal termination.
    pub fn lock_exclusive(&self) -> io::Result<ShmRegionLock> {
        if !self.process_lock {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "SHM region was opened without a process lock"
            ));
        }
        lock_path_exclusive(&self.lock_path)
    }

    #[cfg(test)]
    pub(crate) fn try_lock_exclusive(&self) -> io::Result<ShmRegionLock> {
        if !self.process_lock {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "SHM region was opened without a process lock"
            ));
        }
        let lock_fd = open_lock_file(&self.lock_path)?;
        let rc = unsafe { libc::flock(lock_fd.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
        if rc == 0 { Ok(ShmRegionLock { lock_fd }) } else { Err(io::Error::last_os_error()) }
    }

    /// Remove the underlying segment name. Existing mappings stay
    /// valid until each process drops its `ShmRegion`. Use only on
    /// shutdown / fleet teardown by the process that owns lifecycle.
    pub fn unlink(&self) -> io::Result<()> {
        // SAFETY: name is a valid C string.
        let rc = unsafe { libc::shm_unlink(self.name.as_ptr()) };
        let shm_error = if rc != 0 {
            let err = io::Error::last_os_error();
            // ENOENT is fine — segment was already unlinked.
            if err.raw_os_error() == Some(libc::ENOENT) { None } else { Some(err) }
        } else {
            None
        };
        let mut lock_error = match std::fs::remove_file(&self.lock_path) {
            Ok(()) => None,
            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
            Err(error) => Some(error)
        };
        let name = self.name.to_string_lossy();
        // SAFETY: a plain syscall with no arguments.
        let uid = unsafe { libc::geteuid() };
        match companion_lock_files(&name, uid) {
            Ok(files) => {
                for file in files {
                    if let Err(error) = std::fs::remove_file(&file)
                        && error.kind() != io::ErrorKind::NotFound
                    {
                        lock_error.get_or_insert(error);
                    }
                }
            }
            Err(error) => {
                lock_error.get_or_insert(error);
            }
        }
        if let Some(error) = shm_error.or(lock_error) {
            return Err(error);
        }
        Ok(())
    }
}

#[cfg(not(target_os = "macos"))]
fn configure_new_shm(
    fd: &OwnedFd,
    policy: ShmAccessPolicy
) -> io::Result<()> {
    let Some(gid) = policy.gid() else {
        return Ok(());
    };
    if gid == !0 {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid SHM group id"));
    }
    // SAFETY: this is our new, still owner-only object. Preserve its uid.
    if unsafe { libc::fchown(fd.as_raw_fd(), !0, gid) } != 0 {
        return Err(io::Error::last_os_error());
    }
    // Explicit group-sharing policy, applied only after group ownership is set.
    if unsafe { libc::fchmod(fd.as_raw_fd(), policy.mode() as _) } != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

fn shm_object_size(
    fd: &OwnedFd,
    name: &str,
    owner_uid: u32,
    policy: ShmAccessPolicy
) -> io::Result<usize> {
    let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
    // SAFETY: `fd` is valid and `stat` points to writable storage.
    let stat_rc = unsafe { libc::fstat(fd.as_raw_fd(), stat.as_mut_ptr()) };
    if stat_rc != 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `fstat` succeeded and initialized the structure.
    let stat = unsafe { stat.assume_init() };
    let mode = u64::from(stat.st_mode) & 0o7777;
    if stat.st_uid != owner_uid
        || policy.gid().is_some_and(|gid| gid != stat.st_gid)
        || mode & !u64::from(policy.mode()) != 0
    {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "SHM segment {name} owner/group/mode do not satisfy {policy:?} for uid {owner_uid}"
            )
        ));
    }
    let actual_size = stat.st_size;
    usize::try_from(actual_size).map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("SHM segment {name} reported invalid size {actual_size}")
        )
    })
}

fn validate_minimum_size(
    name: &str,
    actual_size: usize,
    minimum_size: usize
) -> io::Result<()> {
    if actual_size < minimum_size {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "SHM segment {name} size {actual_size} is smaller than requested mapping {minimum_size}"
            )
        ));
    }
    Ok(())
}

/// RAII guard for a [`ShmRegion`]'s process-recoverable exclusive lock.
///
/// Semantic crates use this when a current-state transition must be atomic
/// across fleet processes. Dropping the guard releases the kernel lock.
pub struct ShmRegionLock {
    lock_fd: OwnedFd
}

impl Drop for ShmRegionLock {
    fn drop(&mut self) {
        let _ = unsafe { libc::flock(self.lock_fd.as_raw_fd(), libc::LOCK_UN) };
    }
}

fn lock_path_exclusive(lock_path: &Path) -> io::Result<ShmRegionLock> {
    lock_fd_exclusive(open_lock_file(lock_path)?)
}

fn open_lock_file(lock_path: &Path) -> io::Result<OwnedFd> {
    use std::os::unix::fs::MetadataExt;

    if let Some(dir) = lock_path.parent() {
        ensure_lock_dir(dir)?;
    }

    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .mode(0o600)
        .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW)
        .open(lock_path)?;

    // The directory check makes this unreachable, which is the reason to make
    // it anyway: it turns a property inferred from the directory's mode into
    // one this function establishes about the descriptor it is about to lock.
    let uid = unsafe { libc::geteuid() };
    let owner = file.metadata()?.uid();
    if owner != uid {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("{} is owned by uid {owner} rather than {uid}", lock_path.display())
        ));
    }

    Ok(file.into())
}

fn lock_fd_exclusive(lock_fd: OwnedFd) -> io::Result<ShmRegionLock> {
    loop {
        let rc = unsafe { libc::flock(lock_fd.as_raw_fd(), libc::LOCK_EX) };
        if rc == 0 {
            return Ok(ShmRegionLock { lock_fd });
        }
        let error = io::Error::last_os_error();
        if error.kind() != io::ErrorKind::Interrupted {
            return Err(error);
        }
    }
}

impl Drop for ShmRegion {
    fn drop(&mut self) {
        // SAFETY: ptr came from mmap of `self.len` bytes; munmap is the inverse.
        unsafe {
            libc::munmap(self.ptr.as_ptr().cast(), self.len);
        }
    }
}

// SAFETY: the underlying region is shared memory and synchronization
// happens at the slot level (atomic seq counters); the handle itself
// is just a pointer + length, safe to send/share.
unsafe impl Send for ShmRegion {}
unsafe impl Sync for ShmRegion {}

/// Build the conventional name for an Orbit ring segment.
pub fn ring_segment_name(
    fleet_name: &str,
    kind: u8
) -> String {
    // SAFETY: `geteuid` always returns a value; no error path.
    let uid = unsafe { libc::geteuid() };
    ring_segment_name_for_uid(fleet_name, kind, uid)
}

/// Build the conventional name for an Orbit ring segment owned by `uid`.
///
/// This form is intended for inspection and lifecycle tools that need to
/// address a user other than their own effective uid.
pub fn ring_segment_name_for_uid(
    fleet_name: &str,
    kind: u8,
    uid: u32
) -> String {
    format!("/{SHM_NAMESPACE}-{fleet_name}-{kind}-{uid}")
}

/// Where a fleet's members hold their presence: `<lock dir>/orbit-<fleet>.fleet`.
pub fn fleet_lock_path(fleet_name: &str) -> PathBuf {
    lock_dir().join(format!("{SHM_NAMESPACE}-{fleet_name}.fleet"))
}

/// The same for another user's fleet, for lifecycle tools that address a uid
/// other than their own.
pub fn fleet_lock_path_for_uid(
    fleet_name: &str,
    uid: u32
) -> PathBuf {
    lock_dir_for_uid(uid).join(format!("{SHM_NAMESPACE}-{fleet_name}.fleet"))
}

/// A process's membership in a fleet: a shared `flock` on the fleet's lock
/// file, held for as long as this lives and released by the kernel when the
/// process dies, however it dies. It is what [`try_lock_fleet_exclusive`]
/// contends with, so a tool that removes the fleet's segments cannot do so
/// while any member is alive.
pub struct FleetMembership {
    lock_fd: OwnedFd
}

impl Drop for FleetMembership {
    fn drop(&mut self) {
        let _ = unsafe { libc::flock(self.lock_fd.as_raw_fd(), libc::LOCK_UN) };
    }
}

/// Join the fleet's membership. Waits for a lifecycle tool that holds the
/// exclusive lock at that moment; a clear in progress finishes first.
pub fn join_fleet_membership(fleet_name: &str) -> io::Result<FleetMembership> {
    let lock_fd = open_lock_file(&fleet_lock_path(fleet_name))?;
    // SAFETY: `lock_fd` is an open descriptor owned by this call.
    let rc = unsafe { libc::flock(lock_fd.as_raw_fd(), libc::LOCK_SH) };
    if rc != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(FleetMembership { lock_fd })
}

/// Exclusive hold on a fleet, for the tool that removes its segments.
///
/// `Ok(None)` means a member is alive and the fleet must not be touched;
/// there is deliberately no way to force past it. `Ok(Some(_))` keeps the
/// fleet closed to new members until the guard is dropped, so a removal
/// cannot interleave with a start. Never waits.
pub fn try_lock_fleet_exclusive(
    fleet_name: &str,
    uid: u32
) -> io::Result<Option<ShmRegionLock>> {
    // Creating the file when no member ever joined is right: the guard then
    // keeps a first member from starting in the middle of a removal.
    let lock_fd = open_lock_file(&fleet_lock_path_for_uid(fleet_name, uid))?;
    // SAFETY: `lock_fd` is an open descriptor owned by this call.
    let rc = unsafe { libc::flock(lock_fd.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if rc == 0 {
        return Ok(Some(ShmRegionLock { lock_fd }));
    }
    let error = io::Error::last_os_error();
    if error.kind() == io::ErrorKind::WouldBlock {
        return Ok(None);
    }
    Err(error)
}

/// One process's hold on one lane of a segment: an exclusive `flock` on the
/// lane's own lock file, kept for as long as this lives and released by the
/// kernel when the process dies, however it dies.
///
/// It is how a lane's owner is known to be gone without a timeout and without
/// a PID, which another PID namespace would read wrongly: a hold that can be
/// taken has nobody behind it.
pub struct LaneHold {
    lock_fd: OwnedFd
}

impl Drop for LaneHold {
    fn drop(&mut self) {
        let _ = unsafe { libc::flock(self.lock_fd.as_raw_fd(), libc::LOCK_UN) };
    }
}

/// Take lane `lane` of segment `shm_name`, if no live process holds it.
///
/// `Ok(None)` means a process holding it is alive. Never waits.
pub fn try_hold_lane(
    shm_name: &str,
    lane: usize
) -> io::Result<Option<LaneHold>> {
    let name = format!("{}.lane{lane}", shm_name.trim_start_matches('/'));
    let lock_fd = open_lock_file(&lock_file_path(&name))?;
    // SAFETY: `lock_fd` is an open descriptor owned by this call.
    let rc = unsafe { libc::flock(lock_fd.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if rc == 0 {
        return Ok(Some(LaneHold { lock_fd }));
    }
    let error = io::Error::last_os_error();
    if error.kind() == io::ErrorKind::WouldBlock {
        return Ok(None);
    }
    Err(error)
}

/// Every lock file beside segment `shm_name` of `uid`: the region's own and
/// one per lane that was ever held ([`try_hold_lane`]). What removes a segment
/// removes these with it; an unlocked one left behind is harmless, but it is
/// one more file per lane for every segment that ever existed.
pub fn companion_lock_files(
    shm_name: &str,
    uid: u32
) -> io::Result<Vec<PathBuf>> {
    let base = shm_name.trim_start_matches('/');
    let own = format!("{base}.lock");
    let lane = format!("{base}.lane");
    let dir = lock_dir_for_uid(uid);
    let entries = match std::fs::read_dir(&dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(error)
    };
    let mut found = Vec::new();
    for entry in entries {
        let entry = entry?;
        let Some(file) = entry.file_name().to_str().map(str::to_owned) else {
            continue;
        };
        if file == own || (file.starts_with(&lane) && file.ends_with(".lock")) {
            found.push(entry.path());
        }
    }
    Ok(found)
}

fn lock_file_path(shm_name: &str) -> PathBuf {
    lock_dir().join(format!("{}.lock", shm_name.trim_start_matches('/')))
}

/// Where the companion lock files live.
///
/// They used to live in `/tmp` directly, as
/// `/tmp/orbit-{fleet}-{kind}-{uid}.lock`, opened `O_CREAT` without `O_EXCL`
/// and without asking who owned what the open found. `/tmp` is world-writable,
/// so any local user could create that file first and then hold `LOCK_EX` on it
/// for as long as they liked: every process in the fleet would sit in `flock` —
/// not fail, block — waiting for a lock it was never going to get. The SHM
/// segment name is uid-scoped and so cannot be squatted this way; the lock path
/// was not. `O_NOFOLLOW` prevented the symlink version of the trick and nothing
/// else.
///
/// They now live in a per-uid directory created `0700`, which a user who is not
/// us cannot put a file into. What such a user can still do is create the
/// directory first, so its owner and mode are checked on every open rather than
/// assumed from having created it: a directory that is not ours, or not
/// private, fails the open with the path in the message instead of parking the
/// process on a lock.
///
/// `XDG_RUNTIME_DIR` is preferred where the session provides one, because it is
/// already per-user and `0700` and so is not inside a world-writable directory
/// at all. macOS has no such variable but gives each user a private `TMPDIR`;
/// `/tmp` is the fallback, with the checks above carrying the weight.
fn lock_dir() -> PathBuf {
    let uid = unsafe { libc::geteuid() };
    lock_dir_for_uid(uid)
}

fn lock_dir_for_uid(uid: u32) -> PathBuf {
    let base = std::env::var_os("XDG_RUNTIME_DIR")
        .map(PathBuf::from)
        .filter(|dir| dir.is_absolute())
        .unwrap_or_else(|| PathBuf::from("/tmp"));

    base.join(format!("{SHM_NAMESPACE}-{uid}"))
}

/// Creates the lock directory if it is missing and refuses it if it is not
/// ours. Called when a lock is actually taken rather than when a region is
/// opened: a region that never locks has nothing to squat, and failing its open
/// on a directory it does not use would hand an attacker a wider outage than
/// the one being closed.
fn ensure_lock_dir(dir: &Path) -> io::Result<()> {
    use std::os::unix::fs::DirBuilderExt;

    let uid = unsafe { libc::geteuid() };
    match std::fs::DirBuilder::new().mode(0o700).create(dir) {
        Ok(()) => {}
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
        Err(error) => return Err(error)
    }

    ensure_private_dir(dir, uid)
}

/// Refuses a lock directory that someone else could write to.
///
/// `symlink_metadata` rather than `metadata`: a symlink pointing at a directory
/// we do own would otherwise pass while the lock files landed somewhere the
/// attacker chose.
fn ensure_private_dir(
    dir: &Path,
    uid: u32
) -> io::Result<()> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    let metadata = std::fs::symlink_metadata(dir)?;
    if !metadata.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("{} is not a directory", dir.display())
        ));
    }
    if metadata.uid() != uid {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "{} is owned by uid {} rather than {uid}; refusing to lock in a directory \
                 another user controls",
                dir.display(),
                metadata.uid()
            )
        ));
    }
    if metadata.permissions().mode() & 0o077 != 0 {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "{} is mode {:o}; refusing to lock in a directory others can write to",
                dir.display(),
                metadata.permissions().mode() & 0o777
            )
        ));
    }

    Ok(())
}

#[cfg(test)]
mod fleet_lock_tests {
    use super::{join_fleet_membership, try_lock_fleet_exclusive};

    /// A member alive means the fleet cannot be cleared, and there is no
    /// flag that says otherwise; the member going away is what opens it.
    #[test]
    fn a_member_holds_the_fleet_against_exclusive_takers() {
        let fleet = format!("fl{:x}", std::process::id());
        let uid = unsafe { libc::geteuid() };

        let member = join_fleet_membership(&fleet).expect("join");
        assert!(try_lock_fleet_exclusive(&fleet, uid).expect("try").is_none());

        drop(member);
        let exclusive = try_lock_fleet_exclusive(&fleet, uid).expect("try");
        assert!(exclusive.is_some());
        // And a member cannot join while a removal holds the fleet: the
        // shared lock would block, which is the behaviour, not a test to run.
        drop(exclusive);
        let _ = std::fs::remove_file(super::fleet_lock_path_for_uid(&fleet, uid));
    }
}