PhotoCraft: An open-source, photo editor written by scratch in pure Rust
File names: keep Windows device names (nul, con, com1…) off the disk
Eddi Andree Salazar Matos7c0d30729387
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 3cec3e449..d312100a2 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -268,11 +268,30 @@ pub(crate) fn join(dir: &str, name: &str) -> String {}}-/// A file-name-safe version of a layer name.+/// A file-name-safe version of a layer name. A Windows device name (`nul`, `con.v2`) gets a `_`+/// before its first dot, so the file or folder is usable on Windows, wherever it was written.pub(crate) fn sanitize(name: &str) -> String {let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ' | '.') { c } else { '_' }).collect();let s = s.trim().trim_matches('.').to_string();- if s.is_empty() { "layer".into() } else { s }+ if s.is_empty() {+ return "layer".into();+ }+ if !is_windows_device_name(&s) {+ return s;+ }+ match s.split_once('.') {+ Some((device, rest)) => format!("{device}_.{rest}"),+ None => format!("{s}_"),+ }+}++/// Whether `component` names a Windows device (`CON`, `NUL`, `COM1`…, with any extension):+/// Windows opens the device instead of a file or folder of that name.+pub(crate) fn is_windows_device_name(component: &str) -> bool {+ let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();+ matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$")+ || stem.strip_prefix("COM").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"))+ || stem.strip_prefix("LPT").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"))}pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rsindex 9b5ec43a7..eba3a771f 100644--- a/crates/engine/src/file_cmds/tests.rs+++ b/crates/engine/src/file_cmds/tests.rs@@ -1428,3 +1428,18 @@ fn batch_naming_rejects_outputs_that_replace_inputs_before_processing() {assert_eq!(std::fs::read(&first).unwrap(), before[0]);assert_eq!(std::fs::read(&second).unwrap(), before[1]);}++#[test]+fn sanitize_keeps_windows_device_names_off_the_disk() {+ assert_eq!(sanitize("nul"), "nul_");+ assert_eq!(sanitize("CON"), "CON_");+ assert_eq!(sanitize("com1.v2"), "com1_.v2");+ assert_eq!(sanitize("lpt9 .final"), "lpt9 _.final");+ for name in ["nul", "CON", "com1.v2", "lpt9 .final", "aux", "prn", "conin$", "clock$"] {+ assert!(!is_windows_device_name(&sanitize(name)), "{name} -> {}", sanitize(name));+ }+ // Names that only start like a device are files like any other.+ for name in ["console", "normal", "com10", "lpt0", "nullify", "con_"] {+ assert_eq!(sanitize(name), name);+ }+}diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rsindex 38567ffb6..c8e8dde44 100644--- a/crates/engine/src/print_cmds/tests.rs+++ b/crates/engine/src/print_cmds/tests.rs@@ -869,3 +869,16 @@ fn windows_pdf_component_is_detected_by_loading_its_dll() {fn the_windows_pdf_check_is_a_no_op_elsewhere() {assert!(require_windows_pdf().is_ok());}++#[test]+fn package_of_a_document_named_after_a_windows_device_is_written() {+ // On Windows a folder named `nul` is the NUL device: the save failed with "path not found".+ let dir = tmp("package-device-name");+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8, "name": "nul.psd"})).unwrap();+ let r = s.execute("file.package", json!({"dir": format!("{dir}/pkg")})).unwrap();+ assert_eq!(r["folder"].as_str().unwrap(), format!("{dir}/pkg/nul_"));+ let document = r["document"].as_str().unwrap();+ assert!(document.ends_with("pkg/nul_/nul_.pcraft"), "{document}");+ assert!(std::path::Path::new(document).is_file());+}diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rsindex 755ba0732..60db3a3b5 100644--- a/crates/engine/src/web_cmds.rs+++ b/crates/engine/src/web_cmds.rs@@ -19,7 +19,7 @@ use photocraft_geom::Rect;use serde_json::{Value, json};use crate::commands::CommandSpec;-use crate::file_cmds::{join, native_doc, stem, write_file};+use crate::file_cmds::{is_windows_device_name, join, native_doc, stem, write_file};use crate::{EngineError, Result, Session};fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {@@ -732,7 +732,7 @@ fn slice_file(name: &str) -> String {/// Generated filenames should remain usable on Windows even when a document or slice is named/// after a reserved device. Caller-supplied path components are still rejected below.fn portable_generated_stem(stem: String) -> String {- if is_windows_device_asset_name(&stem) { format!("{stem}_") } else { stem }+ if is_windows_device_name(&stem) { format!("{stem}_") } else { stem }}fn html_escape(s: &str) -> String {@@ -1307,13 +1307,6 @@ fn asset_settings(spec: &AssetSpec) -> WebSettings {}}-fn is_windows_device_asset_name(component: &str) -> bool {- let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();- matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$")- || stem.strip_prefix("COM").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"))- || stem.strip_prefix("LPT").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"))-}-/// Layer names and `default` folders are document data, so reject unsafe output components.fn asset_path_components(relative: &str) -> Result<Vec<&str>> {// Split both separator styles even on Unix, where a backslash would otherwise be a legal@@ -1327,7 +1320,7 @@ fn asset_path_components(relative: &str) -> Result<Vec<&str>> {|| part.ends_with(' ')|| part.contains(':')|| part.contains('\0')- || is_windows_device_asset_name(part)+ || is_windows_device_name(part){return Err(other(format!("asset path {relative:?} has an unsafe component {part:?}")));}