qk-executor 0.24.0

Process execution for the qk task runner
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
//! Running a command in its own user and mount namespace over an overlay of
//! the workspace: what it writes there lands in an upper layer of its own,
//! which the sandbox reads when the task ends.

use std::ffi::CString;
use std::os::fd::AsRawFd;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;

use anyhow::{Context, Result, bail};

use crate::landlock::{self, Rights};

/// The layers of one slot of commands: `upper` and `work`, the overlay's, and
/// `real`, where the workspace is bound aside so that it can be the lower
/// layer.
pub fn layers(overlay: &crate::Overlay, slot: usize) -> [std::path::PathBuf; 3] {
    let command = overlay.directory.join(format!("command-{slot}"));
    ["upper", "work", "real"].map(|name| command.join(name))
}

fn c_path(path: &Path) -> Result<CString> {
    CString::new(path.as_os_str().as_bytes()).context("a path holds a NUL byte")
}

/// What the child does between fork and exec, prepared beforehand: it may
/// make system calls only.
pub struct Setup {
    uid_map: CString,
    gid_map: CString,
    workspace: CString,
    real: CString,
    options: CString,
    /// The descriptor the workspace bound aside is held at while the
    /// overlay is mounted, as `real` may lie in the workspace, in qk's
    /// state, where the overlay hides it: one reserved here, so that no
    /// descriptor the child inherits has its number.
    aside: std::os::fd::OwnedFd,
    /// Each path bound through, relative to the workspace, ending `/.` so
    /// that only a directory resolves: opened through no link both in the
    /// workspace bound aside, through `aside`, and in the overlay, so that a
    /// link put in its place since it was chosen is never followed.
    passthrough: Vec<CString>,
    cwd: CString,
    /// The rights the Landlock rule set handles, the descriptors opened
    /// outside with their rights, the workspace's rights, and each path in
    /// the workspace, relative to it, with its rights and whether to reach
    /// it through no link.
    handled: Rights,
    outside: Vec<(i32, Rights)>,
    workspace_rights: Rights,
    inside: Vec<(CString, Rights, bool)>,
}

impl Setup {
    pub fn new(overlay: &crate::Overlay, slot: usize, cwd: &Path) -> Result<Self> {
        let [upper, work, real] = layers(overlay, slot);
        for directory in [&upper, &work, &real] {
            std::fs::create_dir_all(directory)
                .with_context(|| format!("cannot create {}", directory.display()))?;
        }
        let text = |path: &Path| -> Result<String> {
            let text = path.to_str().context("an overlay's paths must be UTF-8")?;
            // The mount options separate with `,` and lower layers with `:`.
            if text.contains([',', ':', '\\']) {
                bail!("an overlay cannot be mounted at {text}");
            }
            Ok(text.to_owned())
        };
        let options = format!(
            "lowerdir={},upperdir={},workdir={},userxattr",
            text(&real)?,
            text(&upper)?,
            text(&work)?
        );
        // The same user and group inside as outside, so files keep their
        // owner.
        let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
        let aside: std::os::fd::OwnedFd = std::fs::File::open("/dev/null")
            .context("cannot reserve a descriptor")?
            .into();
        let mut passthrough = Vec::new();
        for path in &overlay.passthrough {
            let relative = path
                .strip_prefix(&overlay.workspace)
                .context("a path bound through lies outside the workspace")?;
            passthrough.push(
                landlock::Open::Directory
                    .name(relative)
                    .context("a path holds a NUL byte")?,
            );
        }
        let rules = &overlay.rules;
        let mut inside = Vec::new();
        for (path, rights, open) in &rules.inside {
            let Ok(relative) = path.strip_prefix(&overlay.workspace) else {
                continue;
            };
            let relative = if relative.as_os_str().is_empty() {
                Path::new(".")
            } else {
                relative
            };
            let name = open.name(relative).context("a path holds a NUL byte")?;
            inside.push((name, *rights, *open != landlock::Open::Following));
        }
        Ok(Self {
            aside,
            handled: rules.handled,
            outside: rules
                .outside
                .iter()
                .map(|(fd, rights)| (fd.as_raw_fd(), *rights))
                .collect(),
            workspace_rights: rules.workspace,
            inside,
            uid_map: CString::new(format!("{uid} {uid} 1"))?,
            gid_map: CString::new(format!("{gid} {gid} 1"))?,
            workspace: c_path(&overlay.workspace)?,
            real: c_path(&real)?,
            options: CString::new(options)?,
            passthrough,
            cwd: c_path(cwd)?,
        })
    }

