oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
//! System call filters: `seccomp`.
//!
//! A filter is a small program the kernel runs before every system call of
//! a thread, and whose result says what becomes of the call: an
//! [`Action`]. It is written for the classic BPF machine (the one of
//! socket filters), as a slice of [`Instruction`]s, reads the number of
//! the call, the architecture it is made for and its arguments (as
//! numbers: it cannot follow a pointer), and cannot loop.
//!
//! [`build`], [`allow_list`] and [`deny_list`] write the usual program:
//! check the architecture, then compare the number of the call with a
//! list. [`install`] takes any program, theirs or one written by hand
//! ([`Instruction::new`] and the kernel's `linux/filter.h`).
//!
//! ```no_run
//! # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
//! use oscall::process::linux::{self, seccomp};
//! use oscall::raw::linux::nr;
//!
//! // From here on this thread may read, write and exit, and gets
//! // `EPERM` (1) for anything else.
//! let allowed = [nr::READ, nr::WRITE, nr::EXIT, nr::EXIT_GROUP];
//! let mut buf = [seccomp::Instruction::default(); seccomp::len_for(4)];
//! let program = seccomp::allow_list(&mut buf, &allowed, seccomp::Action::Errno(1))?;
//! linux::set_no_new_privileges()?;
//! seccomp::install(program, seccomp::FilterFlags::empty())?;
//! # }
//! # Ok::<(), oscall::Error>(())
//! ```
//!
//! # What a filter is attached to
//!
//! - **A thread.** [`install`] filters the calling thread, and the threads
//!   and processes it creates afterwards; the other threads of the process
//!   are not touched, unless [`FilterFlags::ALL_THREADS`] is given.
//!   [`ConfineExt::seccomp`](super::ConfineExt::seccomp) installs one in a
//!   child alone, just before its program starts.
//! - **For good.** A filter cannot be removed, and survives `execve`.
//!   Installing another adds to it: every filter runs, and the most
//!   restrictive result wins (in the order of [`Action`]'s documentation).
//! - **To who may not gain privileges.** The caller must have set
//!   [`set_no_new_privileges`](super::set_no_new_privileges), or have
//!   `CAP_SYS_ADMIN` in its user namespace:
//!   [`PermissionDenied`](crate::ErrorKind::PermissionDenied) (`EACCES`)
//!   otherwise. A filter could otherwise be used to make a privileged
//!   program misbehave.
//!
//! # Writing a list
//!
//! System call numbers are those of the architecture
//! ([`raw::linux::nr`](crate::raw::linux::nr)), and so are the calls a
//! program makes: aarch64 and riscv have `openat` and no `open`, 32-bit
//! architectures have `clock_gettime64`, `mmap2`, `_llseek`... A list
//! made for one architecture means nothing on another, which is why the
//! programs written here start by checking it and end the process if it
//! is not the one they were built for. On x86_64 they also end the
//! process for a number of the x32 ABI, whose calls have the same
//! architecture value and other numbers.
//!
//! That check outlives `execve` like the rest of the filter: a 32-bit
//! process that installs such a program and then runs a 64-bit one (an
//! i686 program that runs the `/bin/sh` of an x86_64 system, an armv7 one
//! on aarch64) has it ended at its first system call. A filter that is to
//! hold for programs of several architectures is written by hand, with a
//! list per architecture value ([`DATA_ARCH`], [`Instruction`]).
//!
//! An allow-list has to hold what the runtime of the program needs
//! besides what the program asks for: a libc and `std` make calls of
//! their own (memory, signals, thread exit, `futex`...), which vary with
//! their version. For a child ([`ConfineExt::seccomp`](super::ConfineExt::seccomp))
//! it must allow `execve`, which is the call that starts the program.
//! A deny-list (forbid a few calls, allow the rest) has none of these
//! problems, and protects against what is listed only.
//!
//! # A supervisor that answers for the kernel
//!
//! With [`Action::UserNotify`] a filter hands a call to another process:
//! the thread that made it waits, and a *supervisor* that holds the
//! *listener* of the filter is told, decides, and answers in the kernel's
//! place. It can return a value or an error, do the operation itself and
//! give the caller the resulting handle ([`add_handle`]), or let the call
//! go on ([`Response::continue_syscall`]). This is how a container
//! manager mounts, creates devices or loads modules on behalf of a
//! program that may not.
//!
//! The listener is a handle the installation of the filter returns:
//!
//! - [`install_listener`] for the calling thread, which is then the one
//!   that is filtered: the listener is of use to *another* thread, which
//!   it must reach before the first call that notifies. Threads of one
//!   process share their handles, so a thread installs the filter and
//!   another supervises; or the handle is sent to another process over a
//!   Unix-domain socket
//!   ([`net::unix::send_with_handles`](crate::net::unix::send_with_handles)),
//!   by calls the filter lets through.
//! - [`ConfineExt::seccomp_listener`](super::ConfineExt::seccomp_listener)
//!   for a child, whose listener the caller gets from the
//!   [`Child`](crate::process::Child):
//!   [`ChildExt::take_seccomp_listener`](super::ChildExt::take_seccomp_listener).
//!
//! The supervisor then loops: wait until the listener is readable (a
//! [`Poller`](crate::event::Poller) takes it, through
//! [`event::unix::register`](crate::event::unix::register)),
//! [`receive`] a [`Notification`], and [`respond`]. A filter has one
//! listener at most, and a call that notifies when no listener is left
//! open fails with `ENOSYS`.
//!
//! ```no_run
//! # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
//! # fn supervise(listener: oscall::OwnedHandle) -> oscall::Result<()> {
//! use oscall::process::linux::seccomp::{self, Response};
//! use oscall::raw::linux::{errno, nr};
//!
//! loop {
//!     let call = seccomp::receive(&listener)?;
//!     let response = if call.data.number as usize == nr::MKNODAT {
//!         // ... look at `call.data.args`, do it or not ...
//!         Response::error(call.id, errno::EPERM)
//!     } else {
//!         Response::error(call.id, errno::ENOSYS)
//!     };
//!     seccomp::respond(&listener, &response)?;
//! }
//! # }
//! # }
//! ```
//!
//! **What a supervisor reads of the caller is not what the kernel would
//! have read.** The arguments are numbers; what a pointer among them
//! points to is in the memory of the caller (`/proc/<pid>/mem`), which
//! the caller, or another of its threads, can change at any moment, and
//! the process the notification names may be gone and its identifier
//! reused: check with [`is_valid`] *after* opening anything by that
//! identifier, and before trusting it. See [`Response::continue_syscall`]
//! for why a supervisor cannot be used to *allow* what a filter would
//! otherwise have to forbid.
//!
//! # What is needed of the system
//!
//! `seccomp` filters are in every kernel oscall supports that was built
//! with them (`CONFIG_SECCOMP_FILTER`). qemu-user does not offer the
//! call: [`Unsupported`](crate::ErrorKind::Unsupported). Listeners are
//! from Linux 5.0, [`add_handle`] from 5.9.

