ostrya 0.16.0

Pure-Rust async reimplementation of the ostree repository library
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! The media finder: the search for the one media repository on the mounted
//! volumes.

use std::ffi::OsStr;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use rustix::fs::{AtFlags, Dir, Mode, OFlags, ResolveFlags};
use rustix::io::Errno;

use super::MediaSkip;
use super::mountinfo::{self, Mount};
use crate::error::Result;
use crate::repo::Repo;
use crate::repo_fs::{self, RepoDir};
use crate::summary::{
    OSTREE_METADATA_REF, SUMMARY_FILE, Summary, collection_map_has_ref, parse_ref_list,
    read_root_file_blocking, summary_collection_id,
};

/// The directory of the repository entries of the tool on a volume.
const REPOS_D: &str = ".ostree/repos.d";

/// The paths that the finder probes on a volume after the entries of
/// [`REPOS_D`], in order.
const CANDIDATES: [&str; 3] = [".ostree/repo", "ostree/repo", "var/lib/flatpak/repo"];

/// The pseudo file systems, which hold no media.
const PSEUDO_TYPES: [&str; 18] = [
    "proc",
    "sysfs",
    "devtmpfs",
    "devpts",
    "cgroup",
    "cgroup2",
    "securityfs",
    "debugfs",
    "tracefs",
    "bpf",
    "pstore",
    "mqueue",
    "hugetlbfs",
    "configfs",
    "fusectl",
    "autofs",
    "binfmt_misc",
    "efivarfs",
];

/// The network file systems. The finder does not probe them, so that a dead
/// server cannot stop the scan.
const NETWORK_TYPES: [&str; 16] = [
    "nfs",
    "nfs4",
    "cifs",
    "smb3",
    "smbfs",
    "ceph",
    "9p",
    "virtiofs",
    "davfs",
    "afs",
    "glusterfs",
    "fuse.glusterfs",
    "fuse.sshfs",
    "fuse.rclone",
    "fuse.s3fs",
    "fuse.gvfsd-fuse",
];

/// The device and the inode of a directory.
type Identity = (u64, u64);

/// The media repository that the finder found.
pub(super) struct FoundMedia {
    /// The path of the repository: the mount point or the directory of the
    /// scan, joined with the probed path.
    pub(super) path: PathBuf,
    /// The repository, opened in the strict open mode.
    pub(super) repo: Repo,
    /// The bytes of the summary that the finder read.
    pub(super) summary: Vec<u8>,
}

/// The result of a scan.
pub(super) enum MediaChoice {
    /// No media repository. The list holds each candidate that exists and
    /// that the finder skipped, with the reason, in probe order.
    None(Vec<(PathBuf, MediaSkip)>),
    /// One media repository.
    One(FoundMedia),
    /// More than one media repository: the path of each, in the order of
    /// the mount table.
    Many(Vec<PathBuf>),
}

/// Scans the mounts of the mount table `table` for media, as the client
/// repository `client` reads them.
///
/// For each mount point, the call takes the last line of the table alone
/// (see [`mountinfo::parse`]). It skips the root mount, the pseudo file
/// systems, and the network file systems before a system call on their
/// path. It also skips a mount whose directory it cannot open, and a mount
/// whose directory any user can write (mode bit `o+w`, with or without the
/// sticky bit), such as `/tmp` or `/dev/shm`. On each other mount, it takes
/// the first candidate whose summary lists a collection ref (see `probe`).
/// Candidates with the same device and inode are one media repository, at
/// the path of the first one in table order.
///
/// # Errors
///
/// - [`Error::Io`](crate::Error::Io) if the call cannot read the device
///   and the inode of the client repository.
pub(super) async fn find_media(client: &Repo, table: Vec<u8>) -> Result<MediaChoice> {
    let mut scan = Scan::new(client).await?;
    let points = ostrya_rt::unblock(move || probe_points(&table)).await;
    for point in points {
        // A mount whose directory the scan cannot open holds no media.
        let _ = scan.probe(&point, true).await;
    }
    Ok(scan.choice())
}

/// Scans the directory `dir` alone for media, as the client repository
/// `client` reads them. The call reads no mount table, and `dir` need not
/// be a mount point. The call probes `dir` also if any user can write it.
/// The path of each candidate must cross no mount point.
///
/// # Errors
///
/// - [`Error::Io`](crate::Error::Io) if the call cannot open `dir`, or
///   cannot read the device and the inode of the client repository.
pub(super) async fn find_media_in(client: &Repo, dir: &Path) -> Result<MediaChoice> {
    let mut scan = Scan::new(client).await?;
    scan.probe(dir, false).await?;
    Ok(scan.choice())
}

