1#[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
19pub const RMNET_PREFIX: &str = "rmnet_data";
21
22pub const DEBUGFS: &str = "/sys/kernel/debug";
24
25const COMM_LEN: usize = 15;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct InterfaceAddress {
31 pub interface: String,
33 pub address: Ipv4Addr,
35}
36
37#[derive(Clone, Copy, Debug)]
39pub struct Addresses<'a>(pub &'a [InterfaceAddress]);
40
41#[derive(Debug, thiserror::Error)]
43pub enum CommandError {
44 #[error("failed to run {command}")]
46 Spawn {
47 command: &'static str,
49 #[source]
51 source: io::Error,
52 },
53 #[error("{command} did not finish within {} s", timeout.as_secs())]
55 Timeout {
56 command: &'static str,
58 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
75pub 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
93pub 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
108pub 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
119pub 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#[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#[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
151pub 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
180pub 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#[must_use]
201pub fn exists(path: &str) -> bool {
202 Path::new(path).exists()
203}
204
205fn 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 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}