tilewright-source 0.1.0

Loads and validates Tilewright world source trees into a typed, game-neutral model
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
// Copyright 2026 Seraphina Studios
// SPDX-License-Identifier: MIT

//! Unix access beneath the root through directory handles. Each component
//! is opened relative to the directory before it with `O_NOFOLLOW`, so a
//! symbolic link is never followed, not even one swapped in after a check.
//! Writes, renames and removals act on names inside a directory opened that
//! way, so they never follow a link either.

use super::{Found, RawEntry, RawKind, Refused};
use crate::access::Access;
use rustix::{
    fs::{
        AtFlags, CWD, Dir, FileType, FlockOperation, Gid, Mode, OFlags, Stat, fchmod, fchown,
        flock, fstat, fsync, mkdirat, openat, renameat, statat, unlinkat,
    },
    io::Errno,
};
use std::{
    io::Write as _,
    os::fd::{AsFd, BorrowedFd, OwnedFd},
    path::Path,
};

/// The root directory, opened once so that every access is relative to it.
pub(crate) struct Root(Result<OwnedFd, Errno>);

fn directory_flags() -> OFlags {
    OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
}

fn kind_of(file_type: FileType) -> RawKind {
    match file_type {
        FileType::RegularFile => RawKind::File,
        FileType::Directory => RawKind::Directory,
        FileType::Symlink => RawKind::Link,
        _ => RawKind::Other,
    }
}

/// Why opening `name` in `directory` failed; `prefix` is the path up to and
/// including `name`.
fn classify(directory: BorrowedFd<'_>, name: &str, errno: Errno, prefix: &[&str]) -> Refused {
    match statat(directory, name, AtFlags::SYMLINK_NOFOLLOW) {
        Ok(stat) if kind_of(FileType::from_raw_mode(stat.st_mode)) == RawKind::Link => {
            Refused::Link(prefix.join("/"))
        }
        Ok(_) if errno == Errno::NOTDIR || errno == Errno::NXIO => Refused::Unexpected,
        _ if errno == Errno::NOENT => Refused::Missing,
        _ => Refused::Io(errno.into()),
    }
}

impl Root {
    pub(crate) fn new(path: &Path) -> Self {
        // The root itself may be a link; nothing beneath it is followed.
        Self(openat(
            CWD,
            path,
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
        ))
    }

    /// A second handle on the same directory.
    pub(crate) fn try_clone(&self) -> Self {
        Self(match &self.0 {
            Ok(fd) => fd.try_clone().map_err(|error| {
                error
                    .raw_os_error()
                    .map_or(Errno::IO, Errno::from_raw_os_error)
            }),
            Err(errno) => Err(*errno),
        })
    }