use crate::{AsHandle, ErrorKind, OwnedHandle, Result, sys};

/// What becomes of a system call: the `SECCOMP_RET_*` values. When several
/// filters are installed, the action that comes first in this order is the
/// one taken: `KillProcess`, `KillThread`, `Trap`, `Errno`, `UserNotify`,
/// `Trace`, `Log`, `Allow`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Action {
    /// The call is made (`SECCOMP_RET_ALLOW`).
    Allow,
    /// The call is made, and logged (`SECCOMP_RET_LOG`), where the system
    /// logs that action (`/proc/sys/kernel/seccomp/actions_logged`).
    Log,
    /// The call is not made, and fails with this error number
    /// (`SECCOMP_RET_ERRNO`); the kernel keeps the number under 4096.
    Errno(u16),
    /// The call is not made, and the thread receives `SIGSYS`, whose
    /// handler can find out which call it was (`SECCOMP_RET_TRAP`). The
    /// default action of the signal ends the process, with a core dump.
    Trap,
    /// The thread is ended, as if by `SIGSYS`, without a handler being
    /// run (`SECCOMP_RET_KILL_THREAD`). The rest of the process goes on,
    /// rarely in a state it can cope with: prefer
    /// [`KillProcess`](Self::KillProcess).
    KillThread,
    /// The process is ended, as if by `SIGSYS`, without a handler being
    /// run (`SECCOMP_RET_KILL_PROCESS`).
    KillProcess,
    /// The call waits for the answer of whoever holds the listener of the
    /// filter (`SECCOMP_RET_USER_NOTIF`): see the
    /// [module documentation](self#a-supervisor-that-answers-for-the-kernel).
    /// A filter with this action is installed with [`install_listener`];
    /// installed without, or once the listener is closed, the call fails
    /// with `ENOSYS`.
    UserNotify,
    /// The thread stops before the call, for the tracer that asked to be
    /// told ([`ptrace::Options::TRACE_SECCOMP`](super::ptrace::Options::TRACE_SECCOMP)):
    /// it reports [`ptrace::Stop::Seccomp`](super::ptrace::Stop::Seccomp),
    /// with this number as its
    /// [`event_message`](super::ptrace::event_message)
    /// (`SECCOMP_RET_TRACE`). The tracer may change the call or skip it
    /// before it restarts the thread. When no tracer asked, the call is
    /// not made and fails with `ENOSYS`.
    Trace(u16),
}

