Skip to main content

shell_tunnel/fs/
platform.rs

1//! Cross-platform filesystem differences, absorbed in one place.
2//!
3//! Path separators, reserved names, and stream syntax differ enough between
4//! Windows and Unix that scattering the checks would guarantee one of them is
5//! forgotten. ROADMAP:29 asks for this to exist from the start rather than be
6//! retrofitted.
7
8/// Windows device names, which resolve to devices rather than files no matter
9/// which directory they appear in. Compared without extension: `CON.txt` is
10/// still the console.
11const WINDOWS_RESERVED: &[&str] = &[
12    "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
13    "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
14];
15
16/// Whether one path component is acceptable as-is.
17///
18/// Applied on every platform, not just Windows. A tree written on Linux and
19/// read on Windows would otherwise contain names the other side cannot open,
20/// and a jail that behaves differently per host is not a jail anyone can reason
21/// about.
22///
23/// `..` is *not* rejected here — escape is decided by canonicalisation
24/// (`FsRoot::resolve_existing`), and a substring rule would also reject the
25/// perfectly ordinary `my..file.txt`.
26pub fn check_component(component: &str) -> Result<(), &'static str> {
27    if component.is_empty() {
28        return Err("empty path component");
29    }
30    if component.contains('\0') {
31        return Err("path contains a null byte");
32    }
33    // Alternate Data Streams: `file.txt:secret` addresses hidden content on
34    // NTFS. Nothing legitimate in a transfer API needs it.
35    if component.contains(':') {
36        return Err("path contains a stream separator");
37    }
38    if component.ends_with('.') || component.ends_with(' ') {
39        return Err("path component ends with a dot or space");
40    }
41    let stem = component
42        .split('.')
43        .next()
44        .unwrap_or(component)
45        .to_ascii_uppercase();
46    if WINDOWS_RESERVED.contains(&stem.as_str()) {
47        return Err("path component is a reserved device name");
48    }
49    Ok(())
50}
51
52/// A number that changes when the path starts referring to a different file.
53///
54/// Unix has an inode; Windows has no equivalent reachable from
55/// `std::fs::metadata` (`file_index()` is only populated through a `File`
56/// handle), so it contributes nothing there and the ETag rests on size and
57/// mtime alone. Recorded rather than worked around: a validator that claims
58/// more than the platform gives is worse than one that is honest.
59#[cfg(unix)]
60pub fn file_identity(meta: &std::fs::Metadata) -> u64 {
61    use std::os::unix::fs::MetadataExt;
62    meta.ino()
63}
64
65#[cfg(not(unix))]
66pub fn file_identity(_meta: &std::fs::Metadata) -> u64 {
67    0
68}
69
70/// Remove one filesystem entry, choosing the syscall a symlink actually needs.
71///
72/// `meta` must come from `symlink_metadata` (lstat), never `metadata` (stat)
73/// — the caller needs to know about the entry itself, not whatever it points
74/// to, or every symlink looks identical to its target and this can never
75/// tell a directory symlink from a real directory.
76#[cfg(unix)]
77pub fn remove_entry(path: &std::path::Path, _meta: &std::fs::Metadata) -> std::io::Result<()> {
78    // `unlink` removes the link itself no matter what it points to — file,
79    // directory, or nothing — so there is no branch to make here.
80    std::fs::remove_file(path)
81}
82
83/// Windows counterpart of the Unix `remove_entry` above.
84///
85/// `DeleteFileW` (which `std::fs::remove_file` wraps) refuses a directory
86/// reparse point outright, even though unlinking one is exactly as safe as
87/// unlinking a file symlink — nothing under it is touched either way.
88/// `RemoveDirectoryW` (`std::fs::remove_dir`) is what actually unlinks a
89/// directory reparse point without recursing into it; it only recurses into
90/// a *real* directory's contents, which is why the `not-a-file` refusal in
91/// `api::fs::delete_file` runs before this is ever reached.
92#[cfg(windows)]
93pub fn remove_entry(path: &std::path::Path, meta: &std::fs::Metadata) -> std::io::Result<()> {
94    if meta.is_symlink() {
95        // Follows the link on purpose — the one place in this function that
96        // means to — to learn whether the target is a directory.
97        if let Ok(target) = std::fs::metadata(path) {
98            if target.is_dir() {
99                return std::fs::remove_dir(path);
100            }
101        }
102    }
103    std::fs::remove_file(path)
104}
105
106#[cfg(not(any(unix, windows)))]
107pub fn remove_entry(path: &std::path::Path, _meta: &std::fs::Metadata) -> std::io::Result<()> {
108    std::fs::remove_file(path)
109}
110
111/// Whether `err` reports that the filesystem has run out of space.
112///
113/// Checked against the numeric OS error code, never the rendered message: an
114/// earlier version of the upload API answered this by matching substrings
115/// like `"space"` or `"full"` in `io::Error`'s `Display` output, which
116/// renders in the system locale (wrong on a non-English system) and would
117/// also fire on an ordinary error that happens to name a directory "full".
118/// A caller distinguishing "the disk is full, retry after freeing space"
119/// from "the server has a bug, file a report" needs this to be reliable —
120/// the two respond completely differently.
121///
122/// `ENOSPC` (`libc::ENOSPC`) is the same constant `src/pty/native.rs` and
123/// `src/pty/async_adapter.rs` already compare against for `EIO`, so this
124/// follows an established pattern rather than introducing a new way of
125/// reading `raw_os_error()`. `EDQUOT` (`libc::EDQUOT`) is its quota-analogue
126/// sibling — a per-user or per-directory quota can be exhausted well before
127/// the volume itself is full, and from a client's perspective both answers
128/// are the same instruction ("free something up and retry"). Both are
129/// `libc`'s *named* constants rather than a literal number precisely
130/// because their numeric value is not portable across Unix-likes (`EDQUOT`
131/// is 122 on Linux, 69 on macOS and the BSDs) — `libc` already carries the
132/// platform-correct value for each target, so naming it is also more
133/// correct than hardcoding one.
134///
135/// Windows has two counterparts, not one: `ERROR_DISK_FULL` (112) and
136/// `ERROR_HANDLE_DISK_FULL` (39/`0x27`) — the latter is what a handle-based
137/// write (exactly the path `UploadStore::append`'s `Write` impl takes)
138/// reports for a full volume, per `winerror.h`. Both are documented literals
139/// rather than named constants: there is no crate in this tree's dependency
140/// graph that names them (no `windows-sys`, and this task adds no new
141/// dependencies).
142#[cfg(unix)]
143pub fn is_out_of_space(err: &std::io::Error) -> bool {
144    matches!(err.raw_os_error(), Some(code) if code == libc::ENOSPC || code == libc::EDQUOT)
145}
146
147#[cfg(windows)]
148pub fn is_out_of_space(err: &std::io::Error) -> bool {
149    /// `ERROR_DISK_FULL`, from `winerror.h`.
150    const ERROR_DISK_FULL: i32 = 112;
151    /// `ERROR_HANDLE_DISK_FULL` (`0x27`), from `winerror.h` — reported for a
152    /// full volume on a handle-based write, which is the path uploads take.
153    const ERROR_HANDLE_DISK_FULL: i32 = 39;
154    // `io::Error::raw_os_error()` reports the raw Win32 error code, not an
155    // `errno` — neither of these is to be confused with any POSIX `ENOSPC`
156    // or `EDQUOT` numbering.
157    matches!(
158        err.raw_os_error(),
159        Some(code) if code == ERROR_DISK_FULL || code == ERROR_HANDLE_DISK_FULL
160    )
161}
162
163#[cfg(not(any(unix, windows)))]
164pub fn is_out_of_space(_err: &std::io::Error) -> bool {
165    false
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn ordinary_names_pass() {
174        assert!(check_component("config.json").is_ok());
175        assert!(check_component("my-app_v2").is_ok());
176    }
177
178    #[test]
179    fn a_name_containing_two_dots_is_not_traversal() {
180        // The bug the old substring rule had: `..` inside a name is ordinary.
181        assert!(check_component("my..file.txt").is_ok());
182        assert!(check_component("..config").is_ok());
183    }
184
185    #[test]
186    fn reserved_device_names_are_refused() {
187        assert!(check_component("CON").is_err());
188        assert!(check_component("con").is_err());
189        assert!(check_component("NUL.txt").is_err());
190        assert!(check_component("COM1.log").is_err());
191        // Not reserved: the stem differs.
192        assert!(check_component("CONSOLE").is_ok());
193    }
194
195    #[test]
196    fn stream_separators_are_refused() {
197        assert!(check_component("file.txt:secret").is_err());
198    }
199
200    #[test]
201    fn trailing_dot_or_space_is_refused() {
202        assert!(check_component("name.").is_err());
203        assert!(check_component("name ").is_err());
204    }
205
206    #[test]
207    fn null_bytes_are_refused() {
208        assert!(check_component("na\0me").is_err());
209    }
210
211    #[test]
212    fn empty_components_are_refused() {
213        assert!(check_component("").is_err());
214    }
215
216    /// Cannot deterministically fill a disk to force a real `ENOSPC` in a
217    /// test, so this is the honest substitute: pin `is_out_of_space` against
218    /// the raw OS codes directly, the same numeric values `raw_os_error()`
219    /// would actually report.
220    #[cfg(unix)]
221    #[test]
222    fn is_out_of_space_matches_enospc_and_edquot_only() {
223        let enospc = std::io::Error::from_raw_os_error(libc::ENOSPC);
224        assert!(is_out_of_space(&enospc));
225
226        // The quota-analogue sibling must match too, not just ENOSPC itself.
227        let edquot = std::io::Error::from_raw_os_error(libc::EDQUOT);
228        assert!(is_out_of_space(&edquot));
229
230        // A different errno — e.g. ENOENT — must not be mistaken for either.
231        let enoent = std::io::Error::from_raw_os_error(libc::ENOENT);
232        assert!(!is_out_of_space(&enoent));
233
234        // Not an OS error at all.
235        let other = std::io::Error::other("not an os error");
236        assert!(!is_out_of_space(&other));
237    }
238
239    #[cfg(windows)]
240    #[test]
241    fn is_out_of_space_matches_disk_full_codes_only() {
242        const ERROR_DISK_FULL: i32 = 112;
243        const ERROR_HANDLE_DISK_FULL: i32 = 39;
244
245        let disk_full = std::io::Error::from_raw_os_error(ERROR_DISK_FULL);
246        assert!(is_out_of_space(&disk_full));
247
248        // The handle-based-write sibling must match too — this is the code
249        // an actual full-volume `Write` (the path uploads take) reports.
250        let handle_disk_full = std::io::Error::from_raw_os_error(ERROR_HANDLE_DISK_FULL);
251        assert!(is_out_of_space(&handle_disk_full));
252
253        // A different Win32 code — e.g. ERROR_FILE_NOT_FOUND (2) — must not
254        // be mistaken for either.
255        let not_found = std::io::Error::from_raw_os_error(2);
256        assert!(!is_out_of_space(&not_found));
257
258        let other = std::io::Error::other("not an os error");
259        assert!(!is_out_of_space(&other));
260    }
261}