/// Returns the mount points of the mount table `table` that the finder
/// probes, in table order. The call tests the file system type of a mount
/// before it decodes the mount point.
fn probe_points(table: &[u8]) -> Vec<PathBuf> {
    mountinfo::parse(table)
        .iter()
        .filter(|mount| !is_excluded(mount))
        .map(Mount::point)
        .collect()
}

/// Returns `true` if the finder does not probe the mount `mount`: a pseudo
/// file system, a network file system, or the root mount.
fn is_excluded(mount: &Mount<'_>) -> bool {
    PSEUDO_TYPES
        .iter()
        .chain(&NETWORK_TYPES)
        .any(|ty| ty.as_bytes() == mount.fs_type)
        || mount.escaped_point == b"/"
}

/// The state of a scan.
struct Scan {
    /// The client repository.
    client: Identity,
    /// Each candidate that exists and that the scan skipped, with the reason.
    skipped: Vec<(PathBuf, MediaSkip)>,
    /// The device, the inode, and the path of each media repository, in the
    /// order of the mounts.
    found: Vec<(Identity, PathBuf)>,
    /// The repository and the summary of the first media repository that
    /// the scan found.
    first: Option<(Repo, Vec<u8>)>,
}

/// A directory that the scan probes.
struct MountDir {
    /// The directory, open with `O_PATH`.
    fd: OwnedFd,
    /// The names of the entries of `.ostree/repos.d`, in byte order, or the
    /// reason why the scan skips that directory.
    repos_d: std::result::Result<Vec<Vec<u8>>, MediaSkip>,
}

/// The result of the probe of one candidate.
enum Probe {
    /// The candidate does not exist.
    Missing,
    /// The candidate exists, and the finder skipped it.
    Skipped(MediaSkip),
    /// The candidate is a media repository that the scan found before.
    Found,
    /// The candidate is a media repository.
    Media(Identity, Repo, Vec<u8>),
}

impl Scan {
    /// Starts a scan for the client repository `client`.
    async fn new(client: &Repo) -> Result<Scan> {
        let repo = client.clone();
        let stat = ostrya_rt::unblock(move || repo_fs::stat_fd(repo.repo_fd())).await?;
        let client = (stat.dev, stat.ino);
        Ok(Scan {
            client,
            skipped: Vec::new(),
            found: Vec::new(),
            first: None,
        })
    }

    /// Probes the directory `dir`, and records its media repository.
    ///
    /// The probe order is each entry of `.ostree/repos.d/` in byte order of
    /// the names, then `.ostree/repo`, `ostree/repo`, and
    /// `var/lib/flatpak/repo`. The media repository of `dir` is the first
    /// candidate whose summary lists a collection ref, and the probe stops
    /// there. The probe also stops at a candidate with the device and the
    /// inode of an earlier media repository, and does not record it again.
    /// If `skip_writable` is `true`, the call does not probe a `dir` that
    /// any user can write.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`](crate::Error::Io) if the call cannot open `dir`.
    async fn probe(&mut self, dir: &Path, skip_writable: bool) -> Result<()> {
        let path = dir.to_owned();
        let Some(mount) = ostrya_rt::unblock(move || open_mount(&path, skip_writable)).await?
        else {
            return Ok(());
        };
        let names = mount.repos_d.unwrap_or_else(|skip| {
            self.skipped.push((dir.join(REPOS_D), skip));
            Vec::new()
        });
        let fd = Arc::new(mount.fd);
        let candidates = names
            .iter()
            .map(|name| Path::new(REPOS_D).join(OsStr::from_bytes(name)))
            .chain(CANDIDATES.iter().map(PathBuf::from));
        for relative in candidates {
            let path = dir.join(&relative);
            let fd = Arc::clone(&fd);
            let client = self.client;
            let found: Vec<Identity> = self.found.iter().map(|(id, _)| *id).collect();
            let repo_path = path.clone();
            let probe = ostrya_rt::unblock(move || {
                probe_candidate(fd.as_fd(), &relative, client, &found, repo_path)
                    .unwrap_or_else(Probe::Skipped)
            })
            .await;
            match probe {
                Probe::Missing => {}
                Probe::Skipped(skip) => self.skipped.push((path, skip)),
                Probe::Found => return Ok(()),
                Probe::Media(id, repo, summary) => {
                    if self.first.is_none() {
                        self.first = Some((repo, summary));
                    }
                    self.found.push((id, path));
                    return Ok(());
                }
            }
        }
        Ok(())
    }

    /// Applies the one-media rule to the result of the scan.
    fn choice(self) -> MediaChoice {
        let mut paths: Vec<PathBuf> = self.found.into_iter().map(|(_, path)| path).collect();
        match self.first {
            None => MediaChoice::None(self.skipped),
            Some((repo, summary)) if paths.len() == 1 => MediaChoice::One(FoundMedia {
                path: paths.remove(0),
                repo,
                summary,
            }),
            Some(_) => MediaChoice::Many(paths),
        }
    }
}

