subc-os 0.1.54

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
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
//! Process-group facts for recovery after a daemon no longer keeps its original
//! group leader as an unreaped child to reserve the group's numeric identity.
//!
//! These observations do not authorize a signal by themselves. Callers must
//! compare the group, owner and start time with their recorded container, and
//! repeat the observation immediately before signalling a process.

use std::io;

/// Kernel facts for one process. Linux exposes unreaped zombies; macOS may
/// instead report an exited process as gone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Identity {
    pub pid: u32,
    pub pgid: u32,
    /// The kernel session ID. A shared group number alone is not membership
    /// evidence for a recovered container.
    pub session_id: u32,
    /// Effective user ID, matching `ps -o uid=`.
    pub uid: u32,
    /// Linux clock ticks since boot; macOS microseconds since the Unix epoch.
    pub start_time: u64,
    pub exited: bool,
}

/// Inspect one PID. A process that disappears during inspection is `Ok(None)`.
pub fn inspect(pid: u32) -> io::Result<Option<Identity>> {
    if pid <= 1 || i32::try_from(pid).is_err() {
        return Ok(None);
    }
    #[cfg(target_os = "linux")]
    return inspect_linux(pid, |path| std::fs::read_to_string(path));
    #[cfg(target_os = "macos")]
    return inspect_macos(pid);
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "process-group inspection is unavailable",
    ))
}

/// Read a process's current session without treating permission errors as exit.
/// A successful zero is preserved: the session leader can be outside this PID
/// namespace. Absence and failed reads are distinct from that kernel value.
pub fn session_id(pid: u32) -> io::Result<Option<u32>> {
    let pid = i32::try_from(pid)
        .ok()
        .filter(|pid| *pid > 1)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid session-query PID"))?;
    // SAFETY: getsid only reads a kernel process identifier and takes no pointer.
    #[allow(unsafe_code)]
    let session = unsafe { libc::getsid(pid) };
    if session == -1 {
        let error = io::Error::last_os_error();
        return if gone(&error) { Ok(None) } else { Err(error) };
    }
    u32::try_from(session)
        .ok()
        .map(Some)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid kernel session ID"))
}

/// Read just the kernel process-group ID, without requiring image inspection.
/// A missing process is `Ok(None)`; this does not establish ownership or identity.
pub fn pgid(pid: u32) -> io::Result<Option<u32>> {
    let Some(pid) = i32::try_from(pid).ok().filter(|pid| *pid > 1) else {
        return Ok(None);
    };
    // SAFETY: getpgid takes a validated numeric PID and has no pointer arguments.
    #[allow(unsafe_code)]
    let group = unsafe { libc::getpgid(pid) };
    if group >= 0 {
        return Ok(Some(group as u32));
    }
    let error = io::Error::last_os_error();
    if gone(&error) {
        Ok(None)
    } else {
        Err(error)
    }
}

/// List candidate PIDs, not verified group members. Every PID needs inspection.
pub fn pids() -> io::Result<Vec<u32>> {
    #[cfg(target_os = "linux")]
    {
        let mut pids = Vec::new();
        for entry in std::fs::read_dir("/proc")? {
            let entry = match entry {
                Ok(entry) => entry,
                Err(error) if gone(&error) => continue,
                Err(error) => return Err(error),
            };
            if let Some(pid) = entry
                .file_name()
                .to_str()
                .and_then(|name| name.parse::<u32>().ok())
                .filter(|pid| *pid > 1)
            {
                pids.push(pid);
            }
        }
        Ok(pids)
    }
    #[cfg(target_os = "macos")]
    return pids_macos();
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "process listing is unavailable",
    ))
}

/// Return every process in `group`, or an error if a complete scan could not
/// be read. Callers use this as containment evidence, so a partial list is
/// never a successful empty result.
pub fn members(group: u32) -> io::Result<Vec<u32>> {
    if group <= 1 || i32::try_from(group).is_err() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "invalid process-group ID",
        ));
    }
    #[cfg(target_os = "linux")]
    let result = members_linux(group);
    #[cfg(target_os = "macos")]
    let result = list_pids_macos(PROC_PGRP_ONLY, group);
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let result = Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "process-group membership listing is unavailable",
    ));
    let mut members = result?;
    members.sort_unstable();
    Ok(members)
}

fn gone(error: &io::Error) -> bool {
    error.kind() == io::ErrorKind::NotFound || error.raw_os_error() == Some(libc::ESRCH)
}

