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#[derive(Debug, Clone, PartialEq, Eq, Default)]
15pub struct SmbPath {
16    components: Vec<String>,
17}
18
19impl SmbPath {
20    /// The share root.
21    pub fn root() -> Self {
22        Self::default()
23    }
24
25    /// Construct from a UTF-16 code-unit slice (already decoded from UTF-16LE
26    /// wire bytes).
27    pub fn from_utf16(units: &[u16]) -> SmbResult<Self> {
28        let s = decode_utf16_strict(units)?;
29        s.parse()
30    }
31
32    fn parse_components(s: &str) -> SmbResult<Self> {
33        // Strip a leading separator (clients sometimes prefix `\` or `/`).
34        let trimmed = s
35            .strip_prefix('\\')
36            .or_else(|| s.strip_prefix('/'))
37            .unwrap_or(s);
38        if trimmed.is_empty() {
39            return Ok(Self::root());
40        }
41
42        // 2. Reject forbidden characters anywhere in the path.
43        for ch in trimmed.chars() {
44            if ch == '\0' || ('\u{0001}'..='\u{001F}').contains(&ch) {
45                return Err(SmbError::NameInvalid);
46            }
47            // Allow `\` and `/` as separators, reject the rest of the
48            // Windows-forbidden set anywhere.
49            match ch {
50                '<' | '>' | ':' | '"' | '|' | '?' | '*' => return Err(SmbError::NameInvalid),
51                _ => {}
52            }
53        }
54
55        // 3. Split on `\` or `/`; reject `..` and empty components; skip `.`.
56        let mut components = Vec::new();
57        for raw in trimmed.split(['\\', '/']) {
58            if raw.is_empty() {
59                // Doubled separator like `foo\\bar`: reject.
60                return Err(SmbError::NameInvalid);
61            }
62            if raw == "." {
63                continue;
64            }
65            if raw == ".." {
66                return Err(SmbError::NameInvalid);
67            }
68            // 4. Reject reserved DOS device names.
69            if is_reserved_dos_name(raw) {
70                return Err(SmbError::NameInvalid);
71            }
72            components.push(raw.to_string());
73        }
74        Ok(Self { components })
75    }
76
77    /// Path components in order. Empty for the root.
78    pub fn components(&self) -> &[String] {
79        &self.components
80    }
81
82    /// Is this the share root?
83    pub fn is_root(&self) -> bool {
84        self.components.is_empty()
85    }
86
87    /// Return the parent path, or `None` if this is the root.
88    pub fn parent(&self) -> Option<SmbPath> {
89        if self.is_root() {
90            return None;
91        }
92        let mut parent = self.components.clone();
93        parent.pop();
94        Some(SmbPath { components: parent })
95    }
96
97    /// Return the last component, if any.
98    pub fn file_name(&self) -> Option<&str> {
99        self.components.last().map(|s| s.as_str())
100    }
101
102    /// Validate `last` and append its components to this path.
103    pub fn join(&self, last: &str) -> SmbResult<SmbPath> {
104        // Run `last` through the same validator (treating it as a single-
105        // component path).
106        let extra = last.parse::<SmbPath>()?;
107        let mut out = self.clone();
108        out.components.extend(extra.components);
109        Ok(out)
110    }
111
112    /// Render as a backslash-separated string. Empty for root.
113    pub fn display_backslash(&self) -> String {
114        self.components.join("\\")
115    }
116}
117
118/// True if `a` and `b` name the same entry, comparing names
119/// case-insensitively unless `case_sensitive`.
120pub(crate) fn same_path(a: &SmbPath, b: &SmbPath, case_sensitive: bool) -> bool {
121    a.components().len() == b.components().len() && starts_with(a, b, case_sensitive)
122}
123
124/// `path` with its leading `from` replaced by `to`, if `path` is `from` or
125/// lies below it, comparing names case-insensitively unless
126/// `case_sensitive`.
127pub(crate) fn rebase(
128    path: &SmbPath,
129    from: &SmbPath,
130    to: &SmbPath,
131    case_sensitive: bool,
132) -> Option<SmbPath> {
133    if !starts_with(path, from, case_sensitive) {
134        return None;
135    }
136    let mut components = to.components.clone();
137    components.extend_from_slice(&path.components[from.components.len()..]);
138    Some(SmbPath { components })
139}
140
141fn starts_with(path: &SmbPath, prefix: &SmbPath, case_sensitive: bool) -> bool {
142    path.components.len() >= prefix.components.len()
143        && path
144            .components
145            .iter()
146            .zip(&prefix.components)
147            .all(|(x, y)| {
148                if case_sensitive {
149                    x == y
150                } else {
151                    x.to_lowercase() == y.to_lowercase()
152                }
153            })
154}
155
156impl FromStr for SmbPath {
157    type Err = SmbError;
158
159    fn from_str(s: &str) -> Result<Self, Self::Err> {
160        Self::parse_components(s)
161    }
162}
163
164impl std::fmt::Display for SmbPath {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        if self.is_root() {
167            f.write_str("\\")
168        } else {
169            f.write_str(&self.display_backslash())
170        }
171    }
172}
173
174fn is_reserved_dos_name(s: &str) -> bool {
175    // Strip extension before checking, e.g. "CON.txt" is also reserved.
176    let stem = match s.rsplit_once('.') {
177        Some((stem, _)) => stem,
178        None => s,
179    };
180    let upper = stem.to_ascii_uppercase();
181    matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL") || matches_com_or_lpt(&upper)
182}
183
184fn matches_com_or_lpt(s: &str) -> bool {
185    if s.len() != 4 {
186        return false;
187    }
188    let bytes = s.as_bytes();
189    let prefix = &bytes[..3];
190    let last = bytes[3] as char;
191    if !matches!(last, '1'..='9') {
192        return false;
193    }
194    prefix == b"COM" || prefix == b"LPT"
195}
196
197fn decode_utf16_strict(units: &[u16]) -> SmbResult<String> {
198    // Reject unpaired surrogates explicitly. `String::from_utf16` does this
199    // already; we surface its error as NameInvalid.
200    String::from_utf16(units).map_err(|_| SmbError::NameInvalid)
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    fn utf16(s: &str) -> Vec<u16> {
208        s.encode_utf16().collect()
209    }
210
211    fn p(s: &str) -> SmbPath {
212        s.parse().unwrap()
213    }
214
215    #[test]
216    fn root_paths() {
217        assert!("".parse::<SmbPath>().unwrap().is_root());
218        assert!("\\".parse::<SmbPath>().unwrap().is_root());
219        assert!("/".parse::<SmbPath>().unwrap().is_root());
220        assert!(SmbPath::from_utf16(&utf16("")).unwrap().is_root());
221    }
222
223    #[test]
224    fn simple_paths_split() {
225        let p = "dir\\sub\\file.txt".parse::<SmbPath>().unwrap();
226        assert_eq!(p.components(), &["dir", "sub", "file.txt"]);
227        assert_eq!(p.display_backslash(), "dir\\sub\\file.txt");
228        assert!(!p.is_root());
229        assert_eq!(p.file_name(), Some("file.txt"));
230    }
231
232    #[test]
233    fn forward_slash_accepted() {
234        let p = "a/b/c".parse::<SmbPath>().unwrap();
235        assert_eq!(p.components(), &["a", "b", "c"]);
236    }
237
238    #[test]
239    fn dot_components_skipped() {
240        let p = "a\\.\\b".parse::<SmbPath>().unwrap();
241        assert_eq!(p.components(), &["a", "b"]);
242    }
243
244    #[test]
245    fn parent_returns_one_component_less() {
246        let p = "a\\b\\c".parse::<SmbPath>().unwrap();
247        let parent = p.parent().unwrap();
248        assert_eq!(parent.components(), &["a", "b"]);
249        let grand = parent.parent().unwrap();
250        assert_eq!(grand.components(), &["a"]);
251        let root = grand.parent().unwrap();
252        assert!(root.is_root());
253        assert!(root.parent().is_none());
254    }
255
256    #[test]
257    fn join_appends_component() {
258        let p = "a".parse::<SmbPath>().unwrap();
259        let q = p.join("b").unwrap();
260        assert_eq!(q.components(), &["a", "b"]);
261    }
262
263    #[test]
264    fn rejects_double_dot() {
265        assert!("a\\..\\b".parse::<SmbPath>().is_err());
266        assert!("..".parse::<SmbPath>().is_err());
267    }
268
269    #[test]
270    fn rejects_double_separator() {
271        assert!("a\\\\b".parse::<SmbPath>().is_err());
272    }
273
274    #[test]
275    fn rejects_forbidden_chars() {
276        for bad in ["a<b", "a>b", "a:b", "a\"b", "a|b", "a?b", "a*b"] {
277            assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
278        }
279    }
280
281    #[test]
282    fn rejects_control_chars() {
283        let s = format!("a{}b", '\u{0001}');
284        assert!(s.parse::<SmbPath>().is_err());
285        let s = format!("a{}b", '\u{0000}');
286        assert!(s.parse::<SmbPath>().is_err());
287    }
288
289    #[test]
290    fn rejects_reserved_dos_names() {
291        for bad in [
292            "CON", "con", "PRN", "AUX", "NUL", "COM1", "LPT9", "Con.txt", "NUL.dat",
293        ] {
294            assert!(bad.parse::<SmbPath>().is_err(), "{bad}");
295        }
296    }
297
298    #[test]
299    fn allows_lookalike_names() {
300        // Not reserved.
301        assert!("CON1".parse::<SmbPath>().is_ok());
302        assert!("LPT".parse::<SmbPath>().is_ok());
303        assert!("LPT0".parse::<SmbPath>().is_ok()); // 0 is not in the 1-9 range
304        assert!("NUL_FILE.txt".parse::<SmbPath>().is_ok());
305    }
306
307    #[test]
308    fn rejects_unpaired_surrogate() {
309        let units: [u16; 2] = [0xD800, 0x0061]; // unpaired high surrogate
310        assert!(SmbPath::from_utf16(&units).is_err());
311    }
312
313    #[test]
314    fn rebase_moves_the_path_and_everything_below_it() {
315        let (from, to) = (p("Dir"), p("new\\place"));
316        assert_eq!(rebase(&p("Dir"), &from, &to, true), Some(to.clone()));
317        assert_eq!(
318            rebase(&p("Dir\\Sub\\f.txt"), &from, &to, true),
319            Some(p("new\\place\\Sub\\f.txt"))
320        );
321        assert_eq!(rebase(&p("dir\\f.txt"), &from, &to, true), None);
322        assert_eq!(
323            rebase(&p("dir\\f.txt"), &from, &to, false),
324            Some(p("new\\place\\f.txt"))
325        );
326        assert_eq!(rebase(&p("Dirt"), &from, &to, false), None);
327        assert_eq!(rebase(&p("other\\Dir"), &from, &to, false), None);
328    }
329
330    #[test]
331    fn round_trip_via_utf16() {
332        let p = SmbPath::from_utf16(&utf16("a\\b")).unwrap();
333        assert_eq!(p.components(), &["a", "b"]);
334    }
335}