/// Opens the directory `path` with `O_PATH`, and reads the names of the
/// entries of its `.ostree/repos.d`. If `skip_writable` is `true`, the call
/// returns `None` for a directory that any user can write (mode bit `o+w`),
/// before it reads `.ostree`. Blocks the calling thread.
fn open_mount(path: &Path, skip_writable: bool) -> Result<Option<MountDir>> {
    let fd = rustix::fs::open(
        path,
        OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )?;
    if skip_writable && Mode::from_raw_mode(rustix::fs::fstat(&fd)?.st_mode).contains(Mode::WOTH) {
        return Ok(None);
    }
    let repos_d = repos_d_names(fd.as_fd());
    Ok(Some(MountDir { fd, repos_d }))
}

/// Returns the names of the entries of `.ostree/repos.d` under the
/// directory `dir`, in byte order, or no name if the directory does not
/// exist. Blocks the calling thread.
fn repos_d_names(dir: BorrowedFd<'_>) -> std::result::Result<Vec<Vec<u8>>, MediaSkip> {
    let Some(fd) = open_in_mount(dir, Path::new(REPOS_D))? else {
        return Ok(Vec::new());
    };
    let unreadable = |e: Errno| MediaSkip::Unreadable(e.into());
    let mut names = Vec::new();
    for entry in Dir::new(fd).map_err(unreadable)? {
        let name = entry.map_err(unreadable)?.file_name().to_bytes().to_vec();
        if name != b"." && name != b".." {
            names.push(name);
        }
    }
    names.sort();
    Ok(names)
}

/// Probes the candidate `relative` under the directory `dir`, for the
/// client repository `client` and the media repositories `found` of the
/// scan. The repository of a media candidate stores `path`. Blocks the
/// calling thread.
///
/// The call reads the summary before it opens the repository, so it reads
/// the `config` of a media candidate alone.
fn probe_candidate(
    dir: BorrowedFd<'_>,
    relative: &Path,
    client: Identity,
    found: &[Identity],
    path: PathBuf,
) -> std::result::Result<Probe, MediaSkip> {
    let Some(candidate) = open_in_mount(dir, relative)? else {
        return Ok(Probe::Missing);
    };
    let id = identity(candidate.as_fd()).map_err(|e| MediaSkip::Unreadable(e.into()))?;
    if id == client {
        return Err(MediaSkip::Client);
    }
    if found.contains(&id) {
        return Ok(Probe::Found);
    }
    let root = RepoDir::from_root_fd(candidate);
    let summary = read_root_file_blocking(&root, SUMMARY_FILE)
        .map_err(MediaSkip::Unreadable)?
        .ok_or(MediaSkip::NoCollectionRef)?;
    if !lists_collection_ref(&summary).map_err(MediaSkip::Unreadable)? {
        return Err(MediaSkip::NoCollectionRef);
    }
    let repo = Repo::open_strict_blocking(root, path).map_err(MediaSkip::Unreadable)?;
    Ok(Probe::Media(id, repo, summary))
}

/// Opens the directory `relative` under the directory `dir`, or returns
/// `None` if it does not exist. Blocks the calling thread.
///
/// The open is an `openat2` with `RESOLVE_NO_XDEV`. It follows a symlink,
/// and the resolution of the path crosses no mount point. A path whose
/// resolution crosses a mount point is on another file system. A path with
/// a component before the last one that is not a directory does not exist.
fn open_in_mount(
    dir: BorrowedFd<'_>,
    relative: &Path,
) -> std::result::Result<Option<OwnedFd>, MediaSkip> {
    match rustix::fs::openat2(
        dir,
        relative,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
        ResolveFlags::NO_XDEV,
    ) {
        Ok(fd) => Ok(Some(fd)),
        Err(Errno::NOENT) => Ok(None),
        Err(Errno::NOTDIR) if rustix::fs::statat(dir, relative, AtFlags::empty()).is_err() => {
            Ok(None)
        }
        Err(Errno::XDEV) => Err(MediaSkip::OtherFileSystem),
        Err(e) => Err(MediaSkip::Unreadable(e.into())),
    }
}

/// Returns the device and the inode of the open file `fd`.
pub(super) fn identity(fd: impl AsFd) -> std::result::Result<Identity, Errno> {
    let stat = rustix::fs::fstat(fd)?;
    Ok((stat.st_dev, stat.st_ino))
}