#[cfg(target_os = "linux")]
fn members_linux(group: u32) -> io::Result<Vec<u32>> {
    let mut pids = Vec::new();
    for entry in std::fs::read_dir("/proc")? {
        let entry = entry?;
        if let Some(pid) = entry
            .file_name()
            .to_str()
            .and_then(|name| name.parse::<u32>().ok())
        {
            pids.push(pid);
        }
    }
    members_from_procfs(group, pids, |path| std::fs::read_to_string(path))
}

/// Read each listed process's `stat` and keep the members of `group`.
///
/// A process that exits after `/proc` was listed loses its entry before we
/// read it. It belongs to no group any more, so it is skipped: a reaped
/// process cannot be a member, and a zombie keeps its entry until it is
/// reaped. Any other read error fails the whole scan, because callers use an
/// empty result as proof that the group is empty.
#[cfg(target_os = "linux")]
fn members_from_procfs(
    group: u32,
    pids: impl IntoIterator<Item = u32>,
    read: impl Fn(&std::path::Path) -> io::Result<String>,
) -> io::Result<Vec<u32>> {
    let mut stats = Vec::new();
    for pid in pids {
        let path = std::path::PathBuf::from(format!("/proc/{pid}/stat"));
        match read(&path) {
            Ok(stat) => stats.push((pid, stat)),
            Err(error) if gone(&error) => {}
            Err(error) => {
                return Err(io::Error::new(
                    error.kind(),
                    format!(
                        "could not read {} for a complete process-group scan: {error}",
                        path.display()
                    ),
                ))
            }
        }
    }
    members_from_stats(group, stats)
}

#[cfg(target_os = "linux")]
fn members_from_stats(
    group: u32,
    stats: impl IntoIterator<Item = (u32, String)>,
) -> io::Result<Vec<u32>> {
    let mut members = Vec::new();
    for (pid, stat) in stats {
        let (_, fields) = stat.rsplit_once(") ").ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid /proc/{pid}/stat in process-group scan"),
            )
        })?;
        let fields: Vec<_> = fields.split_whitespace().collect();
        let member_group = fields
            .get(2)
            .and_then(|field| field.parse::<u32>().ok())
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("invalid /proc/{pid}/stat process-group field"),
                )
            })?;
        if member_group == group {
            members.push(pid);
        }
    }
    Ok(members)
}

#[cfg(target_os = "linux")]
fn inspect_linux(
    pid: u32,
    mut read: impl FnMut(&std::path::Path) -> io::Result<String>,
) -> io::Result<Option<Identity>> {
    let root = std::path::PathBuf::from(format!("/proc/{pid}"));
    let sample = || {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "invalid procfs process identity",
        )
    };
    let mut read_existing = |name: &str| match read(&root.join(name)) {
        Ok(text) => Ok(Some(text)),
        Err(error) if gone(&error) => Ok(None),
        Err(error) => Err(error),
    };
    let Some(stat) = read_existing("stat")? else {
        return Ok(None);
    };
    let parse_stat = |stat: &str| -> Option<(u32, u32, u64, bool)> {
        let (_, fields) = stat.rsplit_once(") ")?;
        let fields: Vec<_> = fields.split_whitespace().collect();
        Some((
            fields.get(2)?.parse().ok()?,
            fields.get(3)?.parse().ok()?,
            fields.get(19)?.parse().ok()?,
            matches!(*fields.first()?, "Z" | "X"),
        ))
    };
    let Some((pgid, session_id, start_time, exited)) = parse_stat(&stat) else {
        return Err(sample());
    };
    let Some(status) = read_existing("status")? else {
        return Ok(None);
    };
    let uid = status
        .lines()
        .find_map(|line| {
            line.strip_prefix("Uid:")
                .and_then(|value| value.split_whitespace().nth(1))
        })
        .and_then(|value| value.parse::<u32>().ok())
        .ok_or_else(sample)?;
    let Some(after) = read_existing("stat")? else {
        return Ok(None);
    };
    let Some((after_pgid, after_session, after_start, after_exited)) = parse_stat(&after) else {
        return Err(sample());
    };
    if (pgid, session_id, start_time) != (after_pgid, after_session, after_start) {
        // Do not combine one process's ownership with another process's group.
        return Ok(None);
    }
    Ok(Some(Identity {
        pid,
        pgid,
        session_id,
        uid,
        start_time,
        exited: exited || after_exited,
    }))
}