    /// Enters the namespaces and mounts the overlay. Between fork and exec:
    /// system calls only, no allocation.
    pub fn enter(&self) -> std::io::Result<()> {
        let fail = || Err(std::io::Error::last_os_error());
        unsafe {
            if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) != 0 {
                return fail();
            }
            for (file, text) in [
                (c"/proc/self/setgroups", c"deny"),
                (c"/proc/self/uid_map", self.uid_map.as_c_str()),
                (c"/proc/self/gid_map", self.gid_map.as_c_str()),
            ] {
                let fd = libc::open(file.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC);
                if fd < 0 {
                    return fail();
                }
                let bytes = text.to_bytes();
                let written = libc::write(fd, bytes.as_ptr().cast(), bytes.len());
                libc::close(fd);
                if written < 0 {
                    return fail();
                }
            }
            let none = std::ptr::null();
            if libc::mount(
                none,
                c"/".as_ptr(),
                none,
                libc::MS_REC | libc::MS_PRIVATE,
                none.cast(),
            ) != 0
                || libc::mount(
                    self.workspace.as_ptr(),
                    self.real.as_ptr(),
                    none,
                    libc::MS_BIND | libc::MS_REC,
                    none.cast(),
                ) != 0
            {
                return fail();
            }
            let aside = libc::open(
                self.real.as_ptr(),
                libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
            );
            // In place of the reservation, which `aside` cannot be.
            let held = self.aside.as_raw_fd();
            if aside < 0 || libc::dup3(aside, held, libc::O_CLOEXEC) < 0 {
                return fail();
            }
            libc::close(aside);
            if libc::mount(
                c"overlay".as_ptr(),
                self.workspace.as_ptr(),
                c"overlay".as_ptr(),
                0,
                self.options.as_ptr().cast(),
            ) != 0
            {
                return fail();
            }
            let merged = libc::open(
                self.workspace.as_ptr(),
                libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
            );
            if merged < 0 {
                return fail();
            }
            for relative in &self.passthrough {
                // Each end through no link, as a directory: one where a link
                // or anything else now stands, or that is gone, is not bound,
                // and what the command writes there lands in the overlay.
                let ends = landlock::open_beneath(held, relative)
                    .and_then(|source| Ok((source, landlock::open_beneath(merged, relative)?)));
                let (source, target) = match ends {
                    Ok(ends) => ends,
                    Err(error)
                        if matches!(
                            error.raw_os_error(),
                            Some(libc::ENOENT | libc::ELOOP | libc::EXDEV | libc::ENOTDIR)
                        ) =>
                    {
                        continue;
                    }
                    // Where openat2 is refused, as a seccomp filter may, the
                    // path cannot be bound without following a link that may
                    // stand in it, so the command fails.
                    Err(error) => return Err(error),
                };
                let (mut source_name, mut target_name) = ([0u8; 32], [0u8; 32]);
                if libc::mount(
                    proc_fd(source.as_raw_fd(), &mut source_name).as_ptr(),
                    proc_fd(target.as_raw_fd(), &mut target_name).as_ptr(),
                    none,
                    libc::MS_BIND | libc::MS_REC,
                    none.cast(),
                ) != 0
                {
                    return fail();
                }
            }
            libc::close(merged);
            libc::close(held);
            // The directory it was in is now beneath the overlay.
            if libc::chdir(self.cwd.as_ptr()) != 0 {
                return fail();
            }
            self.restrict()?;
        }
        Ok(())
    }

    /// Builds the Landlock rule set over the mounted overlay and restricts
    /// the command to it. Between fork and exec: system calls only.
    unsafe fn restrict(&self) -> std::io::Result<()> {
        use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
        let ruleset = landlock::create_ruleset(self.handled)?;
        let add = |fd: i32, rights: Rights| {
            landlock::add_rule(ruleset.as_raw_fd(), fd, rights, self.handled)
        };
        for (fd, rights) in &self.outside {
            add(*fd, *rights)?;
        }
        let root = unsafe {
            libc::open(
                self.workspace.as_ptr(),
                libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
            )
        };
        if root < 0 {
            return Err(std::io::Error::last_os_error());
        }
        // SAFETY: open returned a new descriptor, owned here.
        let root = unsafe { OwnedFd::from_raw_fd(root) };
        add(root.as_raw_fd(), self.workspace_rights)?;
        for (relative, rights, unlinked) in &self.inside {
            let opened = if *unlinked {
                landlock::open_beneath(root.as_raw_fd(), relative)
            } else {
                let fd = unsafe {
                    libc::openat(
                        root.as_raw_fd(),
                        relative.as_ptr(),
                        libc::O_PATH | libc::O_CLOEXEC,
                    )
                };
                if fd < 0 {
                    Err(std::io::Error::last_os_error())
                } else {
                    // SAFETY: openat returned a new descriptor, owned here.
                    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
                }
            };
            let fd = match opened {
                Ok(fd) => fd,
                // One that does not exist, or that a link now stands in, is
                // not allowed, as outside the overlay.
                Err(error)
                    if matches!(
                        error.raw_os_error(),
                        Some(libc::ENOENT | libc::ELOOP | libc::EXDEV | libc::ENOTDIR)
                    ) =>
                {
                    continue;
                }
                Err(error) => return Err(error),
            };
            add(fd.as_raw_fd(), *rights)?;
        }
        drop(root);
        landlock::restrict_self(ruleset.as_raw_fd())
    }
}

