From 67fbf2b2ee8a67d8cdafc0c36d87d5d8f4782665 Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Thu, 7 Jul 2022 11:45:26 +0200 Subject: [PATCH] sys: make escape_unit() more flexible, add unescape_unit_path This adds the ability to use these functions with non-utf8 strings as well. Signed-off-by: Wolfgang Bumiller --- proxmox-sys/src/systemd.rs | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/proxmox-sys/src/systemd.rs b/proxmox-sys/src/systemd.rs index 4575a204..6fa459e4 100644 --- a/proxmox-sys/src/systemd.rs +++ b/proxmox-sys/src/systemd.rs @@ -1,3 +1,7 @@ +use std::ffi::OsString; +use std::os::unix::ffi::OsStringExt; +use std::path::PathBuf; + use anyhow::{bail, Error}; #[allow(clippy::manual_range_contains)] @@ -16,16 +20,21 @@ fn parse_hex_digit(d: u8) -> Result { } /// Escape strings for usage in systemd unit names -pub fn escape_unit(mut unit: &str, is_path: bool) -> String { +pub fn escape_unit>(unit: P, is_path: bool) -> String { + escape_unit_bytes(unit.as_ref(), is_path) +} + +fn escape_unit_bytes(mut unit: &[u8], is_path: bool) -> String { if is_path { - unit = unit.trim_matches('/'); + while !unit.is_empty() && unit[0] == b'/' { + unit = &unit[1..]; + } + if unit.is_empty() { return String::from("-"); } } - let unit = unit.as_bytes(); - let mut escaped = String::new(); for (i, c) in unit.iter().enumerate() { @@ -50,6 +59,16 @@ pub fn escape_unit(mut unit: &str, is_path: bool) -> String { /// Unescape strings used in systemd unit names pub fn unescape_unit(text: &str) -> Result { + Ok(String::from_utf8(unescape_unit_do(text)?)?) +} + +/// Unescape strings used in systemd unit names +pub fn unescape_unit_path(text: &str) -> Result { + Ok(OsString::from_vec(unescape_unit_do(text)?).into()) +} + +/// Unescape strings used in systemd unit names +fn unescape_unit_do(text: &str) -> Result, Error> { let mut i = text.as_bytes(); let mut data: Vec = Vec::new(); @@ -79,7 +98,5 @@ pub fn unescape_unit(text: &str) -> Result { } } - let text = String::from_utf8(data)?; - - Ok(text) + Ok(data) }