cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
//! Unix process-group and session containment.
//!
//! Two mechanisms are available:
//! - **ProcessGroup** (`process_group(0)` / `setpgid`): the child becomes a
//!   process-group leader (pgid == pid). Teardown sends `killpg`. cgroup v2
//!   preempts this on Linux when the host offers it: `ContainMode::Strongest` has a process
//!   group only where none is offered, and `ContainMode::BestEffort` also where the leaf cannot
//!   be set up. On macOS the fd marker preempts it, and `ContainMode::BestEffort` has it where the
//!   marker cannot be installed.
//! - **Session** (`setsid`): the child becomes a session leader *and*
//!   process-group leader in a new session, detached from any controlling
//!   terminal. Teardown is identical (`killpg` on the session's initial pgroup,
//!   which equals the leader's pid). Useful for daemon-like children.
//!
//! **Mutual exclusivity:** `setsid` makes the child a session *and*
//! process-group leader simultaneously. Calling `setpgid`/`process_group(0)`
//! on a session leader fails with `EPERM`. Therefore Session mode applies
//! `setsid` *instead of* `process_group(0)` — never both.
//!
//! **Self-`setsid` escape:** a child that calls `setsid` itself exits the
//! parent's session/group; containment is then best-effort. This applies to
//! both mechanisms and is documented as a known limitation (not a sandbox).
//!
//! Parent-side signals use `nix` (not hand-rolled `libc`).
//!
//! # What `killpg` does and does not report
//! Its return value says only whether *at least one* member took the signal. A
//! group holding both a member we may signal and one we may not reports plain
//! success while the second keeps running, on both Unixes. macOS additionally
//! reports `EPERM` for a group whose survivors are all zombies, because xnu
//! excludes zombies from the pgrp iteration before counting. And on Linux even
//! `ESRCH` is not trustworthy as "definitely empty": `__kill_pgrp_info` keeps
//! overwriting its return value with each member's error until one succeeds, so
//! a departed member processed after a live refuser can leave the group's
//! overall `ESRCH` hiding that refuser. None of `killpg`'s three outcomes can be
//! trusted alone on either platform, so teardown always confirms itself against
//! the group's actual membership — see the `group` submodule.
//!
//! # PGID-reuse caveat
//! Once the leader is reaped its PID/PGID may be reissued, and `killpg` would then signal that
//! process's group. On Linux 6.9+ the group's signal goes through the root's pidfd instead, which
//! names the group exactly. Every send by the group's number (the `killpg` where the kernel refuses
//! that, and the leader's signal) runs right after its own check of the root ([`check_number`]:
//! on 6.9+ whether the pidfd's group still has a member). A member's `SIGKILL` resend opens the
//! member by its identity (a pidfd on Linux, an audit token on macOS), then checks the root, then
//! sends through that handle. A member's `SIGTERM` probe checks the root, then the member's
//! identity right before it. Nothing is sent once a check fails; the residual window
//! between a check and its send is documented on `Child::kill_tree`. cgroup v2 names no pid and has
//! no such hole.

use std::io;

use nix::sys::signal::Signal;

use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
use crate::containment::drain_edge::DrainEdge;
use crate::containment::mechanism::{Contains, Release};
use crate::containment::root::NumberLook;
use crate::containment::treewalk::Listing;
use crate::containment::{
    check_number, Containment, Root, SendOutcome, Skip, TerminateOutcome, TreeKill, TreeStop, Why,
};
use crate::error::{Error, Failures};
use std::sync::Arc;

/// A process group or a session, named by the root's pid (`pgid == sid == pid` for a session's
/// leader): its kill and its terminate send by that number, as the root's own state allows
/// ([`kill_group_tree`], [`term_group_tree`]).
#[derive(Debug)]
pub(crate) struct Group {
    pgid: i32,
    session: bool,
}

impl Group {
    /// The process group `pgid`, led by the root.
    pub(crate) fn process_group(pgid: i32) -> Group {
        Group { pgid, session: false }
    }

    /// The session whose initial process group is `pgid`, led by the root.
    pub(crate) fn session(pgid: i32) -> Group {
        Group { pgid, session: true }
    }
}

