Skip to main content

smb_server/
path.rs

1//! `SmbPath`: validated, normalized SMB path used between dispatcher and
2//! backend.
3//!
4//! CREATE, durable reconnect and rename decode wire names to `&[u16]` and
5//! split off any stream suffix with `parse_create_name`, which builds the
6//! `SmbPath`; backends can use it without further checks.
7
8use std::str::FromStr;
9
10use crate::error::{SmbError, SmbResult};
11
12/// A validated, component-list path. No `..`, no Windows-forbidden chars, no
13/// alternate streams. Always relative to the share root; the empty path is
14/// the root.
15///
16/// Each component is a filename as MS-FSCC 2.1.5.2 defines it: 1 to 255
17/// UTF-16 code units, with no control characters and none of
18/// `" * / : < > ? \ |`. The whole path is at most 32,760 UTF-16 code units.
19/// On Windows hosts the reserved device names (`CON`, `PRN`, `AUX`, `NUL`,
20/// `COM1`-`COM9` and `LPT1`-`LPT9`, with or without an extension) are
21/// rejected too.
22#[derive(Debug, Clone, PartialEq, Eq, Default)]
23pub struct SmbPath {
24    components: Vec<String>,
25}
26
27impl SmbPath {
28    /// The share root.
29    pub fn root() -> Self {
30        Self::default()
31    }
32
33    /// Construct from a UTF-16 code-unit slice (already decoded from UTF-16LE
34    /// wire bytes).
35    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        // Strip a leading separator (clients sometimes prefix `\` or `/`).
42        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        // 2. Reject forbidden characters anywhere in the path. `\` and `/`
54        //    are separators here.
55        if trimmed.chars().any(|c| is_control(c) || is_forbidden(c)) {
56            return Err(SmbError::NameInvalid);
57        }
58
59        // 3. Split on `\` or `/`; reject `..` and empty components; skip `.`.
60        let mut components = Vec::new();
61        for raw in trimmed.split(['\\', '/']) {
62            if raw.is_empty() {
63                // Doubled separator like `foo\\bar`: reject.
64                return Err(SmbError::NameInvalid);
65            }
66            if raw == "." {
67                continue;
68            }
69            if raw == ".." {
70                return Err(SmbError::NameInvalid);
71            }
72            // 4. Length and, on Windows hosts, reserved device names.
73            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    /// Path components in order. Empty for the root.
82    pub fn components(&self) -> &[String] {
83        &self.components
84    }
85
86    /// Is this the share root?
87    pub fn is_root(&self) -> bool {
88        self.components.is_empty()
89    }
90
91    /// Return the parent path, or `None` if this is the root.
92    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    /// Return the last component, if any.
102    pub fn file_name(&self) -> Option<&str> {
103        self.components.last().map(|s| s.as_str())
104    }
105
106    /// Validate `last` and append its components to this path.
107    pub fn join(&self, last: &str) -> SmbResult<SmbPath> {
108        // Run `last` through the same validator (treating it as a single-
109        // component path).
110        let extra = last.parse::<SmbPath>()?;
111        let mut out = self.clone();
112        out.components.extend(extra.components);
113        Ok(out)
114    }
115
116    /// Render as a backslash-separated string. Empty for root.
117    pub fn display_backslash(&self) -> String {
118        self.components.join("\\")
119    }
120}
121
122/// True if `a` and `b` name the same entry, comparing names
123/// case-insensitively unless `case_sensitive`.
124pub(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
128/// `path` with its leading `from` replaced by `to`, if `path` is `from` or
129/// lies below it, comparing names case-insensitively unless
130/// `case_sensitive`.
131pub(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
178/// Longest filename component, in UTF-16 code units (MS-FSCC 2.1.5.2).
179const MAX_COMPONENT_UNITS: usize = 255;
180
181/// Longest pathname, in UTF-16 code units (MS-FSCC 2.1.5).
182const MAX_PATH_UNITS: usize = 32_760;
183
184/// True if `name` is one filename component that `SmbPath` accepts, so a
185/// client that sees it in a listing can open it.
186#[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
201/// True if `pattern` is a valid QUERY_DIRECTORY search pattern (MS-FSA
202/// 2.1.5.6.3): a filename component in which the wildcards `* ? < > "` may
203/// appear, or `.` or `..`.
204pub(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
220/// True if `name` is a reserved DOS device name on this host. Only Windows
221/// resolves these names to devices.
222fn 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    // Strip extension before checking, e.g. "CON.txt" is also reserved.
228    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    // Reject unpaired surrogates explicitly. `String::from_utf16` does this
251    // already; we surface its error as NameInvalid.
252    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        // Length counts UTF-16 code units: U+1F600 takes two.
367        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        // Not reserved.
405        assert!("CON1".parse::<SmbPath>().is_ok());
406        assert!("LPT".parse::<SmbPath>().is_ok());
407        assert!("LPT0".parse::<SmbPath>().is_ok()); // 0 is not in the 1-9 range
408        assert!("NUL_FILE.txt".parse::<SmbPath>().is_ok());
409    }
410
411    #[test]
412    fn rejects_unpaired_surrogate() {
413        let units: [u16; 2] = [0xD800, 0x0061]; // unpaired high surrogate
414        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}