Skip to main content

smb_server/
path.rs

1//! `SmbPath`: validated, normalized SMB path used between dispatcher and
2//! backend.
3//!
4//! Handlers decode wire names to `&[u16]` and build an `SmbPath` with
5//! `from_utf16`; backends can use it without further checks.
6
7use std::str::FromStr;
8
9use crate::error::{SmbError, SmbResult};
10
11/// A validated, component-list path. No `..`, no Windows-forbidden chars, no
12/// alternate streams. Always relative to the share root; the empty path is
13/// the root.
14///
15/// Each component is a filename as MS-FSCC 2.1.5.2 defines it: 1 to 255
16/// UTF-16 code units, with no control characters and none of
17/// `" * / : < > ? \ |`. The whole path is at most 32,760 UTF-16 code units.
18/// On Windows hosts the reserved device names (`CON`, `PRN`, `AUX`, `NUL`,
19/// `COM1`-`COM9` and `LPT1`-`LPT9`, with or without an extension) are
20/// rejected too.
21#[derive(Debug, Clone, PartialEq, Eq, Default)]
22pub struct SmbPath {
23    components: Vec<String>,
24}
25
26impl SmbPath {
27    /// The share root.
28    pub fn root() -> Self {
29        Self::default()
30    }
31
32    /// Construct from a UTF-16 code-unit slice (already decoded from UTF-16LE
33    /// wire bytes).
34    pub fn from_utf16(units: &[u16]) -> SmbResult<Self> {
35        let s = decode_utf16_strict(units)?;
36        s.parse()
37    }
38
39    fn parse_components(s: &str) -> SmbResult<Self> {
40        // Strip a leading separator (clients sometimes prefix `\` or `/`).
41        let trimmed = s
42            .strip_prefix('\\')
43            .or_else(|| s.strip_prefix('/'))
44            .unwrap_or(s);
45        if trimmed.is_empty() {
46            return Ok(Self::root());
47        }
48        if trimmed.encode_utf16().count() > MAX_PATH_UNITS {
49            return Err(SmbError::NameInvalid);
50        }
51
52        // 2. Reject forbidden characters anywhere in the path. `\` and `/`
53        //    are separators here.
54        if trimmed.chars().any(|c| is_control(c) || is_forbidden(c)) {
55            return Err(SmbError::NameInvalid);
56        }
57
58        // 3. Split on `\` or `/`; reject `..` and empty components; skip `.`.
59        let mut components = Vec::new();
60        for raw in trimmed.split(['\\', '/']) {
61            if raw.is_empty() {
62                // Doubled separator like `foo\\bar`: reject.
63                return Err(SmbError::NameInvalid);
64            }
65            if raw == "." {
66                continue;
67            }
68            if raw == ".." {
69                return Err(SmbError::NameInvalid);
70            }
71            // 4. Length and, on Windows hosts, reserved device names.
72            if raw.encode_utf16().count() > MAX_COMPONENT_UNITS || host_reserved_name(raw) {
73                return Err(SmbError::NameInvalid);
74            }
75            components.push(raw.to_string());
76        }
77        Ok(Self { components })
78    }
79
80    /// Path components in order. Empty for the root.
81    pub fn components(&self) -> &[String] {
82        &self.components
83    }
84
85    /// Is this the share root?
86    pub fn is_root(&self) -> bool {
87        self.components.is_empty()
88    }
89
90    /// Return the parent path, or `None` if this is the root.
91    pub fn parent(&self) -> Option<SmbPath> {
92        if self.is_root() {
93            return None;
94        }
95        let mut parent = self.components.clone();
96        parent.pop();
97        Some(SmbPath { components: parent })
98    }
99
100    /// Return the last component, if any.
101    pub fn file_name(&self) -> Option<&str> {
102        self.components.last().map(|s| s.as_str())
103    }
104
105    /// Validate `last` and append its components to this path.
106    pub fn join(&self, last: &str) -> SmbResult<SmbPath> {
107        // Run `last` through the same validator (treating it as a single-
108        // component path).
109        let extra = last.parse::<SmbPath>()?;
110        let mut out = self.clone();
111        out.components.extend(extra.components);
112        Ok(out)
113    }
114
115    /// Render as a backslash-separated string. Empty for root.
116    pub fn display_backslash(&self) -> String {
117        self.components.join("\\")
118    }
119}
120
121/// True if `a` and `b` name the same entry, comparing names
122/// case-insensitively unless `case_sensitive`.
123pub(crate) fn same_path(a: &SmbPath, b: &SmbPath, case_sensitive: bool) -> bool {
124    a.components().len() == b.components().len() && starts_with(a, b, case_sensitive)
125}
126
127/// `path` with its leading `from` replaced by `to`, if `path` is `from` or
128/// lies below it, comparing names case-insensitively unless
129/// `case_sensitive`.
130pub(crate) fn rebase(
131    path: &SmbPath,
132    from: &SmbPath,
133    to: &SmbPath,
134    case_sensitive: bool,
135) -> Option<SmbPath> {
136    if !starts_with(path, from, case_sensitive) {
137        return None;
138    }
139    let mut components = to.components.clone();
140    components.extend_from_slice(&path.components[from.components.len()..]);
141    Some(SmbPath { components })
142}
143
144fn starts_with(path: &SmbPath, prefix: &SmbPath, case_sensitive: bool) -> bool {
145    path.components.len() >= prefix.components.len()
146        && path
147            .components
148            .iter()
149            .zip(&prefix.components)
150            .all(|(x, y)| {
151                if case_sensitive {
152                    x == y
153                } else {
154                    x.to_lowercase() == y.to_lowercase()
155                }
156            })
157}
158
159impl FromStr for SmbPath {
160    type Err = SmbError;
161
162    fn from_str(s: &str) -> Result<Self, Self::Err> {
163        Self::parse_components(s)
164    }
165}
166
167impl std::fmt::Display for SmbPath {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        if self.is_root() {
170            f.write_str("\\")
171        } else {
172            f.write_str(&self.display_backslash())
173        }
174    }
175}
176
177/// Longest filename component, in UTF-16 code units (MS-FSCC 2.1.5.2).
178const MAX_COMPONENT_UNITS: usize = 255;
179
180/// Longest pathname, in UTF-16 code units (MS-FSCC 2.1.5).
181const MAX_PATH_UNITS: usize = 32_760;
182
183/// True if `name` is one filename component that `SmbPath` accepts, so a
184/// client that sees it in a listing can open it.
185#[cfg_attr(
186    not(feature = "localfs"),
187    allow(dead_code, reason = "used by LocalFsBackend")
188)]
189pub(crate) fn is_valid_component(name: &str) -> bool {
190    !name.is_empty()
191        && name != "."
192        && name != ".."
193        && name.encode_utf16().count() <= MAX_COMPONENT_UNITS
194        && !name
195            .chars()
196            .any(|c| is_control(c) || is_forbidden(c) || matches!(c, '\\' | '/'))
197        && !host_reserved_name(name)
198}
199
200/// True if `pattern` is a valid QUERY_DIRECTORY search pattern (MS-FSA
201/// 2.1.5.6.3): a filename component in which the wildcards `* ? < > "` may
202/// appear, or `.` or `..`.
203pub(crate) fn is_valid_pattern(pattern: &str) -> bool {
204    !pattern.is_empty()
205        && pattern.encode_utf16().count() <= MAX_COMPONENT_UNITS
206        && !pattern
207            .chars()
208            .any(|c| is_control(c) || matches!(c, ':' | '|' | '\\' | '/'))
209}
210
211fn is_control(c: char) -> bool {
212    ('\u{0000}'..='\u{001F}').contains(&c)
213}
214
215fn is_forbidden(c: char) -> bool {
216    matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*')
217}
218
219/// True if `name` is a reserved DOS device name on this host. Only Windows
220/// resolves these names to devices.
221fn host_reserved_name(name: &str) -> bool {
222    cfg!(windows) && is_reserved_dos_name(name)
223}
224
225fn is_reserved_dos_name(s: &str) -> bool {
226    // Strip extension before checking, e.g. "CON.txt" is also reserved.
227    let stem = match s.rsplit_once('.') {
228        Some((stem, _)) => stem,
229        None => s,
230    };
231    let upper = stem.to_ascii_uppercase();
232    matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL") || matches_com_or_lpt(&upper)
233}
234
235fn matches_com_or_lpt(s: &str) -> bool {
236    if s.len() != 4 {
237        return false;
238    }
239    let bytes = s.as_bytes();
240    let prefix = &bytes[..3];
241    let last = bytes[3] as char;
242    if !matches!(last, '1'..='9') {
243        return false;
244    }
245    prefix == b"COM" || prefix == b"LPT"
246}
247
248fn decode_utf16_strict(units: &[u16]) -> SmbResult<String> {
249    // Reject unpaired surrogates explicitly. `String::from_utf16` does this
250    // already; we surface its error as NameInvalid.
251    String::from_utf16(units).map_err(|_| SmbError::NameInvalid)
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    fn utf16(s: &str) -> Vec<u16> {
259        s.encode_utf16().collect()
260    }
261
262    fn p(s: &str) -> SmbPath {
263        s.parse().unwrap()
264    }
265
266    #[test]
267    fn root_paths() {
268        assert!("".parse::<SmbPath>().unwrap().is_root());
269        assert!("\\".parse::<SmbPath>().unwrap().is_root());
270        assert!("/".parse::<SmbPath>().unwrap().is_root());
271        assert!(SmbPath::from_utf16(&utf16("")).unwrap().is_root());
272    }
273
274    #[test]
275    fn simple_paths_split() {
276        let p = "dir\\sub\\file.txt".parse::<SmbPath>().unwrap();
277        assert_eq!(p.components(), &["dir", "sub", "file.txt"]);
278        assert_eq!(p.display_backslash(), "dir\\sub\\file.txt");
279        assert!(!p.is_root());
280        assert_eq!(p.file_name(), Some("file.txt"));
281    }
282
283    #[test]
284    fn forward_slash_accepted() {
285        let p = "a/b/c".parse::<SmbPath>().unwrap();
286        assert_eq!(p.components(), &["a", "b", "c"]);
287    }
288
289    #[test]
290    fn dot_components_skipped() {
291        let p = "a\\.\\b".parse::<SmbPath>().unwrap();
292        assert_eq!(p.components(), &["a", "b"]);
293    }
294
295    #[test]
296    fn parent_returns_one_component_less() {
297        let p = "a\\b\\c".parse::<SmbPath>().unwrap();
298        let parent = p.parent().unwrap();
299        assert_eq!(parent.components(), &["a", "b"]);
300        let grand = parent.parent().unwrap();
301        assert_eq!(grand.components(), &["a"]);
302        let root = grand.parent().unwrap();
303        assert!(root.is_root());
304        assert!(root.parent().is_none());
305    }
306
307    #[test]
308    fn join_appends_component() {
309        let p = "a".parse::<SmbPath>().unwrap();
310        let q = p.join("b").unwrap();
311        assert_eq!(q.components(), &["a", "b"]);
312    }
313
314    #[test]
315    fn rejects_double_dot() {
316        assert!("a\\..\\b".parse::<SmbPath>().is_err());
317        assert!("..".parse::<SmbPath>().is_err());
318    }
319
320    #[test]
321    fn rejects_double_separator() {
322        assert!("a\\\\b".parse::<SmbPath>().is_err());
323    }
324
325    #[test]
326    fn rejects_forbidden_chars() {
327        for bad in ["a<b", "a>b", "a:b", "a\"b", "a|b", "a?b", "a*b"] {
328            assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
329        }
330    }
331
332    #[test]
333    fn rejects_control_chars() {
334        let s = format!("a{}b", '\u{0001}');
335        assert!(s.parse::<SmbPath>().is_err());
336        let s = format!("a{}b", '\u{0000}');
337        assert!(s.parse::<SmbPath>().is_err());
338    }
339
340    #[cfg(windows)]
341    #[test]
342    fn rejects_reserved_dos_names() {
343        for bad in [
344            "CON", "con", "PRN", "AUX", "NUL", "COM1", "LPT9", "Con.txt", "NUL.dat",
345        ] {
346            assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
347            assert!(!is_valid_component(bad), "{bad}");
348        }
349    }
350
351    #[cfg(not(windows))]
352    #[test]
353    fn accepts_reserved_dos_names_where_the_host_does() {
354        for name in ["CON", "aux.c", "dir\\nul", "LPT9.log"] {
355            assert!(name.parse::<SmbPath>().is_ok(), "{name}");
356        }
357        assert!(is_valid_component("aux.c"));
358    }
359
360    #[test]
361    fn limits_component_and_path_length() {
362        let longest = "x".repeat(255);
363        assert!(longest.parse::<SmbPath>().is_ok());
364        assert!(format!("{longest}y").parse::<SmbPath>().is_err());
365        // Length counts UTF-16 code units: U+1F600 takes two.
366        assert!("\u{1F600}".repeat(127).parse::<SmbPath>().is_ok());
367        assert!("\u{1F600}".repeat(128).parse::<SmbPath>().is_err());
368
369        let component = "x".repeat(254);
370        let path = vec![component.as_str(); 129].join("\\");
371        assert_eq!(path.len(), 32_894);
372        assert!(path.parse::<SmbPath>().is_err());
373        let path = vec![component.as_str(); 128].join("\\");
374        assert_eq!(path.len(), 32_639);
375        assert!(path.parse::<SmbPath>().is_ok());
376    }
377
378    #[test]
379    fn component_validation_matches_path_parsing() {
380        for name in ["a.txt", " lead", "\u{F021}"] {
381            assert!(is_valid_component(name), "{name}");
382            assert!(name.parse::<SmbPath>().is_ok(), "{name}");
383        }
384        for name in ["", ".", "..", "a:b", "a*b", "a\\b", "a/b", "a\u{1}b"] {
385            assert!(!is_valid_component(name), "{name:?}");
386        }
387        assert!(!is_valid_component(&"x".repeat(256)));
388    }
389
390    #[test]
391    fn pattern_validation_allows_wildcards_and_dots() {
392        for pattern in ["*", "*.txt", "a?b", "<.\"", ">", ".", ".."] {
393            assert!(is_valid_pattern(pattern), "{pattern}");
394        }
395        for pattern in ["", "a|b", "a:b", "a\\b", "a/b", "a\u{0}"] {
396            assert!(!is_valid_pattern(pattern), "{pattern:?}");
397        }
398        assert!(!is_valid_pattern(&"*".repeat(256)));
399    }
400
401    #[test]
402    fn allows_lookalike_names() {
403        // Not reserved.
404        assert!("CON1".parse::<SmbPath>().is_ok());
405        assert!("LPT".parse::<SmbPath>().is_ok());
406        assert!("LPT0".parse::<SmbPath>().is_ok()); // 0 is not in the 1-9 range
407        assert!("NUL_FILE.txt".parse::<SmbPath>().is_ok());
408    }
409
410    #[test]
411    fn rejects_unpaired_surrogate() {
412        let units: [u16; 2] = [0xD800, 0x0061]; // unpaired high surrogate
413        assert!(SmbPath::from_utf16(&units).is_err());
414    }
415
416    #[test]
417    fn rebase_moves_the_path_and_everything_below_it() {
418        let (from, to) = (p("Dir"), p("new\\place"));
419        assert_eq!(rebase(&p("Dir"), &from, &to, true), Some(to.clone()));
420        assert_eq!(
421            rebase(&p("Dir\\Sub\\f.txt"), &from, &to, true),
422            Some(p("new\\place\\Sub\\f.txt"))
423        );
424        assert_eq!(rebase(&p("dir\\f.txt"), &from, &to, true), None);
425        assert_eq!(
426            rebase(&p("dir\\f.txt"), &from, &to, false),
427            Some(p("new\\place\\f.txt"))
428        );
429        assert_eq!(rebase(&p("Dirt"), &from, &to, false), None);
430        assert_eq!(rebase(&p("other\\Dir"), &from, &to, false), None);
431    }
432
433    #[test]
434    fn round_trip_via_utf16() {
435        let p = SmbPath::from_utf16(&utf16("a\\b")).unwrap();
436        assert_eq!(p.components(), &["a", "b"]);
437    }
438}