impl Action {
    /// The value a filter returns for this action: `SECCOMP_RET_*`, with
    /// the error number in the low 16 bits of `Errno`.
    pub const fn value(self) -> u32 {
        match self {
            Self::Allow => 0x7fff_0000,
            Self::Log => 0x7ffc_0000,
            Self::Errno(errno) => 0x0005_0000 | errno as u32,
            Self::Trap => 0x0003_0000,
            Self::KillThread => 0,
            Self::KillProcess => 0x8000_0000,
            Self::UserNotify => 0x7fc0_0000,
            Self::Trace(data) => 0x7ff0_0000 | data as u32,
        }
    }
}

/// One instruction of a filter: the kernel's `struct sock_filter`, an
/// instruction of the classic BPF machine.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Instruction {
    /// What to do: a class, a size or an operation, and a source
    /// (`BPF_LD | BPF_W | BPF_ABS`...).
    pub code: u16,
    /// For a conditional jump, how many instructions to skip when the
    /// condition holds.
    pub jt: u8,
    /// For a conditional jump, how many instructions to skip when it does
    /// not.
    pub jf: u8,
    /// The operand: a constant, or an offset in the data.
    pub k: u32,
}

/// The offset of the system call number in what a filter reads (`struct
/// seccomp_data`): an `int`.
pub const DATA_NUMBER: u32 = 0;
/// The offset of the architecture, an `AUDIT_ARCH_*` value of 32 bits.
pub const DATA_ARCH: u32 = 4;
/// The offset of the address of the instruction that made the call, 64
/// bits.
pub const DATA_INSTRUCTION_POINTER: u32 = 8;
/// The offset of the six arguments of the call, 64 bits each whatever the
/// architecture. A filter loads 32 bits at a time: on the little-endian
/// architectures oscall supports, the low half of argument `n` is at
/// `DATA_ARGS + 8 * n`, and the high half 4 bytes further.
pub const DATA_ARGS: u32 = 16;

impl Instruction {
    /// An instruction from its four fields: `BPF_STMT` and `BPF_JUMP`.
    pub const fn new(code: u16, jt: u8, jf: u8, k: u32) -> Self {
        Self { code, jt, jf, k }
    }

    /// Loads the 32 bits at `offset` of the data into the accumulator:
    /// `BPF_LD | BPF_W | BPF_ABS`.
    pub const fn load(offset: u32) -> Self {
        Self::new(0x20, 0, 0, offset)
    }

    /// Skips `if_equal` instructions when the accumulator is `value`, and
    /// `otherwise` instructions when it is not: `BPF_JMP | BPF_JEQ |
    /// BPF_K`.
    pub const fn jump_if_equal(value: u32, if_equal: u8, otherwise: u8) -> Self {
        Self::new(0x15, if_equal, otherwise, value)
    }

    /// Skips `if_reached` instructions when the accumulator, as an
    /// unsigned number, is `value` or more, and `otherwise` instructions
    /// when it is less: `BPF_JMP | BPF_JGE | BPF_K`.
    pub const fn jump_if_at_least(value: u32, if_reached: u8, otherwise: u8) -> Self {
        Self::new(0x35, if_reached, otherwise, value)
    }

