mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Process-level cleanup for fatal signals.
//!
//! SIGHUP, SIGTERM, and SIGINT can interrupt the runner before normal cleanup
//! runs.  The watchdog waits for them through `sigwait`, cleans up the active
//! container, and exits with the signal-style status code.
//!
//! Only the executor binary installs it: one slot cannot describe the several
//! sandboxes a library host can hold, and a library may not exit its caller's
//! process.  There each sandbox handle tears itself down instead.

use std::io::Write;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};

#[cfg(target_os = "linux")]
use std::thread;
#[cfg(target_os = "linux")]
use std::{
    process::{Child, Command, Output, Stdio},
    sync::{atomic::AtomicU64, mpsc, Arc},
    time::{Duration, Instant},
};

#[cfg(target_os = "linux")]
use nix::{
    sys::{
        signal::{kill, killpg, SigSet, Signal},
        wait::{waitid, Id, WaitPidFlag, WaitStatus},
    },
    unistd::{getpid, Pid},
};

#[cfg(target_os = "linux")]
use crate::lxc_common::lxc_bindings::LxcContainer;
#[cfg(target_os = "linux")]
use crate::lxc_common::network_ingress::IngressManager;
use crate::lxc_common::network_iptables::CreatedResources;
#[cfg(target_os = "linux")]
use crate::lxc_common::network_iptables::{EgressHookPoint, NetworkIptablesManager};
#[cfg(target_os = "linux")]
use crate::mxc_common::logger::{Logger, Mode};
#[cfg(target_os = "linux")]
use crate::mxc_common::termination_signals;

#[derive(Default)]
struct ActiveSandbox {
    name: Option<String>,
    created: CreatedResources,
    netns_pid: Option<u32>,

    #[cfg(target_os = "linux")]
    starting_container: Option<LxcContainer>,

    #[cfg(target_os = "linux")]
    startup_monitor: Option<Child>,

    #[cfg(target_os = "linux")]
    startup_tool: Option<StartupTool>,

    #[cfg(target_os = "linux")]
    monitor_reaper: Option<mpsc::Sender<Child>>,
}

static ACTIVE_CONTAINER: OnceLock<Mutex<ActiveSandbox>> = OnceLock::new();
static WATCHDOG_INSTALLED: AtomicBool = AtomicBool::new(false);

#[cfg(target_os = "linux")]
static STARTUP_LOCK: Mutex<()> = Mutex::new(());
#[cfg(target_os = "linux")]
static STARTUP_CANCELLED: AtomicBool = AtomicBool::new(false);
#[cfg(target_os = "linux")]
static STARTUP_TIMED_OUT: AtomicBool = AtomicBool::new(false);
#[cfg(target_os = "linux")]
static DEADLINE_EPOCH: OnceLock<Instant> = OnceLock::new();
#[cfg(target_os = "linux")]
static STARTUP_DEADLINE_MS: AtomicU64 = AtomicU64::new(0);
#[cfg(target_os = "linux")]
pub(super) const STARTUP_TIMEOUT: Duration = Duration::from_secs(60);

#[cfg(target_os = "linux")]
pub(super) const CLEANUP_COMMAND_TIMEOUT: Duration = Duration::from_secs(120);

#[cfg(target_os = "linux")]
struct StartupTool {
    child: Child,
    stdout: std::fs::File,
    stderr: std::fs::File,
}

#[cfg(target_os = "linux")]
struct StartupDeadline;

#[cfg(target_os = "linux")]
impl Drop for StartupDeadline {
    fn drop(&mut self) {
        STARTUP_DEADLINE_MS.store(0, Ordering::Release);
    }
}

fn lock_slot() -> std::sync::MutexGuard<'static, ActiveSandbox> {
    ACTIVE_CONTAINER
        .get_or_init(|| Mutex::new(ActiveSandbox::default()))
        .lock()
        .unwrap_or_else(|p| p.into_inner())
}