impl Contains for Group {
    fn kill(&self, root: Option<&dyn Root>) -> TreeKill<'_> {
        kill_group_tree(self.pgid, root)
    }

    fn send_terminate(&self, _pid: u32, root: Option<&dyn Root>, how: TreeStop) -> (TerminateOutcome, Option<Listing>) {
        (term_group_tree(self.pgid, root, how), None)
    }

    /// No kernel object says "every member has exited".
    fn drain_edge(&self) -> Option<DrainEdge<'_>> {
        None
    }

    fn kind(&self) -> Containment {
        if self.session {
            Containment::Session
        } else {
            Containment::ProcessGroup
        }
    }

    /// Dropping a group kills nothing.
    fn disarm(&self) -> io::Result<()> {
        Ok(())
    }

    fn subject(&self) -> String {
        format!("ProcessGroup({})", self.pgid)
    }

    /// A signal to a group is subject to the kernel's permission check, as the child's own kill is.
    fn would_reach(&self, _pid: u32, _pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> Result<bool, Error> {
        Ok(false)
    }

    fn reached(&self, _child: &crate::child::owned::OwnedChild) -> Result<bool, Error> {
        Ok(false)
    }

    fn release(self) -> (Release, Option<Group>) {
        (Release::nothing(), Some(self))
    }

    #[cfg(all(feature = "tokio", target_os = "linux"))]
    fn awaitable_release(&self) -> Option<crate::containment::mechanism::AwaitableRelease<'_>> {
        None
    }
}

/// Apply pre-spawn group setup to `std_cmd` (root spawns only). Linux asks its own steps for the same
/// (`InChild::process_group`).
/// Must not be combined with `set_session` on the same command.
#[cfg(not(target_os = "linux"))]
pub(crate) fn set_process_group(std_cmd: &mut std::process::Command) {
    use std::os::unix::process::CommandExt;
    std_cmd.process_group(0); // leader: pgid == pid
}

/// Apply pre-spawn session setup: a `setsid` step in the spawn's in-child hook (root spawns
/// only, `ContainMode::Session`).
///
/// `setsid` makes the child a session leader *and* process-group leader (pgid
/// == sid == pid), detached from any controlling terminal. Because the child is
/// already a process-group leader after `setsid`, calling `setpgid` or
/// `process_group(0)` on it would return `EPERM` — do not call
/// `set_process_group` on the same command.
///
/// Failure of `setsid` aborts the spawn.
pub(crate) fn set_session(steps: &mut crate::child::spawn::in_child::InChild) {
    steps.session();
}

/// Hard-kill the whole process group, then confirm the group actually came
/// down. See [`signal_group`]. `Ok(())` means every member the ONE listing pass saw was
/// either reached or already gone — not an atomic, ongoing guarantee: a member that forks a
/// new process into the group after that listing (an ordinary respawning supervisor, not
/// only an adversarial fork-bomb) is never seen, never signalled, and does not affect the
/// verdict. A cgroup (Linux cgroup v2, `cgroup.kill`) is fork-proof where this
/// mechanism structurally cannot be; prefer it when that atomicity matters.
///
/// `killed` gets the listed members whose `SIGKILL` resend was delivered, which the kill's wait waits
/// for; never the root (its owner waits for it), and not a member that was already gone.
pub(crate) fn kill_group(
    pgid: i32,
    root: Option<&dyn Root>,
    killed: &mut Vec<crate::identity::ProcessId>,
) -> Result<(), Error> {
    #[cfg(test)]
    if let Some(outcome) = fault::intercept_kill_group(pgid) {
        return outcome;
    }
    signal_group(pgid, Signal::SIGKILL, root, killed)
}

/// Test seam for [`kill_group`]. Thread-local, with an RAII reset.
#[cfg(test)]
pub(crate) mod fault {
    use std::cell::{Cell, RefCell};

    #[cfg(target_os = "linux")]
    pub(crate) use super::group::fault::{list_instead, set_after_listing};

    thread_local! {
        static TERMED: RefCell<Option<Vec<i32>>> = const { RefCell::new(None) };
        static KILLED: RefCell<Option<Vec<i32>>> = const { RefCell::new(None) };
        #[cfg(target_os = "macos")]
        static FAIL: Cell<bool> = const { Cell::new(false) };
        static REFUSE_GROUP: Cell<bool> = const { Cell::new(false) };
        static REFUSE_FLAG: Cell<bool> = const { Cell::new(false) };
        static GROUP_PROBE_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
        static PROBES_REFUSED: Cell<bool> = const { Cell::new(false) };
    }

    /// While the guard lives, every signal-0 probe of a group's member on THIS thread answers
    /// `EPERM` and is not sent, as a process of another user answers.
    #[cfg(target_os = "linux")]
    pub(crate) fn refuse_probes() -> Refused {
        PROBES_REFUSED.with(|r| r.set(true));
        Refused(())
    }

    pub(super) fn probes_refused() -> bool {
        PROBES_REFUSED.with(Cell::get)
    }

    /// While the guard lives, every send to a whole group on THIS thread (the `killpg`, or the
    /// group send through the root's pidfd) is refused with `EPERM` and not sent, as the kernel
    /// refuses a group whose every member belongs to another user. The leader's signal and the
    /// members' resends after it are sent for real.
    pub(crate) fn refuse_group_sends() -> Refused {
        REFUSE_GROUP.with(|r| r.set(true));
        Refused(())
    }

