Skip to main content

device_tests/
system.rs

1//! Reads the state of the system: interface addresses, processes and mounts.
2
3#[cfg(test)]
4mod tests;
5
6use core::fmt;
7use std::net::Ipv4Addr;
8use std::path::Path;
9use std::process::{ExitStatus, Output, Stdio};
10use std::time::Duration;
11use std::{fs, io};
12
13use nix::ifaddrs;
14use nix::sys::socket::SockaddrIn;
15use nix::unistd::Pid;
16use tokio::process::Command;
17use tokio::time;
18
19/// Interfaces of data calls.
20pub const RMNET_PREFIX: &str = "rmnet_data";
21
22/// Mount point of debugfs.
23pub const DEBUGFS: &str = "/sys/kernel/debug";
24
25/// The kernel truncates `/proc/<pid>/comm` to this many bytes.
26const COMM_LEN: usize = 15;
27
28/// An IPv4 address of an interface.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct InterfaceAddress {
31    /// Name of the interface.
32    pub interface: String,
33    /// The address.
34    pub address: Ipv4Addr,
35}
36
37/// Formats interface addresses as `rmnet_data0 has 10.0.0.1, ...`.
38#[derive(Clone, Copy, Debug)]
39pub struct Addresses<'a>(pub &'a [InterfaceAddress]);
40
41/// Error of [`run`].
42#[derive(Debug, thiserror::Error)]
43pub enum CommandError {
44    /// The command failed to start or its output failed to read.
45    #[error("failed to run {command}")]
46    Spawn {
47        /// The program.
48        command: &'static str,
49        /// Underlying error.
50        #[source]
51        source: io::Error,
52    },
53    /// The command ran too long and was killed.
54    #[error("{command} did not finish within {} s", timeout.as_secs())]
55    Timeout {
56        /// The program.
57        command: &'static str,
58        /// How long it could run.
59        timeout: Duration,
60    },
61}
62
63impl fmt::Display for Addresses<'_> {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        for (index, entry) in self.0.iter().enumerate() {
66            if index > 0 {
67                f.write_str(", ")?;
68            }
69            write!(f, "{} has {}", entry.interface, entry.address)?;
70        }
71        Ok(())
72    }
73}
74
75/// Returns the IPv4 addresses of interfaces whose name starts with `prefix`.
76///
77/// # Errors
78///
79/// Returns an error if the interface addresses can't be read.
80pub fn ipv4_addresses(prefix: &str) -> Result<Vec<InterfaceAddress>, nix::Error> {
81    Ok(ifaddrs::getifaddrs()?
82        .filter(|entry| entry.interface_name.starts_with(prefix))
83        .filter_map(|entry| {
84            let address = entry.address?.as_sockaddr_in()?.ip();
85            Some(InterfaceAddress {
86                interface: entry.interface_name,
87                address,
88            })
89        })
90        .collect())
91}
92
93/// Returns whether `interface` has an IPv4 address that matches `wanted`.
94///
95/// # Errors
96///
97/// Returns an error if the interface addresses can't be read.
98pub fn has_ipv4<F: Fn(Ipv4Addr) -> bool>(interface: &str, wanted: F) -> Result<bool, nix::Error> {
99    Ok(ifaddrs::getifaddrs()?.any(|entry| {
100        entry.interface_name == interface
101            && entry
102                .address
103                .and_then(|address| address.as_sockaddr_in().map(SockaddrIn::ip))
104                .is_some_and(&wanted)
105    }))
106}
107
108/// Returns the names of all running processes from `/proc/<pid>/comm`.
109///
110/// # Errors
111///
112/// Returns an error if `/proc` can't be read.
113pub fn process_names() -> io::Result<Vec<String>> {
114    let mut names = Vec::new();
115    for_each_process(|_pid, comm| names.push(comm))?;
116    Ok(names)
117}
118
119/// Returns the PIDs of the processes of the program `name`.
120///
121/// # Errors
122///
123/// Returns an error if `/proc` can't be read.
124pub fn pids(name: &str) -> io::Result<Vec<Pid>> {
125    let mut pids = Vec::new();
126    for_each_process(|pid, comm| {
127        if comm_matches(&comm, name) {
128            pids.push(pid);
129        }
130    })?;
131    Ok(pids)
132}
133
134/// Returns whether a `comm` value belongs to the program `name`.
135#[must_use]
136pub fn comm_matches(comm: &str, name: &str) -> bool {
137    let truncated = name.get(..COMM_LEN.min(name.len())).unwrap_or(name);
138    comm == truncated
139}
140
141/// Returns whether `mounts` (the content of `/proc/mounts`) has a file system
142/// of `kind` at `target`.
143#[must_use]
144pub fn is_mounted(mounts: &str, target: &str, kind: &str) -> bool {
145    mounts.lines().any(|line| {
146        let mut fields = line.split_whitespace().skip(1);
147        fields.next() == Some(target) && fields.next() == Some(kind)
148    })
149}
150
151/// Runs a command with stdin, stdout and stderr connected to `/dev/null` and
152/// returns its exit status.
153///
154/// Use it for init scripts. A daemon that a script starts inherits the
155/// output pipes of [`run`], which then never sees them close.
156///
157/// # Errors
158///
159/// Returns an error if the command can't start or runs longer than
160/// `timeout`.
161pub async fn run_detached(
162    command: &'static str,
163    args: &[&str],
164    timeout: Duration,
165) -> Result<ExitStatus, CommandError> {
166    let status = Command::new(command)
167        .args(args)
168        .stdin(Stdio::null())
169        .stdout(Stdio::null())
170        .stderr(Stdio::null())
171        .kill_on_drop(true)
172        .status();
173    match time::timeout(timeout, status).await {
174        Ok(Ok(status)) => Ok(status),
175        Ok(Err(source)) => Err(CommandError::Spawn { command, source }),
176        Err(_elapsed) => Err(CommandError::Timeout { command, timeout }),
177    }
178}
179
180/// Runs a command and collects its output.
181///
182/// # Errors
183///
184/// Returns an error if the command can't start or runs longer than
185/// `timeout`.
186pub async fn run(
187    command: &'static str,
188    args: &[&str],
189    timeout: Duration,
190) -> Result<Output, CommandError> {
191    let output = Command::new(command).args(args).kill_on_drop(true).output();
192    match time::timeout(timeout, output).await {
193        Ok(Ok(output)) => Ok(output),
194        Ok(Err(source)) => Err(CommandError::Spawn { command, source }),
195        Err(_elapsed) => Err(CommandError::Timeout { command, timeout }),
196    }
197}
198
199/// Returns whether a path exists.
200#[must_use]
201pub fn exists(path: &str) -> bool {
202    Path::new(path).exists()
203}
204
205/// Calls `f` with the PID and the `comm` value of every running process.
206fn for_each_process<F: FnMut(Pid, String)>(mut f: F) -> io::Result<()> {
207    for entry in fs::read_dir("/proc")? {
208        let path = entry?.path();
209        let Some(pid) = path
210            .file_name()
211            .and_then(|name| name.to_str())
212            .filter(|name| name.bytes().all(|byte| byte.is_ascii_digit()))
213            .and_then(|name| name.parse().ok())
214        else {
215            continue;
216        };
217        // The process can exit while the directory is read.
218        if let Ok(mut comm) = fs::read_to_string(path.join("comm")) {
219            comm.truncate(comm.trim_end().len());
220            f(Pid::from_raw(pid), comm);
221        }
222    }
223    Ok(())
224}