#[cfg(target_os = "macos")]
fn inspect_macos(pid: u32) -> io::Result<Option<Identity>> {
    // Darwin's SZOMB process state: exited but not yet reaped.
    const SZOMB: u32 = 5;
    // SAFETY: libc's C output structure is correctly sized and aligned; its
    // integer fields admit zero, and proc_pidinfo writes at most that size.
    #[allow(unsafe_code)]
    let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
    let size = i32::try_from(std::mem::size_of_val(&info)).expect("proc_bsdinfo fits c_int");
    // SAFETY: the writable buffer has exactly `size` bytes. No pointer escapes.
    #[allow(unsafe_code)]
    let read = unsafe {
        libc::proc_pidinfo(
            pid as i32,
            libc::PROC_PIDTBSDINFO,
            0,
            (&mut info as *mut libc::proc_bsdinfo).cast(),
            size,
        )
    };
    if read <= 0 {
        let error = io::Error::last_os_error();
        return if gone(&error) { Ok(None) } else { Err(error) };
    }
    if read != size || info.pbi_pid != pid {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "incomplete proc_bsdinfo identity",
        ));
    }
    let start_time = info
        .pbi_start_tvsec
        .checked_mul(1_000_000)
        .and_then(|seconds| seconds.checked_add(info.pbi_start_tvusec))
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid process birth time"))?;
    Ok(Some(Identity {
        pid,
        pgid: info.pbi_pgid,
        session_id: match session_id(pid)? {
            Some(session) => session,
            None => return Ok(None),
        },
        uid: info.pbi_uid,
        start_time,
        exited: info.pbi_status == SZOMB,
    }))
}

// libproc.h's selectors are not exported by the libc crate.
#[cfg(target_os = "macos")]
const PROC_ALL_PIDS: u32 = 1;
#[cfg(target_os = "macos")]
const PROC_PGRP_ONLY: u32 = 2;

#[cfg(target_os = "macos")]
fn list_pids_macos(selector: u32, value: u32) -> io::Result<Vec<u32>> {
    // SAFETY: a null, zero-sized output buffer asks libproc for its size only.
    #[allow(unsafe_code)]
    let needed = unsafe { libc::proc_listpids(selector, value, std::ptr::null_mut(), 0) };
    if needed < 0 {
        return Err(io::Error::last_os_error());
    }
    if needed == 0 {
        return Ok(Vec::new());
    }
    let mut count = needed as usize / std::mem::size_of::<libc::pid_t>() + 64;
    for _ in 0..4 {
        let mut pids = vec![0 as libc::pid_t; count];
        let size = i32::try_from(std::mem::size_of_val(pids.as_slice()))
            .map_err(|_| io::Error::other("process list exceeds libproc's buffer limit"))?;
        // SAFETY: the allocation is aligned for pid_t and has `size` bytes.
        #[allow(unsafe_code)]
        let read = unsafe { libc::proc_listpids(selector, value, pids.as_mut_ptr().cast(), size) };
        if read < 0 {
            return Err(io::Error::last_os_error());
        }
        if read == 0 {
            return Ok(Vec::new());
        }
        if read < size {
            pids.truncate(read as usize / std::mem::size_of::<libc::pid_t>());
            return Ok(pids
                .into_iter()
                .filter_map(|pid| u32::try_from(pid).ok())
                .filter(|pid| *pid > 0)
                .collect());
        }
        count *= 2;
    }
    Err(io::Error::new(
        io::ErrorKind::WouldBlock,
        "process list kept growing during inspection",
    ))
}

#[cfg(target_os = "macos")]
fn pids_macos() -> io::Result<Vec<u32>> {
    Ok(list_pids_macos(PROC_ALL_PIDS, 0)?
        .into_iter()
        .filter(|pid| *pid > 1)
        .collect())
}