    /// While the guard lives, the group send through the root's pidfd on THIS thread fails with
    /// `EINVAL` and is not sent, as a kernel before 6.9 refuses `PIDFD_SIGNAL_PROCESS_GROUP`. A test
    /// of the pre-6.9 path holds it; on 6.9+ the root's pidfd decides (`group_exact_tests`,
    /// `drop_group_exact_tests`).
    #[cfg(target_os = "linux")]
    pub(crate) fn refuse_pidfd_group_flag() -> Refused {
        REFUSE_FLAG.with(|r| r.set(true));
        Refused(())
    }

    /// While the guard lives, the signal-0 send through a root's pidfd that asks whether its group
    /// has a member fails with `errno` on THIS thread, and is not made.
    #[cfg(target_os = "linux")]
    pub(crate) fn answer_group_probes_with(errno: i32) -> Refused {
        GROUP_PROBE_ERRNO.with(|e| e.set(Some(errno)));
        Refused(())
    }

    #[must_use = "the sends go out again as soon as the guard is dropped"]
    pub(crate) struct Refused(());

    impl Drop for Refused {
        fn drop(&mut self) {
            REFUSE_GROUP.with(|r| r.set(false));
            REFUSE_FLAG.with(|r| r.set(false));
            GROUP_PROBE_ERRNO.with(|e| e.set(None));
            PROBES_REFUSED.with(|r| r.set(false));
        }
    }

    pub(super) fn group_sends_refused() -> bool {
        REFUSE_GROUP.with(Cell::get)
    }

    pub(super) fn group_probe_errno() -> Option<i32> {
        GROUP_PROBE_ERRNO.with(Cell::get)
    }

    pub(super) fn pidfd_group_flag_refused() -> bool {
        REFUSE_FLAG.with(Cell::get)
    }

    /// From now on `kill_group` on THIS thread records its group and sends nothing, so a test can
    /// assert a kill was not issued without a real `killpg` ever reaching a recyclable number: a
    /// mutant that sends by a reaped root's number reaches no process. Only that `killpg` is
    /// stopped, not a `term_group`, a send by pid or a walk.
    pub(crate) fn record_kill_group() -> KillGroupRecorder {
        KILLED.with(|k| *k.borrow_mut() = Some(Vec::new()));
        KillGroupRecorder(())
    }

    /// From now on `term_group` on THIS thread records its group and sends nothing, as
    /// [`record_kill_group`] does for `kill_group`.
    pub(crate) fn record_term_group() -> TermGroupRecorder {
        TERMED.with(|t| *t.borrow_mut() = Some(Vec::new()));
        TermGroupRecorder(())
    }

    #[must_use = "recording stops as soon as the recorder is dropped"]
    pub(crate) struct TermGroupRecorder(());

    impl TermGroupRecorder {
        /// The groups `term_group` was asked to signal since the recorder was made.
        pub(crate) fn termed(&self) -> Vec<i32> {
            TERMED.with(|t| t.borrow().clone().expect("the recorder is live"))
        }
    }

    impl Drop for TermGroupRecorder {
        fn drop(&mut self) {
            TERMED.with(|t| *t.borrow_mut() = None);
        }
    }

    pub(super) fn intercept_term_group(pgid: i32) -> bool {
        TERMED.with(|t| t.borrow_mut().as_mut().map(|termed| termed.push(pgid)).is_some())
    }

    #[must_use = "recording stops as soon as the recorder is dropped"]
    pub(crate) struct KillGroupRecorder(());

    impl KillGroupRecorder {
        /// From now on the intercepted `kill_group` reports the ordinary `Unassessable` refusal of a
        /// group it could not fully assess, as a live member that refuses the signal would cause.
        #[cfg(target_os = "macos")]
        pub(crate) fn fail_with_unassessable(&self) {
            FAIL.with(|f| f.set(true));
        }

        /// The groups `kill_group` was asked to kill since the recorder was made.
        pub(crate) fn killed(&self) -> Vec<i32> {
            KILLED.with(|k| k.borrow().clone().expect("the recorder is live"))
        }

        /// Asserts `pgid` was killed, and nothing else was. More than once is fine: a macOS fd
        /// marker's sweep re-sends `killpg` on a later pass while a holder still confirms the group.
        #[track_caller]
        pub(crate) fn assert_killed_only(&self, pgid: i32) {
            let killed = self.killed();
            assert!(
                !killed.is_empty() && killed.iter().all(|g| *g == pgid),
                "expected only killpg({pgid}), at least once, got {killed:?}"
            );
        }
    }

    impl Drop for KillGroupRecorder {
        fn drop(&mut self) {
            KILLED.with(|k| *k.borrow_mut() = None);
            #[cfg(target_os = "macos")]
            FAIL.with(|f| f.set(false));
        }
    }