/// `/proc/self/fd/<fd>`, written into `buffer`: the path the descriptor was
/// opened at, to mount from or on. Between fork and exec, so allocating
/// nothing.
fn proc_fd(fd: i32, buffer: &mut [u8; 32]) -> &std::ffi::CStr {
    const PREFIX: &[u8] = b"/proc/self/fd/";
    buffer[..PREFIX.len()].copy_from_slice(PREFIX);
    let mut digits = [0u8; 10];
    let mut count = 0;
    let mut rest = fd.unsigned_abs();
    loop {
        digits[count] = b'0' + (rest % 10) as u8;
        count += 1;
        rest /= 10;
        if rest == 0 {
            break;
        }
    }
    for (index, digit) in digits[..count].iter().rev().enumerate() {
        buffer[PREFIX.len() + index] = *digit;
    }
    buffer[PREFIX.len() + count] = 0;
    std::ffi::CStr::from_bytes_until_nul(&buffer[..]).unwrap_or(c"/proc/self/fd")
}

/// Whether a command can run over an overlay here: in a user and mount
/// namespace of its own, with an overlay mounted on a directory in
/// `directory`, which lies on the workspace's file system. The reason it
/// cannot, if not.
pub fn probe(directory: &Path) -> Result<()> {
    use std::os::unix::process::CommandExt;
    let [lower, upper, work, merged] =
        ["lower", "upper", "work", "merged"].map(|name| directory.join(name));
    for path in [&lower, &upper, &work, &merged] {
        std::fs::create_dir_all(path)
            .with_context(|| format!("cannot create {}", path.display()))?;
    }
    let options = CString::new(format!(
        "lowerdir={},upperdir={},workdir={},userxattr",
        lower.display(),
        upper.display(),
        work.display()
    ))?;
    let merged_path = c_path(&merged)?;
    let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
    let uid_map = CString::new(format!("{uid} {uid} 1"))?;
    let gid_map = CString::new(format!("{gid} {gid} 1"))?;
    // Which step failed, as the child can only return an error code: written
    // to a pipe the parent reads.
    let mut pipe = [0i32; 2];
    if unsafe { libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC) } != 0 {
        return Err(std::io::Error::last_os_error()).context("cannot make a pipe");
    }
    let (reader, writer) = (pipe[0], pipe[1]);
    let mut command = std::process::Command::new("/bin/sh");
    command
        .args(["-c", "exit 0"])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    unsafe {
        command.pre_exec(move || {
            let fail = |step: u8| {
                let error = std::io::Error::last_os_error();
                libc::write(writer, (&step as *const u8).cast(), 1);
                Err(error)
            };
            if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) != 0 {
                return fail(0);
            }
            for (step, (file, text)) in [
                (c"/proc/self/setgroups", c"deny"),
                (c"/proc/self/uid_map", uid_map.as_c_str()),
                (c"/proc/self/gid_map", gid_map.as_c_str()),
            ]
            .into_iter()
            .enumerate()
            {
                let fd = libc::open(file.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC);
                if fd < 0 {
                    return fail(1 + step as u8);
                }
                let bytes = text.to_bytes();
                let written = libc::write(fd, bytes.as_ptr().cast(), bytes.len());
                libc::close(fd);
                if written < 0 {
                    return fail(1 + step as u8);
                }
            }
            if libc::mount(
                c"overlay".as_ptr(),
                merged_path.as_ptr(),
                c"overlay".as_ptr(),
                0,
                options.as_ptr().cast(),
            ) != 0
            {
                return fail(4);
            }
            Ok(())
        });
    }
    let output = command.output();
    unsafe { libc::close(writer) };
    let mut step = [u8::MAX];
    let read = unsafe { libc::read(reader, step.as_mut_ptr().cast(), 1) };
    unsafe { libc::close(reader) };
    clear(directory);
    let what = match (read, step[0]) {
        (1, 0) => "making a user and mount namespace",
        (1, 1) => "denying setgroups",
        (1, 2) => "mapping the user",
        (1, 3) => "mapping the group",
        (1, 4) => "mounting an overlay",
        _ => "running a command over an overlay",
    };
    let where_ = directory.display();
    match output {
        Ok(output) if output.status.success() => Ok(()),
        Ok(output) => bail!("{what} in {where_} failed: {}", output.status),
        Err(error) => Err(error).with_context(|| format!("{what} in {where_} failed")),
    }
}