    /// Ends the filter with `action`: `BPF_RET | BPF_K`.
    pub const fn ret(action: Action) -> Self {
        Self::new(0x06, 0, 0, action.value())
    }
}

/// The architecture value (`AUDIT_ARCH_*`) of system calls made by code of
/// the target architecture: what [`DATA_ARCH`] holds for them.
pub const AUDIT_ARCH: u32 = sys::process::seccomp::AUDIT_ARCH;
/// `AUDIT_ARCH_X86_64`. The calls of the x32 ABI have it too, with bit 30
/// set in their number.
pub const AUDIT_ARCH_X86_64: u32 = sys::process::seccomp::AUDIT_ARCH_X86_64;
/// `AUDIT_ARCH_I386`: 32-bit x86, also when the kernel is x86_64.
pub const AUDIT_ARCH_X86: u32 = sys::process::seccomp::AUDIT_ARCH_X86;
/// `AUDIT_ARCH_AARCH64`.
pub const AUDIT_ARCH_AARCH64: u32 = sys::process::seccomp::AUDIT_ARCH_AARCH64;
/// `AUDIT_ARCH_ARM`: 32-bit ARM, also when the kernel is aarch64.
pub const AUDIT_ARCH_ARM: u32 = sys::process::seccomp::AUDIT_ARCH_ARM;
/// `AUDIT_ARCH_RISCV64`.
pub const AUDIT_ARCH_RISCV64: u32 = sys::process::seccomp::AUDIT_ARCH_RISCV64;
/// `AUDIT_ARCH_RISCV32`.
pub const AUDIT_ARCH_RISCV32: u32 = sys::process::seccomp::AUDIT_ARCH_RISCV32;

/// The instructions before the rules: the architecture check and, on
/// x86_64, the refusal of the x32 numbers.
const PREAMBLE: usize = if cfg!(target_arch = "x86_64") { 6 } else { 4 };

/// The bit that marks a system call number of the x32 ABI
/// (`__X32_SYSCALL_BIT`).
const X32_SYSCALL_BIT: u32 = 0x4000_0000;

/// The number of instructions [`build`] writes for `rules` rules: the size
/// of the buffer to give it, usable as the length of an array.
pub const fn len_for(rules: usize) -> usize {
    PREAMBLE + 2 * rules + 1
}

/// Writes into `buf` a filter that takes, for a system call whose number
/// is the first of a pair of `rules`, the action that is the second, and
/// for any other call the action `otherwise`. Returns the program, which
/// is the start of `buf`.
///
/// The numbers are those of the target architecture
/// ([`raw::linux::nr`](crate::raw::linux::nr)). A call made for another
/// architecture (32-bit code in a 64-bit process, where the kernel has
/// that), and on x86_64 a call of the x32 ABI, ends the process
/// ([`Action::KillProcess`]): the numbers would not mean the same calls.
/// When a number is listed twice, its first rule applies.
///
/// # Errors
///
/// [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall) if `buf` is
/// shorter than [`len_for`]`(rules.len())`;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a number that does
/// not fit in 32 bits, and for more rules than a filter can hold (4096
/// instructions: 2044 rules).
pub fn build<'b>(
    buf: &'b mut [Instruction],
    rules: &[(usize, Action)],
    otherwise: Action,
) -> Result<&'b [Instruction]> {
    emit(buf, rules.len(), rules.iter().copied(), otherwise)
}