    pub(super) fn intercept_kill_group(pgid: i32) -> Option<Result<(), crate::error::Error>> {
        let recorded = KILLED.with(|k| k.borrow_mut().as_mut().map(|killed| killed.push(pgid)).is_some());
        if !recorded {
            return None;
        }
        #[cfg(target_os = "macos")]
        if FAIL.with(|f| f.get()) {
            return Some(Err(crate::error::Error::Unassessable {
                detail: "forced by a test".into(),
                source: None,
            }));
        }
        Some(Ok(()))
    }
}

/// Send `SIGTERM` to the whole process group, then confirm no live
/// member refused it. See [`signal_group`].
#[cfg(test)]
pub(crate) fn term_group(pgid: i32, root: Option<&dyn Root>) -> Result<(), Error> {
    term_group_sent(pgid, root, crate::signal::Signal::Term).into_tree_result()
}

/// [`term_group`], saying whether the signal went out: [`NotSent`](SendOutcome::NotSent) is a send that
/// did not happen, [`Sent`](SendOutcome::Sent) what the check after the send found.
pub(crate) fn term_group_sent(pgid: i32, root: Option<&dyn Root>, signal: crate::signal::Signal) -> SendOutcome {
    #[cfg(test)]
    if fault::intercept_term_group(pgid) {
        return SendOutcome::Sent(Ok(()));
    }
    // A cooperative signal is only probed, never resent: no member is reached by a handle of its own.
    signal_group_sent(pgid, signal.as_nix(), root, &mut Vec::new())
}

/// What a process group's kill or terminate sends by the root's number, from one look at `root`
/// ([`look`](crate::containment::root::look)), decided again by the root's pidfd on Linux 6.9+. Each
/// send by the number after it checks the root again ([`check_number`]).
fn group_look(root: &dyn Root) -> NumberLook {
    let look = crate::containment::root::look(root);
    #[cfg(target_os = "linux")]
    let look = crate::containment::root::through_the_pidfd(look, root);
    #[cfg(test)]
    crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
    look
}

/// What a skipped send to the group `pgid` left undone, and why.
fn skipped_group(pgid: i32, verb: &str, look: NumberLook) -> Skip {
    let (why, root_alone) = match look {
        NumberLook::Untrusted(state) => (Why::untrusted(&state), false),
        NumberLook::MayNameAnother {
            refusal,
            exact_root,
            probe,
        } => (Why::MayNameAnother(refusal, probe), exact_root),
        NumberLook::Trusted | NumberLook::GroupGone => {
            unreachable!("a send to a group that is not skipped has no skip to say")
        }
    };
    Skip {
        action: format!("{verb} its process group (pgid {pgid})"),
        why,
        root_alone,
        holders: None,
    }
}

/// What a group sends once empty: nothing.
fn log_empty_group(pgid: i32) {
    log::debug!(
        "containment::unix: the root is reaped, and its pidfd shows process group {pgid} has no member left, so nothing is sent"
    );
}

/// [`kill_group`], decided on one look at `root`: the group is killed as usual while the root's number
/// names it; sent nothing when it is empty ([`TreeKillOutcome::Answered`]); and skipped, nothing sent
/// by the number, when the number may name another process ([`TreeKillOutcome::Skipped`]: on Linux the
/// caller kills the root alone through its handle when [`Skip::root_alone`]). A group kill is given
/// its `root`, as [`check_number`] needs it.
pub(crate) fn kill_group_tree<'a>(pgid: i32, root: Option<&dyn Root>) -> TreeKill<'a> {
    let mut killed = Vec::new();
    let ran = |sent: Result<(), Error>| TreeKillOutcome::Ran(sent.map_err(Unkilled::from));
    let outcome = match root {
        None => {
            debug_assert!(false, "a group kill was given no root to look at");
            ran(kill_group(pgid, None, &mut killed))
        }
        Some(root) => match group_look(root) {
            NumberLook::Trusted => ran(kill_group(pgid, Some(root), &mut killed)),
            NumberLook::GroupGone => {
                log_empty_group(pgid);
                TreeKillOutcome::Answered(Ok(()))
            }
            look => TreeKillOutcome::Skipped(skipped_group(pgid, "kill", look)),
        },
    };
    TreeKill::of(outcome).reaching(killed)
}

/// [`term_group`] as a tree call decides it, on one look at `root` ([`kill_group_tree`]). A skip ends
/// the call, or, on Linux when the root's handle still names it exactly, leaves the root alone to the
/// caller ([`TerminateOutcome::RootThroughPidfd`]). A send that did not go out is
/// [`TerminateOutcome::NotSent`].
pub(crate) fn term_group_tree(pgid: i32, root: Option<&dyn Root>, how: TreeStop) -> TerminateOutcome {
    let signal = how.signal();
    let sent = |root: Option<&dyn Root>| TerminateOutcome::of(term_group_sent(pgid, root, signal), Some(how.earlier()));
    let Some(root) = root else {
        debug_assert!(false, "a group terminate was given no root to look at");
        return sent(None);
    };
    match group_look(root) {
        NumberLook::Trusted => sent(Some(root)),
        NumberLook::GroupGone => {
            log_empty_group(pgid);
            TerminateOutcome::Sent {
                result: Ok(()),
                earlier: None,
            }
        }
        look => {
            let skip = skipped_group(pgid, "signal", look);
            if skip.root_alone {
                TerminateOutcome::RootThroughPidfd(skip)
            } else {
                TerminateOutcome::End(skip)
            }
        }
    }
}