/// Returns `true` if the summary `bytes` lists a collection ref: a ref in
/// the collection map, or a ref in field 0 other than the anchor ref
/// `ostree-metadata` when the summary states a collection id. The call
/// parses the global metadata dict, and parses the refs of field 0 only
/// when the summary states a collection id.
fn lists_collection_ref(bytes: &[u8]) -> Result<bool> {
    let metadata = Summary::parse_metadata(bytes)?;
    if collection_map_has_ref(&metadata)? {
        return Ok(true);
    }
    let own = summary_collection_id(&metadata).is_some();
    Ok(own
        && parse_ref_list(bytes)?
            .iter()
            .any(|entry| entry.name != OSTREE_METADATA_REF))
}

#[cfg(test)]
mod tests {
    use std::os::unix::fs::PermissionsExt;
    use std::process::{Command, Stdio};

    use ostrya_core::{Type, Value, to_bytes};

    use super::*;
    use crate::summary::COLLECTION_ID_KEY;
    use crate::{CreateOptions, Error, RepoMode};

    /// The collection of the test media.
    const ID: &str = "org.example.Os";
    /// The variable that names the scratch directory of the child of
    /// [`the_finder_finds_media_on_a_tmpfs_in_a_user_namespace`].
    const NAMESPACE_CHILD: &str = "OSTRYA_MEDIA_FIND_CHILD";

    /// A scratch directory that the value removes when it drops.
    struct Scratch {
        root: PathBuf,
    }

    impl Scratch {
        fn new(dir: &Path) -> Scratch {
            let root = dir.join(format!(
                "ostrya-media-find-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            let _ = std::fs::remove_dir_all(&root);
            std::fs::create_dir_all(&root).unwrap();
            Scratch { root }
        }

        /// Creates the empty directory `name` in the scratch directory, and
        /// returns its path.
        fn dir(&self, name: &str) -> PathBuf {
            let path = self.root.join(name);
            std::fs::create_dir_all(&path).unwrap();
            path
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.root);
        }
    }

    /// Returns the bytes of a summary with the refs `refs` in field 0, the
    /// collection id `own`, and the refs of each collection of `map`.
    fn summary(own: Option<&str>, refs: &[&str], map: &[(&str, &[&str])]) -> Vec<u8> {
        let entries = |names: &[&str]| {
            let entry = |name: &&str| {
                Value::Tuple(vec![
                    Value::Str((*name).to_owned()),
                    Value::Tuple(vec![
                        Value::U64(0),
                        Value::Bytes(vec![1; 32]),
                        Value::Array(Vec::new()),
                    ]),
                ])
            };
            Value::Array(names.iter().map(entry).collect())
        };
        let item = |key: &str, ty: &str, value: Value| {
            Value::Tuple(vec![
                Value::Str(key.to_owned()),
                Value::Variant(Box::new((Type::parse(ty).unwrap(), value))),
            ])
        };
        let mut metadata = Vec::new();
        if let Some(id) = own {
            metadata.push(item(COLLECTION_ID_KEY, "s", Value::Str(id.to_owned())));
        }
        if !map.is_empty() {
            let map = map
                .iter()
                .map(|(id, names)| Value::Tuple(vec![Value::Str((*id).to_owned()), entries(names)]))
                .collect();
            metadata.push(item(
                "ostree.summary.collection-map",
                "a{sa(s(taya{sv}))}",
                Value::Array(map),
            ));
        }
        let value = Value::Tuple(vec![entries(refs), Value::Array(metadata)]);
        to_bytes(&Type::parse("(a(s(taya{sv}))a{sv})").unwrap(), &value).unwrap()
    }

    /// The summary of media that hold the ref `os/stable` of [`ID`] in the
    /// collection map.
    fn media_summary() -> Vec<u8> {
        summary(None, &[], &[(ID, &["os/stable"])])
    }