    fn root(&self) -> Result<BorrowedFd<'_>, Refused> {
        match &self.0 {
            Ok(fd) => Ok(fd.as_fd()),
            Err(Errno::NOENT) => Err(Refused::Missing),
            Err(errno) => Err(Refused::Io((*errno).into())),
        }
    }

    /// Runs `access` on the directory holding the last of `components` and
    /// that component's name, opening the directories one at a time.
    fn parent<T>(
        &self,
        components: &[&str],
        access: impl FnOnce(BorrowedFd<'_>, &str) -> Result<T, Refused>,
    ) -> Result<T, Refused> {
        let root = self.root()?;
        let Some((name, parents)) = components.split_last() else {
            return Err(Refused::Unexpected);
        };
        let mut current: Option<OwnedFd> = None;
        for (index, component) in parents.iter().enumerate() {
            let directory = current.as_ref().map_or(root, AsFd::as_fd);
            let opened = openat(directory, *component, directory_flags(), Mode::empty())
                .map_err(|errno| classify(directory, component, errno, &components[..=index]))?;
            current = Some(opened);
        }
        access(current.as_ref().map_or(root, AsFd::as_fd), name)
    }

    /// Opens a regular file and returns it with its length.
    pub(crate) fn file(&self, components: &[&str]) -> Result<(std::fs::File, u64), Refused> {
        self.parent(components, |directory, name| {
            // Non-blocking, so opening a FIFO cannot hang before it is rejected.
            let flags = OFlags::RDONLY
                | OFlags::NOFOLLOW
                | OFlags::CLOEXEC
                | OFlags::NOCTTY
                | OFlags::NONBLOCK;
            let fd = openat(directory, name, flags, Mode::empty())
                .map_err(|errno| classify(directory, name, errno, components))?;
            let stat = fstat(&fd).map_err(|errno| Refused::Io(errno.into()))?;
            if kind_of(FileType::from_raw_mode(stat.st_mode)) != RawKind::File {
                return Err(Refused::Unexpected);
            }
            Ok((
                std::fs::File::from(fd),
                u64::try_from(stat.st_size).unwrap_or(0),
            ))
        })
    }

    /// What the last of `components` is, without following it.
    pub(crate) fn kind(&self, components: &[&str]) -> Result<Found, Refused> {
        self.parent(components, |directory, name| {
            match statat(directory, name, AtFlags::SYMLINK_NOFOLLOW) {
                Ok(stat) => match kind_of(FileType::from_raw_mode(stat.st_mode)) {
                    RawKind::File => Ok(Found::File),
                    RawKind::Directory => Ok(Found::Directory),
                    RawKind::Link => Err(Refused::Link(components.join("/"))),
                    RawKind::Other => Ok(Found::Other),
                },
                Err(Errno::NOENT) => Ok(Found::Missing),
                Err(errno) => Err(Refused::Io(errno.into())),
            }
        })
    }

    /// Opens the directory `components`, creating missing ones when
    /// `create`.
    pub(crate) fn directory(
        &self,
        components: &[&str],
        create: bool,
    ) -> Result<Directory, Refused> {
        let root = self.root()?;
        let mut current: Option<OwnedFd> = None;
        for (index, component) in components.iter().enumerate() {
            let directory = current.as_ref().map_or(root, AsFd::as_fd);
            let opened = match openat(directory, *component, directory_flags(), Mode::empty()) {
                Err(Errno::NOENT) if create => {
                    match mkdirat(directory, *component, Mode::from_raw_mode(0o777)) {
                        Ok(()) | Err(Errno::EXIST) => {}
                        Err(errno) => return Err(Refused::Io(errno.into())),
                    }
                    openat(directory, *component, directory_flags(), Mode::empty())
                }
                opened => opened,
            }
            .map_err(|errno| classify(directory, component, errno, &components[..=index]))?;
            current = Some(opened);
        }
        match current {
            Some(directory) => Ok(Directory(directory)),
            None => root
                .try_clone_to_owned()
                .map(Directory)
                .map_err(Refused::Io),
        }
    }

    /// Makes the directory `components` in its existing parent; `false`
    /// when an entry by that name was already there.
    pub(crate) fn make_directory(&self, components: &[&str]) -> Result<bool, Refused> {
        let Some((name, parent)) = components.split_last() else {
            return Ok(false);
        };
        let parent = self.directory(parent, false)?;
        match mkdirat(&parent.0, *name, Mode::from_raw_mode(0o777)) {
            Ok(()) => Ok(true),
            Err(Errno::EXIST) => Ok(false),
            Err(errno) => Err(classify(parent.0.as_fd(), name, errno, components)),
        }
    }

    /// Takes an exclusive advisory lock on the root directory, held until
    /// the returned lock is dropped; `None` when another holds it.
    pub(crate) fn lock(&self) -> Result<Option<Lock>, Refused> {
        let fd = openat(self.root()?, ".", directory_flags(), Mode::empty())
            .map_err(|errno| Refused::Io(errno.into()))?;
        match flock(&fd, FlockOperation::NonBlockingLockExclusive) {
            Ok(()) => Ok(Some(Lock(fd))),
            Err(Errno::WOULDBLOCK) => Ok(None),
            Err(errno) => Err(Refused::Io(errno.into())),
        }
    }

    /// Lists a directory. Entries are read as they are iterated.
    pub(crate) fn list(&self, components: &[&str]) -> Result<Listing, Refused> {
        let directory = if components.is_empty() {
            self.root()?.try_clone_to_owned().map_err(Refused::Io)?
        } else {
            self.parent(components, |directory, name| {
                openat(directory, name, directory_flags(), Mode::empty())
                    .map_err(|errno| classify(directory, name, errno, components))
            })?
        };
        let entries = Dir::read_from(&directory).map_err(|errno| Refused::Io(errno.into()))?;
        Ok(Listing {
            directory,
            entries,
            done: false,
        })
    }
}

pub(crate) struct Listing {
    directory: OwnedFd,
    entries: Dir,
    done: bool,
}

impl Iterator for Listing {
    type Item = std::io::Result<RawEntry>;

