summaryrefslogtreecommitdiffstats
path: root/vendor/rustix/src/process/procctl.rs
blob: 443aa90a45fdfaa96ae03d30278f026828280f5e (plain)
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
//! Bindings for the FreeBSD `procctl` system call.
//!
//! There are similarities (but also differences) with Linux's `prctl` system
//! call, whose interface is located in the `prctl.rs` file.

#![allow(unsafe_code)]

use core::mem::MaybeUninit;
use core::ptr;

use bitflags::bitflags;

use crate::backend::c::{c_int, c_uint, c_void};
use crate::backend::process::syscalls;
use crate::backend::process::types::{RawId, Signal};
use crate::io;
use crate::process::{Pid, RawPid};

//
// Helper functions.
//

/// Subset of `idtype_t` C enum, with only the values allowed by `procctl`.
#[repr(i32)]
pub enum IdType {
    /// Process id.
    Pid = 0,
    /// Process group id.
    Pgid = 2,
}

/// A process selector for use with the `procctl` interface.
///
/// `None` represents the current process. `Some((IdType::Pid, pid))`
/// represents the process with pid `pid`. `Some((IdType::Pgid, pgid))`
/// represents the control processes belonging to the process group with id
/// `pgid`.
pub type ProcSelector = Option<(IdType, Pid)>;
fn proc_selector_to_raw(selector: ProcSelector) -> (IdType, RawPid) {
    match selector {
        Some((idtype, id)) => (idtype, id.as_raw_nonzero().get()),
        None => (IdType::Pid, 0),
    }
}

#[inline]
pub(crate) unsafe fn procctl(
    option: c_int,
    process: ProcSelector,
    data: *mut c_void,
) -> io::Result<()> {
    let (idtype, id) = proc_selector_to_raw(process);
    syscalls::procctl(idtype as c_uint, id as RawId, option, data)
}

#[inline]
pub(crate) unsafe fn procctl_set<P>(
    option: c_int,
    process: ProcSelector,
    data: &P,
) -> io::Result<()> {
    procctl(option, process, (data as *const P as *mut P).cast())
}

#[inline]
pub(crate) unsafe fn procctl_get_optional<P>(
    option: c_int,
    process: ProcSelector,
) -> io::Result<P> {
    let mut value: MaybeUninit<P> = MaybeUninit::uninit();
    procctl(option, process, value.as_mut_ptr().cast())?;
    Ok(value.assume_init())
}

//
// PROC_PDEATHSIG_STATUS/PROC_PDEATHSIG_CTL
//

const PROC_PDEATHSIG_STATUS: c_int = 12;

/// Get the current value of the parent process death signal.
///
/// # References
///  - [Linux: `prctl(PR_GET_PDEATHSIG,...)`]
///  - [FreeBSD: `procctl(PROC_PDEATHSIG_STATUS,...)`]
///
/// [Linux: `prctl(PR_GET_PDEATHSIG,...)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
/// [FreeBSD: `procctl(PROC_PDEATHSIG_STATUS,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn parent_process_death_signal() -> io::Result<Option<Signal>> {
    unsafe { procctl_get_optional::<c_int>(PROC_PDEATHSIG_STATUS, None) }.map(Signal::from_raw)
}

const PROC_PDEATHSIG_CTL: c_int = 11;

/// Set the parent-death signal of the calling process.
///
/// # References
///  - [Linux: `prctl(PR_SET_PDEATHSIG,...)`]
///  - [FreeBSD: `procctl(PROC_PDEATHSIG_CTL,...)`]
///
/// [Linux: `prctl(PR_SET_PDEATHSIG,...)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
/// [FreeBSD: `procctl(PROC_PDEATHSIG_CTL,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn set_parent_process_death_signal(signal: Option<Signal>) -> io::Result<()> {
    let signal = signal.map_or(0, |signal| signal as c_int);
    unsafe { procctl_set::<c_int>(PROC_PDEATHSIG_CTL, None, &signal) }
}

//
// PROC_TRACE_CTL
//

const PROC_TRACE_CTL: c_int = 7;

const PROC_TRACE_CTL_ENABLE: i32 = 1;
const PROC_TRACE_CTL_DISABLE: i32 = 2;
const PROC_TRACE_CTL_DISABLE_EXEC: i32 = 3;

/// `PROC_TRACE_CTL_*`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(i32)]
pub enum DumpableBehavior {
    /// Not dumpable.
    NotDumpable = PROC_TRACE_CTL_DISABLE,
    /// Dumpable.
    Dumpable = PROC_TRACE_CTL_ENABLE,
    /// Not dumpable, and this behaviour is preserved across `execve` calls.
    NotDumpableExecPreserved = PROC_TRACE_CTL_DISABLE_EXEC,
}

