From a51998605a3d003a59366e0203b1735d533b5521 Mon Sep 17 00:00:00 2001 From: Philipp Schuster Date: Fri, 27 Jun 2025 14:09:15 +0200 Subject: [PATCH] net_util: add Tap::if_name_as_str Signed-off-by: Philipp Schuster On-behalf-of: SAP philipp.schuster@sap.com --- net_util/src/open_tap.rs | 2 +- net_util/src/tap.rs | 25 ++++++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/net_util/src/open_tap.rs b/net_util/src/open_tap.rs index e02e3b5e8..21c48f839 100644 --- a/net_util/src/open_tap.rs +++ b/net_util/src/open_tap.rs @@ -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)?; diff --git a/net_util/src/tap.rs b/net_util/src/tap.rs index bc841de11..6d90293b8 100644 --- a/net_util/src/tap.rs +++ b/net_util/src/tap.rs @@ -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) -> Self { Tap { tap_file, if_name }