net_util: add Tap::if_name_as_str

Signed-off-by: Philipp Schuster <philipp.schuster@cyberus-technology.de>
On-behalf-of: SAP philipp.schuster@sap.com
This commit is contained in:
Philipp Schuster 2025-06-27 14:09:15 +02:00 committed by Rob Bradford
parent b8be33dff7
commit a51998605a
2 changed files with 25 additions and 2 deletions

View file

@ -135,7 +135,7 @@ pub fn open_tap(
// same device.
tap = open_tap_rx_q_0(if_name, ip_addr, netmask, host_mac, mtu, num_rx_q, flags)?;
// Set the name of the tap device we open in subsequent iterations.
ifname = String::from_utf8(tap.get_if_name().to_vec()).unwrap();
ifname = tap.if_name_as_str().to_string();
} else {
tap = Tap::open_named(ifname.as_str(), num_rx_q, flags).map_err(Error::TapOpen)?;

View file

@ -481,10 +481,33 @@ impl Tap {
ifreq
}
pub fn get_if_name(&self) -> &[u8] {
/// Returns the raw bytes of the interface name, which may or may not be
/// valid UTF-8.
pub fn if_name_as_bytes(&self) -> &[u8] {
&self.if_name
}
/// Returns the interface name as a string, truncated at the first NUL byte
/// if present.
///
/// # Panic
/// Panics if the interface name is not encoded as valid UTF-8. This can
/// only be caused by unrecoverable internal errors as users and management
/// software are only allowed to specify interfaces names as Rust strings,
/// thus valid UTF-8. Also, self-generated interface names form CHV are
/// also always created from Rust strings, thus valid UTF-8.
pub fn if_name_as_str(&self) -> &str {
// All bytes until first NUL.
let nul_terminated = self
.if_name_as_bytes()
.split(|&b| b == 0)
.next()
.unwrap_or(&[]);
// Panicking here is fine, see function documentation.
std::str::from_utf8(nul_terminated).expect("Tap interface name should be valid UTF-8")
}
#[cfg(fuzzing)]
pub fn new_for_fuzzing(tap_file: File, if_name: Vec<u8>) -> Self {
Tap { tap_file, if_name }