Skip to content

An open-source cross-platform alternative to AirDrop

fix: normalize filenames to NFC so Korean jamo display correctly on Windows (#3683)

Sagar Ghag58955fd54ef1
diff --git a/Cargo.lock b/Cargo.lock
index b284ff28..3aa9e202 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2213,6 +2213,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"tungstenite 0.30.0",
+ "unicode-normalization",
"uuid",
"webrtc",
"x509-parser 0.18.1",
@@ -4126,6 +4127,12 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
[[package]]
name = "tokio"
version = "1.53.1"
@@ -4472,6 +4479,15 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+[[package]]
+name = "unicode-normalization"
+version = "0.1.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
+dependencies = [
+ "tinyvec",
+]
+
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
diff --git a/packages/core/Cargo.toml b/packages/core/Cargo.toml
index 0fa34482..21229bba 100644
--- a/packages/core/Cargo.toml
+++ b/packages/core/Cargo.toml
@@ -37,6 +37,7 @@ tokio-util = { version = "0.7.19", features = ["rt"], optional = true }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23" }
tungstenite = "0.30.0"
+unicode-normalization = "0.1"
uuid = { version = "1.24.0", features = ["serde", "v4"] }
webrtc = { version = "0.14.0", optional = true }
x509-parser = { version = "0.18.1", features = ["verify"], optional = true }
diff --git a/packages/core/src/http/server/v2.rs b/packages/core/src/http/server/v2.rs
index 9d034a74..41fc33e2 100644
--- a/packages/core/src/http/server/v2.rs
+++ b/packages/core/src/http/server/v2.rs
@@ -15,6 +15,7 @@ use crate::http::server::PeerIp;
use crate::http::server::{common, AppState, RequestClientInfo, V2State};
use crate::model::discovery::PROTOCOL_VERSION_V2;
use crate::model::transfer::FileDto;
+use crate::util::filename;
use hyper::body::Incoming;
use hyper::{Request, Response, StatusCode};
use std::collections::{HashMap, HashSet};
@@ -239,7 +240,7 @@ pub(crate) async fn prepare_upload(
)
.await?;
- let payload = req
+ let mut payload = req
.into_body()
.collect_to_json::<PrepareUploadRequestDtoV2>()
.await?;
@@ -248,6 +249,12 @@ pub(crate) async fn prepare_upload(
return Err(AppError::BadRequest("No files provided".to_string()));
}
+ // Senders on macOS send NFD names (e.g. Korean as separate jamo). Normalize
+ // once here so every consumer (UI, history, save path) sees NFC.
+ for file in payload.files.values_mut() {
+ file.file_name = filename::normalize(&file.file_name);
+ }
+
let session_id = Uuid::new_v4().to_string();
let cancelled = CancellationToken::new();
diff --git a/packages/core/src/util/filename.rs b/packages/core/src/util/filename.rs
index 1fb5dbd6..b4873c0a 100644
--- a/packages/core/src/util/filename.rs
+++ b/packages/core/src/util/filename.rs
@@ -1,5 +1,7 @@
//! Filename sanitization for untrusted, peer-supplied file names.
+use unicode_normalization::UnicodeNormalization;
+
/// Characters that are illegal on Windows and FAT volumes.
const ILLEGAL_WINDOWS_CHARS: &[char] = &['<', '>', ':', '"', '/', '\\', '|', '?', '*'];
@@ -108,10 +110,19 @@ pub fn sanitize(name: &str, rules: Rules) -> String {
sanitize_with(name, rules, &Options::default())
}
+/// Normalizes `name` to Unicode NFC without any other rewriting.
+///
+/// macOS (HFS+/APFS) emits NFD; Windows and most Linux desktops expect NFC.
+/// Without this, Korean jamo and accented Latin characters arrive decomposed.
+pub fn normalize(name: &str) -> String {
+ name.nfc().collect()
+}
+
/// [`sanitize`] with explicit replacement and placeholder strings.
pub fn sanitize_with(name: &str, rules: Rules, options: &Options) -> String {
- let mut result = String::with_capacity(name.len());
- for c in name.chars() {
+ let normalized = normalize(name);
+ let mut result = String::with_capacity(normalized.len());
+ for c in normalized.chars() {
if rules.is_illegal_char(c) {
result.push_str(options.replacement);
} else {
@@ -154,9 +165,15 @@ fn collapse_trailing_run(result: &mut String, replacement: &str) {
}
/// Whether `name` is already legal under `rules`, i.e. whether [`sanitize`]
-/// would leave it untouched. Suitable for validating user input before it is
-/// written.
+/// would leave it untouched apart from NFC normalization. Suitable for
+/// validating user input before it is written.
+///
+/// Decomposed input (e.g. a name pasted from macOS Finder) is legal: sanitize
+/// only composes it, so it is checked in its composed form.
pub fn is_valid(name: &str, rules: Rules) -> bool {
+ let normalized = normalize(name);
+ let name = normalized.as_str();
+
if name.is_empty() || name.len() > MAX_LEN || is_relative(name) {
return false;
}
@@ -341,8 +358,47 @@ mod tests {
assert!(is_valid(&"a".repeat(255), Rules::Posix));
}
- /// `is_valid` must agree with `sanitize` — otherwise a name the UI accepts
- /// still gets rewritten on save, or vice versa.
+ /// NFD names (e.g. Korean jamo from macOS) are normalized to NFC so they
+ /// display correctly on Windows and Linux.
+ #[test]
+ fn test_nfc_normalization() {
+ // Korean "오삐한테" in NFD (decomposed jamo)
+ let nfd = "\u{110B}\u{1169}\u{1108}\u{1175}\u{1112}\u{1161}\u{11AB}\u{1110}\u{1166}";
+ // Same string in NFC (precomposed syllables)
+ let nfc = "오삐한테";
+ assert_ne!(nfd, nfc);
+
+ for rules in [
+ Rules::Windows,
+ Rules::Hfs,
+ Rules::Fat,
+ Rules::Posix,
+ Rules::Universal,
+ ] {
+ assert_eq!(
+ sanitize(nfd, rules),
+ nfc,
+ "NFD not normalized for {rules:?}"
+ );
+ assert!(is_valid(nfc, rules), "NFC should be valid for {rules:?}");
+ assert!(is_valid(nfd, rules), "NFD should be valid for {rules:?}");
+ }
+
+ // Latin with combining accent: e + combining acute → é
+ let nfd_latin = "re\u{0301}sume\u{0301}.txt";
+ let nfc_latin = "résumé.txt";
+ assert_eq!(sanitize(nfd_latin, Rules::Posix), nfc_latin);
+
+ // normalize only composes; it must not rewrite separators or illegal characters.
+ assert_eq!(
+ normalize(&format!("dir/{nfd}:.txt")),
+ format!("dir/{nfc}:.txt")
+ );
+ }
+
+ /// `is_valid` must agree with `sanitize` (up to NFC normalization) —
+ /// otherwise a name the UI accepts still gets rewritten on save, or vice
+ /// versa.
#[test]
fn test_is_valid_matches_sanitize() {
let names = [
@@ -367,6 +423,15 @@ mod tests {
"文件.txt",
&"a".repeat(255),
&"a".repeat(256),
+ // NFD: "오삐한테" as jamo, and "résumé" with combining accents.
+ "\u{110B}\u{1169}\u{1108}\u{1175}\u{1112}\u{1161}\u{11AB}\u{1110}\u{1166}.txt",
+ "re\u{0301}sume\u{0301}.txt",
+ "a\u{0301}:b",
+ "con\u{0301}",
+ // Over the limit in NFD (720 bytes) but not in NFC (240 bytes).
+ &"\u{1112}\u{1161}\u{11AB}".repeat(80),
+ // Over the limit even in NFC (400 bytes).
+ &"e\u{0301}".repeat(200),
];
for rules in [
@@ -379,7 +444,7 @@ mod tests {
for name in names {
assert_eq!(
is_valid(name, rules),
- sanitize(name, rules) == name,
+ sanitize(name, rules) == normalize(name),
"mismatch for {name:?} under {rules:?}"
);
}
diff --git a/packages/core/tests/v2_server.rs b/packages/core/tests/v2_server.rs
index 4aa4cb72..3a2714c9 100644
--- a/packages/core/tests/v2_server.rs
+++ b/packages/core/tests/v2_server.rs
@@ -1376,6 +1376,64 @@ async fn test_prepare_upload_declined() {
assert_status(result, 403);
}
+/// macOS sends NFD names; the app must only ever see NFC (e.g. Korean as
+/// precomposed syllables instead of separate jamo).
+#[tokio::test]
+async fn test_prepare_upload_normalizes_file_names_to_nfc() {
+ let (event_tx, mut event_rx) = mpsc::channel::<ServerEventV2>(16);
+ let (_stop_tx, stop_rx) = oneshot::channel::<()>();
+ let handle = start_with_port(
+ 0,
+ None,
+ ClientInfo {
+ alias: "Test Server".to_string(),
+ version: "2.2".to_string(),
+ device_model: None,
+ device_type: None,
+ token: "server-fingerprint".to_string(),
+ },
+ None,
+ Some(ServerConfigV2 {
+ pin: None,
+ verify_checksums: true,
+ event_tx,
+ }),
+ WebConfig::default(),
+ stop_rx,
+ )
+ .await
+ .expect("Failed to start server");
+
+ // "오삐한테" as decomposed jamo, inside a folder.
+ let nfd = "dir/\u{110B}\u{1169}\u{1108}\u{1175}\u{1112}\u{1161}\u{11AB}\u{1110}\u{1166}.txt";
+ let client = LsHttpClientV2::try_new_without_cert().unwrap();
+ let request = client.prepare_upload(
+ ProtocolType::Http,
+ "127.0.0.1",
+ handle.port(),
+ None,
+ prepare_upload_request(&[file_dto("file-a", nfd, 5)]),
+ None,
+ CancellationToken::new(),
+ );
+
+ let observe = async {
+ loop {
+ if let Some(ServerEventV2::PrepareUpload {
+ files, decision_tx, ..
+ }) = event_rx.recv().await
+ {
+ let _ = decision_tx.send(PrepareUploadDecisionV2::Decline);
+ return files["file-a"].file_name.clone();
+ }
+ }
+ };
+
+ let (result, file_name) = tokio::join!(request, observe);
+ assert_status(result, 403);
+ assert_eq!(file_name, "dir/오삐한테.txt");
+}
+
#[tokio::test]
async fn test_pin() {
let server = start_test_server(Some("123456".to_string()), true, None).await;
diff --git a/packages/localsend_isolates/lib/rust/api/filename.dart b/packages/localsend_isolates/lib/rust/api/filename.dart
index 7ff86f81..b4200b36 100644
--- a/packages/localsend_isolates/lib/rust/api/filename.dart
+++ b/packages/localsend_isolates/lib/rust/api/filename.dart
@@ -11,5 +11,5 @@ import 'package:localsend_isolates/rust/frb_generated.dart';
String sanitizeFileName({required String name}) => RustLib.instance.api.crateApiFilenameSanitizeFileName(name: name);
/// Whether `name` is a legal file name on the current platform, i.e. whether
-/// [sanitize_file_name] would leave it untouched.
+/// [sanitize_file_name] would leave it untouched apart from NFC normalization.
bool isValidFileName({required String name}) => RustLib.instance.api.crateApiFilenameIsValidFileName(name: name);
diff --git a/packages/localsend_isolates/rust/src/api/filename.rs b/packages/localsend_isolates/rust/src/api/filename.rs
index 072ce8e1..3f2ba99a 100644
--- a/packages/localsend_isolates/rust/src/api/filename.rs
+++ b/packages/localsend_isolates/rust/src/api/filename.rs
@@ -9,7 +9,7 @@ pub fn sanitize_file_name(name: String) -> String {
}
/// Whether `name` is a legal file name on the current platform, i.e. whether
-/// [sanitize_file_name] would leave it untouched.
+/// [sanitize_file_name] would leave it untouched apart from NFC normalization.
#[frb(sync)]
pub fn is_valid_file_name(name: String) -> bool {
filename::is_valid(&name, filename::Rules::current())