    fn next(&mut self) -> Option<Self::Item> {
        while !self.done {
            let entry = match self.entries.next()? {
                Ok(entry) => entry,
                Err(errno) => {
                    self.done = true;
                    return Some(Err(errno.into()));
                }
            };
            let name = entry.file_name();
            if matches!(name.to_bytes(), b"." | b"..") {
                continue;
            }
            let kind = match entry.file_type() {
                FileType::Unknown => {
                    match statat(&self.directory, name, AtFlags::SYMLINK_NOFOLLOW) {
                        Ok(stat) => kind_of(FileType::from_raw_mode(stat.st_mode)),
                        Err(errno) => return Some(Err(errno.into())),
                    }
                }
                known => kind_of(known),
            };
            return Some(Ok(RawEntry {
                name: std::str::from_utf8(name.to_bytes()).ok().map(str::to_owned),
                kind,
            }));
        }
        None
    }
}

/// An exclusive lock on the root, released when dropped.
pub(crate) struct Lock(#[allow(dead_code)] OwnedFd);

/// A directory beneath the root, opened without following links.
pub(crate) struct Directory(OwnedFd);

impl Directory {
    /// Who may use the regular file `name`, if there is one. A file whose
    /// access publishing could not keep is refused: on Linux one with an
    /// access control list, since its mode bits do not say who may read it
    /// and a file replacing it could not keep the list. Other systems' lists
    /// are not read.
    pub(crate) fn access(&self, name: &str) -> Result<Option<Access>, Refused> {
        match statat(&self.0, name, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(stat) if kind_of(FileType::from_raw_mode(stat.st_mode)) == RawKind::File => {
                self.file_access(name, &stat)
            }
            Ok(_) | Err(Errno::NOENT) => Ok(None),
            Err(errno) => Err(Refused::Io(errno.into())),
        }
    }

    /// The access of the regular file `name`, opened to check what its
    /// status does not show.
    #[cfg(target_os = "linux")]
    fn file_access(&self, name: &str, _: &Stat) -> Result<Option<Access>, Refused> {
        let flags =
            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC | OFlags::NOCTTY;
        let fd = openat(&self.0, name, flags, Mode::empty())
            .map_err(|errno| classify(self.0.as_fd(), name, errno, &[name]))?;
        // What is read is what was opened.
        let stat = fstat(&fd).map_err(|errno| Refused::Io(errno.into()))?;
        if kind_of(FileType::from_raw_mode(stat.st_mode)) != RawKind::File {
            return Ok(None);
        }
        refuse_access_control_lists(&fd, false)?;
        Ok(Some(Access {
            control: labels(&fd)?,
            ..access_of(&stat)
        }))
    }

    #[cfg(not(target_os = "linux"))]
    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    fn file_access(&self, _: &str, stat: &Stat) -> Result<Option<Access>, Refused> {
        Ok(Some(access_of(stat)))
    }

    /// Who may use this directory. On Linux, a directory with an access
    /// control list, its own or one it gives new files, is refused.
    pub(crate) fn own_access(&self) -> Result<Access, Refused> {
        let stat = fstat(&self.0).map_err(|errno| Refused::Io(errno.into()))?;
        #[cfg(target_os = "linux")]
        refuse_access_control_lists(&self.0, true)?;
        Ok(Access {
            control: labels(&self.0)?,
            ..access_of(&stat)
        })
    }

    /// Gives this directory the mode and group of `access`, and checks
    /// that the system gave it the labels of `access`.
    pub(crate) fn set_own_access(&self, access: &Access) -> Result<(), Refused> {
        check_labels(&self.0, access)?;
        set_access(&self.0, access)
    }

    /// Writes a new file `name` holding `bytes` and syncs it. Whatever was
    /// at `name` is removed first, so a link or a second hard link there is
    /// never written through. With `access`, the file must have the labels
    /// of `access`, and on Linux loses an access control list its directory
    /// gives it, both before anything is written; it is its owner's alone
    /// until written, then gets that mode and group. Without, the
    /// platform's default.
    pub(crate) fn write(
        &self,
        name: &str,
        access: Option<&Access>,
        bytes: &[u8],
    ) -> Result<(), Refused> {
        self.remove_file(name)?;
        let flags = OFlags::WRONLY
            | OFlags::CREATE
            | OFlags::EXCL
            | OFlags::NOFOLLOW
            | OFlags::CLOEXEC
            | OFlags::NOCTTY;
        // A file with permissions of its own is only its owner's until it
        // has them: they are set after writing, which would clear set-user
        // and set-group bits set before.
        let mode = if access.is_some() { 0o600 } else { 0o666 };
        let fd = openat(&self.0, name, flags, Mode::from_raw_mode(mode))
            .map_err(|errno| classify(self.0.as_fd(), name, errno, &[name]))?;
        let written = (|| {
            let mut file = std::fs::File::from(fd);
            if let Some(access) = access {
                // An access control list the directory gives new files
                // would let others read what the mode bits do not, and a
                // label other than the one asked for would be another
                // audience; both are dealt with before a byte is written.
                #[cfg(target_os = "linux")]
                strip_access_control_list(&file)?;
                check_labels(&file, access)?;
            }
            file.write_all(bytes).map_err(Refused::Io)?;
            if let Some(access) = access {
                set_access(&file, access)?;
            }
            file.sync_all().map_err(Refused::Io)
        })();
        if written.is_err() {
            // A partial file is not left behind.
            let _ = self.remove_file(name);
        }
        written
    }

    /// Renames `from` to `to` in this directory, replacing `to`.
    pub(crate) fn rename(&self, from: &str, to: &str) -> Result<(), Refused> {
        renameat(&self.0, from, &self.0, to).map_err(|errno| Refused::Io(errno.into()))
    }

    /// Removes the file or link `name`; `false` when there was none.
    pub(crate) fn remove_file(&self, name: &str) -> Result<bool, Refused> {
        match unlinkat(&self.0, name, AtFlags::empty()) {
            Ok(()) => Ok(true),
            Err(Errno::NOENT) => Ok(false),
            Err(errno) => Err(Refused::Io(errno.into())),
        }
    }

    /// Removes the empty directory `name`; `false` when it is missing or
    /// not empty.
    pub(crate) fn remove_directory(&self, name: &str) -> Result<bool, Refused> {
        match unlinkat(&self.0, name, AtFlags::REMOVEDIR) {
            Ok(()) => Ok(true),
            Err(Errno::NOENT | Errno::NOTEMPTY | Errno::EXIST) => Ok(false),
            Err(errno) => Err(Refused::Io(errno.into())),
        }
    }

    /// Checks, before anything is made, that the `SELinux` policy gives a
    /// file made here as `name` the label it gives one made as `staged`. A
    /// rule of the policy that keys a new file's label on its name applies
    /// when a file is made, not when it is renamed, so a file staged under
    /// another name and renamed to `name` would keep a label the policy
    /// does not give `name`. The staged file's own label is checked when it
    /// is written. Where `SELinux` labels nothing here, there is nothing to
    /// check; where it labels the directory but cannot be asked, the check
    /// fails.
    #[cfg(target_os = "linux")]
    pub(crate) fn check_final_name(&self, staged: &str, name: &str) -> Result<(), Refused> {
        let Some(directory) = label(&self.0, "security.selinux")? else {
            return Ok(());
        };
        // A thread that sets the label of what it makes (`setfscreatecon`)
        // gives both names that label; the staged file's is checked when
        // it is written.
        if selinux::creates_as_set().map_err(Refused::Io)? {
            return Ok(());
        }
        // A labelled tree whose policy cannot be asked, as in a container
        // that hides the SELinux file system, is refused, not guessed at.
        let given = selinux::compute_create(&directory, staged).map_err(Refused::Io)?;
        let expected = selinux::compute_create(&directory, name).map_err(Refused::Io)?;
        if given == expected {
            Ok(())
        } else {
            Err(unkept(
                "the system's policy labels a new file of its name otherwise than the file staged for it, and renaming does not relabel",
            ))
        }
    }

    #[cfg(not(target_os = "linux"))]
    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    pub(crate) fn check_final_name(&self, _: &str, _: &str) -> Result<(), Refused> {
        Ok(())
    }

    /// The ID of the mount this directory is on: from `statx`, or before
    /// Linux 5.8, whose `statx` does not give it, from the descriptor's
    /// `/proc/self/fdinfo` entry; why not where neither says.
    #[cfg(target_os = "linux")]
    pub(crate) fn mount_id(&self) -> Result<Result<u64, String>, Refused> {
        use rustix::fs::{StatxFlags, statx};
        use std::os::fd::AsRawFd as _;
        let found = statx(&self.0, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID);
        // As before Linux 5.8, statx gives no mount ID: its mask lacks it
        // and the field is zero.
        #[cfg(test)]
        let (found, fdinfo) = match NO_STATX_MOUNT_ID.with(std::cell::Cell::get) {
            Some(fdinfo) => (
                found.map(|mut found| {
                    found.stx_mask &= !StatxFlags::MNT_ID.bits();
                    found.stx_mnt_id = 0;
                    found
                }),
                fdinfo,
            ),
            None => (found, "/proc/self/fdinfo"),
        };
        #[cfg(not(test))]
        let fdinfo = "/proc/self/fdinfo";
        match found {
            Ok(found) if found.stx_mask & StatxFlags::MNT_ID.bits() != 0 => {
                return Ok(Ok(found.stx_mnt_id));
            }
            Ok(_) | Err(Errno::NOSYS) => {}
            Err(errno) => return Err(Refused::Io(errno.into())),
        }
        Ok(
            match super::mounts::fdinfo_mount_id(fdinfo, self.0.as_raw_fd()) {
                Ok(Some(id)) => Ok(id),
                Ok(None) => Err("the kernel does not say which mount it is on".to_owned()),
                Err(reason) => Err(format!("statx gives no mount ID, and {reason}")),
            },
        )
    }

    /// The file system this directory is on, where it is not one whose
    /// access control lists publishing reads, or why it could not be told;
    /// see [`unchecked_file_system`]. Its mount is found by mount ID among
    /// `mounts`, whose type must be one of those, and `statfs` must give
    /// that type's magic number too.
    #[cfg(target_os = "linux")]
    pub(crate) fn unchecked_file_system(&self, mounts: &Mounts) -> Result<Option<String>, Refused> {
        #[cfg(test)]
        if let Some((found, magic)) = GIVEN_FILE_SYSTEM.with(std::cell::Cell::get) {
            return Ok(unchecked_file_system(found.as_bytes(), magic));
        }
        let unknown = |reason: &str| Ok(Some(format!("one that could not be told: {reason}")));
        // Mounts that could not be read are the cause, whatever else.
        if let Some(reason) = mounts.unreadable() {
            return unknown(reason);
        }
        let id = match self.mount_id()? {
            Ok(id) => id,
            Err(reason) => return unknown(&reason),
        };
        let found = match mounts.type_of(id) {
            Ok(found) => found,
            Err(reason) => return unknown(&reason),
        };
        Ok(unchecked_file_system(found, self.magic()?))
    }

    /// The magic number `statfs` gives the file system of this directory.
    #[cfg(target_os = "linux")]
    pub(crate) fn magic(&self) -> Result<u32, Refused> {
        let statistics = rustix::fs::fstatfs(&self.0).map_err(|errno| Refused::Io(errno.into()))?;
        // The magic numbers are 32 bits wide, whatever the width of the
        // field.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        Ok(statistics.f_type as u32)
    }

    /// Elsewhere access control lists are not read at all.
    #[cfg(not(target_os = "linux"))]
    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    pub(crate) fn unchecked_file_system(&self, _: &Mounts) -> Result<Option<String>, Refused> {
        Ok(None)
    }

    /// Syncs the directory, so renames and removals in it are durable. On
    /// macOS `fsync` does not flush the drive's cache, so the directory is
    /// synced with `F_FULLFSYNC`, as std syncs files, or with `fsync` where
    /// the file system has no such sync.
    pub(crate) fn sync(&self) -> Result<bool, Refused> {
        #[cfg(target_os = "macos")]
        match rustix::fs::fcntl_fullfsync(&self.0) {
            Ok(()) => return Ok(true),
            Err(Errno::NOTSUP | Errno::OPNOTSUPP | Errno::INVAL | Errno::NOTTY) => {}
            Err(errno) => return Err(Refused::Io(errno.into())),
        }
        fsync(&self.0)
            .map(|()| true)
            .map_err(|errno| Refused::Io(errno.into()))
    }
}

/// Who may use a file or directory, from its status, without labels.
fn access_of(stat: &Stat) -> Access {
    Access {
        mode: mode_bits(stat.st_mode),
        user: stat.st_uid,
        group: stat.st_gid,
        control: [0; 32],
    }
}

/// The permission bits of a mode, which is a `u16` on Apple platforms.
#[allow(clippy::useless_conversion)]
fn mode_bits(mode: rustix::fs::RawMode) -> u32 {
    u32::from(mode) & 0o7777
}

/// Gives an open file or directory the mode and group of `access`: the
/// group first, since changing it may clear the set-group bit. A group the
/// user may not give is an error, since the group bits would otherwise
/// apply to another group.
fn set_access(fd: impl AsFd, access: &Access) -> Result<(), Refused> {
    let stat = fstat(&fd).map_err(|errno| Refused::Io(errno.into()))?;
    if stat.st_gid != access.group {
        fchown(&fd, None, Some(Gid::from_raw(access.group)))
            .map_err(|errno| Refused::Io(errno.into()))?;
    }
    let mode = rustix::fs::RawMode::try_from(access.mode & 0o7777)
        .map_err(|_| Refused::Io(std::io::ErrorKind::InvalidInput.into()))?;
    fchmod(&fd, Mode::from_raw_mode(mode)).map_err(|errno| Refused::Io(errno.into()))?;
    // The system may drop a bit without failing, such as the set-group bit
    // for a user outside the group, so the result is checked.
    let stat = fstat(&fd).map_err(|errno| Refused::Io(errno.into()))?;
    if mode_bits(stat.st_mode) != access.mode || stat.st_gid != access.group {
        return Err(Refused::Io(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            format!(
                "could not be given mode {:o} and group {}: it has mode {:o} and group {}",
                access.mode,
                access.group,
                mode_bits(stat.st_mode),
                stat.st_gid
            ),
        )));
    }
    Ok(())
}