#[cfg(test)]
thread_local! {
    /// Opens the gate for one test thread, leaving it shut for the tests
    /// running beside it.
    static WATCHDOG_OVERRIDE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

pub(crate) fn watchdog_installed() -> bool {
    #[cfg(test)]
    if let Some(overridden) = WATCHDOG_OVERRIDE.with(std::cell::Cell::get) {
        return overridden;
    }
    WATCHDOG_INSTALLED.load(Ordering::Acquire)
}

pub fn exit_after_signal_cleanup(exit_code: i32) -> ! {
    let _ = std::io::stdout().flush();

    #[cfg(target_os = "linux")]
    if watchdog_installed() {
        let active = lock_slot();
        if STARTUP_CANCELLED.load(Ordering::Acquire) {
            drop(active);
            loop {
                thread::park();
            }
        }
        std::process::exit(exit_code);
    }
    std::process::exit(exit_code)
}

#[cfg(target_os = "linux")]
pub(crate) fn check_startup_cancellation() -> Result<(), String> {
    if watchdog_installed() && STARTUP_CANCELLED.load(Ordering::Acquire) {
        Err("LXC startup was cancelled".to_string())
    } else {
        Ok(())
    }
}

#[cfg(target_os = "linux")]
fn write_fatal_diagnostic(message: &str) {
    use std::fs::OpenOptions;
    use std::os::unix::fs::OpenOptionsExt;

    // Reopen stderr with independent file-status flags instead of changing the original handle.
    if let Ok(mut stderr) = OpenOptions::new()
        .append(true)
        .custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOCTTY)
        .open("/proc/self/fd/2")
    {
        let _ = stderr.write(format!("{message}\n").as_bytes());
    }
}

#[cfg(target_os = "linux")]
fn elapsed_millis() -> u64 {
    DEADLINE_EPOCH
        .get_or_init(Instant::now)
        .elapsed()
        .as_millis() as u64
}

#[cfg(target_os = "linux")]
pub(crate) fn startup_time_remaining() -> Option<Duration> {
    if !watchdog_installed() || STARTUP_CANCELLED.load(Ordering::Acquire) {
        return None;
    }
    let deadline = STARTUP_DEADLINE_MS.load(Ordering::Acquire);
    (deadline != 0).then(|| Duration::from_millis(deadline.saturating_sub(elapsed_millis())))
}

#[cfg(target_os = "linux")]
pub(crate) fn record_startup_timeout() {
    if startup_time_remaining().is_some() {
        STARTUP_TIMED_OUT.store(true, Ordering::Release);
    }
}

#[cfg(target_os = "linux")]
fn cancel_timed_out_startup(running: Arc<AtomicBool>) {
    while running.load(Ordering::Acquire) {
        let now = elapsed_millis();
        let startup = STARTUP_DEADLINE_MS.load(Ordering::Acquire);
        if startup != 0 && now >= startup {
            if let Some(active) = ACTIVE_CONTAINER.get() {
                if let Ok(_slot) = active.try_lock() {
                    if STARTUP_DEADLINE_MS.load(Ordering::Acquire) == startup
                        && !STARTUP_CANCELLED.load(Ordering::Acquire)
                    {
                        STARTUP_TIMED_OUT.store(true, Ordering::Release);
                        STARTUP_CANCELLED.store(true, Ordering::Release);
                        let _ = kill(getpid(), Signal::SIGTERM);
                    }
                }
            }
        }
        thread::sleep(Duration::from_millis(10));
    }
}

#[cfg(target_os = "linux")]
fn read_startup_output(file: std::fs::File) -> Vec<u8> {
    use std::io::ErrorKind;
    use std::os::unix::fs::FileExt;

    let length = file
        .metadata()
        .ok()
        .and_then(|metadata| usize::try_from(metadata.len()).ok())
        .unwrap_or(0);
    let mut output = vec![0; length];
    let mut offset = 0;
    while offset < length {
        match file.read_at(&mut output[offset..], offset as u64) {
            Ok(0) => break,
            Ok(count) => offset += count,
            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
            Err(_) => break,
        }
    }
    output.truncate(offset);
    output
}