/// Signal the group and report what was actually achieved. `killpg`'s return value is a
/// best-effort first delivery attempt, never the final verdict — see the module docs and
/// `verify` for why none of `Ok`/`ESRCH`/`EPERM` can be trusted alone on either platform.
fn signal_group(
    pgid: i32,
    signal: Signal,
    root: Option<&dyn Root>,
    killed: &mut Vec<crate::identity::ProcessId>,
) -> Result<(), Error> {
    signal_group_sent(pgid, signal, root, killed).into_tree_result()
}

/// [`signal_group`], saying whether the signal went out: [`NotSent`](SendOutcome::NotSent) is a send that
/// did not happen (an invalid `pgid`, a failed check of the root, a failed `killpg`),
/// [`Sent`](SendOutcome::Sent) what `verify` found after it. Never [`RootExited`](SendOutcome::RootExited):
/// a group's send looks at no walk.
///
/// **The `pgid` guard lives HERE, before any signal is sent — not only in `group::state`.**
/// A `pgid` of `0` signals the CALLER's own process group (per POSIX); a negative one risks
/// the broadcast/double-negation hazard this file's Background measures. A check placed after
/// the dangerous syscall it claims to guard is not a guard.
fn signal_group_sent(
    pgid: i32,
    signal: Signal,
    root: Option<&dyn Root>,
    killed: &mut Vec<crate::identity::ProcessId>,
) -> SendOutcome {
    // NOT a debug_assert!: an invalid `pgid` reaching this function is a directly and deliberately
    // TESTED, ordinary input-validation outcome, not a "should never happen" internal contract —
    // `kill_group_and_term_group_reject_non_positive_pgid` (this file) calls this path with
    // `0`/`-1`/`i32::MIN` on purpose and asserts a plain `Err`, not a panic.
    if pgid <= 0 {
        return SendOutcome::NotSent(Error::Unassessable {
            detail: format!(
                "process group {pgid} is not a valid group id to signal (0 addresses this \
                 process's own group; negative wraps to a broadcast or double-negation hazard)"
            ),
            source: None,
        });
    }
    let sent = match send_to_group(pgid, signal, root) {
        Ok(sent) => sent,
        Err(unchecked) => return SendOutcome::NotSent(unchecked),
    };
    match sent {
        Ok(()) => {}
        // NOT trusted as "definitely empty": Linux's __kill_pgrp_info returns the LAST
        // per-member error once none succeed, so ESRCH can mean "empty" or "a departed member
        // processed after a live refuser" indistinguishably. `verify` below re-lists and
        // settles it either way.
        Err(nix::errno::Errno::ESRCH) => {}
        // Preserved exactly as before this fix: the pgid == pid direct-to-leader fallback
        // for the sudo-wrapper case (sibling #54 territory — do not remove or reshape).
        Err(nix::errno::Errno::EPERM) => {
            _ = signal_direct(pgid, signal, root);
        }
        Err(e) => {
            return SendOutcome::NotSent(Error::Containment {
                detail: format!("{signal} could not be sent to process group {pgid}"),
                source: Some(Error::io_cause(io::Error::from(e))),
            })
        }
    }
    SendOutcome::Sent(verify(pgid, signal, root, killed))
}

/// The send to the whole group, and the kernel's answer to it. On Linux it goes through the root's
/// pidfd with `PIDFD_SIGNAL_PROCESS_GROUP`, which names the group exactly: the kernel resolves it
/// from the pidfd's process, not from a number. Only when the kernel refuses the flag (`EINVAL`,
/// expected below Linux 6.9), or the root has no pidfd, and always on macOS, it goes by the group's number,
/// right after the root's check. A failed check sends nothing and is the call's error.
///
/// The check and the `killpg` are two syscalls: a reaper elsewhere in the process can reap the root
/// between them, and the number can then name another group. That window is a standing property of
/// process-group containment without the flag; a program with such a reaper should use cgroup
/// containment, whose kill names no pid.
pub(crate) fn send_to_group(
    pgid: i32,
    signal: Signal,
    root: Option<&dyn Root>,
) -> Result<Result<(), nix::errno::Errno>, Error> {
    #[cfg(target_os = "linux")]
    if let Some(pidfd) = root.and_then(Root::pidfd) {
        match pidfd_signal(pidfd, signal, Through::Group) {
            Err(nix::errno::Errno::EINVAL) => log::debug!(
                "containment::unix: the kernel refused PIDFD_SIGNAL_PROCESS_GROUP (expected below Linux 6.9), so process group {pgid} is signalled by its number"
            ),
            sent => return Ok(sent),
        }
    }
    check_number(root).map_err(|why| Error::Unassessable {
        detail: format!(
            "process group {pgid}: {why}, so its number may name another group, and {signal} was not sent by it"
        ),
        source: why.cause(),
    })?;
    Ok(send_signal(Target::Group, Sys::Group(pgid), signal))
}