/// The access control lists Linux file systems keep beside the mode bits:
/// POSIX, NFS version 4 (also as ZFS shows them) and rich ones.
#[cfg(target_os = "linux")]
const ACCESS_CONTROL_LISTS: [&str; 4] = [
    "system.posix_acl_access",
    "system.nfs4_acl",
    "system.nfs4_acl_xdr",
    "system.richacl",
];

/// The local file systems that keep their access control lists, where
/// they have any, as the attributes above: each by the type the kernel
/// names its mounts with and the magic number `statfs` gives. On any
/// other, network, host-shared, FUSE, stacked (overlayfs, whose upper layer
/// may be remote) and foreign ones among them, who may read a file may not
/// be what its mode bits and those attributes say. Both are asked, since a
/// file system that shares another, as 9p does, may pass on its magic
/// number.
#[cfg(target_os = "linux")]
const CHECKED_FILE_SYSTEMS: [(&str, u32); 9] = [
    ("ext2", 0x0000_EF53),
    ("ext3", 0x0000_EF53),
    ("ext4", 0x0000_EF53),
    ("xfs", 0x5846_5342),
    ("btrfs", 0x9123_683E),
    ("tmpfs", 0x0102_1994),
    ("f2fs", 0xF2F5_2010),
    ("zfs", 0x2FC1_2FC1),
    ("bcachefs", 0xCA45_1A4E),
];