/// Removes an overlay's directory, whose work directory overlayfs leaves
/// unreadable.
pub fn clear(directory: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let mut stack = vec![directory.to_owned()];
    while let Some(path) = stack.pop() {
        if std::fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.is_dir()) {
            let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700));
            if let Ok(entries) = std::fs::read_dir(&path) {
                stack.extend(entries.flatten().map(|entry| entry.path()));
            }
        }
    }
    let _ = std::fs::remove_dir_all(directory);
}

/// Applies to the workspace what each command's upper layer holds within
/// the overlay's `keep`, entry by entry. Entry by entry, since an overlay
/// another task has mounted would keep seeing a directory replaced whole as
/// it was.
pub fn settle(overlay: &crate::Overlay) -> crate::Settled {
    let mut settled = crate::Settled::default();
    for slot in 0.. {
        let [upper, ..] = layers(overlay, slot);
        if !upper.parent().is_some_and(Path::exists) {
            break;
        }
        if upper.is_dir() {
            let layer = Layer {
                upper: &upper,
                root: &overlay.workspace,
                keep: &overlay.keep,
                passthrough: &overlay.passthrough,
            };
            layer.apply(Path::new(""), false, &mut settled);
        }
    }
    settled
}

/// One command's upper layer, applied to the workspace at `root`.
struct Layer<'a> {
    upper: &'a Path,
    root: &'a Path,
    /// Where the task may write.
    keep: &'a crate::Keep,
    /// Bound through the overlay: what lies there the layer never holds.
    passthrough: &'a [std::path::PathBuf],
}