/// Writes the program of `count` rules.
fn emit(
    buf: &mut [Instruction],
    count: usize,
    rules: impl Iterator<Item = (usize, Action)>,
    otherwise: Action,
) -> Result<&[Instruction]> {
    let len = len_for(count);
    if len > 4096 {
        return Err(ErrorKind::InvalidInput.into());
    }
    let program = buf.get_mut(..len).ok_or(ErrorKind::BufferTooSmall)?;
    let kill = Instruction::ret(Action::KillProcess);
    program[0] = Instruction::load(DATA_ARCH);
    program[1] = Instruction::jump_if_equal(AUDIT_ARCH, 1, 0);
    program[2] = kill;
    program[3] = Instruction::load(DATA_NUMBER);
    if PREAMBLE == 6 {
        program[4] = Instruction::jump_if_at_least(X32_SYSCALL_BIT, 0, 1);
        program[5] = kill;
    }
    let mut at = PREAMBLE;
    for (number, action) in rules.take(count) {
        let number = u32::try_from(number).map_err(|_| ErrorKind::InvalidInput)?;
        program[at] = Instruction::jump_if_equal(number, 0, 1);
        program[at + 1] = Instruction::ret(action);
        at += 2;
    }
    program[at] = Instruction::ret(otherwise);
    Ok(program)
}

/// A filter that allows the system calls whose numbers are in `allowed`,
/// and takes the action `otherwise` for every other: [`build`] with
/// [`Action::Allow`] for each number. See the
/// [module documentation](self#writing-a-list) for what such a list must
/// hold.
pub fn allow_list<'b>(
    buf: &'b mut [Instruction],
    allowed: &[usize],
    otherwise: Action,
) -> Result<&'b [Instruction]> {
    let rules = allowed.iter().map(|&number| (number, Action::Allow));
    emit(buf, allowed.len(), rules, otherwise)
}

/// A filter that takes `action` for the system calls whose numbers are in
/// `denied`, and allows every other: [`build`] with `action` for each
/// number and [`Action::Allow`] for the rest.
pub fn deny_list<'b>(
    buf: &'b mut [Instruction],
    denied: &[usize],
    action: Action,
) -> Result<&'b [Instruction]> {
    let rules = denied.iter().map(|&number| (number, action));
    emit(buf, denied.len(), rules, Action::Allow)
}

crate::macros::flags! {
    /// How a filter is installed: the `SECCOMP_FILTER_FLAG_*`.
    pub struct FilterFlags: u32 {
        /// Every thread of the process gets the filter, not the caller
        /// alone (`SECCOMP_FILTER_FLAG_TSYNC`). It fails, with no thread
        /// changed, if one of them has a filter the caller does not have
        /// (the error is then the identifier of that thread, as the
        /// kernel returns it, which no [`ErrorKind`] names), or is in
        /// strict mode.
        const ALL_THREADS = 1;
        /// Every action of the filter but [`Action::Allow`] is logged,
        /// where the system logs that action
        /// (`SECCOMP_FILTER_FLAG_LOG`).
        const LOG = 1 << 1;
        /// Leaves the mitigation of speculative store bypass as it is,
        /// which installing a filter otherwise switches on for the thread
        /// (`SECCOMP_FILTER_FLAG_SPEC_ALLOW`).
        const ALLOW_SPECULATION = 1 << 2;
        /// Once the supervisor has received a notification, only a signal
        /// that ends the caller interrupts its wait: others are held
        /// until the answer comes
        /// (`SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV`, Linux 5.19).
        /// Without it any signal with a handler interrupts the call, and
        /// the supervisor may have done for nothing what a restarted call
        /// asks for again. Only for a filter with a listener
        /// ([`install_listener`]):
        /// [`InvalidInput`](crate::ErrorKind::InvalidInput) otherwise.
        const WAIT_KILLABLE = 1 << 3;
    }
}

/// Installs `program` as a system call filter of the calling **thread**:
/// `seccomp(SECCOMP_SET_MODE_FILTER)`. See the
/// [module documentation](self#what-a-filter-is-attached-to) for what
/// that means, and for what the caller must have done first.
///
/// The kernel checks the program (every jump lands inside it, it ends
/// with a return, it only reads the data of a system call) and copies it:
/// the slice is not needed afterwards.
///
/// From the moment this returns, the calling thread makes the system
/// calls its filter allows, and no other: what the rest of the program,
/// its runtime included, does about a call that fails or about a thread
/// that is killed is the caller's concern.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// [`set_no_new_privileges`](super::set_no_new_privileges) nor
/// `CAP_SYS_ADMIN`; [`InvalidInput`](crate::ErrorKind::InvalidInput) for
/// an empty program, one of more than 4096 instructions, and one the
/// kernel refuses; [`OutOfMemory`](crate::ErrorKind::OutOfMemory) when the
/// filters of the thread would exceed what the kernel allows in total;
/// [`Unsupported`](crate::ErrorKind::Unsupported) where there is no such
/// call (qemu-user).
pub fn install(program: &[Instruction], flags: FilterFlags) -> Result<()> {
    sys::process::seccomp::install(program, flags)
}