/// The file system of type `found` with the `statfs` magic number `magic`,
/// in words, where it is not one of [`CHECKED_FILE_SYSTEMS`] with its own
/// magic number; `None` where it is. A type is shown with every byte that
/// is not printable ASCII escaped, since anyone who mounts a FUSE file
/// system chooses its type.
#[cfg(target_os = "linux")]
pub(crate) fn unchecked_file_system(found: &[u8], magic: u32) -> Option<String> {
    let shown = found.escape_ascii().to_string();
    match CHECKED_FILE_SYSTEMS
        .iter()
        .find(|(name, _)| name.as_bytes() == found)
    {
        Some((_, expected)) if *expected == magic => None,
        Some(_) => Some(format!("{shown}, though statfs gives type {magic:#x}")),
        None => Some(shown),
    }
}

/// The mounts of this process, read once to tell the file systems of
/// several directories.
#[cfg(target_os = "linux")]
pub(crate) use super::mounts::Mounts;

/// Elsewhere there are no mounts to read.
#[cfg(not(target_os = "linux"))]
pub(crate) struct Mounts;

#[cfg(not(target_os = "linux"))]
impl Mounts {
    pub(crate) fn read() -> Self {
        Self
    }
}

/// The mandatory access control labels Linux security modules keep, which
/// say who may read a file beside its mode bits.
#[cfg(target_os = "linux")]
const LABELS: [&str; 2] = ["security.selinux", "security.SMACK64"];

