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 is why the `not-a-file` refusal in
120/// `api::fs::delete_file` runs before this is ever reached.
121#[cfg(windows)]
122pub fn remove_entry(path: &std::path::Path, meta: &std::fs::Metadata) -> std::io::Result<()> {
123 if meta.is_symlink() {
124 // Follows the link on purpose — the one place in this function that
125 // means to — to learn whether the target is a directory.
126 if let Ok(target) = std::fs::metadata(path) {
127 if target.is_dir() {
128 return std::fs::remove_dir(path);
129 }
130 }
131 }
132 std::fs::remove_file(path)
133}
134
135#[cfg(not(any(unix, windows)))]
136pub fn remove_entry(path: &std::path::Path, _meta: &std::fs::Metadata) -> std::io::Result<()> {
137 std::fs::remove_file(path)
138}
139
140/// Whether `err` reports that the filesystem has run out of space.
141///
142/// Checked against the numeric OS error code, never the rendered message: an
143/// earlier version of the upload API answered this by matching substrings
144/// like `"space"` or `"full"` in `io::Error`'s `Display` output, which
145/// renders in the system locale (wrong on a non-English system) and would
146/// also fire on an ordinary error that happens to name a directory "full".
147/// A caller distinguishing "the disk is full, retry after freeing space"
148/// from "the server has a bug, file a report" needs this to be reliable —
149/// the two respond completely differently.
150///
151/// `ENOSPC` (`libc::ENOSPC`) is the same constant `src/pty/native.rs` and
152/// `src/pty/async_adapter.rs` already compare against for `EIO`, so this
153/// follows an established pattern rather than introducing a new way of
154/// reading `raw_os_error()`. `EDQUOT` (`libc::EDQUOT`) is its quota-analogue
155/// sibling — a per-user or per-directory quota can be exhausted well before
156/// the volume itself is full, and from a client's perspective both answers
157/// are the same instruction ("free something up and retry"). Both are
158/// `libc`'s *named* constants rather than a literal number precisely
159/// because their numeric value is not portable across Unix-likes (`EDQUOT`
160/// is 122 on Linux, 69 on macOS and the BSDs) — `libc` already carries the
161/// platform-correct value for each target, so naming it is also more
162/// correct than hardcoding one.
163///
164/// Windows has two counterparts, not one: `ERROR_DISK_FULL` (112) and
165/// `ERROR_HANDLE_DISK_FULL` (39/`0x27`) — the latter is what a handle-based
166/// write (exactly the path `UploadStore::append`'s `Write` impl takes)
167/// reports for a full volume, per `winerror.h`. Both are documented literals
168/// rather than named constants: there is no crate in this tree's dependency
169/// graph that names them (no `windows-sys`, and this task adds no new
170/// dependencies).
171#[cfg(unix)]
172pub fn is_out_of_space(err: &std::io::Error) -> bool {
173 matches!(err.raw_os_error(), Some(code) if code == libc::ENOSPC || code == libc::EDQUOT)
174}
175
176#[cfg(windows)]
177pub fn is_out_of_space(err: &std::io::Error) -> bool {
178 /// `ERROR_DISK_FULL`, from `winerror.h`.
179 const ERROR_DISK_FULL: i32 = 112;
180 /// `ERROR_HANDLE_DISK_FULL` (`0x27`), from `winerror.h` — reported for a
181 /// full volume on a handle-based write, which is the path uploads take.
182 const ERROR_HANDLE_DISK_FULL: i32 = 39;
183 // `io::Error::raw_os_error()` reports the raw Win32 error code, not an
184 // `errno` — neither of these is to be confused with any POSIX `ENOSPC`
185 // or `EDQUOT` numbering.
186 matches!(
187 err.raw_os_error(),
188 Some(code) if code == ERROR_DISK_FULL || code == ERROR_HANDLE_DISK_FULL
189 )
190}
191
192#[cfg(not(any(unix, windows)))]
193pub fn is_out_of_space(_err: &std::io::Error) -> bool {
194 false
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn ordinary_names_pass() {
203 assert!(check_component("config.json").is_ok());
204 assert!(check_component("my-app_v2").is_ok());
205 }
206
207 #[test]
208 fn a_name_containing_two_dots_is_not_traversal() {
209 // The bug the old substring rule had: `..` inside a name is ordinary.
210 assert!(check_component("my..file.txt").is_ok());
211 assert!(check_component("..config").is_ok());
212 }
213
214 #[test]
215 fn reserved_device_names_are_refused() {
216 assert!(check_component("CON").is_err());
217 assert!(check_component("con").is_err());
218 assert!(check_component("NUL.txt").is_err());
219 assert!(check_component("COM1.log").is_err());
220 // Not reserved: the stem differs.
221 assert!(check_component("CONSOLE").is_ok());
222 }
223
224 #[test]
225 fn stream_separators_are_refused() {
226 assert!(check_component("file.txt:secret").is_err());
227 }
228
229 #[test]
230 fn trailing_dot_or_space_is_refused() {
231 assert!(check_component("name.").is_err());
232 assert!(check_component("name ").is_err());
233 }
234
235 #[test]
236 fn null_bytes_are_refused() {
237 assert!(check_component("na\0me").is_err());
238 }
239
240 #[test]
241 fn empty_components_are_refused() {
242 assert!(check_component("").is_err());
243 }
244
245 /// Cannot deterministically fill a disk to force a real `ENOSPC` in a
246 /// test, so this is the honest substitute: pin `is_out_of_space` against
247 /// the raw OS codes directly, the same numeric values `raw_os_error()`
248 /// would actually report.
249 #[cfg(unix)]
250 #[test]
251 fn is_out_of_space_matches_enospc_and_edquot_only() {
252 let enospc = std::io::Error::from_raw_os_error(libc::ENOSPC);
253 assert!(is_out_of_space(&enospc));
254
255 // The quota-analogue sibling must match too, not just ENOSPC itself.
256 let edquot = std::io::Error::from_raw_os_error(libc::EDQUOT);
257 assert!(is_out_of_space(&edquot));
258
259 // A different errno — e.g. ENOENT — must not be mistaken for either.
260 let enoent = std::io::Error::from_raw_os_error(libc::ENOENT);
261 assert!(!is_out_of_space(&enoent));
262
263 // Not an OS error at all.
264 let other = std::io::Error::other("not an os error");
265 assert!(!is_out_of_space(&other));
266 }
267
268 #[cfg(windows)]
269 #[test]
270 fn is_out_of_space_matches_disk_full_codes_only() {
271 const ERROR_DISK_FULL: i32 = 112;
272 const ERROR_HANDLE_DISK_FULL: i32 = 39;
273
274 let disk_full = std::io::Error::from_raw_os_error(ERROR_DISK_FULL);
275 assert!(is_out_of_space(&disk_full));
276
277 // The handle-based-write sibling must match too — this is the code
278 // an actual full-volume `Write` (the path uploads take) reports.
279 let handle_disk_full = std::io::Error::from_raw_os_error(ERROR_HANDLE_DISK_FULL);
280 assert!(is_out_of_space(&handle_disk_full));
281
282 // A different Win32 code — e.g. ERROR_FILE_NOT_FOUND (2) — must not
283 // be mistaken for either.
284 let not_found = std::io::Error::from_raw_os_error(2);
285 assert!(!is_out_of_space(¬_found));
286
287 let other = std::io::Error::other("not an os error");
288 assert!(!is_out_of_space(&other));
289 }
290}