/// Installs `program` as [`install`] does, and returns the *listener* of
/// the filter: the handle on which the calls it answers with
/// [`Action::UserNotify`] are received and answered
/// (`SECCOMP_FILTER_FLAG_NEW_LISTENER`). See the
/// [module documentation](self#a-supervisor-that-answers-for-the-kernel).
///
/// The caller is the one filtered: its next call that notifies waits for
/// someone else to answer through the handle, which a thread that waits
/// for itself never will. Hand the listener over first, by calls the
/// filter allows.
///
/// With [`FilterFlags::ALL_THREADS`], a thread that cannot take the
/// filter makes the call fail with
/// [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess)
/// (`SECCOMP_FILTER_FLAG_TSYNC_ESRCH`, Linux 5.7) rather than with its
/// identifier, which would look like a handle.
///
/// The handle is close-on-exec. It is readable when a notification is
/// waiting, and can be given to a [`Poller`](crate::event::Poller) with
/// [`event::unix::register`](crate::event::unix::register); it reports
/// [`HANGUP`](crate::event::Readiness::HANGUP) once nothing is left that
/// the filter applies to.
///
/// # Errors
///
/// As [`install`]; [`ResourceBusy`](crate::ErrorKind::ResourceBusy) if a
/// filter of the thread has a listener already.
pub fn install_listener(program: &[Instruction], flags: FilterFlags) -> Result<OwnedHandle> {
    sys::process::seccomp::install_listener(program, flags)
}

/// What a filter reads of a system call, and what a supervisor is told of
/// it: `struct seccomp_data`. The offsets of its fields are [`DATA_NUMBER`]
/// and the constants after it.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct SyscallData {
    /// The number of the call, in the architecture [`arch`](Self::arch):
    /// [`raw::linux::nr`](crate::raw::linux::nr) has those of the target.
    pub number: i32,
    /// The architecture the call was made for: an `AUDIT_ARCH_*` value
    /// ([`AUDIT_ARCH`] for code like the caller's). A 64-bit kernel also
    /// runs 32-bit programs, whose numbers mean other calls.
    pub arch: u32,
    /// The address of the instruction that made the call.
    pub instruction_pointer: u64,
    /// The six arguments, as numbers. A pointer among them is an address
    /// in the memory of the process that made the call.
    pub args: [u64; 6],
}

/// A system call that waits for an answer: what [`receive`] returns
/// (`struct seccomp_notif`).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Notification {
    /// What names this call in the answer, and to [`is_valid`] and
    /// [`add_handle`]: unique for the filter.
    pub id: u64,
    /// The thread that made the call, as the process namespace of the
    /// supervisor knows it; 0 if it is not visible there.
    pub pid: u32,
    /// Nothing yet: the kernel writes 0.
    pub flags: u32,
    /// The call.
    pub data: SyscallData,
}

/// The answer to a [`Notification`]: what [`respond`] sends
/// (`struct seccomp_notif_resp`).
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Response {
    id: u64,
    val: i64,
    error: i32,
    flags: u32,
}

impl Response {
    /// The call `id` returns `value`, as if it had succeeded.
    pub const fn success(id: u64, value: i64) -> Self {
        Self {
            id,
            val: value,
            error: 0,
            flags: 0,
        }
    }

    /// The call `id` fails with the error number `errno`
    /// ([`raw::linux::errno`](crate::raw::linux::errno)): a positive
    /// number, as [`Error::raw_os_error`](crate::Error::raw_os_error)
    /// gives it.
    pub const fn error(id: u64, errno: i32) -> Self {
        Self {
            id,
            val: 0,
            // The kernel returns it as it is: a negative number is an
            // error.
            error: errno.wrapping_neg(),
            flags: 0,
        }
    }