/// Labels that publishing refuses, since it could not keep them.
#[cfg(target_os = "linux")]
const UNKEPT_LABELS: [&str; 3] = [
    "security.SMACK64EXEC",
    "security.SMACK64MMAP",
    "security.SMACK64TRANSMUTE",
];

/// An error for access control that publishing could not keep.
fn unkept(what: &str) -> Refused {
    Refused::Io(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        format!("{what}, which publishing could not keep"),
    ))
}

/// Refuses an open file or directory that has a POSIX, NFS version 4 or
/// rich access control list, and for a `directory` also a default list it
/// gives new files.
#[cfg(target_os = "linux")]
fn refuse_access_control_lists(fd: impl AsFd, directory: bool) -> Result<(), Refused> {
    let found = has_any(&fd, &ACCESS_CONTROL_LISTS)?
        || (directory && has_any(&fd, &["system.posix_acl_default"])?);
    if found {
        return Err(unkept("it has an access control list"));
    }
    Ok(())
}

/// Whether the open file has any of the extended attributes `names`.
#[cfg(target_os = "linux")]
fn has_any(fd: impl AsFd, names: &[&str]) -> Result<bool, Refused> {
    for name in names {
        // Asked with no room, the call gives the size of a value that is
        // there, or says there is none.
        match rustix::fs::fgetxattr(&fd, *name, &mut [0_u8; 0][..]) {
            Ok(_) | Err(Errno::RANGE) => return Ok(true),
            Err(Errno::NODATA | Errno::NOTSUP) => {}
            Err(errno) => return Err(Refused::Io(errno.into())),
        }
    }
    Ok(false)
}