/// Set the state of the `dumpable` attribute for the process indicated by
/// `idtype` and `id`. This determines whether the process can be traced and
/// whether core dumps are produced for the process upon delivery of a signal
/// whose default behavior is to produce a core dump.
///
/// This is similar to `set_dumpable_behavior` on Linux, with the exception
/// that on FreeBSD there is an extra argument `process`. When `process` is set
/// to `None`, the operation is performed for the current process, like on
/// Linux.
///
/// # References
///  - [FreeBSD `procctl(PROC_TRACE_CTL,...)`]
///
/// [FreeBSD `procctl(PROC_TRACE_CTL,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn set_dumpable_behavior(process: ProcSelector, config: DumpableBehavior) -> io::Result<()> {
    unsafe { procctl(PROC_TRACE_CTL, process, config as usize as *mut _) }
}

//
// PROC_TRACE_STATUS
//

const PROC_TRACE_STATUS: c_int = 8;

/// Tracing status as returned by [`trace_status`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum TracingStatus {
    /// Tracing is disabled for the process.
    NotTraceble,
    /// Tracing is not disabled for the process, but not debugger/tracer is
    /// attached.
    Tracable,
    /// The process is being traced by the process whose pid is stored in the
    /// first component of this variant.
    BeingTraced(Pid),
}

/// Get the tracing status of the process indicated by `idtype` and `id`.
///
/// # References
///  - [FreeBSD `procctl(PROC_TRACE_STATUS,...)`]
///
/// [FreeBSD `procctl(PROC_TRACE_STATUS,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn trace_status(process: ProcSelector) -> io::Result<TracingStatus> {
    let val = unsafe { procctl_get_optional::<c_int>(PROC_TRACE_STATUS, process) }?;
    match val {
        -1 => Ok(TracingStatus::NotTraceble),
        0 => Ok(TracingStatus::Tracable),
        pid => {
            let pid = unsafe { Pid::from_raw(pid as RawPid) }.ok_or(io::Errno::RANGE)?;
            Ok(TracingStatus::BeingTraced(pid))
        }
    }
}

//
// PROC_REAP_*
//

const PROC_REAP_ACQUIRE: c_int = 2;
const PROC_REAP_RELEASE: c_int = 3;

/// Acquire or release the reaper status of the calling process.
///
/// # References
///  - [FreeBSD: `procctl(PROC_REAP_ACQUIRE/RELEASE,...)`]
///
/// [FreeBSD: `procctl(PROC_REAP_ACQUIRE/RELEASE,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn set_reaper_status(reaper: bool) -> io::Result<()> {
    unsafe {
        procctl(
            if reaper {
                PROC_REAP_ACQUIRE
            } else {
                PROC_REAP_RELEASE
            },
            None,
            ptr::null_mut(),
        )
    }
}

const PROC_REAP_STATUS: c_int = 4;

bitflags! {
    /// `REAPER_STATUS_*`.
    pub struct ReaperStatusFlags: c_uint {
        /// The process has acquired reaper status.
        const OWNED = 1;
        /// The process is the root of the reaper tree (pid 1).
        const REALINIT = 2;
    }
}

#[repr(C)]
struct procctl_reaper_status {
    rs_flags: c_uint,
    rs_children: c_uint,
    rs_descendants: c_uint,
    rs_reaper: RawPid,
    rs_pid: RawPid,
    rs_pad0: [c_uint; 15],
}

/// Reaper status as returned by [`get_reaper_status`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ReaperStatus {
    /// The flags.
    pub flags: ReaperStatusFlags,
    /// The number of children of the reaper among the descendants.
    pub children: usize,
    /// The total number of descendants of the reaper(s), not counting
    /// descendants of the reaper in the subtree.
    pub descendants: usize,
    /// The pid of the reaper for the specified process id.
    pub reaper: Pid,
    /// The pid of one reaper child if there are any descendants.
    pub pid: Pid,
}

/// Get information about the reaper of the specified process (or the process
/// itself if it is a reaper).
///
/// # References
///  - [FreeBSD: `procctl(PROC_REAP_STATUS,...)`]
///
/// [FreeBSD: `procctl(PROC_REAP_STATUS,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn get_reaper_status(process: ProcSelector) -> io::Result<ReaperStatus> {
    let raw = unsafe { procctl_get_optional::<procctl_reaper_status>(PROC_REAP_STATUS, process) }?;
    Ok(ReaperStatus {
        flags: ReaperStatusFlags::from_bits_truncate(raw.rs_flags),
        children: raw.rs_children as _,
        descendants: raw.rs_descendants as _,
        reaper: unsafe { Pid::from_raw(raw.rs_reaper) }.ok_or(io::Errno::RANGE)?,
        pid: unsafe { Pid::from_raw(raw.rs_pid) }.ok_or(io::Errno::RANGE)?,
    })
}

