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/// The filesystem roots a machine-wide scope is measured against.
60///
61/// Unix has exactly one; every mount hangs below it. Windows has one per
62/// drive and nothing above them, which is the whole reason a machine-wide
63/// scope cannot be expressed as a single path there — `--fs-root C:\` can
64/// never reach `D:`, by construction rather than by policy.
65///
66/// Probed once, by asking whether each letter is a directory. A drive that
67/// appears afterwards is deliberately not picked up: a server should reach
68/// what it was started with, not silently widen when someone plugs in a disk.
69/// Canonicalised, which on Windows means the verbatim form (`\\?\C:\`).
70/// `Path::canonicalize` returns verbatim paths, so an anchor left in its
71/// plain `C:\` form would fail `starts_with` against every resolved path and
72/// the containment check would refuse everything that actually exists.
73#[cfg(windows)]
74pub fn filesystem_anchors() -> Vec<std::path::PathBuf> {
75 (b'A'..=b'Z')
76 .map(|letter| std::path::PathBuf::from(format!("{}:\\", letter as char)))
77 .filter(|anchor| anchor.is_dir())
78 .filter_map(|anchor| anchor.canonicalize().ok())
79 .collect()
80}
81
82/// See the Windows variant: one root, and everything hangs below it.
83#[cfg(not(windows))]
84pub fn filesystem_anchors() -> Vec<std::path::PathBuf> {
85 vec![std::path::PathBuf::from("/")]
86}
87
88#[cfg(unix)]
89pub fn file_identity(meta: &std::fs::Metadata) -> u64 {
90 use std::os::unix::fs::MetadataExt;
91 meta.ino()
92}
93
94#[cfg(not(unix))]
95pub fn file_identity(_meta: &std::fs::Metadata) -> u64 {
96 0
97}
98
99/// Remove one filesystem entry, choosing the syscall a symlink actually needs.
100///
101/// `meta` must come from `symlink_metadata` (lstat), never `metadata` (stat)
102/// — the caller needs to know about the entry itself, not whatever it points
103/// to, or every symlink looks identical to its target and this can never
104/// tell a directory symlink from a real directory.
105#[cfg(unix)]
106pub fn remove_entry(path: &std::path::Path, _meta: &std::fs::Metadata) -> std::io::Result<()> {
107 // `unlink` removes the link itself no matter what it points to — file,
108 // directory, or nothing — so there is no branch to make here.
109 std::fs::remove_file(path)
110}
111
112/// Windows counterpart of the Unix `remove_entry` above.
113///
114/// `DeleteFileW` (which `std::fs::remove_file` wraps) refuses a directory
115/// reparse point outright, even though unlinking one is exactly as safe as
116/// unlinking a file symlink — nothing under it is touched either way.
117/// `RemoveDirectoryW` (`std::fs::remove_dir`) is what actually unlinks a
118/// directory reparse point without recursing into it; it only recurses into
119/// a *real* directory's contents, which both of this function's callers keep
120/// away from it: `api::fs::delete_file` refuses a real directory outright
121/// unless `recursive=true` names it, and from there `fs::tree::remove_tree`
122/// calls this only for a non-directory entry (`meta.is_dir()`, from `lstat`,
123/// routes a real directory to `remove_dir` itself instead — a directory
124/// *symlink* still reaches here, same as everywhere else in this function).
125#[cfg(windows)]
126pub fn remove_entry(path: &std::path::Path, meta: &std::fs::Metadata) -> std::io::Result<()> {
127 if meta.is_symlink() {
128 // Follows the link on purpose — the one place in this function that
129 // means to — to learn whether the target is a directory.
130 if let Ok(target) = std::fs::metadata(path) {
131 if target.is_dir() {
132 return std::fs::remove_dir(path);
133 }
134 }
135 }
136 std::fs::remove_file(path)
137}
138
139#[cfg(not(any(unix, windows)))]
140pub fn remove_entry(path: &std::path::Path, _meta: &std::fs::Metadata) -> std::io::Result<()> {
141 std::fs::remove_file(path)
142}
143
144/// Whether `err` reports that the filesystem has run out of space.
145///
146/// Checked against the numeric OS error code, never the rendered message: an
147/// earlier version of the upload API answered this by matching substrings
148/// like `"space"` or `"full"` in `io::Error`'s `Display` output, which
149/// renders in the system locale (wrong on a non-English system) and would
150/// also fire on an ordinary error that happens to name a directory "full".
151/// A caller distinguishing "the disk is full, retry after freeing space"
152/// from "the server has a bug, file a report" needs this to be reliable —
153/// the two respond completely differently.
154///
155/// `ENOSPC` (`libc::ENOSPC`) is the same constant `src/pty/native.rs` and
156/// `src/pty/async_adapter.rs` already compare against for `EIO`, so this
157/// follows an established pattern rather than introducing a new way of
158/// reading `raw_os_error()`. `EDQUOT` (`libc::EDQUOT`) is its quota-analogue
159/// sibling — a per-user or per-directory quota can be exhausted well before
160/// the volume itself is full, and from a client's perspective both answers
161/// are the same instruction ("free something up and retry"). Both are
162/// `libc`'s *named* constants rather than a literal number precisely
163/// because their numeric value is not portable across Unix-likes (`EDQUOT`
164/// is 122 on Linux, 69 on macOS and the BSDs) — `libc` already carries the
165/// platform-correct value for each target, so naming it is also more
166/// correct than hardcoding one.
167///
168/// Windows has two counterparts, not one: `ERROR_DISK_FULL` (112) and
169/// `ERROR_HANDLE_DISK_FULL` (39/`0x27`) — the latter is what a handle-based
170/// write (exactly the path `UploadStore::append`'s `Write` impl takes)
171/// reports for a full volume, per `winerror.h`. Both are documented literals
172/// rather than named constants: there is no crate in this tree's dependency
173/// graph that names them (no `windows-sys`, and this task adds no new
174/// dependencies).
175#[cfg(unix)]
176pub fn is_out_of_space(err: &std::io::Error) -> bool {
177 matches!(err.raw_os_error(), Some(code) if code == libc::ENOSPC || code == libc::EDQUOT)
178}
179
180#[cfg(windows)]
181pub fn is_out_of_space(err: &std::io::Error) -> bool {
182 /// `ERROR_DISK_FULL`, from `winerror.h`.
183 const ERROR_DISK_FULL: i32 = 112;
184 /// `ERROR_HANDLE_DISK_FULL` (`0x27`), from `winerror.h` — reported for a
185 /// full volume on a handle-based write, which is the path uploads take.
186 const ERROR_HANDLE_DISK_FULL: i32 = 39;
187 // `io::Error::raw_os_error()` reports the raw Win32 error code, not an
188 // `errno` — neither of these is to be confused with any POSIX `ENOSPC`
189 // or `EDQUOT` numbering.
190 matches!(
191 err.raw_os_error(),
192 Some(code) if code == ERROR_DISK_FULL || code == ERROR_HANDLE_DISK_FULL
193 )
194}
195
196#[cfg(not(any(unix, windows)))]
197pub fn is_out_of_space(_err: &std::io::Error) -> bool {
198 false
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn ordinary_names_pass() {
207 assert!(check_component("config.json").is_ok());
208 assert!(check_component("my-app_v2").is_ok());
209 }
210
211 #[test]
212 fn a_name_containing_two_dots_is_not_traversal() {
213 // The bug the old substring rule had: `..` inside a name is ordinary.
214 assert!(check_component("my..file.txt").is_ok());
215 assert!(check_component("..config").is_ok());
216 }
217
218 #[test]
219 fn reserved_device_names_are_refused() {
220 assert!(check_component("CON").is_err());
221 assert!(check_component("con").is_err());
222 assert!(check_component("NUL.txt").is_err());
223 assert!(check_component("COM1.log").is_err());
224 // Not reserved: the stem differs.
225 assert!(check_component("CONSOLE").is_ok());
226 }
227
228 #[test]
229 fn stream_separators_are_refused() {
230 assert!(check_component("file.txt:secret").is_err());
231 }
232
233 #[test]
234 fn trailing_dot_or_space_is_refused() {
235 assert!(check_component("name.").is_err());
236 assert!(check_component("name ").is_err());
237 }
238
239 #[test]
240 fn null_bytes_are_refused() {
241 assert!(check_component("na\0me").is_err());
242 }
243
244 #[test]
245 fn empty_components_are_refused() {
246 assert!(check_component("").is_err());
247 }
248
249 /// Cannot deterministically fill a disk to force a real `ENOSPC` in a
250 /// test, so this is the honest substitute: pin `is_out_of_space` against
251 /// the raw OS codes directly, the same numeric values `raw_os_error()`
252 /// would actually report.
253 #[cfg(unix)]
254 #[test]
255 fn is_out_of_space_matches_enospc_and_edquot_only() {
256 let enospc = std::io::Error::from_raw_os_error(libc::ENOSPC);
257 assert!(is_out_of_space(&enospc));
258
259 // The quota-analogue sibling must match too, not just ENOSPC itself.
260 let edquot = std::io::Error::from_raw_os_error(libc::EDQUOT);
261 assert!(is_out_of_space(&edquot));
262
263 // A different errno — e.g. ENOENT — must not be mistaken for either.
264 let enoent = std::io::Error::from_raw_os_error(libc::ENOENT);
265 assert!(!is_out_of_space(&enoent));
266
267 // Not an OS error at all.
268 let other = std::io::Error::other("not an os error");
269 assert!(!is_out_of_space(&other));
270 }
271
272 #[cfg(windows)]
273 #[test]
274 fn is_out_of_space_matches_disk_full_codes_only() {
275 const ERROR_DISK_FULL: i32 = 112;
276 const ERROR_HANDLE_DISK_FULL: i32 = 39;
277
278 let disk_full = std::io::Error::from_raw_os_error(ERROR_DISK_FULL);
279 assert!(is_out_of_space(&disk_full));
280
281 // The handle-based-write sibling must match too — this is the code
282 // an actual full-volume `Write` (the path uploads take) reports.
283 let handle_disk_full = std::io::Error::from_raw_os_error(ERROR_HANDLE_DISK_FULL);
284 assert!(is_out_of_space(&handle_disk_full));
285
286 // A different Win32 code — e.g. ERROR_FILE_NOT_FOUND (2) — must not
287 // be mistaken for either.
288 let not_found = std::io::Error::from_raw_os_error(2);
289 assert!(!is_out_of_space(¬_found));
290
291 let other = std::io::Error::other("not an os error");
292 assert!(!is_out_of_space(&other));
293 }
294}