    /// Creates an archive repository at `path`, and its parents, with the
    /// summary `summary`.
    async fn repo_at(path: &Path, summary: Option<&[u8]>) -> Repo {
        std::fs::create_dir_all(path).unwrap();
        let repo = Repo::create(path, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        if let Some(bytes) = summary {
            std::fs::write(path.join("summary"), bytes).unwrap();
        }
        repo
    }

    /// Returns a mount table with a mount of each `(point, type)`.
    fn table(mounts: &[(&Path, &str)]) -> Vec<u8> {
        let mut out = String::new();
        for (i, (point, ty)) in mounts.iter().enumerate() {
            out.push_str(&format!(
                "{} 1 0:{i} / {} rw,relatime shared:{i} - {ty} src rw\n",
                i + 100,
                point.display()
            ));
        }
        out.into_bytes()
    }

    /// Returns the media of `choice`, or panics.
    fn one(choice: MediaChoice) -> FoundMedia {
        match choice {
            MediaChoice::One(found) => found,
            MediaChoice::None(skipped) => panic!("no media: {skipped:?}"),
            MediaChoice::Many(paths) => panic!("more than one media: {paths:?}"),
        }
    }

    /// Returns the skipped candidates of `choice` with their reasons as
    /// text, or panics.
    fn skipped(choice: MediaChoice) -> Vec<(PathBuf, String)> {
        match choice {
            MediaChoice::None(skipped) => skipped
                .into_iter()
                .map(|(path, skip)| {
                    let reason = match skip {
                        MediaSkip::Unreadable(Error::Io(_)) => "unreadable".to_owned(),
                        other => format!("{other:?}"),
                    };
                    (path, reason)
                })
                .collect(),
            MediaChoice::One(found) => panic!("media at {}", found.path.display()),
            MediaChoice::Many(paths) => panic!("more than one media: {paths:?}"),
        }
    }

    /// A candidate repository on `/dev/shm`, on another file system than
    /// the scratch directory, or `None` with a printed reason.
    fn other_file_system(scratch: &Scratch) -> Option<Scratch> {
        let shm = Path::new("/dev/shm");
        let dev =
            |path: &Path| std::fs::metadata(path).map(|m| std::os::unix::fs::MetadataExt::dev(&m));
        match (dev(shm), dev(&scratch.root)) {
            (Ok(a), Ok(b)) if a != b => Some(Scratch::new(shm)),
            _ => {
                eprintln!(
                    "skipping the other file system: /dev/shm is missing or on the scratch file system"
                );
                None
            }
        }
    }

    /// A mount with no candidate holds no media. A mount with media gives
    /// one media, and two mounts with media give the path of each in table
    /// order. A mount directory that the client can search and cannot list
    /// is probed.
    #[test]
    fn the_finder_takes_one_media_and_reports_two() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            let empty = scratch.dir("empty");
            let a = scratch.dir("a");
            let b = scratch.dir("b");
            repo_at(&a.join(".ostree/repo"), Some(&media_summary())).await;
            repo_at(&b.join("ostree/repo"), Some(&media_summary())).await;

            let choice = find_media(&client, table(&[(&empty, "ext4")])).await;
            assert!(skipped(choice.unwrap()).is_empty());
            std::fs::set_permissions(&a, std::fs::Permissions::from_mode(0o311)).unwrap();
            let choice = find_media(&client, table(&[(&empty, "ext4"), (&a, "vfat")])).await;
            let _ = std::fs::set_permissions(&a, std::fs::Permissions::from_mode(0o755));
            let found = one(choice.unwrap());
            assert_eq!(found.path, a.join(".ostree/repo"));
            assert_eq!(found.summary, media_summary());
            assert!(found.repo.remotes_dir().is_none());
            assert_eq!(found.repo.path(), a.join(".ostree/repo"));
            let choice = find_media(&client, table(&[(&b, "exfat"), (&a, "vfat")])).await;
            let MediaChoice::Many(paths) = choice.unwrap() else {
                panic!("two mounts give two media");
            };
            assert_eq!(paths, [b.join("ostree/repo"), a.join(".ostree/repo")]);
        });
    }

    /// The entries of `.ostree/repos.d` come first, in name order, whatever
    /// the order of their creation. A candidate whose summary lists no
    /// collection ref, or that has no summary, is skipped, and the next
    /// candidate is the media. A summary with its own collection id lists
    /// the refs of that id in field 0. A later candidate of the mount is not
    /// used.
    #[test]
    fn the_first_candidate_with_a_collection_ref_is_the_media() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            let mount = scratch.dir("mount");
            let repos_d = mount.join(".ostree/repos.d");
            let local = summary(None, &["os/stable"], &[]);
            let own = summary(Some(ID), &["os/stable"], &[]);
            repo_at(&repos_d.join("b"), Some(&own)).await;
            repo_at(&repos_d.join("a"), Some(&media_summary())).await;
            repo_at(&repos_d.join("d"), None).await;
            repo_at(&repos_d.join("c"), Some(&local)).await;
            repo_at(&mount.join(".ostree/repo"), Some(&media_summary())).await;

            let choice = find_media(&client, table(&[(&mount, "ext4")])).await;
            assert_eq!(one(choice.unwrap()).path, repos_d.join("a"));

            std::fs::remove_dir_all(repos_d.join("a")).unwrap();
            let choice = find_media(&client, table(&[(&mount, "ext4")])).await;
            assert_eq!(one(choice.unwrap()).path, repos_d.join("b"));

            std::fs::remove_dir_all(repos_d.join("b")).unwrap();
            std::fs::remove_dir_all(mount.join(".ostree/repo")).unwrap();
            let choice = find_media(&client, table(&[(&mount, "ext4")])).await;
            assert_eq!(
                skipped(choice.unwrap()),
                [
                    (repos_d.join("c"), "NoCollectionRef".to_owned()),
                    (repos_d.join("d"), "NoCollectionRef".to_owned()),
                ]
            );
        });
    }

    /// A summary with its own collection id whose field 0 lists only the
    /// anchor ref `ostree-metadata` lists no collection ref. A second ref
    /// in field 0 makes the candidate media. The anchor ref in an entry of
    /// the collection map is a collection ref, also when the summary states
    /// the collection id of the entry.
    #[test]
    fn a_repository_with_only_its_anchor_ref_is_no_media() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            let mount = scratch.dir("mount");
            let path = mount.join("ostree/repo");
            let anchor = summary(Some(ID), &["ostree-metadata"], &[]);
            repo_at(&path, Some(&anchor)).await;

            let choice = find_media_in(&client, &mount).await;
            assert_eq!(
                skipped(choice.unwrap()),
                [(path.clone(), "NoCollectionRef".to_owned())]
            );

            let both = summary(Some(ID), &["ostree-metadata", "os/stable"], &[]);
            std::fs::write(path.join("summary"), both).unwrap();
            let choice = find_media_in(&client, &mount).await;
            assert_eq!(one(choice.unwrap()).path, path);

            let map = summary(None, &[], &[(ID, &["ostree-metadata"])]);
            std::fs::write(path.join("summary"), map).unwrap();
            let choice = find_media_in(&client, &mount).await;
            assert_eq!(one(choice.unwrap()).path, path);

            let own_map = summary(
                Some(ID),
                &["ostree-metadata"],
                &[(ID, &["ostree-metadata"])],
            );
            std::fs::write(path.join("summary"), own_map).unwrap();
            let choice = find_media_in(&client, &mount).await;
            assert_eq!(one(choice.unwrap()).path, path);
        });
    }

    /// The finder skips the client repository, a candidate it cannot read,
    /// and a candidate on another file system than the mount. A directory
    /// given in place of the mount table gets the same checks.
    #[test]
    fn the_finder_skips_the_client_and_candidates_it_cannot_take() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let mount = scratch.dir("mount");
            let client = repo_at(&mount.join(".ostree/repo"), Some(&media_summary())).await;
            let mut expected = vec![(mount.join(".ostree/repo"), "Client".to_owned())];
            let unreadable = scratch.dir("mount/ostree/repo");
            std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).unwrap();
            if rustix::process::geteuid().is_root() {
                eprintln!("skipping the unreadable candidate: root reads each directory");
                std::fs::remove_dir(&unreadable).unwrap();
            } else {
                expected.push((unreadable.clone(), "unreadable".to_owned()));
            }
            let other = other_file_system(&scratch);
            if let Some(other) = &other {
                repo_at(&other.root.join("repo"), Some(&media_summary())).await;
                std::fs::create_dir_all(mount.join("var/lib/flatpak")).unwrap();
                std::os::unix::fs::symlink(
                    other.root.join("repo"),
                    mount.join("var/lib/flatpak/repo"),
                )
                .unwrap();
                expected.push((
                    mount.join("var/lib/flatpak/repo"),
                    "OtherFileSystem".to_owned(),
                ));
            }

            let found = skipped(
                find_media(&client, table(&[(&mount, "ext4")]))
                    .await
                    .unwrap(),
            );
            let given = skipped(find_media_in(&client, &mount).await.unwrap());
            let _ = std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755));
            assert_eq!(found, expected);
            assert_eq!(given, expected);
            assert!(matches!(
                find_media_in(&client, &scratch.root.join("absent")).await,
                Err(Error::Io(_))
            ));
        });
    }

    /// A candidate under a component that is not a directory does not
    /// exist. A candidate that is not a directory is unreadable.
    #[test]
    fn a_path_through_a_file_is_no_candidate() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            let mount = scratch.dir("mount");
            std::fs::write(mount.join(".ostree"), b"").unwrap();
            std::fs::write(mount.join("ostree"), b"").unwrap();
            std::fs::create_dir_all(mount.join("var/lib/flatpak")).unwrap();
            std::fs::write(mount.join("var/lib/flatpak/repo"), b"").unwrap();

            let choice = find_media(&client, table(&[(&mount, "ext4")])).await;
            assert_eq!(
                skipped(choice.unwrap()),
                [(mount.join("var/lib/flatpak/repo"), "unreadable".to_owned())]
            );
        });
    }

    /// One repository at two mount points is one media, at the path of the
    /// first mount in table order.
    #[test]
    fn one_repository_at_two_mount_points_is_one_media() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            let a = scratch.dir("a");
            repo_at(&a.join(".ostree/repo"), Some(&media_summary())).await;
            let b = scratch.root.join("b");
            std::os::unix::fs::symlink("a", &b).unwrap();

            let choice = find_media(&client, table(&[(&b, "ext4"), (&a, "ext4")])).await;
            assert_eq!(one(choice.unwrap()).path, b.join(".ostree/repo"));
        });
    }

    /// The finder probes no root mount, no pseudo file system, and no
    /// network file system.
    #[test]
    fn the_finder_probes_no_excluded_mount() {
        let points: Vec<PathBuf> = PSEUDO_TYPES
            .iter()
            .chain(&NETWORK_TYPES)
            .map(|ty| PathBuf::from(format!("/mnt/{ty}")))
            .collect();
        let mut mounts = vec![(Path::new("/"), "ext4")];
        for (point, ty) in points.iter().zip(PSEUDO_TYPES.iter().chain(&NETWORK_TYPES)) {
            mounts.push((point, ty));
        }
        mounts.push((Path::new("/mnt/media"), "ext4"));
        assert_eq!(probe_points(&table(&mounts)), [Path::new("/mnt/media")]);
    }

    /// The scan of the mount table skips a mount whose directory any user
    /// can write, with or without the sticky bit, and records no skipped
    /// candidate. A directory given in place of the mount table is probed.
    #[test]
    fn the_scan_skips_a_mount_that_any_user_can_write() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            for mode in [0o1777, 0o777] {
                let mount = scratch.dir(&format!("{mode:o}"));
                repo_at(&mount.join(".ostree/repo"), Some(&media_summary())).await;
                std::fs::set_permissions(&mount, std::fs::Permissions::from_mode(mode)).unwrap();

                let choice = find_media(&client, table(&[(&mount, "tmpfs")])).await;
                assert!(skipped(choice.unwrap()).is_empty(), "mode {mode:o}");
                let choice = find_media_in(&client, &mount).await;
                assert_eq!(one(choice.unwrap()).path, mount.join(".ostree/repo"));
            }
        });
    }

    /// A mount of an excluded type over a mount with media hides the media.
    /// A mount of another type over an excluded mount is probed.
    #[test]
    fn the_last_mount_at_a_mount_point_counts() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            let mount = scratch.dir("mount");
            repo_at(&mount.join(".ostree/repo"), Some(&media_summary())).await;

            let choice = find_media(&client, table(&[(&mount, "ext4"), (&mount, "nfs")])).await;
            assert!(skipped(choice.unwrap()).is_empty());
            let choice = find_media(&client, table(&[(&mount, "nfs"), (&mount, "ext4")])).await;
            assert_eq!(one(choice.unwrap()).path, mount.join(".ostree/repo"));
        });
    }

    /// A directory given in place of the mount table skips a candidate on
    /// another file system than the directory, and takes the next one.
    #[test]
    fn a_given_directory_skips_a_candidate_on_another_file_system() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let Some(other) = other_file_system(&scratch) else {
                return;
            };
            let client = repo_at(&scratch.root.join("client"), None).await;
            let dir = scratch.dir("dir/.ostree");
            repo_at(&other.root.join("repo"), Some(&media_summary())).await;
            std::os::unix::fs::symlink(other.root.join("repo"), dir.join("repo")).unwrap();
            let dir = scratch.root.join("dir");
            repo_at(&dir.join("ostree/repo"), Some(&media_summary())).await;

            let choice = find_media_in(&client, &dir).await;
            assert_eq!(one(choice.unwrap()).path, dir.join("ostree/repo"));
        });
    }

    /// Creates a btrfs subvolume at `path`, or returns `false` if the host
    /// cannot create it.
    fn btrfs_subvolume(path: &Path) -> bool {
        Command::new("btrfs")
            .args(["subvolume", "create"])
            .arg(path)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    }

    /// A repository in a btrfs subvolume of the mount is media, although
    /// the device of the subvolume is not the device of the mount. The
    /// subvolume is `.ostree` or `.ostree/repo`.
    #[test]
    fn a_repository_in_a_btrfs_subvolume_is_media() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new(&std::env::temp_dir());
            let client = repo_at(&scratch.root.join("client"), None).await;
            let cases = [("a", ".ostree"), ("b", ".ostree/repo")].map(|(name, subvolume)| {
                let mount = scratch.dir(name);
                let subvolume = mount.join(subvolume);
                std::fs::create_dir_all(subvolume.parent().unwrap()).unwrap();
                (btrfs_subvolume(&subvolume), mount, subvolume)
            });
            if !cases.iter().all(|(created, ..)| *created) {
                eprintln!("skipping: the host cannot create a btrfs subvolume");
                return;
            }
            let dev = |path: &Path| {
                std::os::unix::fs::MetadataExt::dev(&std::fs::metadata(path).unwrap())
            };
            for (_, mount, subvolume) in cases {
                assert_ne!(dev(&subvolume), dev(&mount));
                repo_at(&mount.join(".ostree/repo"), Some(&media_summary())).await;

                let choice = find_media(&client, table(&[(&mount, "btrfs")])).await;
                assert_eq!(one(choice.unwrap()).path, mount.join(".ostree/repo"));
                let choice = find_media_in(&client, &mount).await;
                assert_eq!(one(choice.unwrap()).path, mount.join(".ostree/repo"));
            }
        });
    }

    /// The finder reads the mount table of the process and finds media on
    /// a `tmpfs`. The test runs the child half in a new mount namespace, in
    /// a user namespace when it does not run as root.
    #[test]
    fn the_finder_finds_media_on_a_tmpfs_in_a_user_namespace() {
        let scratch = Scratch::new(&std::env::temp_dir());
        let unshare = |args: &[&str]| {
            Command::new("unshare")
                .args(args)
                .arg("true")
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
        };
        if unshare(&[]).is_err() {
            eprintln!("skipping: unshare is not available");
            return;
        }
        let root = rustix::process::geteuid().is_root();
        if !root && !unshare(&["--map-root-user"]).is_ok_and(|s| s.success()) {
            eprintln!("skipping: the host grants no user namespace");
            return;
        }
        let namespace: &[&str] = if root {
            &["-m", "--propagation", "private"]
        } else {
            &["--map-root-user", "-m", "--propagation", "private"]
        };
        if !unshare(namespace).is_ok_and(|s| s.success()) {
            eprintln!("skipping: the host grants no mount namespace");
            return;
        }
        let out = Command::new("unshare")
            .args(namespace)
            .arg(std::env::current_exe().unwrap())
            .args([
                "media::find::tests::tmpfs_media_subprocess",
                "--exact",
                "--ignored",
                "--nocapture",
            ])
            .env(NAMESPACE_CHILD, &scratch.root)
            .stdin(Stdio::null())
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        if let Some(line) = stdout
            .lines()
            .find(|l| l.starts_with("tmpfs mount refused"))
        {
            eprintln!("skipping: {line}");
            return;
        }
        assert!(
            out.status.success() && stdout.contains("1 passed"),
            "the child reported {}:\n{stdout}{}",
            out.status,
            String::from_utf8_lossy(&out.stderr),
        );
    }

    /// The half of [`the_finder_finds_media_on_a_tmpfs_in_a_user_namespace`]
    /// that mounts a `tmpfs` with media and scans the mount table. It runs
    /// only if this test binary runs again with the environment set.
    #[test]
    #[ignore = "helper process for the_finder_finds_media_on_a_tmpfs_in_a_user_namespace"]
    fn tmpfs_media_subprocess() {
        let Some(dir) = std::env::var_os(NAMESPACE_CHILD).map(PathBuf::from) else {
            return;
        };
        let dir = std::fs::canonicalize(dir).unwrap();
        let mount = dir.join("mnt");
        std::fs::create_dir(&mount).unwrap();
        match Command::new("mount")
            .args(["-t", "tmpfs", "-o", "mode=0755", "tmpfs"])
            .arg(&mount)
            .output()
        {
            Ok(out) if out.status.success() => {}
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr);
                println!("tmpfs mount refused: {}", stderr.trim());
                return;
            }
            Err(e) => {
                println!("tmpfs mount refused: mount: {e}");
                return;
            }
        }
        let nested = mount.join("ostree");
        std::fs::create_dir(&nested).unwrap();
        let out = Command::new("mount")
            .args(["-t", "tmpfs", "tmpfs"])
            .arg(&nested)
            .output()
            .unwrap();
        assert!(out.status.success(), "{out:?}");
        ostrya_rt::block_on(async {
            let client = repo_at(&dir.join("client"), None).await;
            repo_at(&mount.join(".ostree/repo"), Some(&media_summary())).await;
            repo_at(&nested.join("repo"), Some(&media_summary())).await;
            let table = mountinfo::read_table().await.unwrap();
            let paths = match find_media(&client, table).await.unwrap() {
                MediaChoice::One(found) => vec![found.path],
                MediaChoice::Many(paths) => paths,
                MediaChoice::None(skipped) => panic!("no media: {skipped:?}"),
            };
            assert!(paths.contains(&mount.join(".ostree/repo")), "{paths:?}");

            std::fs::remove_dir_all(mount.join(".ostree")).unwrap();
            let choice = find_media_in(&client, &mount).await.unwrap();
            assert_eq!(
                skipped(choice),
                [(nested.join("repo"), "OtherFileSystem".to_owned())]
            );
        });
    }
}