1use std::str::FromStr;
9
10use crate::error::{SmbError, SmbResult};
11
12#[derive(Debug, Clone, PartialEq, Eq, Default)]
23pub struct SmbPath {
24 components: Vec<String>,
25}
26
27impl SmbPath {
28 pub fn root() -> Self {
30 Self::default()
31 }
32
33 pub fn from_utf16(units: &[u16]) -> SmbResult<Self> {
36 let s = decode_utf16_strict(units)?;
37 s.parse()
38 }
39
40 fn parse_components(s: &str) -> SmbResult<Self> {
41 let trimmed = s
43 .strip_prefix('\\')
44 .or_else(|| s.strip_prefix('/'))
45 .unwrap_or(s);
46 if trimmed.is_empty() {
47 return Ok(Self::root());
48 }
49 if trimmed.encode_utf16().count() > MAX_PATH_UNITS {
50 return Err(SmbError::NameInvalid);
51 }
52
53 if trimmed.chars().any(|c| is_control(c) || is_forbidden(c)) {
56 return Err(SmbError::NameInvalid);
57 }
58
59 let mut components = Vec::new();
61 for raw in trimmed.split(['\\', '/']) {
62 if raw.is_empty() {
63 return Err(SmbError::NameInvalid);
65 }
66 if raw == "." {
67 continue;
68 }
69 if raw == ".." {
70 return Err(SmbError::NameInvalid);
71 }
72 if raw.encode_utf16().count() > MAX_COMPONENT_UNITS || host_reserved_name(raw) {
74 return Err(SmbError::NameInvalid);
75 }
76 components.push(raw.to_string());
77 }
78 Ok(Self { components })
79 }
80
81 pub fn components(&self) -> &[String] {
83 &self.components
84 }
85
86 pub fn is_root(&self) -> bool {
88 self.components.is_empty()
89 }
90
91 pub fn parent(&self) -> Option<SmbPath> {
93 if self.is_root() {
94 return None;
95 }
96 let mut parent = self.components.clone();
97 parent.pop();
98 Some(SmbPath { components: parent })
99 }
100
101 pub fn file_name(&self) -> Option<&str> {
103 self.components.last().map(|s| s.as_str())
104 }
105
106 pub fn join(&self, last: &str) -> SmbResult<SmbPath> {
108 let extra = last.parse::<SmbPath>()?;
111 let mut out = self.clone();
112 out.components.extend(extra.components);
113 Ok(out)
114 }
115
116 pub fn display_backslash(&self) -> String {
118 self.components.join("\\")
119 }
120}
121
122pub(crate) fn same_path(a: &SmbPath, b: &SmbPath, case_sensitive: bool) -> bool {
125 a.components().len() == b.components().len() && starts_with(a, b, case_sensitive)
126}
127
128pub(crate) fn rebase(
132 path: &SmbPath,
133 from: &SmbPath,
134 to: &SmbPath,
135 case_sensitive: bool,
136) -> Option<SmbPath> {
137 if !starts_with(path, from, case_sensitive) {
138 return None;
139 }
140 let mut components = to.components.clone();
141 components.extend_from_slice(&path.components[from.components.len()..]);
142 Some(SmbPath { components })
143}
144
145fn starts_with(path: &SmbPath, prefix: &SmbPath, case_sensitive: bool) -> bool {
146 path.components.len() >= prefix.components.len()
147 && path
148 .components
149 .iter()
150 .zip(&prefix.components)
151 .all(|(x, y)| {
152 if case_sensitive {
153 x == y
154 } else {
155 x.to_lowercase() == y.to_lowercase()
156 }
157 })
158}
159
160impl FromStr for SmbPath {
161 type Err = SmbError;
162
163 fn from_str(s: &str) -> Result<Self, Self::Err> {
164 Self::parse_components(s)
165 }
166}
167
168impl std::fmt::Display for SmbPath {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 if self.is_root() {
171 f.write_str("\\")
172 } else {
173 f.write_str(&self.display_backslash())
174 }
175 }
176}
177
178const MAX_COMPONENT_UNITS: usize = 255;
180
181const MAX_PATH_UNITS: usize = 32_760;
183
184#[cfg_attr(
187 not(feature = "localfs"),
188 allow(dead_code, reason = "used by LocalFsBackend")
189)]
190pub(crate) fn is_valid_component(name: &str) -> bool {
191 !name.is_empty()
192 && name != "."
193 && name != ".."
194 && name.encode_utf16().count() <= MAX_COMPONENT_UNITS
195 && !name
196 .chars()
197 .any(|c| is_control(c) || is_forbidden(c) || matches!(c, '\\' | '/'))
198 && !host_reserved_name(name)
199}
200
201pub(crate) fn is_valid_pattern(pattern: &str) -> bool {
205 !pattern.is_empty()
206 && pattern.encode_utf16().count() <= MAX_COMPONENT_UNITS
207 && !pattern
208 .chars()
209 .any(|c| is_control(c) || matches!(c, ':' | '|' | '\\' | '/'))
210}
211
212fn is_control(c: char) -> bool {
213 ('\u{0000}'..='\u{001F}').contains(&c)
214}
215
216fn is_forbidden(c: char) -> bool {
217 matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*')
218}
219
220fn host_reserved_name(name: &str) -> bool {
223 cfg!(windows) && is_reserved_dos_name(name)
224}
225
226fn is_reserved_dos_name(s: &str) -> bool {
227 let stem = match s.rsplit_once('.') {
229 Some((stem, _)) => stem,
230 None => s,
231 };
232 let upper = stem.to_ascii_uppercase();
233 matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL") || matches_com_or_lpt(&upper)
234}
235
236fn matches_com_or_lpt(s: &str) -> bool {
237 if s.len() != 4 {
238 return false;
239 }
240 let bytes = s.as_bytes();
241 let prefix = &bytes[..3];
242 let last = bytes[3] as char;
243 if !matches!(last, '1'..='9') {
244 return false;
245 }
246 prefix == b"COM" || prefix == b"LPT"
247}
248
249fn decode_utf16_strict(units: &[u16]) -> SmbResult<String> {
250 String::from_utf16(units).map_err(|_| SmbError::NameInvalid)
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 fn utf16(s: &str) -> Vec<u16> {
260 s.encode_utf16().collect()
261 }
262
263 fn p(s: &str) -> SmbPath {
264 s.parse().unwrap()
265 }
266
267 #[test]
268 fn root_paths() {
269 assert!("".parse::<SmbPath>().unwrap().is_root());
270 assert!("\\".parse::<SmbPath>().unwrap().is_root());
271 assert!("/".parse::<SmbPath>().unwrap().is_root());
272 assert!(SmbPath::from_utf16(&utf16("")).unwrap().is_root());
273 }
274
275 #[test]
276 fn simple_paths_split() {
277 let p = "dir\\sub\\file.txt".parse::<SmbPath>().unwrap();
278 assert_eq!(p.components(), &["dir", "sub", "file.txt"]);
279 assert_eq!(p.display_backslash(), "dir\\sub\\file.txt");
280 assert!(!p.is_root());
281 assert_eq!(p.file_name(), Some("file.txt"));
282 }
283
284 #[test]
285 fn forward_slash_accepted() {
286 let p = "a/b/c".parse::<SmbPath>().unwrap();
287 assert_eq!(p.components(), &["a", "b", "c"]);
288 }
289
290 #[test]
291 fn dot_components_skipped() {
292 let p = "a\\.\\b".parse::<SmbPath>().unwrap();
293 assert_eq!(p.components(), &["a", "b"]);
294 }
295
296 #[test]
297 fn parent_returns_one_component_less() {
298 let p = "a\\b\\c".parse::<SmbPath>().unwrap();
299 let parent = p.parent().unwrap();
300 assert_eq!(parent.components(), &["a", "b"]);
301 let grand = parent.parent().unwrap();
302 assert_eq!(grand.components(), &["a"]);
303 let root = grand.parent().unwrap();
304 assert!(root.is_root());
305 assert!(root.parent().is_none());
306 }
307
308 #[test]
309 fn join_appends_component() {
310 let p = "a".parse::<SmbPath>().unwrap();
311 let q = p.join("b").unwrap();
312 assert_eq!(q.components(), &["a", "b"]);
313 }
314
315 #[test]
316 fn rejects_double_dot() {
317 assert!("a\\..\\b".parse::<SmbPath>().is_err());
318 assert!("..".parse::<SmbPath>().is_err());
319 }
320
321 #[test]
322 fn rejects_double_separator() {
323 assert!("a\\\\b".parse::<SmbPath>().is_err());
324 }
325
326 #[test]
327 fn rejects_forbidden_chars() {
328 for bad in ["a<b", "a>b", "a:b", "a\"b", "a|b", "a?b", "a*b"] {
329 assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
330 }
331 }
332
333 #[test]
334 fn rejects_control_chars() {
335 let s = format!("a{}b", '\u{0001}');
336 assert!(s.parse::<SmbPath>().is_err());
337 let s = format!("a{}b", '\u{0000}');
338 assert!(s.parse::<SmbPath>().is_err());
339 }
340
341 #[cfg(windows)]
342 #[test]
343 fn rejects_reserved_dos_names() {
344 for bad in [
345 "CON", "con", "PRN", "AUX", "NUL", "COM1", "LPT9", "Con.txt", "NUL.dat",
346 ] {
347 assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
348 assert!(!is_valid_component(bad), "{bad}");
349 }
350 }
351
352 #[cfg(not(windows))]
353 #[test]
354 fn accepts_reserved_dos_names_where_the_host_does() {
355 for name in ["CON", "aux.c", "dir\\nul", "LPT9.log"] {
356 assert!(name.parse::<SmbPath>().is_ok(), "{name}");
357 }
358 assert!(is_valid_component("aux.c"));
359 }
360
361 #[test]
362 fn limits_component_and_path_length() {
363 let longest = "x".repeat(255);
364 assert!(longest.parse::<SmbPath>().is_ok());
365 assert!(format!("{longest}y").parse::<SmbPath>().is_err());
366 assert!("\u{1F600}".repeat(127).parse::<SmbPath>().is_ok());
368 assert!("\u{1F600}".repeat(128).parse::<SmbPath>().is_err());
369
370 let component = "x".repeat(254);
371 let path = vec![component.as_str(); 129].join("\\");
372 assert_eq!(path.len(), 32_894);
373 assert!(path.parse::<SmbPath>().is_err());
374 let path = vec![component.as_str(); 128].join("\\");
375 assert_eq!(path.len(), 32_639);
376 assert!(path.parse::<SmbPath>().is_ok());
377 }
378
379 #[test]
380 fn component_validation_matches_path_parsing() {
381 for name in ["a.txt", " lead", "\u{F021}"] {
382 assert!(is_valid_component(name), "{name}");
383 assert!(name.parse::<SmbPath>().is_ok(), "{name}");
384 }
385 for name in ["", ".", "..", "a:b", "a*b", "a\\b", "a/b", "a\u{1}b"] {
386 assert!(!is_valid_component(name), "{name:?}");
387 }
388 assert!(!is_valid_component(&"x".repeat(256)));
389 }
390
391 #[test]
392 fn pattern_validation_allows_wildcards_and_dots() {
393 for pattern in ["*", "*.txt", "a?b", "<.\"", ">", ".", ".."] {
394 assert!(is_valid_pattern(pattern), "{pattern}");
395 }
396 for pattern in ["", "a|b", "a:b", "a\\b", "a/b", "a\u{0}"] {
397 assert!(!is_valid_pattern(pattern), "{pattern:?}");
398 }
399 assert!(!is_valid_pattern(&"*".repeat(256)));
400 }
401
402 #[test]
403 fn allows_lookalike_names() {
404 assert!("CON1".parse::<SmbPath>().is_ok());
406 assert!("LPT".parse::<SmbPath>().is_ok());
407 assert!("LPT0".parse::<SmbPath>().is_ok()); assert!("NUL_FILE.txt".parse::<SmbPath>().is_ok());
409 }
410
411 #[test]
412 fn rejects_unpaired_surrogate() {
413 let units: [u16; 2] = [0xD800, 0x0061]; assert!(SmbPath::from_utf16(&units).is_err());
415 }
416
417 #[test]
418 fn rebase_moves_the_path_and_everything_below_it() {
419 let (from, to) = (p("Dir"), p("new\\place"));
420 assert_eq!(rebase(&p("Dir"), &from, &to, true), Some(to.clone()));
421 assert_eq!(
422 rebase(&p("Dir\\Sub\\f.txt"), &from, &to, true),
423 Some(p("new\\place\\Sub\\f.txt"))
424 );
425 assert_eq!(rebase(&p("dir\\f.txt"), &from, &to, true), None);
426 assert_eq!(
427 rebase(&p("dir\\f.txt"), &from, &to, false),
428 Some(p("new\\place\\f.txt"))
429 );
430 assert_eq!(rebase(&p("Dirt"), &from, &to, false), None);
431 assert_eq!(rebase(&p("other\\Dir"), &from, &to, false), None);
432 }
433
434 #[test]
435 fn round_trip_via_utf16() {
436 let p = SmbPath::from_utf16(&utf16("a\\b")).unwrap();
437 assert_eq!(p.components(), &["a", "b"]);
438 }
439}