#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
    use super::*;
    use std::os::unix::process::CommandExt;
    use std::process::Command;

    fn ps_birth_seconds(parts: &[&str]) -> u64 {
        let months = [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        ];
        let clock: Vec<i32> = parts[3].split(':').map(|n| n.parse().unwrap()).collect();
        // SAFETY: tm is an integer/pointer C structure with a valid zero value.
        #[allow(unsafe_code)]
        let mut birth: libc::tm = unsafe { std::mem::zeroed() };
        birth.tm_mon = months.iter().position(|month| *month == parts[1]).unwrap() as i32;
        birth.tm_mday = parts[2].parse().unwrap();
        birth.tm_year = parts[4].parse::<i32>().unwrap() - 1900;
        birth.tm_hour = clock[0];
        birth.tm_min = clock[1];
        birth.tm_sec = clock[2];
        // SAFETY: timegm receives one fully initialized, writable tm and does
        // not retain its address. UTC avoids changing the test process's TZ.
        #[allow(unsafe_code)]
        u64::try_from(unsafe { libc::timegm(&mut birth) }).unwrap()
    }

    fn assert_matches_ps(pid: u32) {
        let facts = inspect(pid).unwrap().expect("our process is still alive");
        // SAFETY: the test reads the session of its own process or owned child.
        #[allow(unsafe_code)]
        let expected_session = u32::try_from(unsafe { libc::getsid(pid as i32) }).unwrap();
        assert_eq!(facts.session_id, expected_session, "inspection session");
        assert_eq!(
            session_id(pid).unwrap(),
            Some(expected_session),
            "fresh kernel session query"
        );
        let output = Command::new("ps")
            .env("LC_ALL", "C")
            .env("TZ", "UTC0")
            .args(["-p", &pid.to_string(), "-o", "uid=,pgid=,lstart="])
            .output()
            .unwrap();
        assert!(output.status.success(), "ps: {:?}", output);
        let text = String::from_utf8(output.stdout).unwrap();
        let fields: Vec<_> = text.split_whitespace().collect();
        assert_eq!(fields.len(), 7, "ps identity: {text}");
        assert_eq!(facts.pid, pid);
        assert_eq!(facts.uid, fields[0].parse::<u32>().unwrap(), "owner");
        assert_eq!(facts.pgid, fields[1].parse::<u32>().unwrap(), "group");
        assert_eq!(
            pgid(pid).unwrap(),
            Some(fields[1].parse::<u32>().unwrap()),
            "group-only query"
        );
        #[cfg(target_os = "macos")]
        let birth = facts.start_time / 1_000_000;
        #[cfg(target_os = "linux")]
        let birth = {
            let boot = std::fs::read_to_string("/proc/stat")
                .unwrap()
                .lines()
                .find_map(|line| {
                    line.strip_prefix("btime ")
                        .and_then(|n| n.parse::<u64>().ok())
                })
                .unwrap();
            // SAFETY: sysconf takes a constant selector, with no pointers.
            #[allow(unsafe_code)]
            let ticks = u64::try_from(unsafe { libc::sysconf(libc::_SC_CLK_TCK) }).unwrap();
            boot + facts.start_time / ticks
        };
        assert_eq!(
            birth,
            ps_birth_seconds(&fields[2..]),
            "birth time: {facts:?} vs {text}"
        );
        assert!(!facts.exited);
        assert!(
            pids().unwrap().contains(&pid),
            "PID enumeration includes our process"
        );
    }

    #[test]
    fn process_group_facts_match_ps_for_self_and_owned_child() {
        let mut child = Command::new("sleep")
            .arg("2")
            .process_group(0)
            .spawn()
            .unwrap();
        assert_matches_ps(std::process::id());
        assert_matches_ps(child.id());
        assert!(child.wait().unwrap().success());
        assert_eq!(inspect(child.id()).unwrap(), None);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn group_scan_rejects_a_malformed_entry_instead_of_returning_a_partial_list() {
        let stats = [
            (42, "42 (leader) S 1 42".to_owned()),
            (99, "not a procfs stat".to_owned()),
        ];
        assert_eq!(
            members_from_stats(42, stats).unwrap_err().kind(),
            io::ErrorKind::InvalidData
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn group_scan_skips_a_process_that_exits_mid_scan_and_fails_on_other_errors() {
        let read = |path: &std::path::Path| match path.to_str().unwrap() {
            "/proc/42/stat" => Ok("42 (leader) S 1 42".to_owned()),
            "/proc/43/stat" => Err(io::Error::from(io::ErrorKind::NotFound)),
            _ => Err(io::Error::from(io::ErrorKind::PermissionDenied)),
        };
        assert_eq!(members_from_procfs(42, [42, 43], read).unwrap(), [42]);
        assert_eq!(
            members_from_procfs(42, [42, 43, 44], read)
                .unwrap_err()
                .kind(),
            io::ErrorKind::PermissionDenied
        );
    }

    #[test]
    fn process_group_members_include_the_owned_group_leader() {
        let mut child = Command::new("sleep")
            .arg("2")
            .process_group(0)
            .spawn()
            .unwrap();
        assert_eq!(members(child.id()).unwrap(), [child.id()]);
        assert!(child.wait().unwrap().success());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn process_group_exit_between_procfs_reads_is_gone() {
        let mut child = Command::new("sleep").arg("1").spawn().unwrap();
        let pid = child.id();
        let result = inspect_linux(pid, |path| {
            if path.file_name().unwrap() == "status" {
                assert!(child.wait().unwrap().success());
            }
            std::fs::read_to_string(path)
        });
        assert!(child.wait().unwrap().success());
        assert_eq!(result.unwrap(), None);
    }
}