/// The largest label read; real ones are far shorter.
#[cfg(target_os = "linux")]
const LABEL_LIMIT: usize = 4096;

/// A digest of the open file's or directory's mandatory access control
/// labels, all zero when it has none. Elsewhere than on Linux there are
/// none.
#[cfg(target_os = "linux")]
fn labels(fd: impl AsFd) -> Result<[u8; 32], Refused> {
    use sha2::{Digest as _, Sha256};
    // Smack's other labels say how a file is executed or mapped, or how a
    // directory labels what is made in it; a replacement, or an entry made
    // again, would not get them.
    if has_any(&fd, &UNKEPT_LABELS)? {
        return Err(unkept(
            "it has a Smack execution, mapping or transmuting label",
        ));
    }
    let mut values = Vec::with_capacity(LABELS.len());
    for name in LABELS {
        values.push((name, label(&fd, name)?));
    }
    #[cfg(test)]
    if let Some(given) = given_label(&fd)? {
        values[0].1 = Some(given);
    }
    if values.iter().all(|(_, value)| value.is_none()) {
        return Ok([0; 32]);
    }
    let mut hasher = Sha256::new();
    for (name, value) in values {
        hasher.update(name.as_bytes());
        match value {
            None => hasher.update([0]),
            Some(value) => {
                hasher.update([1]);
                hasher.update(u64::try_from(value.len()).unwrap_or(u64::MAX).to_le_bytes());
                hasher.update(&value);
            }
        }
    }
    Ok(hasher.finalize().into())
}

/// The label `name` of an open file or directory, if it has one.
#[cfg(target_os = "linux")]
fn label(fd: impl AsFd, name: &str) -> Result<Option<Vec<u8>>, Refused> {
    let size = match rustix::fs::fgetxattr(&fd, name, &mut [0_u8; 0][..]) {
        Ok(size) => size,
        Err(Errno::NODATA | Errno::NOTSUP) => return Ok(None),
        Err(errno) => return Err(Refused::Io(errno.into())),
    };
    if size > LABEL_LIMIT {
        return Err(unkept("it has a label longer than publishing reads"));
    }
    let mut value = vec![0_u8; size];
    // A label that grew since its size was read is an error too.
    let read = rustix::fs::fgetxattr(&fd, name, &mut value[..])
        .map_err(|errno| Refused::Io(errno.into()))?;
    value.truncate(read);
    Ok(Some(value))
}

#[cfg(all(test, target_os = "linux"))]
thread_local! {
    /// `SELinux` labels by device and inode, for tests: setting a
    /// `security.*` attribute takes privileges a test does not have.
    pub(crate) static GIVEN_LABELS: std::cell::RefCell<std::collections::BTreeMap<(u64, u64), Vec<u8>>> =
        const { std::cell::RefCell::new(std::collections::BTreeMap::new()) };
}

#[cfg(all(test, target_os = "linux"))]
thread_local! {
    /// Takes `statx` to give no mount ID, as before Linux 5.8, clearing it
    /// from what statx gives, and the descriptors' fdinfo to be in this
    /// directory, for tests.
    pub(crate) static NO_STATX_MOUNT_ID: std::cell::Cell<Option<&'static str>> =
        const { std::cell::Cell::new(None) };
    /// The file system type and `statfs` magic number every directory
    /// reports, for tests: the file systems it matters for cannot be
    /// mounted in one.
    pub(crate) static GIVEN_FILE_SYSTEM: std::cell::Cell<Option<(&'static str, u32)>> =
        const { std::cell::Cell::new(None) };
}

#[cfg(all(test, target_os = "linux"))]
fn given_label(fd: impl AsFd) -> Result<Option<Vec<u8>>, Refused> {
    let stat = fstat(&fd).map_err(|errno| Refused::Io(errno.into()))?;
    Ok(GIVEN_LABELS.with(|labels| labels.borrow().get(&(stat.st_dev, stat.st_ino)).cloned()))
}

#[cfg(not(target_os = "linux"))]
#[allow(clippy::unnecessary_wraps)]
fn labels(_fd: impl AsFd) -> Result<[u8; 32], Refused> {
    Ok([0; 32])
}

/// Checks that the open file or directory has the labels of `access`:
/// publishing never relabels, so an entry its directory, or the system's
/// policy, labels otherwise is refused.
fn check_labels(fd: impl AsFd, access: &Access) -> Result<(), Refused> {
    if labels(fd)? == access.control {
        Ok(())
    } else {
        Err(unkept(
            "the system gave it other mandatory access control labels (SELinux, Smack) than the entries publishing compared it with",
        ))
    }
}

/// Removes the POSIX access control list a new file got from its
/// directory, so that its mode bits alone say who may read it; any other
/// list that stays is an error.
#[cfg(target_os = "linux")]
fn strip_access_control_list(fd: impl AsFd) -> Result<(), Refused> {
    match rustix::fs::fremovexattr(&fd, "system.posix_acl_access") {
        Ok(()) | Err(Errno::NODATA | Errno::NOTSUP) => {}
        Err(errno) => return Err(Refused::Io(errno.into())),
    }
    if has_any(&fd, &ACCESS_CONTROL_LISTS)? {
        return Err(Refused::Io(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "the directory gives new files an access control list that cannot be removed",
        )));
    }
    Ok(())
}