const PROC_REAP_GETPIDS: c_int = 5;

bitflags! {
    /// `REAPER_PIDINFO_*`.
    pub struct PidInfoFlags: c_uint {
        /// This structure was filled by the kernel.
        const VALID = 1;
        /// The pid field identifies a direct child of the reaper.
        const CHILD = 2;
        /// The reported process is itself a reaper. Descendants of a subordinate reaper are not reported.
        const REAPER = 4;
        /// The reported process is in the zombie state.
        const ZOMBIE = 8;
        /// The reported process is stopped by SIGSTOP/SIGTSTP.
        const STOPPED = 16;
        /// The reported process is in the process of exiting.
        const EXITING = 32;
    }
}

#[repr(C)]
#[derive(Default, Clone)]
struct procctl_reaper_pidinfo {
    pi_pid: RawPid,
    pi_subtree: RawPid,
    pi_flags: c_uint,
    pi_pad0: [c_uint; 15],
}

#[repr(C)]
struct procctl_reaper_pids {
    rp_count: c_uint,
    rp_pad0: [c_uint; 15],
    rp_pids: *mut procctl_reaper_pidinfo,
}

/// A child process of a reaper.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct PidInfo {
    /// The flags of the process.
    pub flags: PidInfoFlags,
    /// The pid of the process.
    pub pid: Pid,
    /// The pid of the child of the reaper which is the (grand-..)parent of the
    /// process.
    pub subtree: Pid,
}

/// Get the list of descendants of the specified reaper process.
///
/// # References
///  - [FreeBSD: `procctl(PROC_REAP_GETPIDS,...)`]
///
/// [FreeBSD: `procctl(PROC_REAP_GETPIDS,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
pub fn get_reaper_pids(process: ProcSelector) -> io::Result<Vec<PidInfo>> {
    // Sadly no better way to guarantee that we get all the results than to
    // allocate ~8MB of memory..
    const PID_MAX: usize = 99999;
    let mut pids: Vec<procctl_reaper_pidinfo> = vec![Default::default(); PID_MAX];
    let mut pinfo = procctl_reaper_pids {
        rp_count: PID_MAX as _,
        rp_pad0: [0; 15],
        rp_pids: pids.as_mut_slice().as_mut_ptr(),
    };
    unsafe {
        procctl(
            PROC_REAP_GETPIDS,
            process,
            (&mut pinfo as *mut procctl_reaper_pids).cast(),
        )?
    };
    let mut result = Vec::new();
    for raw in pids.into_iter() {
        let flags = PidInfoFlags::from_bits_truncate(raw.pi_flags);
        if !flags.contains(PidInfoFlags::VALID) {
            break;
        }
        result.push(PidInfo {
            flags,
            subtree: unsafe { Pid::from_raw(raw.pi_subtree) }.ok_or(io::Errno::RANGE)?,
            pid: unsafe { Pid::from_raw(raw.pi_pid) }.ok_or(io::Errno::RANGE)?,
        });
    }
    Ok(result)
}

const PROC_REAP_KILL: c_int = 6;

bitflags! {
    /// `REAPER_KILL_*`.
    struct KillFlags: c_uint {
        const CHILDREN = 1;
        const SUBTREE = 2;
    }
}

#[repr(C)]
struct procctl_reaper_kill {
    rk_sig: c_int,
    rk_flags: c_uint,
    rk_subtree: RawPid,
    rk_killed: c_uint,
    rk_fpid: RawPid,
    rk_pad0: [c_uint; 15],
}

/// Reaper status as returned by [`get_reaper_status`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct KillResult {
    /// The number of processes that were signalled.
    pub killed: usize,
    /// The pid of the first process that wasn't successfully signalled.
    pub first_failed: Option<Pid>,
}

/// Deliver a signal to some subset of
///
/// # References
///  - [FreeBSD: `procctl(PROC_REAP_KILL,...)`]
///
/// [FreeBSD: `procctl(PROC_REAP_KILL,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
pub fn reaper_kill(
    process: ProcSelector,
    signal: Signal,
    direct_children: bool,
    subtree: Option<Pid>,
) -> io::Result<KillResult> {
    let mut flags = KillFlags::empty();
    flags.set(KillFlags::CHILDREN, direct_children);
    flags.set(KillFlags::SUBTREE, subtree.is_some());
    let mut req = procctl_reaper_kill {
        rk_sig: signal as c_int,
        rk_flags: flags.bits(),
        rk_subtree: subtree.map(|p| p.as_raw_nonzero().into()).unwrap_or(0),
        rk_killed: 0,
        rk_fpid: 0,
        rk_pad0: [0; 15],
    };
    unsafe {
        procctl(
            PROC_REAP_KILL,
            process,
            (&mut req as *mut procctl_reaper_kill).cast(),
        )?
    };
    Ok(KillResult {
        killed: req.rk_killed as _,
        first_failed: if req.rk_fpid == -1 {
            None
        } else {
            unsafe { Pid::from_raw(req.rk_fpid) }
        },
    })
}