impl Layer<'_> {
    fn allowed(&self, target: &Path) -> bool {
        self.keep.allows(self.root, target)
    }

    /// Whether something bound through the overlay lies beneath `target`.
    fn holds_bound(&self, target: &Path) -> bool {
        self.passthrough
            .iter()
            .any(|through| through.starts_with(target))
    }

    /// Whether something the task may write lies beneath `target`.
    fn holds_kept(&self, target: &Path) -> bool {
        self.keep.holds(target)
    }

    /// Whether `relative`, a directory made in the workspace, is one `keep`
    /// names by name, beneath none other.
    fn names(&self, relative: &Path) -> bool {
        let named = |part: &std::ffi::OsStr| self.keep.names.iter().any(|name| part == name);
        relative.file_name().is_some_and(named)
            && relative
                .parent()
                .is_none_or(|parent| !parent.components().any(|part| named(part.as_os_str())))
    }

    /// Applies what the layer holds under `relative`, adding what it may
    /// not write to `settled.discarded` and what could not be applied to
    /// `settled.failed`. A whiteout removes; an opaque directory, or one
    /// beneath it, which hides what the workspace holds there as `hidden`
    /// says, replaces what was there; anything else is moved into place.
    /// Nothing is reached through a symbolic link in the workspace: a command
    /// could leave one in an output pointing out of it, which a later
    /// command's directory would be applied through. A link where the layer
    /// holds a directory is replaced by it, as the command did, or, outside
    /// what it may write, keeps the directory's entries out. `relative`
    /// itself holds no link: each directory is checked before what it holds
    /// is applied. Returns whether it applied anything.
    fn apply(&self, relative: &Path, hidden: bool, settled: &mut crate::Settled) -> bool {
        use std::os::unix::fs::{FileTypeExt, MetadataExt};
        let mut applied = hidden && self.prune(relative, settled);
        let entries = match std::fs::read_dir(self.upper.join(relative)) {
            Ok(entries) => entries,
            Err(error) => {
                settled.fail(&self.upper.join(relative), &error);
                return applied;
            }
        };
        for entry in entries {
            let entry = match entry {
                Ok(entry) => entry,
                Err(error) => {
                    settled.fail(&self.upper.join(relative), &error);
                    continue;
                }
            };
            let relative = relative.join(entry.file_name());
            let source = self.upper.join(&relative);
            let target = self.root.join(&relative);
            let metadata = match std::fs::symlink_metadata(&source) {
                Ok(metadata) => metadata,
                Err(error) => {
                    settled.fail(&source, &error);
                    continue;
                }
            };
            let name = relative.to_string_lossy().into_owned();
            let kind = metadata.file_type();
            let existing = std::fs::symlink_metadata(&target).ok();
            let is_dir = existing.as_ref().is_some_and(|existing| existing.is_dir());
            let is_link = existing
                .as_ref()
                .is_some_and(|existing| existing.is_symlink());
            if kind.is_char_device() && metadata.rdev() == 0 {
                // A whiteout.
                if self.allowed(&target) {
                    settled.removed(&target);
                    applied = true;
                } else if is_dir && self.holds_kept(&target) {
                    // A directory above outputs is gone, and so is what it
                    // held of them.
                    applied |= self.prune(&relative, settled);
                } else {
                    settled.discarded.insert(name);
                }
            } else if kind.is_dir() {
                let replaces = hidden || opaque(&source);
                if self.allowed(&target) {
                    // A file or link in its place goes, as the command
                    // removed it; a directory only when the layer's replaces
                    // it whole. What is bound through beneath it stays.
                    let prunes = is_dir && replaces && self.holds_bound(&target);
                    if existing.is_some() && (!is_dir || replaces) && !prunes {
                        settled.removed(&target);
                    }
                    // What lies above holds no link, so neither does what
                    // this makes.
                    let made = std::fs::create_dir_all(&target).and_then(|()| {
                        match std::fs::symlink_metadata(&target)?.is_dir() {
                            true => Ok(()),
                            false => Err(std::io::Error::other("not a directory")),
                        }
                    });
                    match made {
                        Ok(()) => {
                            if !is_dir && self.names(&relative) {
                                settled.made.push(target.clone());
                            }
                            self.apply(&relative, prunes, settled);
                            // After its entries, which a read-only mode
                            // would keep out.
                            let _ = std::fs::set_permissions(&target, metadata.permissions());
                            applied = true;
                        }
                        Err(error) => settled.fail(&target, &error),
                    }
                } else if is_link {
                    settled.discarded.insert(name);
                } else if self.apply(&relative, replaces && is_dir, settled) {
                    applied = true;
                } else if !is_dir {
                    // A directory it made outside its outputs, holding
                    // nothing of them.
                    settled.discarded.insert(name);
                }
            } else if self.allowed(&target) {
                if let Some(parent) = target.parent() {
                    let _ = std::fs::create_dir_all(parent);
                }
                if is_dir {
                    settled.removed(&target);
                }
                // A rename replaces a link at the target rather than follow
                // it.
                if std::fs::rename(&source, &target).is_err() {
                    let _ = remove(&target);
                    // Copied as it is: a link the command made is never
                    // followed by qk, which Landlock does not hold, to a
                    // file the command could not read.
                    let copied = if kind.is_symlink() {
                        std::fs::read_link(&source)
                            .and_then(|link| std::os::unix::fs::symlink(link, &target))
                    } else if kind.is_file() {
                        std::fs::copy(&source, &target).map(|_| ())
                    } else {
                        settled.discarded.insert(name);
                        continue;
                    };
                    if let Err(error) = copied {
                        settled.fail(&target, &error);
                        continue;
                    }
                }
                applied = true;
            } else {
                settled.discarded.insert(name);
            }
        }
        applied
    }

    /// Beneath a directory the layer replaces whole or removes: removes what
    /// the workspace holds under `relative` and the layer does not, where the
    /// task may write, and adds the rest to `settled.discarded`. What is
    /// bound through the overlay stays: the layer never holds it.
    fn prune(&self, relative: &Path, settled: &mut crate::Settled) -> bool {
        let entries = match std::fs::read_dir(self.root.join(relative)) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return false,
            Err(error) => {
                settled.fail(&self.root.join(relative), &error);
                return false;
            }
        };
        let mut removed = false;
        for entry in entries {
            let entry = match entry {
                Ok(entry) => entry,
                Err(error) => {
                    settled.fail(&self.root.join(relative), &error);
                    continue;
                }
            };
            let relative = relative.join(entry.file_name());
            if std::fs::symlink_metadata(self.upper.join(&relative)).is_ok() {
                continue;
            }
            let target = self.root.join(&relative);
            if self
                .passthrough
                .iter()
                .any(|through| target.starts_with(through))
            {
                continue;
            }
            let real_dir = entry.file_type().is_ok_and(|kind| kind.is_dir());
            if real_dir
                && (self.holds_bound(&target)
                    || (!self.allowed(&target) && self.holds_kept(&target)))
            {
                removed |= self.prune(&relative, settled);
            } else if self.allowed(&target) {
                settled.removed(&target);
                removed = true;
            } else {
                settled
                    .discarded
                    .insert(relative.to_string_lossy().into_owned());
            }
        }
        removed
    }
}