#[cfg(target_os = "linux")]
pub(crate) fn run_startup_tool(mut command: Command, timeout: Duration) -> Result<Output, String> {
    use std::os::unix::process::CommandExt;

    let tool = command.get_program().to_string_lossy().into_owned();
    termination_signals::unblock_in_child(&mut command);
    if !watchdog_installed() {
        return command
            .output()
            .map_err(|error| format!("Failed to run {tool}: {error}"));
    }

    let stdout = tempfile::tempfile().map_err(|error| error.to_string())?;
    let stderr = tempfile::tempfile().map_err(|error| error.to_string())?;
    command
        .process_group(0)
        .stdin(Stdio::null())
        .stdout(stdout.try_clone().map_err(|error| error.to_string())?)
        .stderr(stderr.try_clone().map_err(|error| error.to_string())?);
    let deadline = Instant::now() + timeout.min(startup_time_remaining().unwrap_or(timeout));
    {
        let mut slot = lock_slot();
        check_startup_cancellation()?;
        let child = command
            .spawn()
            .map_err(|error| format!("Failed to run {tool}: {error}"))?;
        slot.startup_tool = Some(StartupTool {
            child,
            stdout,
            stderr,
        });
    }
    loop {
        {
            let mut slot = lock_slot();
            check_startup_cancellation()?;
            let child = slot
                .startup_tool
                .as_mut()
                .ok_or("LXC startup tool was cancelled")?;
            if let Some(status) = child
                .child
                .try_wait()
                .map_err(|error| format!("Failed to wait for {tool}: {error}"))?
            {
                let completed = slot
                    .startup_tool
                    .take()
                    .ok_or("LXC startup tool was cancelled")?;
                drop(slot);
                return Ok(Output {
                    status,
                    stdout: read_startup_output(completed.stdout),
                    stderr: read_startup_output(completed.stderr),
                });
            }
            if let Some(monitor) = &slot.startup_monitor {
                if matches!(
                    waitid(
                        Id::Pid(Pid::from_raw(monitor.id() as i32)),
                        WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT,
                    ),
                    Ok(WaitStatus::Exited(..) | WaitStatus::Signaled(..))
                ) {
                    return Err("lxc-start exited before startup finished".into());
                }
            }
        }
        if Instant::now() >= deadline {
            record_startup_timeout();
            return Err(format!(
                "{tool} did not finish within {}s",
                timeout.as_secs()
            ));
        }
        thread::sleep(Duration::from_millis(10));
    }
}

#[cfg(target_os = "linux")]
pub(crate) fn run_owned_startup(mut command: Command, readiness: Command) -> Result<(), String> {
    use std::os::unix::process::CommandExt;

    let stderr = tempfile::tempfile().map_err(|error| error.to_string())?;
    let (reaper, monitor) = mpsc::channel::<Child>();
    thread::Builder::new()
        .name("lxc-monitor-reaper".into())
        .spawn(move || {
            if let Ok(mut child) = monitor.recv() {
                let _ = child.wait();
            }
        })
        .map_err(|error| format!("spawn LXC monitor reaper: {error}"))?;

    // Keep the startup monitor owned and create terminal devices without a console directory.
    command
        .args(["-F", "-s", "lxc.console.path=none", "-s", "lxc.tty.dir="])
        .process_group(0)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(stderr.try_clone().map_err(|error| error.to_string())?);
    {
        let mut slot = lock_slot();
        check_startup_cancellation()?;
        slot.startup_monitor = Some(
            command
                .spawn()
                .map_err(|error| format!("Failed to run lxc-start: {error}"))?,
        );
        slot.monitor_reaper = Some(reaper);
    }

    let result = run_startup_tool(readiness, Duration::from_secs(45)).and_then(|output| {
        if output.status.success() {
            Ok(())
        } else {
            Err(format!(
                "lxc-wait failed: {}",
                String::from_utf8_lossy(&output.stderr)
            ))
        }
    });
    result.map_err(|error| {
        format!(
            "{error}; lxc-start: {}",
            String::from_utf8_lossy(&read_startup_output(stderr))
        )
    })
}