    /// The call `id` is made after all, by the kernel, as if the filter
    /// had allowed it (`SECCOMP_USER_NOTIF_FLAG_CONTINUE`, Linux 5.5).
    ///
    /// **This cannot make a decision the security of anything rests on.**
    /// The supervisor looked at the arguments, and at the memory they
    /// point to, at one moment; the kernel reads them again when it makes
    /// the call, and the caller, or another thread or process that shares
    /// its memory, may have changed in between what a pointer leads to: a
    /// path that was checked becomes another path. A supervisor may
    /// continue calls it would have allowed whatever their arguments, and
    /// those whose arguments are plain numbers; what must be checked is
    /// done by the supervisor itself, on values it has copied, with the
    /// result given back ([`success`](Self::success), [`add_handle`]).
    /// The other filters of the caller are not run again either: the call
    /// goes on from where this filter stopped it.
    pub const fn continue_syscall(id: u64) -> Self {
        Self {
            id,
            val: 0,
            error: 0,
            flags: sys::process::seccomp::SECCOMP_USER_NOTIF_FLAG_CONTINUE,
        }
    }
}

/// The sizes the running kernel has for the structures of a listener:
/// what [`notification_sizes`] returns (`struct seccomp_notif_sizes`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct NotificationSizes {
    /// Of a [`Notification`].
    pub notification: u16,
    /// Of a [`Response`].
    pub response: u16,
    /// Of a [`SyscallData`].
    pub data: u16,
}

/// The sizes the running kernel has for the structures of a listener:
/// `seccomp(SECCOMP_GET_NOTIF_SIZES)`.
///
/// They are those of [`Notification`], [`Response`] and [`SyscallData`]
/// in every kernel there has been so far. [`receive`] asks once, and
/// fails with [`Unsupported`](crate::ErrorKind::Unsupported) on a kernel
/// that would write more than a [`Notification`] holds.
pub fn notification_sizes() -> Result<NotificationSizes> {
    sys::process::seccomp::notification_sizes()
}

/// Receives the next system call that waits for an answer on `listener`:
/// `ioctl(SECCOMP_IOCTL_NOTIF_RECV)`.
///
/// It waits until there is one. To wait for several things at once, or
/// for a limited time, wait for the handle to be readable first.
///
/// # Errors
///
/// [`NotFound`](crate::ErrorKind::NotFound) when the call that made the
/// handle readable is gone by the time it is received (its thread was
/// killed), and when nothing is left that the filter applies to;
/// [`Interrupted`](crate::ErrorKind::Interrupted) when a signal handler
/// runs during the wait; `ENOTTY` for a handle that is no listener.
pub fn receive<L: AsHandle + ?Sized>(listener: &L) -> Result<Notification> {
    sys::process::seccomp::receive(listener.as_handle())
}

/// Answers a system call received from `listener`:
/// `ioctl(SECCOMP_IOCTL_NOTIF_SEND)`. The thread that made the call goes
/// on with the answer.
///
/// # Errors
///
/// [`NotFound`](crate::ErrorKind::NotFound) when the call is gone (its
/// thread was killed, or a signal interrupted it: the kernel then
/// restarts it and notifies again, under another identifier);
/// [`InProgress`](crate::ErrorKind::InProgress) when it was answered
/// already; [`InvalidInput`](crate::ErrorKind::InvalidInput) for an
/// answer that continues the call and also gives a value or an error.
pub fn respond<L: AsHandle + ?Sized>(listener: &L, response: &Response) -> Result<()> {
    sys::process::seccomp::respond(listener.as_handle(), response)
}

/// Whether the system call `id` still waits for its answer:
/// `ioctl(SECCOMP_IOCTL_NOTIF_ID_VALID)`.
///
/// A supervisor that opens something of the caller by its identifier
/// (`/proc/<pid>/mem`, a pidfd) asks this *afterwards*: if the call still
/// waits, the process it opened is the one that made it, and not another
/// the identifier was given to since.
pub fn is_valid<L: AsHandle + ?Sized>(listener: &L, id: u64) -> Result<bool> {
    sys::process::seccomp::is_valid(listener.as_handle(), id)
}