/// What a send through [`send_signal`] reaches.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(not(test), allow(dead_code, reason = "only a test build records it"))]
pub(crate) enum Target {
    /// A whole process group.
    Group,
    /// A group's leader alone, after the group's send was refused.
    Leader,
    /// A listed member of a group, by its pid: probed here. A member's `SIGKILL` resend goes
    /// through the handle opened for its identity, and a test build notes it itself.
    Member(u32),
    /// A member of a cgroup leaf, by its pid, that `CgroupLeaf::terminate` signals. A test build
    /// notes the send, with the route of the syscall made, in `cgroup::fault::take_member_terms`.
    #[cfg(target_os = "linux")]
    LeafMember(u32),
}

/// The syscall [`send_signal`] makes.
#[derive(Clone, Copy)]
#[cfg_attr(
    not(target_os = "linux"),
    allow(dead_code, reason = "only Linux sends through a pidfd")
)]
pub(crate) enum Sys<'a> {
    /// `pidfd_send_signal` through a pidfd, with its flags.
    Pidfd(std::os::fd::BorrowedFd<'a>, libc::c_uint),
    /// `killpg` of a group's number.
    Group(i32),
    /// `kill` of a pid.
    Process(i32),
}

/// Sends `signal` to `target` by `sys`, and gives the kernel's answer. See [`send`].
pub(crate) fn send_signal(target: Target, sys: Sys<'_>, signal: Signal) -> nix::Result<()> {
    send(target, sys, signal as libc::c_int)
}

/// Sends signal 0 to `target` by `sys`: whether it exists and may be signalled. See [`send`].
pub(crate) fn probe_signal(target: Target, sys: Sys<'_>) -> nix::Result<()> {
    send(target, sys, 0)
}

/// Sends `signo` to `target` by `sys`, and gives the kernel's answer. Every send to a process
/// group, its leader or a member, signal 0 included, goes through here and makes its syscall here,
/// so a test build records it ([`GroupStep`](crate::send_log::GroupStep)) once the syscall
/// returned, with its signal number: a send that is skipped leaves no record. In a test build a
/// seam may answer in place of the kernel: `EINVAL` for the pidfd group flag, `EPERM` for a group's
/// signal, the seam's errno for a group's probe, `EPERM` for a member's probe.
fn send(target: Target, sys: Sys<'_>, signo: libc::c_int) -> nix::Result<()> {
    use nix::errno::Errno;
    #[cfg(test)]
    let seam = match (target, sys) {
        (Target::Group, Sys::Pidfd(..)) if fault::pidfd_group_flag_refused() => Some(Errno::EINVAL),
        (Target::Group, Sys::Pidfd(..)) if signo == 0 => fault::group_probe_errno().map(Errno::from_raw),
        (Target::Group, _) if signo != 0 && fault::group_sends_refused() => Some(Errno::EPERM),
        (Target::Member(_), _) if signo == 0 && fault::probes_refused() => Some(Errno::EPERM),
        _ => None,
    };
    #[cfg(not(test))]
    let seam: Option<Errno> = None;
    let sent = match (seam, sys) {
        (Some(errno), _) => Err(errno),
        #[cfg(target_os = "linux")]
        (None, Sys::Pidfd(pidfd, flags)) => pidfd_send_syscall(pidfd, signo, flags),
        #[cfg(not(target_os = "linux"))]
        (None, Sys::Pidfd(..)) => unreachable!("only Linux sends through a pidfd"),
        // SAFETY: plain syscalls on numbers; each caller checked the number right before.
        (None, Sys::Group(pgid)) => Errno::result(unsafe { libc::killpg(pgid, signo) }).map(drop),
        // SAFETY: as above.
        (None, Sys::Process(pid)) => Errno::result(unsafe { libc::kill(pid, signo) }).map(drop),
    };
    #[cfg(test)]
    {
        use crate::send_log::{GroupStep, Route};
        let route = match sys {
            Sys::Pidfd(..) => Route::Pidfd,
            Sys::Group(_) | Sys::Process(_) => Route::Number,
        };
        match target {
            Target::Group => crate::send_log::record_group(GroupStep::Group(route, signo)),
            Target::Leader => crate::send_log::record_group(GroupStep::Leader(route, signo)),
            Target::Member(pid) => crate::send_log::record_group(GroupStep::Member(route, pid, signo)),
            #[cfg(target_os = "linux")]
            Target::LeafMember(pid) => crate::containment::cgroup::fault::record_member_term(sys, pid, signo),
        }
    }
    #[cfg(not(test))]
    let _ = target;
    sent
}