#[cfg(target_os = "linux")]
fn stopped_monitor_children(monitor: Pid, deadline: Instant) -> Result<Vec<Pid>, String> {
    use std::fs;

    let children_path = format!("/proc/{monitor}/task/{monitor}/children");
    match fs::read_to_string(&children_path) {
        Ok(children) => {
            return children
                .split_whitespace()
                .map(|child| {
                    child
                        .parse::<i32>()
                        .map(Pid::from_raw)
                        .map_err(|error| format!("{children_path}: {error}"))
                })
                .collect();
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(format!("{children_path}: {error}")),
    }
    let status_path = format!("/proc/{monitor}/status");
    let status =
        fs::read_to_string(&status_path).map_err(|error| format!("{status_path}: {error}"))?;
    let field = |text: &str, name: &str| {
        text.lines()
            .find_map(|line| line.strip_prefix(name))
            .and_then(|value| value.trim().parse::<i32>().ok())
    };
    if field(&status, "Pid:") != Some(monitor.as_raw())
        || field(&status, "PPid:") != Some(getpid().as_raw())
    {
        return Err("Cannot compare startup child PIDs across PID namespaces".into());
    }
    let mounts = fs::read_to_string("/proc/self/mountinfo")
        .map_err(|error| format!("Cannot inspect /proc mount options: {error}"))?;
    let proc_options = mounts.lines().find_map(|line| {
        let (mount, filesystem) = line.split_once(" - ")?;
        let mut filesystem = filesystem.split_whitespace();
        if mount.split_whitespace().nth(4)? != "/proc" || filesystem.next()? != "proc" {
            return None;
        }
        filesystem.nth(1)
    });
    let options = proc_options.ok_or("Cannot identify the /proc mount")?;
    if options
        .split(',')
        .filter_map(|option| option.strip_prefix("hidepid="))
        .any(|value| value != "0" && value != "off")
    {
        return Err("Cannot enumerate startup children through restricted /proc".into());
    }
    let mut children = Vec::new();
    for entry in fs::read_dir("/proc").map_err(|error| error.to_string())? {
        if Instant::now() >= deadline {
            return Err("Startup child enumeration exceeded its cleanup deadline".into());
        }
        let entry = entry.map_err(|error| error.to_string())?;
        let Ok(pid) = entry.file_name().to_string_lossy().parse::<i32>() else {
            continue;
        };
        let status = match fs::read_to_string(entry.path().join("status")) {
            Ok(status) => status,
            Err(error)
                if error.kind() == std::io::ErrorKind::NotFound
                    || error.raw_os_error() == Some(nix::libc::ESRCH) =>
            {
                continue
            }
            Err(error) => return Err(format!("Cannot inspect /proc/{pid}/status: {error}")),
        };
        let parent =
            field(&status, "PPid:").ok_or_else(|| format!("Cannot parse /proc/{pid}/status"))?;
        if parent == monitor.as_raw() {
            children.push(Pid::from_raw(pid));
        }
    }
    Ok(children)
}

#[cfg(target_os = "linux")]
fn reap_before(child: &mut Child, deadline: Instant) -> Result<(), String> {
    loop {
        if child
            .try_wait()
            .map_err(|error| error.to_string())?
            .is_some()
        {
            return Ok(());
        }
        if Instant::now() >= deadline {
            return Err(format!(
                "Startup process {} could not be reaped before its cleanup deadline",
                child.id()
            ));
        }
        thread::sleep(Duration::from_millis(10));
    }
}

#[cfg(target_os = "linux")]
fn interrupt_startup_tool(mut tool: StartupTool) -> Result<(), String> {
    use nix::errno::Errno;

    let pid = Pid::from_raw(tool.child.id() as i32);
    let deadline = Instant::now() + CLEANUP_COMMAND_TIMEOUT;

    // WNOWAIT reserves the group leader's PID until the final signal.
    let flags = WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT;
    let graceful = match killpg(pid, Signal::SIGTERM) {
        Ok(()) | Err(Errno::ESRCH) => loop {
            match waitid(Id::Pid(pid), flags) {
                Ok(WaitStatus::Exited(..) | WaitStatus::Signaled(..)) => break Ok(()),
                Err(Errno::EINTR) => continue,
                Err(error) => break Err(format!("Cannot observe startup command {pid}: {error}")),
                _ if Instant::now() >= deadline => {
                    break Err(format!(
                        "Startup command {pid} did not finish cleanup within {}s",
                        CLEANUP_COMMAND_TIMEOUT.as_secs()
                    ));
                }
                _ => thread::sleep(Duration::from_millis(10)),
            }
        },
        Err(error) => Err(format!("Cannot interrupt startup command {pid}: {error}")),
    };
    let killed = match killpg(pid, Signal::SIGKILL) {
        Ok(()) | Err(Errno::ESRCH) => Ok(()),
        Err(error) => Err(format!("Cannot kill startup command group {pid}: {error}")),
    };
    let reaped = reap_before(&mut tool.child, Instant::now() + Duration::from_secs(5));
    let stderr = read_startup_output(tool.stderr);
    if !stderr.is_empty() {
        write_fatal_diagnostic(String::from_utf8_lossy(&stderr).trim());
    }
    graceful.and(killed).and(reaped)
}

#[cfg(target_os = "linux")]
fn interrupt_startup_monitor(monitor: Option<Child>) -> Result<(), String> {
    let deadline = Instant::now() + Duration::from_secs(5);
    if let Some(mut monitor) = monitor {
        let pid = Pid::from_raw(monitor.id() as i32);
        let flags = WaitPidFlag::WEXITED
            | WaitPidFlag::WSTOPPED
            | WaitPidFlag::WNOHANG
            | WaitPidFlag::WNOWAIT;

        // WNOWAIT reserves the PID and process group until every signal has been sent.
        let state = waitid(Id::Pid(pid), flags).map_err(|error| error.to_string())?;
        if matches!(state, WaitStatus::StillAlive | WaitStatus::Stopped(..)) {
            let _ = kill(pid, Signal::SIGSTOP);
            loop {
                match waitid(Id::Pid(pid), flags) {
                    Ok(WaitStatus::Stopped(..)) => {
                        match stopped_monitor_children(pid, deadline) {
                            Ok(children) => {
                                for child in children {
                                    if let Err(error) = kill(child, Signal::SIGKILL) {
                                        write_fatal_diagnostic(&format!(
                                            "Cannot kill startup child {child}: {error}"
                                        ));
                                    }
                                }
                            }
                            Err(error) => write_fatal_diagnostic(&format!(
                                "{error}; a container with a custom parent-death signal may require manual cleanup"
                            )),
                        }
                        break;
                    }
                    Ok(WaitStatus::Exited(..) | WaitStatus::Signaled(..)) => break,
                    Err(error) => {
                        return Err(format!("Cannot observe startup monitor {pid}: {error}"))
                    }
                    _ if Instant::now() >= deadline => {
                        write_fatal_diagnostic(&format!(
                            "Startup monitor {pid} did not stop before its cleanup deadline"
                        ));
                        break;
                    }
                    _ => thread::sleep(Duration::from_millis(10)),
                }
            }
        }
        let _ = killpg(pid, Signal::SIGKILL);
        reap_before(&mut monitor, deadline)?;
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn interrupt_startup_commands(
    monitor: Option<Child>,
    tool: Option<StartupTool>,
) -> Result<(), String> {
    let tool = tool.map(interrupt_startup_tool).transpose();
    let monitor = interrupt_startup_monitor(monitor);
    match (tool, monitor) {
        (Err(tool), Err(monitor)) => Err(format!("{tool}; {monitor}")),
        (Err(error), _) | (_, Err(error)) => Err(error),
        (Ok(_), Ok(())) => Ok(()),
    }
}

#[cfg(target_os = "linux")]
pub(crate) fn with_container_startup<T>(
    container: &LxcContainer,
    start: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
    if !watchdog_installed() {
        return start();
    }

    let startup = STARTUP_LOCK
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    let deadline = StartupDeadline;
    STARTUP_DEADLINE_MS.store(
        elapsed_millis() + STARTUP_TIMEOUT.as_millis() as u64,
        Ordering::Release,
    );

    {
        let mut slot = lock_slot();
        check_startup_cancellation()?;
        slot.starting_container = Some(LxcContainer::new(
            container.name(),
            Some(container.lxc_path()),
        ));
    }

    let mut result = start();
    let mut slot = lock_slot();
    if check_startup_cancellation().is_ok() {
        if result.is_ok() {
            if let Some(monitor) = slot.startup_monitor.take() {
                match slot.monitor_reaper.take() {
                    Some(reaper) => {
                        if let Err(error) = reaper.send(monitor) {
                            slot.startup_monitor = Some(error.0);
                            result = Err(
                                "LXC monitor reaper disconnected before startup handoff".into()
                            );
                        }
                    }
                    None => {
                        slot.startup_monitor = Some(monitor);
                        result = Err("LXC startup has no monitor reaper".into());
                    }
                }
            }
        }
        if result.is_ok() {
            slot.starting_container = None;
            drop(deadline);
            return result;
        }
        let monitor = slot.startup_monitor.take();
        let tool = slot.startup_tool.take();
        slot.monitor_reaper = None;
        drop(slot);
        let interrupted = interrupt_startup_commands(monitor, tool);
        slot = lock_slot();
        if interrupted.is_ok() {
            slot.starting_container = None;
        } else if let Err(error) = interrupted {
            result = Err(format!("{}; {error}", result.err().unwrap_or_default()));
        }
        if check_startup_cancellation().is_ok() {
            drop(deadline);
            return result;
        }
    }

    if let Err(error) = &result {
        write_fatal_diagnostic(error);
    }

    drop(slot);
    drop(startup);
    loop {
        thread::park();
    }
}

#[cfg(not(target_os = "linux"))]
pub(crate) fn with_container_startup<T>(
    _container: &crate::lxc_common::lxc_bindings::LxcContainer,
    start: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
    start()
}

/// Registers the container the watchdog destroys.
pub fn set_active(name: &str) {
    if !watchdog_installed() {
        return;
    }
    let mut slot = lock_slot();
    slot.name = Some(name.to_owned());
    slot.created = CreatedResources::default();
    slot.netns_pid = None;
}

pub fn set_active_pid(pid: u32) {
    if !watchdog_installed() {
        return;
    }
    let mut slot = lock_slot();
    if slot.name.is_some() {
        slot.netns_pid = Some(pid);
    }
}

pub(crate) fn set_active_created(created: CreatedResources) {
    if !watchdog_installed() {
        return;
    }
    let mut slot = lock_slot();
    if slot.name.is_some() {
        slot.created = created;
    }
}

#[cfg(test)]
fn active_snapshot() -> (Option<String>, CreatedResources, Option<u32>) {
    let slot = lock_slot();
    (slot.name.clone(), slot.created, slot.netns_pid)
}

#[cfg(test)]
fn clear_active() {
    *lock_slot() = ActiveSandbox::default();
}

/// Blocks fatal signals in this thread and spawns the cleanup watchdog.
///
/// `pthread_sigmask` changes only the calling thread's mask, and new threads
/// inherit their creator's mask.  Call this before spawning any thread that
/// should leave signal delivery to the watchdog.
///
/// Child processes inherit the mask as well; spawns undo it with
/// [`termination_signals::unblock_in_child`].
#[cfg(target_os = "linux")]
pub fn install() -> Result<(), String> {
    if watchdog_installed() {
        return Ok(());
    }
    let mask = termination_signals::mask();
    mask.thread_block()
        .map_err(|e| format!("pthread_sigmask: {}", e))?;

    let running = Arc::new(AtomicBool::new(true));
    let guard_running = Arc::clone(&running);
    DEADLINE_EPOCH.get_or_init(Instant::now);
    if let Err(error) = thread::Builder::new()
        .name("lxc-startup-deadline".into())
        .spawn(move || cancel_timed_out_startup(guard_running))
    {
        let _ = mask.thread_unblock();
        return Err(format!("spawn lxc-startup-deadline thread: {error}"));
    }
    match thread::Builder::new()
        .name("lxc-signal-cleanup".into())
        .spawn(move || run_watchdog(mask))
    {
        Ok(_) => {
            WATCHDOG_INSTALLED.store(true, Ordering::Release);
            Ok(())
        }
        Err(err) => {
            running.store(false, Ordering::Release);
            let _ = mask.thread_unblock();
            Err(format!("spawn lxc-signal-cleanup thread: {err}"))
        }
    }
}

/// Non-Linux stub for workspace builds on Windows and macOS.
#[cfg(not(target_os = "linux"))]
pub fn install() -> Result<(), String> {
    Ok(())
}

#[cfg(target_os = "linux")]
fn run_watchdog(mask: SigSet) -> ! {
    loop {
        let Ok(sig) = mask.wait() else { continue };
        let exit_code = if STARTUP_TIMED_OUT.load(Ordering::Acquire) {
            124
        } else {
            128 + sig as i32
        };
        let (monitor, tool) = {
            let mut slot = lock_slot();
            STARTUP_CANCELLED.store(true, Ordering::Release);
            slot.monitor_reaper = None;
            (slot.startup_monitor.take(), slot.startup_tool.take())
        };
        let owned_monitor = monitor.is_some();
        if let Err(error) = interrupt_startup_commands(monitor, tool) {
            write_fatal_diagnostic(&error);
        } else if owned_monitor {
            lock_slot().starting_container = None;
        }
        if STARTUP_TIMED_OUT.load(Ordering::Acquire) {
            write_fatal_diagnostic("LXC startup timed out.  Cleaning up before exit.");
        }
        let _startup = STARTUP_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let active = std::mem::take(&mut *lock_slot());
        if let Some(name) = active.name {
            let mut buf_logger = Logger::new(Mode::Buffer);
            if let Some(pid) = active.netns_pid {
                NetworkIptablesManager::force_cleanup(
                    &name,
                    EgressHookPoint::ContainerNetns(pid),
                    active.created,
                    &mut buf_logger,
                );
                IngressManager::force_cleanup(&name, pid, &mut buf_logger);
            }
            if let Err(error) =
                LxcContainer::new(&name, None).destroy_with_reporter(write_fatal_diagnostic)
            {
                write_fatal_diagnostic(&error);
            }
        } else if let Some(container) = active.starting_container {
            if let Err(error) = container.stop() {
                write_fatal_diagnostic(&error);
            }
        }

        // Terminate without flushing another thread's buffered output.
        unsafe { nix::libc::_exit(exit_code) }
    }
}

#[cfg(all(test, target_os = "linux"))]
#[path = "signal_cleanup_timeout_spec.rs"]
mod timeout_spec;

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

    /// Serializes the tests that share the watchdog's one registration slot.
    static TEST_LOCK: Mutex<()> = Mutex::new(());

    /// The watchdog flag one test needs.
    struct Watchdog {
        _lock: MutexGuard<'static, ()>,
    }

    impl Watchdog {
        fn installed() -> Self {
            Self::enter(true)
        }

        fn uninstalled() -> Self {
            Self::enter(false)
        }

        // The flag is set directly rather than through `install`, which spawns
        // a watchdog that would exit the test binary on the first Ctrl-C.
        fn enter(installed: bool) -> Self {
            let lock = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());
            clear_active();
            set_watchdog_override(Some(installed));
            Self { _lock: lock }
        }
    }

    impl Drop for Watchdog {
        fn drop(&mut self) {
            set_watchdog_override(None);
            clear_active();
        }
    }

    fn set_watchdog_override(value: Option<bool>) {
        WATCHDOG_OVERRIDE.with(|slot| slot.set(value));
    }

    #[test]
    fn the_watchdogs_view_of_a_container_is_built_and_reset_as_a_single_unit() {
        let _watchdog = Watchdog::installed();

        set_active_created(CreatedResources::for_test(true, true, true, true));
        set_active_pid(4242);
        let (name, created, netns_pid) = active_snapshot();
        assert_eq!(name, None, "no container should be registered yet");
        assert_eq!(
            created,
            CreatedResources::default(),
            "ownership published with no registered container must be discarded"
        );
        assert_eq!(
            netns_pid, None,
            "a netns PID published with no registered container must be discarded"
        );

        set_active("ctr-a");
        set_active_pid(1234);
        let v4_chain_only = CreatedResources::for_test(true, false, false, false);
        set_active_created(v4_chain_only);
        assert_eq!(
            active_snapshot(),
            (Some("ctr-a".to_owned()), v4_chain_only, Some(1234)),
            "a registered container must see its own identity and ownership"
        );

        let both_chains = CreatedResources::for_test(true, true, false, false);
        set_active_created(both_chains);
        assert_eq!(
            active_snapshot().1,
            both_chains,
            "the most recent publication is what the watchdog must act on"
        );

        set_active("ctr-b");
        assert_eq!(
            active_snapshot(),
            (Some("ctr-b".to_owned()), CreatedResources::default(), None),
            "registering a new container must reset ownership and netns PID"
        );
    }

    #[test]
    fn a_host_that_installed_no_watchdog_registers_nothing() {
        let _watchdog = Watchdog::uninstalled();

        set_active("ctr-a");
        set_active_pid(1234);
        set_active_created(CreatedResources::for_test(true, true, true, true));

        assert_eq!(
            active_snapshot(),
            (None, CreatedResources::default(), None),
            "one slot cannot describe the several sandboxes a library host can hold, \
             and no watchdog is running to act on what it holds"
        );
    }

    #[test]
    fn an_open_gate_is_confined_to_the_thread_that_opened_it() {
        let _watchdog = Watchdog::installed();

        let seen_elsewhere = std::thread::spawn(watchdog_installed)
            .join()
            .expect("the probe thread must not panic");

        assert!(
            !seen_elsewhere,
            "a test running beside this one would publish its own chain ownership \
             into the slot, overwriting whichever container this one registered"
        );
    }

    #[test]
    fn each_setter_consults_the_watchdog_gate_for_itself() {
        let _watchdog = Watchdog::installed();

        set_active("ctr-a");
        let registered = CreatedResources::for_test(true, false, false, false);
        set_active_created(registered);
        set_active_pid(1234);
        assert_eq!(
            active_snapshot(),
            (Some("ctr-a".to_owned()), registered, Some(1234)),
            "the gates can only be tested against a slot that is fully populated"
        );

        WATCHDOG_OVERRIDE.with(|slot| slot.set(Some(false)));

        set_active_pid(9999);
        assert_eq!(
            active_snapshot().2,
            Some(1234),
            "set_active_pid must consult the gate rather than lean on the registered \
             container check, which passes here"
        );

        set_active_created(CreatedResources::for_test(true, true, true, true));
        assert_eq!(
            active_snapshot().1,
            registered,
            "set_active_created must consult the gate rather than lean on the \
             registered container check, which passes here"
        );

        set_active("ctr-b");
        assert_eq!(
            active_snapshot().0,
            Some("ctr-a".to_owned()),
            "set_active must consult the gate"
        );
    }

    /// Bubblewrap builds its egress chain through the LXC crate's manager, so
    /// its ownership publications reach this slot even inside `lxc-exec`, where
    /// the watchdog is installed.
    #[test]
    fn a_backend_that_registers_no_container_publishes_no_ownership() {
        use crate::lxc_common::network_iptables::{EgressHookPoint, NetworkIptablesManager};
        use crate::mxc_common::logger::{Logger, Mode};
        use crate::mxc_common::models::{ContainerPolicy, NetworkAction, NetworkEgressPolicy};

        let _watchdog = Watchdog::installed();
        let _fake = crate::lxc_common::network_iptables::test_firewall::install();

        let mut manager =
            NetworkIptablesManager::new("mxc-bwrap-publish-test", EgressHookPoint::Unhooked);
        let policy = ContainerPolicy {
            network_egress: Some(NetworkEgressPolicy {
                default: NetworkAction::Allow,
                ..Default::default()
            }),
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);

        manager
            .apply_firewall_rules(&policy, &mut logger)
            .expect("the fake firewall accepts every command");
        assert!(
            manager.rules_applied(),
            "the chain must have been built, or nothing was published to the slot"
        );

        assert_eq!(
            active_snapshot(),
            (None, CreatedResources::default(), None),
            "the watchdog destroys a container by name and this backend has none to give \
             it, so taking the ownership record would aim the removal at whichever LXC \
             container registered last"
        );
    }

    /// A library host that blocks the termination signals itself must not
    /// pass them on blocked to startup tools such as the address-reservation
    /// shell.
    #[cfg(target_os = "linux")]
    #[test]
    fn startup_tools_run_with_the_hosts_blocked_signals_unblocked() {
        let _watchdog = Watchdog::uninstalled();

        struct Restore(SigSet);
        impl Drop for Restore {
            fn drop(&mut self) {
                let _ = self.0.thread_set_mask();
            }
        }
        let _restore = Restore(
            termination_signals::mask()
                .thread_swap_mask(nix::sys::signal::SigmaskHow::SIG_BLOCK)
                .expect("block the termination signals"),
        );

        let mut command = Command::new("cat");
        command.arg("/proc/self/status");
        let output = run_startup_tool(command, Duration::from_secs(10)).expect("run cat");
        assert!(output.status.success(), "{}", output.status);
        let status = String::from_utf8(output.stdout).expect("utf-8");
        let blocked = status
            .lines()
            .find_map(|line| line.strip_prefix("SigBlk:"))
            .map(|hex| u64::from_str_radix(hex.trim(), 16).expect("hex signal set"))
            .unwrap_or_else(|| panic!("SigBlk missing from:\n{status}"));
        for signal in termination_signals::TERMINATION_SIGNALS {
            assert_eq!(
                blocked & (1u64 << (*signal as u32 - 1)),
                0,
                "{signal} still blocked in the startup tool"
            );
        }
    }
}