crate::macros::flags! {
    /// How [`add_handle`] gives a handle.
    pub struct AddHandleFlags: u32 {
        /// The new handle is close-on-exec in the process that receives
        /// it (`O_CLOEXEC`).
        const CLOSE_ON_EXEC = 1;
        /// Answers the call as well, with the number of the new handle as
        /// its result, in one step (`SECCOMP_ADDFD_FLAG_SEND`, Linux
        /// 5.14): no [`respond`] follows. Done in two steps, a caller
        /// killed in between leaves no one to close the handle, and one
        /// interrupted gets a second handle when it tries again.
        const RESPOND = 1 << 1;
    }
}

/// Gives the process that made the system call `id` a handle of the
/// supervisor's: `ioctl(SECCOMP_IOCTL_NOTIF_ADDFD)` (Linux 5.9). Returns
/// the number the handle has *in that process*.
///
/// This is how a supervisor does on behalf of the caller what returns a
/// handle (`openat`, `socket`, `accept`): it opens the thing itself and
/// answers with the number, in one step with [`AddHandleFlags::RESPOND`].
///
/// With `at`, the handle is installed under that number, replacing what
/// the process had there (`SECCOMP_ADDFD_FLAG_SETFD`), as `dup3` would;
/// without, under the lowest number that is free.
///
/// # Errors
///
/// [`NotFound`](crate::ErrorKind::NotFound) when the call is gone;
/// [`InProgress`](crate::ErrorKind::InProgress) when it was answered
/// already; [`BadHandle`](crate::ErrorKind::BadHandle) for a handle that
/// is not open; [`TooManyOpenFiles`](crate::ErrorKind::TooManyOpenFiles)
/// when the process may have no more.
pub fn add_handle<L: AsHandle + ?Sized, H: AsHandle + ?Sized>(
    listener: &L,
    id: u64,
    handle: &H,
    at: Option<u32>,
    flags: AddHandleFlags,
) -> Result<u32> {
    sys::process::seccomp::add_handle(listener.as_handle(), id, handle.as_handle(), at, flags)
}

crate::macros::flags! {
    /// The settings of a listener: what [`set_listener_flags`] sets.
    pub struct ListenerFlags: u32 {
        /// The supervisor and the caller wake each other on the same
        /// processor, the one giving way to the other
        /// (`SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP`): faster for a
        /// supervisor that answers at once.
        const SYNC_WAKE_UP = 1;
    }
}

/// Replaces the settings of `listener`:
/// `ioctl(SECCOMP_IOCTL_NOTIF_SET_FLAGS)` (Linux 6.7).
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) on a kernel that has
/// no such request.
pub fn set_listener_flags<L: AsHandle + ?Sized>(listener: &L, flags: ListenerFlags) -> Result<()> {
    sys::process::seccomp::set_listener_flags(listener.as_handle(), flags)
}

/// Puts the calling **thread** in strict mode:
/// `seccomp(SECCOMP_SET_MODE_STRICT)`. From then on it may only call
/// `read`, `write`, `exit` (of the thread: not `exit_group`, which is what
/// [`exit`](crate::process::exit) and every runtime call) and
/// `rt_sigreturn`; any other call ends it with `SIGKILL`.
///
/// This is the filter of a computation that needs nothing but descriptors
/// it already has. A thread in that mode can only leave by the `exit`
/// system call ([`raw::linux`](crate::raw::linux)), and what is left of a
/// process whose main thread did so is for its other threads to end.
///
/// Unlike a filter, it needs no privilege and no
/// [`set_no_new_privileges`](super::set_no_new_privileges).
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if the thread has a
/// filter already.
pub fn set_strict() -> Result<()> {
    sys::process::seccomp::set_strict()
}

/// Whether the system calls of a thread are filtered: what [`mode`]
/// returns.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Mode {
    /// They are not.
    Disabled,
    /// Strict mode: [`set_strict`].
    Strict,
    /// One filter or more: [`install`].
    Filter,
}

/// Whether the system calls of the calling thread are filtered:
/// `prctl(PR_GET_SECCOMP)`.
///
/// The question is itself a system call. In strict mode it ends the
/// thread, so [`Mode::Strict`] is never seen; and a filter may forbid it,
/// with whatever action it chose.
pub fn mode() -> Result<Mode> {
    sys::process::seccomp::mode()
}