/// `SELinux`'s own answer to which label a new file gets.
#[cfg(target_os = "linux")]
pub(crate) mod selinux {
    use std::{
        fs,
        io::{self, Read as _, Write as _},
    };

    /// Where the kernel's `SELinux` file system is mounted.
    const FILE_SYSTEM: &str = "/sys/fs/selinux";

    /// The largest label read back.
    const LIMIT: u64 = 4096;

    /// A label without the NUL or newline that ends it.
    pub(crate) fn trimmed(label: &[u8]) -> &[u8] {
        let end = label
            .iter()
            .rposition(|byte| !matches!(byte, b'\0' | b'\n'))
            .map_or(0, |last| last + 1);
        &label[..end]
    }

    /// Whether this thread sets the label of the files it makes itself
    /// (`setfscreatecon`), so that no rule of the policy applies to them.
    pub(super) fn creates_as_set() -> io::Result<bool> {
        match fs::read("/proc/thread-self/attr/fscreate") {
            Ok(label) => Ok(!trimmed(&label).is_empty()),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
            Err(error) => Err(error),
        }
    }

    /// The label the policy gives a regular file this thread makes as
    /// `name` in a directory labelled `directory`. An error where the
    /// policy cannot be asked, such as where the `SELinux` file system is
    /// not mounted.
    pub(super) fn compute_create(directory: &[u8], name: &str) -> io::Result<Vec<u8>> {
        let class = fs::read_to_string(format!("{FILE_SYSTEM}/class/file/index"))
            .map_err(|error| {
                io::Error::new(
                    error.kind(),
                    format!("the tree has SELinux labels, but {FILE_SYSTEM} cannot be asked which label a new file gets ({error})"),
                )
            })?
            .trim()
            .parse::<u16>()
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
        let thread = fs::read("/proc/thread-self/attr/current")?;
        let query = request(&thread, directory, class, name)?;
        let mut answer = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(format!("{FILE_SYSTEM}/create"))?;
        // The kernel takes the question in one write.
        if answer.write(&query)? != query.len() {
            return Err(io::Error::new(
                io::ErrorKind::WriteZero,
                "the label question was not taken whole",
            ));
        }
        let mut label = Vec::new();
        answer.take(LIMIT).read_to_end(&mut label)?;
        Ok(trimmed(&label).to_vec())
    }

    /// The question `SELinux`'s `create` file answers: the labels of who
    /// makes the file and of where, the class of file, and its name,
    /// percent-encoded so that no byte of it ends the question.
    pub(crate) fn request(
        source: &[u8],
        target: &[u8],
        class: u16,
        name: &str,
    ) -> io::Result<Vec<u8>> {
        let (source, target) = (trimmed(source), trimmed(target));
        let plain = |label: &[u8]| !label.is_empty() && label.iter().all(u8::is_ascii_graphic);
        if !plain(source) || !plain(target) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "a label is not plain text",
            ));
        }
        let mut query = Vec::with_capacity(source.len() + target.len() + name.len() * 3 + 16);
        query.extend_from_slice(source);
        query.push(b' ');
        query.extend_from_slice(target);
        query.extend_from_slice(format!(" {class} ").as_bytes());
        for byte in name.bytes() {
            if byte.is_ascii_alphanumeric() || b"-_.".contains(&byte) {
                query.push(byte);
            } else {
                query.extend_from_slice(format!("%{byte:02x}").as_bytes());
            }
        }
        Ok(query)
    }
}