impl crate::Settled {
    fn fail(&mut self, path: &Path, error: &std::io::Error) {
        self.failed.push(format!("{}: {error}", path.display()));
    }

    /// Removes `target`, noting a failure unless it is already gone.
    fn removed(&mut self, target: &Path) {
        if let Err(error) = remove(target)
            && error.kind() != std::io::ErrorKind::NotFound
        {
            self.fail(target, &error);
        }
    }
}

/// Removes a file, a link itself, or a directory with what it holds,
/// following no link.
fn remove(target: &Path) -> std::io::Result<()> {
    match std::fs::symlink_metadata(target)? {
        metadata if metadata.is_dir() => std::fs::remove_dir_all(target),
        _ => std::fs::remove_file(target),
    }
}

/// Whether overlayfs marked a directory of its upper layer opaque: it hides
/// what the lower layer holds there.
fn opaque(directory: &Path) -> bool {
    let Ok(path) = c_path(directory) else {
        return false;
    };
    let mut value = [0u8; 2];
    let length = unsafe {
        libc::lgetxattr(
            path.as_ptr(),
            c"user.overlay.opaque".as_ptr(),
            value.as_mut_ptr().cast(),
            value.len(),
        )
    };
    length == 1 && value[0] == b'y'
}

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

    /// A file in `upper` at `relative`, with what lies above it.
    fn write(upper: &Path, relative: &str) {
        let path = upper.join(relative);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, relative).unwrap();
    }

    #[test]
    fn writes_a_descriptors_path_without_allocating() {
        let mut buffer = [0u8; 32];
        assert_eq!(proc_fd(7, &mut buffer), c"/proc/self/fd/7");
        assert_eq!(
            proc_fd(1234567890, &mut buffer),
            c"/proc/self/fd/1234567890"
        );
    }

    /// A directory chosen to be bound through that a link replaced before a
    /// command entered its overlay is not bound: the link is not followed,
    /// and what the command writes there lands in its upper layer. One still
    /// a directory is bound, and the write reaches the workspace.
    #[test]
    fn binds_no_link_put_in_place_of_a_directory_bound_through() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().canonicalize().unwrap();
        if let Err(error) = probe(&root.join("probe")) {
            eprintln!("skipped: an overlay cannot be mounted here: {error:#}");
            return;
        }
        let workspace = root.join("workspace");
        for directory in ["swapped", "kept", "secret"] {
            std::fs::create_dir_all(workspace.join(directory)).unwrap();
        }
        let Ok(abi) = landlock::abi() else {
            eprintln!("skipped: Landlock is not available");
            return;
        };
        let everything: std::os::fd::OwnedFd = std::fs::File::open("/").unwrap().into();
        let overlay = crate::Overlay {
            workspace: workspace.clone(),
            directory: root.join("overlay"),
            passthrough: vec![workspace.join("swapped"), workspace.join("kept")],
            rules: crate::OverlayRules {
                handled: Rights::handled(abi),
                outside: vec![(everything, Rights::ALL)],
                workspace: Rights::ALL,
                inside: Vec::new(),
            },
            keep: crate::Keep::default(),
            settled: std::sync::OnceLock::new(),
        };
        let setup = Setup::new(&overlay, 0, &workspace).unwrap();
        // Chosen as a directory, then replaced by a link before the command.
        std::fs::remove_dir(workspace.join("swapped")).unwrap();
        std::os::unix::fs::symlink("secret", workspace.join("swapped")).unwrap();
        let mut command = std::process::Command::new("/bin/sh");
        command
            .args(["-c", "echo x > swapped/written && echo x > kept/written"])
            .current_dir(&workspace);
        unsafe {
            std::os::unix::process::CommandExt::pre_exec(&mut command, move || setup.enter());
        }
        let status = command.status().unwrap();
        assert!(status.success());
        let [upper, ..] = layers(&overlay, 0);
        assert!(!workspace.join("secret/written").exists());
        assert!(upper.join("secret/written").is_file());
        assert!(workspace.join("kept/written").is_file());
        clear(&overlay.directory);
    }

    /// What a command wrote beneath a `node_modules`, there before or made by
    /// it, is applied, removals and replacements too; the rest is not.
    #[test]
    fn keeps_what_is_written_in_any_node_modules() {
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path().join("workspace");
        for file in [
            "lib/node_modules/stale/a",
            "app/node_modules/old/a",
            "filed/node_modules",
            "stubbed",
            "elsewhere/kept",
        ] {
            write(&workspace, file);
        }
        std::fs::create_dir_all(workspace.join("linked")).unwrap();
        std::os::unix::fs::symlink(workspace.join("lib"), workspace.join("linked/node_modules"))
            .unwrap();
        std::os::unix::fs::symlink(workspace.join("elsewhere"), workspace.join("tied")).unwrap();
        let overlay = crate::Overlay {
            workspace: workspace.clone(),
            directory: temp.path().join("overlay"),
            passthrough: Vec::new(),
            rules: crate::OverlayRules::default(),
            keep: crate::Keep {
                paths: vec![workspace.join("dist")],
                names: vec!["node_modules".into()],
            },
            settled: std::sync::OnceLock::new(),
        };
        let [upper, ..] = layers(&overlay, 0);
        // A `node_modules` made where none was, and in place of a file and
        // of a link.
        for file in [
            "pkg/node_modules/x/a",
            "pkg/stray.js",
            "dist/out.js",
            "filed/node_modules/x/a",
            "linked/node_modules/x/a",
            // Beneath a file, and beneath a link.
            "stubbed/node_modules/x/a",
            "tied/node_modules/x/a",
        ] {
            write(&upper, file);
        }
        // A whiteout, and an opaque directory, where the file system lets
        // them be made here as overlayfs makes them.
        std::fs::create_dir_all(upper.join("app/node_modules")).unwrap();
        let whiteout = c_path(&upper.join("app/node_modules/old")).unwrap();
        let whited = unsafe { libc::mknod(whiteout.as_ptr(), libc::S_IFCHR, 0) } == 0;
        write(&upper, "lib/node_modules/fresh/a");
        let lib = c_path(&upper.join("lib/node_modules")).unwrap();
        let opaque = unsafe {
            libc::lsetxattr(
                lib.as_ptr(),
                c"user.overlay.opaque".as_ptr(),
                b"y".as_ptr().cast(),
                1,
                0,
            )
        } == 0;
        let settled = overlay.settle();
        // Beneath a file it cannot be made, and fails; beneath a link, which
        // is never followed, the link's entry is discarded whole.
        assert_eq!(settled.failed.len(), 1, "{:?}", settled.failed);
        assert!(
            settled.failed[0].contains("stubbed/node_modules"),
            "{:?}",
            settled.failed
        );
        assert_eq!(
            settled.discarded,
            std::collections::BTreeSet::from(
                ["pkg/stray.js", "stubbed", "tied"].map(str::to_owned)
            )
        );
        assert!(workspace.join("stubbed").is_file());
        assert!(!workspace.join("elsewhere/node_modules").exists());
        let mut made = settled.made.clone();
        made.sort();
        assert_eq!(
            made,
            [
                "filed/node_modules",
                "linked/node_modules",
                "pkg/node_modules"
            ]
            .map(|path| workspace.join(path))
        );
        // The link is replaced, not followed.
        assert!(!workspace.join("lib/x").exists());
        for file in [
            "pkg/node_modules/x/a",
            "dist/out.js",
            "lib/node_modules/fresh/a",
            "filed/node_modules/x/a",
            "linked/node_modules/x/a",
        ] {
            assert!(workspace.join(file).is_file(), "{file}");
        }
        assert!(!workspace.join("pkg/stray.js").exists());
        if whited {
            assert!(!workspace.join("app/node_modules/old").exists());
        } else {
            eprintln!("skipped: a whiteout cannot be made here");
        }
        if opaque {
            assert!(!workspace.join("lib/node_modules/stale").exists());
        } else {
            eprintln!("skipped: an opaque directory cannot be marked here");
        }
    }
}