Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

wezterm-gui: keep Windows-reserved characters out of downloaded names

RoversX32a905a276e9
diff --git a/wezterm-gui/src/download.rs b/wezterm-gui/src/download.rs
index 10115689..7ef2076f 100644
--- a/wezterm-gui/src/download.rs
+++ b/wezterm-gui/src/download.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use std::borrow::Cow;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
@@ -26,16 +27,22 @@ fn neuter_name(name: &str) -> Option<&str> {
/// files in that folder.
/// Returns the selected name and the opened File on success.
fn resolve_file_name(name: Option<&str>) -> anyhow::Result<(PathBuf, File)> {
+ // `neuter_name` is left exactly as it is, refusal of every `:` included:
+ // that is stricter than Linux needs, but relaxing it there would change
+ // what this does on a platform that has no problem with the name. The
+ // host's own filename rules are applied to what it returns -- and never
+ // to the fallback, which needs nothing done to it.
let name = name
.and_then(neuter_name)
- .unwrap_or("downloaded-via-wezterm");
+ .map(|name| crate::termwindow::remote_walk::DownloadNameRules::host().sanitize(name))
+ .unwrap_or(Cow::Borrowed("downloaded-via-wezterm"));
let download_dir = dirs_next::download_dir()
.ok_or_else(|| anyhow::anyhow!("unable to locate download directory"))?;
for n in 0..20 {
let candidate = if n == 0 {
- download_dir.join(name)
+ download_dir.join(&*name)
} else {
download_dir.join(&format!("{}.{}", name, n))
};
@@ -72,3 +79,26 @@ pub fn save_to_downloads(orig_name: Option<String>, data: &[u8]) -> anyhow::Resu
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::neuter_name;
+
+ /// `neuter_name` refuses a `:` on every platform, and must go on doing
+ /// so. It is stricter than unix needs -- `a:b.txt` is an ordinary name
+ /// there -- but it is what this has always done, and the host filename
+ /// rules are layered on top of it rather than replacing it, so that
+ /// tightening Windows leaves the other platforms exactly as they were.
+ #[test]
+ fn a_stream_supplied_name_never_keeps_a_colon() {
+ assert_eq!(neuter_name("report:2024.txt"), None);
+ assert_eq!(neuter_name("C:evil.txt"), None);
+ assert_eq!(neuter_name("."), None);
+ assert_eq!(neuter_name(".."), None);
+ // Separators are cut, not refused -- both of them, on every
+ // platform, which is stricter than `Path::file_name` on unix.
+ assert_eq!(neuter_name("a/b/c.txt"), Some("c.txt"));
+ assert_eq!(neuter_name("a\\b\\c.txt"), Some("c.txt"));
+ assert_eq!(neuter_name("report.txt"), Some("report.txt"));
+ }
+}
diff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rs
index ed3d7291..527296d1 100644
--- a/wezterm-gui/src/termwindow/remote_files.rs
+++ b/wezterm-gui/src/termwindow/remote_files.rs
@@ -2,6 +2,7 @@ use crate::workspace_threads::{RemoteFilesSource, RemoteFilesTarget};
use config::SshDomain;
use smol::channel::Sender;
use smol::io::{AsyncReadExt, AsyncWriteExt};
+use std::borrow::Cow;
use std::collections::{HashMap, HashSet, VecDeque};
use std::future::Future;
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -506,6 +507,25 @@ fn sanitized_download_name(file_name: &str) -> &str {
.unwrap_or("download")
}
+/// A server-supplied name reduced to something this host can store: a single
+/// component that the host's filename rules then accept. Unchanged off
+/// Windows, where those rules are the identity.
+///
+/// The order is load-bearing. `/` and `\` are reserved *characters* under the
+/// Windows rules, so sanitizing before taking the basename would rewrite
+/// `../../etc/passwd` into one long name on Windows while Linux still landed
+/// `passwd` -- one server, two platforms, two different files. Taking the
+/// basename first keeps them together, and hands `extension_split_index` a
+/// string whose bytes will not shift under it.
+///
+/// Deliberately not folded into `sanitized_download_name`, and so not into
+/// `download_name_candidates`: that is also how an *upload* picks a free name
+/// on the remote server, where this host's rules have no business.
+fn host_download_name(name: &str) -> Cow<'_, str> {
+ crate::termwindow::remote_walk::DownloadNameRules::host()
+ .sanitize(sanitized_download_name(name))
+}
+
/// Where a name's extension begins, for collision numbering. The LAST dot,
/// not the first: dots inside a stem are ordinary characters (a macOS
/// screenshot is `… at 12.50.59 PM.png`, and numbering it at the first dot
@@ -559,7 +579,8 @@ pub(crate) fn reserve_download_directory(
name: &str,
mut reserve: impl FnMut(&Path) -> bool,
) -> Option<PathBuf> {
- for candidate in folder_download_name_candidates(name) {
+ let name = host_download_name(name);
+ for candidate in folder_download_name_candidates(&name) {
let destination = directory.join(&candidate);
if reserve(&destination) {
return Some(destination);
@@ -581,7 +602,8 @@ pub(crate) fn reserve_download_path(
exists: impl Fn(&Path) -> bool,
mut reserve: impl FnMut(&Path) -> bool,
) -> Option<(PathBuf, PathBuf)> {
- for name in download_name_candidates(file_name) {
+ let file_name = host_download_name(file_name);
+ for name in download_name_candidates(&file_name) {
let destination = directory.join(&name);
if exists(&destination) {
continue;
@@ -3649,6 +3671,27 @@ mod tests {
destination.display()
);
assert_eq!(partial.parent(), Some(dir));
+ // And whatever it landed as, this host can actually store it.
+ let landed = destination.file_name().and_then(|n| n.to_str()).unwrap();
+ assert!(
+ crate::termwindow::remote_walk::DownloadNameRules::host().accepts(landed),
+ "{hostile:?} landed as {landed:?}, which this host refuses"
+ );
+ }
+ // Names this host cannot store are rewritten rather than refused: the
+ // transfer is what was asked for, the spelling is incidental. On unix
+ // they are ordinary names and come through untouched.
+ for reserved in ["report:2024.txt", "why?.txt", "CON", "trailing."] {
+ let (destination, _) =
+ reserve_download_path(dir, reserved, |_| false, |_| true).expect("a name");
+ let landed = destination.file_name().and_then(|n| n.to_str()).unwrap();
+ assert!(
+ crate::termwindow::remote_walk::DownloadNameRules::host().accepts(landed),
+ "{reserved:?} landed as {landed:?}, which this host refuses"
+ );
+ if cfg!(unix) {
+ assert_eq!(landed, reserved, "unix has no quarrel with this name");
+ }
}
// A dotfile keeps its leading dot instead of being read as extension.
let mut names = download_name_candidates(".bashrc");
diff --git a/wezterm-gui/src/termwindow/remote_walk.rs b/wezterm-gui/src/termwindow/remote_walk.rs
index 17d581f0..af599f7a 100644
--- a/wezterm-gui/src/termwindow/remote_walk.rs
+++ b/wezterm-gui/src/termwindow/remote_walk.rs
@@ -13,6 +13,7 @@
use super::remote_files::{
RemoteFileBackend, RemoteFileKind, RemotePath, RemoteTransferProgress, REMOTE_TRANSFER_CANCELED,
};
+use std::borrow::Cow;
use std::collections::{HashSet, VecDeque};
use std::path::{Component, Path};
@@ -77,14 +78,14 @@ fn name_is_single_host_component(name: &str) -> bool {
/// Kept explicit rather than hidden behind `cfg` so macOS and Windows
/// behavior can be exercised by the ordinary Linux test suite.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-enum DownloadNameRules {
+pub(crate) enum DownloadNameRules {
Unix,
MacOs,
Windows,
}
impl DownloadNameRules {
- fn host() -> Self {
+ pub(crate) fn host() -> Self {
if cfg!(target_os = "windows") {
Self::Windows
} else if cfg!(target_os = "macos") {
@@ -99,13 +100,32 @@ impl DownloadNameRules {
}
}
- fn accepts(self, name: &str) -> bool {
+ pub(crate) fn accepts(self, name: &str) -> bool {
match self {
Self::Unix | Self::MacOs => name_is_single_host_component(name),
Self::Windows => windows_download_name_is_valid(name),
}
}
+ /// `name` rewritten until [`Self::accepts`] takes it, borrowed unchanged
+ /// when it already does -- for a destination whose name is incidental,
+ /// like a download, where refusing the transfer over a character is
+ /// worse than landing it under a near-miss of the server's name.
+ ///
+ /// Only the Windows rules rewrite anything. `:`, `?` and the rest are
+ /// ordinary characters elsewhere, and renaming a file a user asked for
+ /// by name is its own kind of wrong.
+ ///
+ /// Expects a single component: run it after the name has been reduced to
+ /// a basename, never before, or `/` and `\` are rewritten into the name
+ /// instead of splitting it and the two platforms land different files.
+ pub(crate) fn sanitize(self, name: &str) -> Cow<'_, str> {
+ match self {
+ Self::Unix | Self::MacOs => Cow::Borrowed(name),
+ Self::Windows => windows_download_name(name),
+ }
+ }
+
fn collision_key(self, name: &str) -> Option<String> {
match self {
Self::Unix => None,
@@ -119,37 +139,86 @@ impl DownloadNameRules {
}
}
-fn windows_download_name_is_valid(name: &str) -> bool {
- if name.is_empty()
- || matches!(name, "." | "..")
- || name.ends_with([' ', '.'])
- || name.encode_utf16().count() > 255
- || name.chars().any(|ch| {
- ch <= '\u{1f}' || matches!(ch, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')
- })
- {
- return false;
- }
+/// A character Win32 refuses in a path component, plus the control range.
+fn windows_reserved_char(ch: char) -> bool {
+ ch <= '\u{1f}' || matches!(ch, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')
+}
- // Device names remain reserved even with an extension (for example
- // `CON.txt`). Windows also recognizes the ISO-8859-1 superscript forms of
- // COM/LPT 1-3.
+/// Whether the name's stem is a reserved device. They remain reserved with
+/// an extension (`CON.txt` is `CON`), and Windows also recognizes the
+/// ISO-8859-1 superscript forms of COM/LPT 1-3.
+fn windows_reserved_stem(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or(name).to_uppercase();
- if matches!(
+ matches!(
stem.as_str(),
"CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
- ) {
- return false;
- }
- let reserved_port = ["COM", "LPT"].iter().any(|prefix| {
+ ) || ["COM", "LPT"].iter().any(|prefix| {
stem.strip_prefix(prefix).is_some_and(|suffix| {
matches!(
suffix,
"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
)
})
- });
- !reserved_port
+ })
+}
+
+fn windows_download_name_is_valid(name: &str) -> bool {
+ !name.is_empty()
+ && !matches!(name, "." | "..")
+ && !name.ends_with([' ', '.'])
+ && name.encode_utf16().count() <= 255
+ && !name.chars().any(windows_reserved_char)
+ && !windows_reserved_stem(name)
+}
+
+/// Drop the trailing dots and spaces Windows would drop anyway. Left in
+/// place they are how one name silently becomes another: `report.` and
+/// `report` are the same file, and only one of them is what was asked for.
+fn trim_trailing_dots_and_spaces(name: &mut String) {
+ while name.ends_with([' ', '.']) {
+ name.pop();
+ }
+}
+
+/// `name` rewritten until [`windows_download_name_is_valid`] takes it.
+///
+/// Reserved characters become `_`, a reserved device stem is pushed out of
+/// the way with a prefix, and the length is cut on a character boundary.
+/// A name that survives none of that is `download`.
+fn windows_download_name(name: &str) -> Cow<'_, str> {
+ if windows_download_name_is_valid(name) {
+ return Cow::Borrowed(name);
+ }
+ let mut out: String = name
+ .chars()
+ .map(|ch| if windows_reserved_char(ch) { '_' } else { ch })
+ .collect();
+ trim_trailing_dots_and_spaces(&mut out);
+ if windows_reserved_stem(&out) {
+ out.insert(0, '_');
+ }
+ // The limit counts UTF-16 units, so the cut has to be found by walking
+ // characters rather than by slicing bytes. Trimming again afterwards
+ // because the cut can expose a dot or a space; the stem cannot become
+ // reserved this way, since cutting the end leaves a stem shorter than
+ // itself only when the stem was already over the limit.
+ if out.encode_utf16().count() > 255 {
+ let mut units = 0usize;
+ let mut end = out.len();
+ for (index, ch) in out.char_indices() {
+ if units + ch.len_utf16() > 255 {
+ end = index;
+ break;
+ }
+ units += ch.len_utf16();
+ }
+ out.truncate(end);
+ trim_trailing_dots_and_spaces(&mut out);
+ }
+ if out.is_empty() {
+ out.push_str("download");
+ }
+ Cow::Owned(out)
}
/// Walk `root` into a flat, parents-first plan.
@@ -594,6 +663,56 @@ mod tests {
}
}
+ /// The invariant the download path leans on: whatever `sanitize` returns
+ /// is a name the same rules accept. Without it the edges are easy to get
+ /// half-right -- a trailing dot removed but the reserved stem it exposes
+ /// left alone, a length cut that re-exposes a dot.
+ #[test]
+ fn sanitizing_a_windows_name_always_yields_one_windows_accepts() {
+ let long = "a".repeat(300);
+ let long_tail = format!("{}.", "b".repeat(255));
+ let wide = "😀".repeat(200);
+ for name in [
+ "report:2024.txt",
+ "a<b>c|d?e*f\"g",
+ "trailing.",
+ "trailing ",
+ "CON",
+ "con.txt",
+ "AUX.log",
+ "COM1",
+ "LPT9.data",
+ "COM¹",
+ "CONIN$",
+ "CON.",
+ "..",
+ ".",
+ "....",
+ ".. ",
+ "",
+ "\u{1}\u{2}",
+ &long,
+ &long_tail,
+ &wide,
+ ] {
+ let sanitized = DownloadNameRules::Windows.sanitize(name);
+ assert!(
+ DownloadNameRules::Windows.accepts(&sanitized),
+ "sanitize({name:?}) produced {sanitized:?}, which is still refused"
+ );
+ }
+ // A name that is already fine is handed back untouched, not copied.
+ assert!(matches!(
+ DownloadNameRules::Windows.sanitize("report.txt"),
+ Cow::Borrowed("report.txt")
+ ));
+ // Elsewhere the name is the user's, and stays theirs.
+ assert_eq!(
+ DownloadNameRules::Unix.sanitize("report:2024.txt"),
+ "report:2024.txt"
+ );
+ }
+
#[test]
fn case_insensitive_targets_reject_collisions_before_download() {
let backend = MapBackend::new(&[(