Skip to main content

tuwunel_core/utils/
sys.rs

1//! Operating-system resource and platform-integration utilities.
2//!
3//! Submodules expose compute, resource-limit, storage, and usage information.
4//! Top-level helpers normalize executable paths, parse device metadata, and
5//! classify socket file descriptors on Unix.
6
7pub mod compute;
8
9pub mod limits;
10
11pub mod storage;
12
13pub mod usage;
14
15#[cfg(all(test, any(unix, windows)))]
16mod tests;
17
18#[cfg(unix)]
19use std::os::fd::AsFd;
20use std::{env::vars_os, path::PathBuf, process::Command};
21
22#[cfg(unix)]
23use nix::{
24	errno::Errno,
25	sys::socket::{getsockopt, sockopt::Ipv6V6Only},
26};
27
28pub use self::{
29	compute::available_parallelism,
30	limits::*,
31	usage::{Usage, statm, thread_usage, usage},
32};
33use crate::{Result, at};
34
35/// Removes inherited environment names matching any supplied prefix from a command.
36///
37/// Names are trimmed before ASCII-case-insensitive prefix matching. Other
38/// environment variables and command settings are retained.
39#[must_use]
40pub fn command_without_env_prefixes(command: Command, prefixes: &[&str]) -> Command {
41	vars_os()
42		.map(|(name, _)| name)
43		.filter(|name| {
44			let name = name.to_string_lossy();
45			let name = name.trim();
46
47			prefixes.iter().any(|prefix| {
48				name.get(..prefix.len())
49					.is_some_and(|head| head.eq_ignore_ascii_case(prefix))
50			})
51		})
52		.fold(command, |mut command, name| {
53			command.env_remove(name);
54			command
55		})
56}
57
58/// Returns the current executable path without a trailing deletion marker.
59///
60/// The literal ` (deleted)` suffix is removed when the path is valid UTF-8.
61/// Other paths remain unchanged, and executable lookup errors are propagated.
62pub fn current_exe() -> Result<PathBuf> {
63	let exe = std::env::current_exe()?;
64	match exe.to_str() {
65		| None => Ok(exe),
66		| Some(str) => Ok(str
67			.strip_suffix(" (deleted)")
68			.map(PathBuf::from)
69			.unwrap_or(exe)),
70	}
71}
72
73/// Reports whether the current executable path carries a deletion marker.
74///
75/// A trailing ` (deleted)` suffix can indicate that the executable was removed
76/// or replaced. Lookup failures and non-UTF-8 paths return `false`.
77#[must_use]
78pub fn current_exe_deleted() -> bool {
79	std::env::current_exe().is_ok_and(|exe| {
80		exe.to_str()
81			.is_some_and(|exe| exe.ends_with(" (deleted)"))
82	})
83}
84
85/// Searches newline-delimited `KEY=VALUE` text for a key.
86///
87/// Lines without `=` are ignored, and the first exact key match is returned.
88/// The borrowed value contains everything after the first `=`, including any
89/// additional separators.
90#[inline]
91#[must_use]
92pub fn uevent_find<'a>(uevent: &'a str, key: &'a str) -> Option<&'a str> {
93	uevent
94		.lines()
95		.filter_map(|line| line.split_once('='))
96		.find(|&(key_, _)| key.eq(key_))
97		.map(at!(1))
98}
99
100/// Classifies the socket address families recognized by the server.
101///
102/// IPv4 and IPv6 addresses share the Internet variant, while Unix-domain
103/// addresses use the local variant. Other address families are rejected by
104/// [`get_socket_family`].
105#[cfg(unix)]
106#[derive(Clone, Copy, Debug)]
107pub enum SocketFamily {
108	/// An IPv4 or IPv6 Internet socket.
109	///
110	/// Both Internet address families map to this variant.
111	Inet,
112
113	/// A Unix-domain socket.
114	///
115	/// Every recognized local socket address maps to this variant.
116	Unix,
117}
118
119/// Determines the address family of an open socket file descriptor on Unix.
120///
121/// IPv4 and IPv6 descriptors return [`SocketFamily::Inet`], and Unix-domain
122/// descriptors return [`SocketFamily::Unix`]. Socket inspection failures,
123/// missing families, and unsupported families are returned as errors.
124#[cfg(unix)]
125pub fn get_socket_family(fd: i32) -> Result<SocketFamily> {
126	use nix::sys::socket::{AddressFamily, SockaddrLike, SockaddrStorage};
127
128	use crate::{Err, err};
129
130	let sockname: SockaddrStorage = nix::sys::socket::getsockname(fd)?;
131
132	let family = sockname
133		.family()
134		.ok_or_else(|| err!("Invalid socket"))?;
135
136	match family {
137		| AddressFamily::Inet | AddressFamily::Inet6 => Ok(SocketFamily::Inet),
138		| AddressFamily::Unix => Ok(SocketFamily::Unix),
139		| _ => Err!("Unknown socket family: {family:?}"),
140	}
141}
142
143/// Whether an IPv6 socket serves IPv6 traffic alone.
144///
145/// A dual-stack socket answers on the IPv4-mapped range too, so an unspecified
146/// address of one binds both families. The option does not exist on other
147/// families, which are reported as unrestricted.
148#[cfg(unix)]
149pub fn is_ipv6_only<F: AsFd>(socket: &F) -> Result<bool> {
150	getsockopt(socket, Ipv6V6Only).or_else(|e| match e {
151		| Errno::ENOPROTOOPT => Ok(false),
152		| _ => Err(e.into()),
153	})
154}