/// `signal` to the process group `pidfd`'s process leads, through `pidfd` (a pidfd, or a
/// `/proc/<pid>` directory, which the kernel takes as one): exact, as [`send_to_group`]'s. `EINVAL`
/// is a kernel before 6.9, which refuses the flag.
#[cfg(target_os = "linux")]
pub(crate) fn pidfd_signal_group(pidfd: std::os::fd::BorrowedFd<'_>, signal: Signal) -> Result<(), nix::errno::Errno> {
    pidfd_signal(pidfd, signal, Through::Group)
}

/// What a send through the root's pidfd reaches.
#[cfg(target_os = "linux")]
#[derive(Clone, Copy, PartialEq, Eq)]
enum Through {
    /// The root's whole process group (`PIDFD_SIGNAL_PROCESS_GROUP`).
    Group,
    /// The root alone.
    Leader,
}

/// Whether the process group `pidfd`'s process leads still has a member, zombies included, from a
/// signal-0 send with `PIDFD_SIGNAL_PROCESS_GROUP`, which names the group exactly. While it has one,
/// the group's number is still its own: the kernel does not reissue a pid that is any process's
/// group id. `Ok(None)` where the kernel refuses the flag (before Linux 6.9). Any other errno is
/// the `Err`: it says nothing of the group (the kernel gives `EPERM` for a group whose every member
/// is another user's, and a seccomp filter may give it for any group, one that took the number
/// included), and a caller left to decide without it keeps it as a cause.
#[cfg(target_os = "linux")]
pub(crate) fn pidfd_group_has_member(pidfd: std::os::fd::BorrowedFd<'_>) -> Result<Option<bool>, nix::errno::Errno> {
    match probe_signal(Target::Group, Sys::Pidfd(pidfd, libc::PIDFD_SIGNAL_PROCESS_GROUP)) {
        Ok(()) => Ok(Some(true)),
        Err(nix::errno::Errno::ESRCH) => Ok(Some(false)),
        Err(nix::errno::Errno::EINVAL) => Ok(None),
        Err(e) => Err(e),
    }
}

/// `signal` through `pidfd`, to what `through` names. The kernel's errno is the answer: `EINVAL`
/// for a flag it does not know.
#[cfg(target_os = "linux")]
fn pidfd_signal(pidfd: std::os::fd::BorrowedFd<'_>, signal: Signal, through: Through) -> Result<(), nix::errno::Errno> {
    let (target, flags) = match through {
        Through::Group => (Target::Group, libc::PIDFD_SIGNAL_PROCESS_GROUP),
        Through::Leader => (Target::Leader, 0),
    };
    send_signal(target, Sys::Pidfd(pidfd, flags), signal)
}

/// `pidfd_send_signal(pidfd, signo, NULL, flags)`. The kernel's errno is the answer.
#[cfg(target_os = "linux")]
fn pidfd_send_syscall(
    pidfd: std::os::fd::BorrowedFd<'_>,
    signo: libc::c_int,
    flags: libc::c_uint,
) -> Result<(), nix::errno::Errno> {
    use std::os::fd::AsRawFd as _;
    // SAFETY: `pidfd` is a live pidfd for the call's duration, and a null `siginfo_t` asks the kernel
    // to fill in the defaults, as `kill(2)` does.
    let rc = unsafe {
        libc::syscall(
            libc::SYS_pidfd_send_signal,
            pidfd.as_raw_fd(),
            signo,
            std::ptr::null::<libc::siginfo_t>(),
            flags,
        )
    };
    if rc == 0 {
        Ok(())
    } else {
        Err(nix::errno::Errno::last())
    }
}

/// Turn the group's actual membership into a contract answer — the single source of truth
/// regardless of what `killpg` reported. See `group`'s module docs for the listing and
/// signal-delivery design (one pass; `SIGKILL` resends for real, `SIGTERM` only probes).
fn verify(
    pgid: i32,
    signal: Signal,
    root: Option<&dyn Root>,
    killed: &mut Vec<crate::identity::ProcessId>,
) -> Result<(), Error> {
    answer_of(
        group::state(&crate::identity::HostKernel, pgid, signal, root, killed),
        pgid,
        signal,
    )
}