//
// PROC_TRAPCAP_STATUS/PROC_TRAPCAP_CTL
//

const PROC_TRAPCAP_CTL: c_int = 9;

const PROC_TRAPCAP_CTL_ENABLE: i32 = 1;
const PROC_TRAPCAP_CTL_DISABLE: i32 = 2;

/// `PROC_TRAPCAP_CTL_*`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(i32)]
pub enum TrapCapBehavior {
    /// Disable the [`Signal::Trap`] signal delivery on capability mode access
    /// violations.
    Disable = PROC_TRAPCAP_CTL_DISABLE,
    /// Enable the [`Signal::Trap`] signal delivery on capability mode access
    /// violations.
    Enable = PROC_TRAPCAP_CTL_ENABLE,
}

/// Set the current value of the capability mode violation trapping behavior.
/// If this behavior is enabled, the kernel would deliver a [`Signal::Trap`]
/// signal on any return from a system call that would result in a
/// [`io::Errno::NOTCAPABLE`]` or [`io::Errno::CAPMODE`] error.
///
/// This behavior is inherited by the children of the process and is kept
/// across `execve` calls.
///
/// # References
///  - [FreeBSD: `procctl(PROC_TRAPCAP_CTL,...)`]
///
/// [FreeBSD: `procctl(PROC_TRAPCAP_CTL,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn set_trap_cap_behavior(process: ProcSelector, config: TrapCapBehavior) -> io::Result<()> {
    let config = config as c_int;
    unsafe { procctl_set::<c_int>(PROC_TRAPCAP_CTL, process, &config) }
}

const PROC_TRAPCAP_STATUS: c_int = 10;

/// Get the current value of the capability mode violation trapping behavior.
///
/// # References
///  - [FreeBSD: `procctl(PROC_TRAPCAP_STATUS,...)`]
///
/// [FreeBSD: `procctl(PROC_TRAPCAP_STATUS,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn trap_cap_behavior(process: ProcSelector) -> io::Result<TrapCapBehavior> {
    let val = unsafe { procctl_get_optional::<c_int>(PROC_TRAPCAP_STATUS, process) }?;
    match val {
        PROC_TRAPCAP_CTL_DISABLE => Ok(TrapCapBehavior::Disable),
        PROC_TRAPCAP_CTL_ENABLE => Ok(TrapCapBehavior::Enable),
        _ => Err(io::Errno::RANGE),
    }
}

//
// PROC_NO_NEW_PRIVS_STATUS/PROC_NO_NEW_PRIVS_CTL
//

const PROC_NO_NEW_PRIVS_CTL: c_int = 19;

const PROC_NO_NEW_PRIVS_ENABLE: c_int = 1;

/// Enable the `no_new_privs` mode that ignores SUID and SGID bits
/// on `execve` in the specified process and its future descendants.
///
/// This is similar to `set_no_new_privs` on Linux, with the exception
/// that on FreeBSD there is no argument `no_new_privs` argument as it's
/// only possible to enable this mode and there's no going back.
///
/// # References
///  - [Linux: `prctl(PR_SET_NO_NEW_PRIVS,...)`]
///  - [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_CTL,...)`]
///
/// [Linux: `prctl(PR_SET_NO_NEW_PRIVS,...)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
/// [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_CTL,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn set_no_new_privs(process: ProcSelector) -> io::Result<()> {
    unsafe { procctl_set::<c_int>(PROC_NO_NEW_PRIVS_CTL, process, &PROC_NO_NEW_PRIVS_ENABLE) }
}

const PROC_NO_NEW_PRIVS_STATUS: c_int = 20;

/// Check the `no_new_privs` mode of the specified process.
///
/// # References
///  - [Linux: `prctl(PR_GET_NO_NEW_PRIVS,...)`]
///  - [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_STATUS,...)`]
///
/// [Linux: `prctl(PR_GET_NO_NEW_PRIVS,...)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
/// [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_STATUS,...)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
#[inline]
pub fn no_new_privs(process: ProcSelector) -> io::Result<bool> {
    unsafe { procctl_get_optional::<c_int>(PROC_NO_NEW_PRIVS_STATUS, process) }
        .map(|x| x == PROC_NO_NEW_PRIVS_ENABLE)
}