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 three counterparts, not one: `ERROR_DISK_FULL` (112),
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 — and `ERROR_DISK_QUOTA_EXCEEDED` (1295), which
172/// is `EDQUOT`'s counterpart and was missing while the Unix side had it: a
173/// per-user quota on an NTFS volume is exhausted with the volume itself far
174/// from full, and answering `500` there tells a client to file a bug about a
175/// condition it could have fixed by freeing space. All three are documented
176/// literals rather than named constants: there is no crate in this tree's
177/// dependency graph that names them (no `windows-sys`, and this task adds no
178/// new dependencies). 1295's identity was confirmed on Windows by rendering
179/// it — "The requested file operation failed because the storage quota was
180/// exceeded" — rather than read off a table.
181///
182/// `ERROR_NOT_ENOUGH_QUOTA` (1816) is deliberately *not* here despite the
183/// name: it renders as "Not enough quota is available to process this
184/// command" and reports a process memory quota, which is not a condition
185/// freeing disk space resolves.
186#[cfg(unix)]
187pub fn is_out_of_space(err: &std::io::Error) -> bool {
188 matches!(err.raw_os_error(), Some(code) if code == libc::ENOSPC || code == libc::EDQUOT)
189}
190
191#[cfg(windows)]
192pub fn is_out_of_space(err: &std::io::Error) -> bool {
193 /// `ERROR_DISK_FULL`, from `winerror.h`.
194 const ERROR_DISK_FULL: i32 = 112;
195 /// `ERROR_HANDLE_DISK_FULL` (`0x27`), from `winerror.h` — reported for a
196 /// full volume on a handle-based write, which is the path uploads take.
197 const ERROR_HANDLE_DISK_FULL: i32 = 39;
198 /// `ERROR_DISK_QUOTA_EXCEEDED`, from `winerror.h` — a quota exhausted on a
199 /// volume with space left, which is `EDQUOT`'s counterpart.
200 const ERROR_DISK_QUOTA_EXCEEDED: i32 = 1295;
201 // `io::Error::raw_os_error()` reports the raw Win32 error code, not an
202 // `errno` — none of these is to be confused with any POSIX `ENOSPC`
203 // or `EDQUOT` numbering.
204 matches!(
205 err.raw_os_error(),
206 Some(code)
207 if code == ERROR_DISK_FULL
208 || code == ERROR_HANDLE_DISK_FULL
209 || code == ERROR_DISK_QUOTA_EXCEEDED
210 )
211}
212
213#[cfg(not(any(unix, windows)))]
214pub fn is_out_of_space(_err: &std::io::Error) -> bool {
215 false
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 #[test]
223 fn ordinary_names_pass() {
224 assert!(check_component("config.json").is_ok());
225 assert!(check_component("my-app_v2").is_ok());
226 }
227
228 #[test]
229 fn a_name_containing_two_dots_is_not_traversal() {
230 // The bug the old substring rule had: `..` inside a name is ordinary.
231 assert!(check_component("my..file.txt").is_ok());
232 assert!(check_component("..config").is_ok());
233 }
234
235 #[test]
236 fn reserved_device_names_are_refused() {
237 assert!(check_component("CON").is_err());
238 assert!(check_component("con").is_err());
239 assert!(check_component("NUL.txt").is_err());
240 assert!(check_component("COM1.log").is_err());
241 // Not reserved: the stem differs.
242 assert!(check_component("CONSOLE").is_ok());
243 }
244
245 #[test]
246 fn stream_separators_are_refused() {
247 assert!(check_component("file.txt:secret").is_err());
248 }
249
250 #[test]
251 fn trailing_dot_or_space_is_refused() {
252 assert!(check_component("name.").is_err());
253 assert!(check_component("name ").is_err());
254 }
255
256 #[test]
257 fn null_bytes_are_refused() {
258 assert!(check_component("na\0me").is_err());
259 }
260
261 #[test]
262 fn empty_components_are_refused() {
263 assert!(check_component("").is_err());
264 }
265
266 /// Cannot deterministically fill a disk to force a real `ENOSPC` in a
267 /// test, so this is the honest substitute: pin `is_out_of_space` against
268 /// the raw OS codes directly, the same numeric values `raw_os_error()`
269 /// would actually report.
270 #[cfg(unix)]
271 #[test]
272 fn is_out_of_space_matches_enospc_and_edquot_only() {
273 let enospc = std::io::Error::from_raw_os_error(libc::ENOSPC);
274 assert!(is_out_of_space(&enospc));
275
276 // The quota-analogue sibling must match too, not just ENOSPC itself.
277 let edquot = std::io::Error::from_raw_os_error(libc::EDQUOT);
278 assert!(is_out_of_space(&edquot));
279
280 // A different errno — e.g. ENOENT — must not be mistaken for either.
281 let enoent = std::io::Error::from_raw_os_error(libc::ENOENT);
282 assert!(!is_out_of_space(&enoent));
283
284 // Not an OS error at all.
285 let other = std::io::Error::other("not an os error");
286 assert!(!is_out_of_space(&other));
287 }
288
289 #[cfg(windows)]
290 #[test]
291 fn is_out_of_space_matches_disk_full_codes_only() {
292 const ERROR_DISK_FULL: i32 = 112;
293 const ERROR_HANDLE_DISK_FULL: i32 = 39;
294 const ERROR_DISK_QUOTA_EXCEEDED: i32 = 1295;
295 const ERROR_NOT_ENOUGH_QUOTA: i32 = 1816;
296
297 let disk_full = std::io::Error::from_raw_os_error(ERROR_DISK_FULL);
298 assert!(is_out_of_space(&disk_full));
299
300 // The handle-based-write sibling must match too — this is the code
301 // an actual full-volume `Write` (the path uploads take) reports.
302 let handle_disk_full = std::io::Error::from_raw_os_error(ERROR_HANDLE_DISK_FULL);
303 assert!(is_out_of_space(&handle_disk_full));
304
305 // A quota exhausted on a volume with space left is the same
306 // instruction to the client, and is what the Unix side's `EDQUOT`
307 // already covered.
308 let quota = std::io::Error::from_raw_os_error(ERROR_DISK_QUOTA_EXCEEDED);
309 assert!(is_out_of_space("a));
310
311 // Named like a quota and is not one: 1816 is a process memory quota,
312 // which freeing disk space does not resolve.
313 let memory_quota = std::io::Error::from_raw_os_error(ERROR_NOT_ENOUGH_QUOTA);
314 assert!(!is_out_of_space(&memory_quota));
315
316 // A different Win32 code — e.g. ERROR_FILE_NOT_FOUND (2) — must not
317 // be mistaken for any of them.
318 let not_found = std::io::Error::from_raw_os_error(2);
319 assert!(!is_out_of_space(¬_found));
320
321 let other = std::io::Error::other("not an os error");
322 assert!(!is_out_of_space(&other));
323 }
324}