/// The contract answer for `state`, what `signal` left of the group `pgid`. Each member that refused
/// or could not be assessed is held as an error of its own, naming its pid, with its cause: the refusers
/// first, as the `source` of the answer ([`Error::Several`] when there are two or more).
fn answer_of(state: group::GroupState, pgid: i32, signal: Signal) -> Result<(), Error> {
    let member = |pid: u32, words: &str, cause: Error, unassessed: bool| {
        Arc::new(Error::of_member(pid, words, cause, unassessed))
    };
    match state {
        group::GroupState::Cleared => Ok(()),
        group::GroupState::Refused { refused, unassessable } => {
            let mut detail = format!(
                "{signal} did not clear {n} member(s) of process group {pgid}; the tree is still up \
                 and this process cannot bring it down",
                n = refused.len(),
            );
            if !unassessable.is_empty() {
                // The group's true state may be WORSE than `refused` alone says — these
                // members were never confirmed either way, not confirmed clear.
                detail.push_str(&format!(
                    "; additionally, {n} member(s) could not be assessed at all",
                    n = unassessable.len(),
                ));
            }
            let members = refused
                .into_iter()
                .map(|(pid, cause)| member(pid, "refused the signal", cause, false))
                .chain(
                    unassessable
                        .into_iter()
                        .map(|(pid, cause)| member(pid, "could not be assessed", cause, true)),
                );
            let source = Failures::collect(members).map(Failures::into_cause);
            Err(Error::Containment { detail, source })
        }
        group::GroupState::Unassessed { members } => {
            let detail = format!(
                "{n} member(s) of process group {pgid} could not be assessed after {signal}",
                n = members.len(),
            );
            let members = members
                .into_iter()
                .map(|(pid, cause)| member(pid, "could not be assessed", cause, true));
            Err(Error::Unassessable {
                detail,
                source: Failures::collect(members).map(Failures::into_cause),
            })
        }
        // A refused listing is the platform's `Unsupported`, like a wait's or spawn's, not an unassessable group.
        group::GroupState::Unlistable {
            source: group::ListingFailure::Unsupported(refused),
            ..
        } => Err(refused),
        group::GroupState::Unlistable {
            detail,
            source: group::ListingFailure::Failed(source),
        } => Err(Error::Unassessable {
            detail,
            source: Some(Error::io_cause(source)),
        }),
    }
}

/// Signal `pid` directly. Already-gone is success. Kept, unmodified, because sibling #54
/// explicitly forbids touching this fallback — but the two signals it guards need opposite
/// framing, worked out fully rather than left as one general "unclear":
///
/// - **`kill_group` (`SIGKILL`)**: redundant for a member `converge` actually reaches, NOT
///   provably redundant overall. `converge` only resends to a member it has classified
///   `Liveness::Alive` AND successfully re-verified (`classify_member`/`resend_sigkill`);
///   any member whose liveness or identity the OS refuses to confirm (`Liveness::Unknown` /
///   `Resolved::Unknown`) is never signalled by `converge` at all — for THOSE, this direct
///   call is the only delivery attempt, not a duplicate. It is also not the same check: this
///   call checks the root itself, while `converge` checks each member's token as well. Kept as
///   the only delivery for members `converge` never signals.
/// - **`term_group` (`SIGTERM`)**: NOT redundant — the only real one. `converge`'s `SIGTERM`
///   path deliberately never resends — only probes, to avoid tripping a program's own
///   double-signal escalation convention — so this is the ONLY actual `SIGTERM`
///   delivery attempt to the leader after `killpg` reports `EPERM`. Do not remove or reframe
///   this arm as optional for the graceful path.
///
/// Its failure is intentionally NOT propagated (best-effort; `verify`'s listing decides the
/// contract answer either way), but is now logged rather than silently discarded, so a
/// genuine `SIGTERM` delivery failure here — the one case that matters — leaves a trace.
///
/// On Linux it goes through the root's pidfd when it has one, which names the leader exactly;
/// otherwise by `pid`, right after the root's own check, and not at all if that fails.
fn signal_direct(pid: i32, signal: Signal, root: Option<&dyn Root>) -> io::Result<()> {
    #[cfg(target_os = "linux")]
    let sent = root
        .and_then(Root::pidfd)
        .map(|pidfd| pidfd_signal(pidfd, signal, Through::Leader));
    #[cfg(not(target_os = "linux"))]
    let sent = None;
    let sent = match sent {
        Some(sent) => sent,
        None => {
            if let Err(why) = check_number(root) {
                log::debug!(
                    "containment::unix::signal_direct: {why}, so {signal} was not sent to pid {pid}",
                    why = crate::error::Report(&why)
                );
                return Err(io::Error::other(why));
            }
            send_signal(Target::Leader, Sys::Process(pid), signal)
        }
    };
    match sent {
        Ok(()) | Err(nix::errno::Errno::ESRCH) => Ok(()),
        Err(e) => {
            log::debug!(
                "containment::unix::signal_direct: kill({pid}, {signal}) failed: {report}",
                report = crate::error::Report(&e)
            );
            Err(io::Error::from(e))
        }
    }
}

#[path = "unix/group.rs"]
mod group;

#[cfg(test)]
#[path = "unix_tests.rs"]
mod unix_tests;

#[cfg(test)]
#[path = "unix_send_tests.rs"]
mod unix_send_tests;