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
184pub(crate) fn is_valid_component(name: &str) -> bool {
187 !name.is_empty()
188 && name != "."
189 && name != ".."
190 && name.encode_utf16().count() <= MAX_COMPONENT_UNITS
191 && !name
192 .chars()
193 .any(|c| is_control(c) || is_forbidden(c) || matches!(c, '\\' | '/'))
194 && !host_reserved_name(name)
195}
196
197pub(crate) fn is_valid_pattern(pattern: &str) -> bool {
201 !pattern.is_empty()
202 && pattern.encode_utf16().count() <= MAX_COMPONENT_UNITS
203 && !pattern
204 .chars()
205 .any(|c| is_control(c) || matches!(c, ':' | '|' | '\\' | '/'))
206}
207
208fn is_control(c: char) -> bool {
209 ('\u{0000}'..='\u{001F}').contains(&c)
210}
211
212fn is_forbidden(c: char) -> bool {
213 matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*')
214}
215
216fn host_reserved_name(name: &str) -> bool {
219 cfg!(windows) && is_reserved_dos_name(name)
220}
221
222fn is_reserved_dos_name(s: &str) -> bool {
223 let stem = match s.rsplit_once('.') {
225 Some((stem, _)) => stem,
226 None => s,
227 };
228 let upper = stem.to_ascii_uppercase();
229 matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL") || matches_com_or_lpt(&upper)
230}
231
232fn matches_com_or_lpt(s: &str) -> bool {
233 if s.len() != 4 {
234 return false;
235 }
236 let bytes = s.as_bytes();
237 let prefix = &bytes[..3];
238 let last = bytes[3] as char;
239 if !matches!(last, '1'..='9') {
240 return false;
241 }
242 prefix == b"COM" || prefix == b"LPT"
243}
244
245fn decode_utf16_strict(units: &[u16]) -> SmbResult<String> {
246 String::from_utf16(units).map_err(|_| SmbError::NameInvalid)
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 fn utf16(s: &str) -> Vec<u16> {
256 s.encode_utf16().collect()
257 }
258
259 fn p(s: &str) -> SmbPath {
260 s.parse().unwrap()
261 }
262
263 #[test]
264 fn root_paths() {
265 assert!("".parse::<SmbPath>().unwrap().is_root());
266 assert!("\\".parse::<SmbPath>().unwrap().is_root());
267 assert!("/".parse::<SmbPath>().unwrap().is_root());
268 assert!(SmbPath::from_utf16(&utf16("")).unwrap().is_root());
269 }
270
271 #[test]
272 fn simple_paths_split() {
273 let p = "dir\\sub\\file.txt".parse::<SmbPath>().unwrap();
274 assert_eq!(p.components(), &["dir", "sub", "file.txt"]);
275 assert_eq!(p.display_backslash(), "dir\\sub\\file.txt");
276 assert!(!p.is_root());
277 assert_eq!(p.file_name(), Some("file.txt"));
278 }
279
280 #[test]
281 fn forward_slash_accepted() {
282 let p = "a/b/c".parse::<SmbPath>().unwrap();
283 assert_eq!(p.components(), &["a", "b", "c"]);
284 }
285
286 #[test]
287 fn dot_components_skipped() {
288 let p = "a\\.\\b".parse::<SmbPath>().unwrap();
289 assert_eq!(p.components(), &["a", "b"]);
290 }
291
292 #[test]
293 fn parent_returns_one_component_less() {
294 let p = "a\\b\\c".parse::<SmbPath>().unwrap();
295 let parent = p.parent().unwrap();
296 assert_eq!(parent.components(), &["a", "b"]);
297 let grand = parent.parent().unwrap();
298 assert_eq!(grand.components(), &["a"]);
299 let root = grand.parent().unwrap();
300 assert!(root.is_root());
301 assert!(root.parent().is_none());
302 }
303
304 #[test]
305 fn join_appends_component() {
306 let p = "a".parse::<SmbPath>().unwrap();
307 let q = p.join("b").unwrap();
308 assert_eq!(q.components(), &["a", "b"]);
309 }
310
311 #[test]
312 fn rejects_double_dot() {
313 assert!("a\\..\\b".parse::<SmbPath>().is_err());
314 assert!("..".parse::<SmbPath>().is_err());
315 }
316
317 #[test]
318 fn rejects_double_separator() {
319 assert!("a\\\\b".parse::<SmbPath>().is_err());
320 }
321
322 #[test]
323 fn rejects_forbidden_chars() {
324 for bad in ["a<b", "a>b", "a:b", "a\"b", "a|b", "a?b", "a*b"] {
325 assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
326 }
327 }
328
329 #[test]
330 fn rejects_control_chars() {
331 let s = format!("a{}b", '\u{0001}');
332 assert!(s.parse::<SmbPath>().is_err());
333 let s = format!("a{}b", '\u{0000}');
334 assert!(s.parse::<SmbPath>().is_err());
335 }
336
337 #[cfg(windows)]
338 #[test]
339 fn rejects_reserved_dos_names() {
340 for bad in [
341 "CON", "con", "PRN", "AUX", "NUL", "COM1", "LPT9", "Con.txt", "NUL.dat",
342 ] {
343 assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
344 assert!(!is_valid_component(bad), "{bad}");
345 }
346 }
347
348 #[cfg(not(windows))]
349 #[test]
350 fn accepts_reserved_dos_names_where_the_host_does() {
351 for name in ["CON", "aux.c", "dir\\nul", "LPT9.log"] {
352 assert!(name.parse::<SmbPath>().is_ok(), "{name}");
353 }
354 assert!(is_valid_component("aux.c"));
355 }
356
357 #[test]
358 fn limits_component_and_path_length() {
359 let longest = "x".repeat(255);
360 assert!(longest.parse::<SmbPath>().is_ok());
361 assert!(format!("{longest}y").parse::<SmbPath>().is_err());
362 assert!("\u{1F600}".repeat(127).parse::<SmbPath>().is_ok());
364 assert!("\u{1F600}".repeat(128).parse::<SmbPath>().is_err());
365
366 let component = "x".repeat(254);
367 let path = vec![component.as_str(); 129].join("\\");
368 assert_eq!(path.len(), 32_894);
369 assert!(path.parse::<SmbPath>().is_err());
370 let path = vec![component.as_str(); 128].join("\\");
371 assert_eq!(path.len(), 32_639);
372 assert!(path.parse::<SmbPath>().is_ok());
373 }
374
375 #[test]
376 fn component_validation_matches_path_parsing() {
377 for name in ["a.txt", " lead", "\u{F021}"] {
378 assert!(is_valid_component(name), "{name}");
379 assert!(name.parse::<SmbPath>().is_ok(), "{name}");
380 }
381 for name in ["", ".", "..", "a:b", "a*b", "a\\b", "a/b", "a\u{1}b"] {
382 assert!(!is_valid_component(name), "{name:?}");
383 }
384 assert!(!is_valid_component(&"x".repeat(256)));
385 }
386
387 #[test]
388 fn pattern_validation_allows_wildcards_and_dots() {
389 for pattern in ["*", "*.txt", "a?b", "<.\"", ">", ".", ".."] {
390 assert!(is_valid_pattern(pattern), "{pattern}");
391 }
392 for pattern in ["", "a|b", "a:b", "a\\b", "a/b", "a\u{0}"] {
393 assert!(!is_valid_pattern(pattern), "{pattern:?}");
394 }
395 assert!(!is_valid_pattern(&"*".repeat(256)));
396 }
397
398 #[test]
399 fn allows_lookalike_names() {
400 assert!("CON1".parse::<SmbPath>().is_ok());
402 assert!("LPT".parse::<SmbPath>().is_ok());
403 assert!("LPT0".parse::<SmbPath>().is_ok()); assert!("NUL_FILE.txt".parse::<SmbPath>().is_ok());
405 }
406
407 #[test]
408 fn rejects_unpaired_surrogate() {
409 let units: [u16; 2] = [0xD800, 0x0061]; assert!(SmbPath::from_utf16(&units).is_err());
411 }
412
413 #[test]
414 fn rebase_moves_the_path_and_everything_below_it() {
415 let (from, to) = (p("Dir"), p("new\\place"));
416 assert_eq!(rebase(&p("Dir"), &from, &to, true), Some(to.clone()));
417 assert_eq!(
418 rebase(&p("Dir\\Sub\\f.txt"), &from, &to, true),
419 Some(p("new\\place\\Sub\\f.txt"))
420 );
421 assert_eq!(rebase(&p("dir\\f.txt"), &from, &to, true), None);
422 assert_eq!(
423 rebase(&p("dir\\f.txt"), &from, &to, false),
424 Some(p("new\\place\\f.txt"))
425 );
426 assert_eq!(rebase(&p("Dirt"), &from, &to, false), None);
427 assert_eq!(rebase(&p("other\\Dir"), &from, &to, false), None);
428 }
429
430 #[test]
431 fn round_trip_via_utf16() {
432 let p = SmbPath::from_utf16(&utf16("a\\b")).unwrap();
433 assert_eq!(p.components(), &["a", "b"]);
434 }
435}