From f4a8283d741582c3c729af896b8265ad7cd929b5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:15:22 +0100 Subject: [PATCH 1/6] Export templates: subfolders and spec-based URP/USD templates --- crates/formats/README.md | 8 +- crates/formats/src/export/mod.rs | 54 ++++-- crates/formats/src/export/tests.rs | 161 +++++++++++++++++- crates/formats/src/presets.rs | 43 +++++ crates/ui-egui/src/export_window.rs | 14 +- .../tests/it/export_template_guards.rs | 6 +- crates/ui-egui/tests/it/output_templates.rs | 3 + docs/features.md | 5 +- 8 files changed, 268 insertions(+), 26 deletions(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index f56dbc36..ca377337 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -119,7 +119,11 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; the normal channel, then with the baked normal map, by Reoriented Normal Mapping. DirectX flips green. -Built-in presets: +File names may hold folders: `/` separates folder names inside the output directory (each one +sanitized; a backslash, `..`, a leading `/` and empty folder names are refused), and the folders +are created when the files are written. + +Built-in presets (each one lists the public specification its packing follows in `src/presets.rs`): | Preset | Files (`$mesh_$textureSet_…`) | |---|---| @@ -131,6 +135,8 @@ Built-in presets: | Blender (Principled BSDF) | `BaseColor`, `Metallic`, `Roughness`, `Normal` (OpenGL), `Height` (16-bit), `Emission`, `Specular` | | Godot 4 (ORM) | `albedo` (A = opacity), `orm` (R AO, G roughness, B metal), `normal` (OpenGL), `emission` | | OpenPBR (separate maps) | one map per OpenPBR Surface input the set has: `base_color`, `base_metalness`, `specular_roughness`, `specular_roughness_anisotropy`, `coat_weight`, `coat_roughness`, `fuzz_weight`, `fuzz_color`, `fuzz_roughness`, `transmission_weight`, `subsurface_weight`, `emission_color`, `geometry_opacity`, `geometry_normal` (OpenGL), `height` (16-bit) | +| Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | +| USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index a76a46b0..35fe4621 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -53,14 +53,18 @@ pub const FILE_TOKENS: [(&str, &str); 6] = [ ("$udim", "UV tile number (1001 for sets without UV tiles)"), ]; -/// Why `template` is not a valid file name template: path separators, `..`, control characters -/// and unknown `$` variables are refused. +/// Why `template` is not a valid file name template. `/` separates folders inside the output +/// directory; a backslash, `..`, a leading `/`, an empty folder name, control characters and +/// unknown `$` variables are refused. pub fn template_error(template: &str) -> Option { if template.trim().is_empty() || template.len() > MAX_TEMPLATE { return Some(format!("file name \"{template}\" is empty or longer than {MAX_TEMPLATE} bytes")); } - if template.contains(['/', '\\']) || template.contains("..") || template.chars().any(char::is_control) { - return Some(format!("file name \"{template}\" contains a path separator, \"..\" or a control character")); + if template.contains('\\') || template.contains("..") || template.chars().any(char::is_control) { + return Some(format!("file name \"{template}\" contains a backslash, \"..\" or a control character")); + } + if template.split('/').any(|segment| segment.trim().is_empty()) { + return Some(format!("file name \"{template}\" starts or ends with \"/\" or has an empty folder name")); } let mut rest = template; while let Some(i) = rest.find('$') { @@ -574,6 +578,11 @@ pub fn sanitize_file_stem(s: &str) -> String { out } +/// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. +pub fn sanitize_file_path(s: &str) -> String { + s.split('/').map(sanitize_file_stem).collect::>().join("/") +} + /// The files `opts` produces for texture set `ts`, without rendering (for the export dialog). /// Template variables: [`FILE_TOKENS`]. pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { @@ -635,11 +644,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export check_psd_size(size, channels, bit_depth)?; } + // A name of the project, mesh or texture set never adds a folder + let no_folder = |name: &str| name.replace('/', "_"); let stem = template .replace("$udim", &tile.unwrap_or(1001).to_string()) - .replace("$project", &project.name) - .replace("$mesh", mesh_name) - .replace("$textureSet", &set.name) + .replace("$project", &no_folder(&project.name)) + .replace("$mesh", &no_folder(mesh_name)) + .replace("$textureSet", &no_folder(&set.name)) .replace("$channel", channel_label(map)) .replace("$colorSpace", color_space); @@ -647,14 +658,14 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let token_stem = tile.map(|_| { let t = template .replace("$udim", "UDIMTOKEN") - .replace("$project", &project.name) - .replace("$mesh", mesh_name) - .replace("$textureSet", &set.name) + .replace("$project", &no_folder(&project.name)) + .replace("$mesh", &no_folder(mesh_name)) + .replace("$textureSet", &no_folder(&set.name)) .replace("$channel", channel_label(map)) .replace("$colorSpace", color_space); - sanitize_file_stem(&t) + sanitize_file_path(&t) }); - let stem = sanitize_file_stem(&stem); + let stem = sanitize_file_path(&stem); let ext = format.extension(); let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); @@ -1544,18 +1555,29 @@ fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl /// Write exported files into `dir` (created if missing) via [`crate::write_batch_atomic`]: /// all filenames are validated and staged before any rename, and a later rename failure rolls /// back earlier publications (concurrent readers may briefly observe a mixed generation during -/// the rename loop). Names must be plain file names. +/// the rename loop). Names are file names, or relative paths with `/` between sanitized folder +/// names; the folders are created inside `dir`. #[cfg(not(target_arch = "wasm32"))] pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result> { std::fs::create_dir_all(dir)?; + let root = dir.canonicalize()?; let mut targets = Vec::with_capacity(files.len()); for f in files { // Cap the sanitized stem before adding the extension let (stem, ext) = f.name.rsplit_once('.').unwrap_or((&f.name, "")); - if f.name.is_empty() || stem != sanitize_file_stem(stem) || !ext.chars().all(|c| c.is_ascii_alphanumeric()) || f.name.trim_matches('.').is_empty() { - return Err(FormatError::Invalid(format!("\"{}\" is not a plain file name", f.name))); + if f.name.is_empty() || stem != sanitize_file_path(stem) || !ext.chars().all(|c| c.is_ascii_alphanumeric()) || f.name.trim_matches('.').is_empty() { + return Err(FormatError::Invalid(format!("\"{}\" is not a file name or a relative path", f.name))); } - targets.push((dir.join(&f.name), f.bytes.as_slice())); + + // A folder that links elsewhere must not take the file out of `dir` + let target = dir.join(&f.name); + if let Some(parent) = target.parent().filter(|parent| *parent != dir) { + std::fs::create_dir_all(parent)?; + if !parent.canonicalize()?.starts_with(&root) { + return Err(FormatError::Invalid(format!("\"{}\" leads out of the output folder", f.name))); + } + } + targets.push((target, f.bytes.as_slice())); } crate::write_batch_atomic(targets.iter().map(|(path, bytes)| (path.as_path(), *bytes)))?; Ok(targets.into_iter().map(|(path, _)| path).collect()) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 8a8ca682..f7077577 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -565,7 +565,7 @@ fn validation_rejects_bad_presets() { p.validate().is_err() }; let long = "x".repeat(300); - for file in ["a/b", r"a\b", "..", "x..y", "$meshes_$foo", "$", "", " ", "a\u{7}b", long.as_str()] { + for file in ["/a", "a/", "a//b", r"a\b", "..", "x..y", "a/../b", "$meshes_$foo", "$", "", " ", "a\u{7}b", long.as_str()] { assert!(refused(&|p| p.maps[0].file = file.into()), "file template {file:?} must be refused"); } assert!(refused(&|p| p.name = " ".into())); @@ -726,6 +726,9 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() { // The length limit cuts the longer placeholder where it doesn't cut the tile number: none then assert_eq!(udim_names(format!("{}_$udim_$textureSet", "a".repeat(MAX_STEM - 10))), [None, None]); + + // A folder stays in the placeholder name + assert_eq!(udim_names("Base/$textureSet_$udim".into()), [Some("Base/Body_.png".to_string()), Some("Base/Body_.png".to_string())]); } #[test] @@ -1329,3 +1332,159 @@ fn diffusion_padding_fills_beyond_the_dilation_smoothly() { } } } + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn folder_templates_write_their_folders_inside_the_output_directory() { + let fx = Fx::new(&default_channels()); + let dir = std::env::temp_dir().join(format!("tc-formats-export-folders-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("$project.ts/$textureSet/roughness"), rough("Roughness/$textureSet_Roughness")] }; + let files = fx.render(&ExportOptions::new(preset)); + + write_files(&files, &dir).unwrap(); + + assert!(dir.join("My_Project.ts/Body_Set/roughness.png").is_file(), "{:?}", files.iter().map(|f| f.name.as_str()).collect::>()); + assert!(dir.join("Roughness/Body_Set_Roughness.png").is_file()); + for name in ["../evil.png", "/evil.png", "a//evil.png", r"a\evil.png"] { + let evil = ExportedFile { name: name.into(), ..files[0].clone() }; + assert!(write_files(&[evil], &dir).is_err(), "{name}"); + } + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn file_names_in_different_folders_do_not_collide_and_the_same_path_does() { + let fx = Fx::new(&default_channels()); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("a/x"), rough("b/x"), rough("A/x")] }; + + let names: Vec = list_outputs(&fx.project, 0, "sphere", &ExportOptions::new(preset)).unwrap().into_iter().map(|p| p.name).collect(); + + assert_eq!(names, ["a/x.png", "b/x.png", "A/x_2.png"]); +} + +/// A set whose channels hold distinct constants, to see where a template writes each of them +fn packing_fixture() -> Fx { + let mut channels = default_channels(); + channels.extend([Channel::AmbientOcclusion, Channel::Opacity, Channel::Emissive]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::AmbientOcclusion, |_, _| [0.6; 3]); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + fx.set_all(Channel::Emissive, |_, _| [0.3; 3]); + fx +} + +/// The 8-bit value of an image position as RGBA +fn pixel(file: &ExportedFile) -> [i32; 4] { + decode(file).to_rgba8().get_pixel(3, 3).0.map(i32::from) +} + +fn byte(value: f32) -> i32 { + (value * 255.0).round() as i32 +} + +fn assert_close(actual: [i32; 4], expected: [i32; 4], what: &str) { + assert!(actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= 1), "{what}: {actual:?} instead of {expected:?}"); +} + +#[test] +fn packed_templates_write_occlusion_roughness_and_metallic_where_the_spec_says() { + let fx = packing_fixture(); + let expected = [byte(0.6), byte(0.4), byte(0.8)]; + + for (template, file) in + [("glTF PBR Metal Roughness", "OcclusionRoughnessMetallic"), ("Unreal Engine (Packed)", "OcclusionRoughnessMetallic"), ("Godot 4 (ORM)", "orm")] + { + let files = fx.render_preset(template); + + let [r, g, b, _] = pixel(find(&files, file)); + assert_close([r, g, b, 0], [expected[0], expected[1], expected[2], 0], &format!("{template}: R occlusion, G roughness, B metallic")); + } +} + +#[test] +fn unity_templates_write_smoothness_in_the_alpha_of_the_metallic_map() { + let fx = packing_fixture(); + let smoothness = byte(1.0 - 0.4); + + let hdrp = pixel(find(&fx.render_preset("Unity HDRP (Mask Map)"), "MaskMap")); + let urp = pixel(find(&fx.render_preset("Unity URP Lit (Metallic Smoothness)"), "MetallicMap")); + + assert_close(hdrp, [byte(0.8), byte(0.6), 0, smoothness], "HDRP mask map: R metallic, G occlusion, B detail mask, A smoothness"); + assert_close(urp, [byte(0.8), 0, 0, smoothness], "URP metallic map: R metallic, A smoothness"); +} + +#[test] +fn the_usd_preview_surface_template_writes_one_map_per_input_named_like_it() { + let fx = packing_fixture(); + + let files = fx.render_preset("USD Preview Surface (separate maps)"); + + let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect(); + for (input, expected) in [("roughness", byte(0.4)), ("metallic", byte(0.8)), ("occlusion", byte(0.6)), ("opacity", byte(0.9))] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is one 8-bit channel: {names:?}"); + assert_close(pixel(file), [expected, expected, expected, 255], input); + } + for input in ["diffuseColor", "emissiveColor", "normal"] { + assert_eq!(decode(find(&files, &format!("_{input}.png"))).color(), image::ColorType::Rgb8, "{input} is a colour map: {names:?}"); + } + assert!(!names.iter().any(|name| name.contains("clearcoat")), "sets without the coat write no coat maps: {names:?}"); +} + +#[test] +fn only_the_unreal_template_writes_a_directx_normal_map() { + let mut fx = packing_fixture(); + let tilt = Vec3::new(0.3, 0.4, 0.0); + let tilt = Vec3::new(tilt.x, tilt.y, (1.0 - tilt.length_squared()).sqrt()); + fx.set_all(Channel::Normal, |_, _| (tilt * 0.5 + Vec3::splat(0.5)).to_array()); + let open_gl_green = byte(tilt.y * 0.5 + 0.5); + + for (template, file, flipped) in [ + ("glTF PBR Metal Roughness", "_Normal.png", false), + ("Unreal Engine (Packed)", "_Normal.png", true), + ("Unity HDRP (Mask Map)", "_Normal.png", false), + ("Unity URP Lit (Metallic Smoothness)", "NormalMap", false), + ("Godot 4 (ORM)", "normal", false), + ("USD Preview Surface (separate maps)", "_normal.png", false), + ] { + let green = pixel(find(&fx.render_preset(template), file))[1]; + + let want = if flipped { 255 - open_gl_green } else { open_gl_green }; + assert!((green - want).abs() <= 1, "{template}: green {green} instead of {want}"); + } +} + +#[test] +fn spec_templates_write_8_bit_png_files_with_the_expected_colour_encoding() { + let fx = packing_fixture(); + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + + for template in ["glTF PBR Metal Roughness", "Unreal Engine (Packed)", "Unity HDRP (Mask Map)", "Unity URP Lit (Metallic Smoothness)", "Godot 4 (ORM)"] { + let files = fx.render_preset(template); + + let color = files.iter().find(|f| ["BaseColor", "BaseMap", "albedo"].iter().any(|stem| f.name.contains(stem))).unwrap(); + + assert!(files.iter().all(|f| f.name.ends_with(".png")), "{template}: {:?}", files.iter().map(|f| &f.name).collect::>()); + let [r, g, b, a] = pixel(color); + assert_close([r, g, b, 0], [base[0], base[1], base[2], 0], &format!("{template}: sRGB-encoded base color")); + assert!((a - byte(0.9)).abs() <= 1, "{template}: opacity in alpha"); + } +} + +#[test] +fn a_slash_in_a_project_or_texture_set_name_does_not_make_a_folder() { + let mut fx = Fx::new(&default_channels()); + fx.project.name = "Wood/Oak".into(); + fx.project.texture_sets[0].name = "Body/Hull".into(); + let preset = + ExportPreset { name: "t".into(), maps: vec![gray_map("$project_$textureSet", SourceRef::Channel { channel: Channel::Roughness, component: 0 })] }; + + let names: Vec = list_outputs(&fx.project, 0, "sphere", &ExportOptions::new(preset)).unwrap().into_iter().map(|p| p.name).collect(); + + assert_eq!(names, ["Wood_Oak_Body_Hull.png"]); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 24f9f050..2f2879a4 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -92,11 +92,15 @@ pub fn builtin_presets() -> Vec { maps.push(map("ambientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0)))); maps }), + // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material preset("glTF PBR Metal Roughness", gltf_pbr_maps(|s| format!("$mesh_$textureSet_{s}"))), + // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material (R occlusion, G roughness, B metallic) and the base color, roughness, metallic and normal inputs of + // https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine preset( "Unreal Engine (Packed)", vec![map("BaseColor", 8, base_with_alpha()), map("OcclusionRoughnessMetallic", 8, orm()), map("Normal", 8, normal(VirtualMap::NormalDirectX))], ), + // Spec: https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@17.0/manual/Mask-Map-and-Detail-Map.html preset( "Unity HDRP (Mask Map)", vec![ @@ -115,6 +119,7 @@ pub fn builtin_presets() -> Vec { map("Normal", 8, normal(VirtualMap::NormalOpenGl)), ], ), + // Spec: https://docs.unity3d.com/Manual/StandardShaderMaterialParameterMetallic.html (smoothness in the metallic map's alpha) preset( "Unity Standard (Metallic Smoothness)", vec![ @@ -133,6 +138,7 @@ pub fn builtin_presets() -> Vec { map("Occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), ], ), + // Spec: https://docs.blender.org/manual/en/latest/render/shader_nodes/shader/principled.html preset( "Blender (Principled BSDF)", vec![ @@ -145,6 +151,7 @@ pub fn builtin_presets() -> Vec { map("Specular", 8, gray(ch(Channel::SpecularLevel, 0))), ], ), + // Spec: https://docs.godotengine.org/en/stable/tutorials/3d/standard_material_3d.html (ORM material: R occlusion, G roughness, B metallic) preset( "Godot 4 (ORM)", vec![ @@ -154,6 +161,7 @@ pub fn builtin_presets() -> Vec { map("emission", 8, rgb(|k| ch(Channel::Emissive, k))), ], ), + // Spec: https://academysoftwarefoundation.github.io/OpenPBR/ // One map per OpenPBR input present in the texture set preset("OpenPBR (separate maps)", { let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0))); @@ -176,6 +184,41 @@ pub fn builtin_presets() -> Vec { map("height", 16, gray(ch(Channel::Height, 0))), ] }), + // Spec: https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.0/manual/lit-shader.html (smoothness in the metallic map's alpha) + preset( + "Unity URP Lit (Metallic Smoothness)", + vec![ + map("BaseMap", 8, base_with_alpha()), + map( + "MetallicMap", + 8, + vec![ + (Dest::R, ch(Channel::Metallic, 0)), + (Dest::G, SourceRef::Constant(0.0)), + (Dest::B, SourceRef::Constant(0.0)), + (Dest::A, virt(VirtualMap::Glossiness, 0)), + ], + ), + map("NormalMap", 8, normal(VirtualMap::NormalOpenGl)), + map("OcclusionMap", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("EmissionMap", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), + // Spec: https://openusd.org/release/spec_usdpreviewsurface.html (one texture per input, named like it) + preset( + "USD Preview Surface (separate maps)", + vec![ + map("diffuseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("emissiveColor", 8, rgb(|k| ch(Channel::Emissive, k))), + map("metallic", 8, gray(ch(Channel::Metallic, 0))), + map("roughness", 8, gray(ch(Channel::Roughness, 0))), + map("normal", 8, normal(VirtualMap::NormalOpenGl)), + map("occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("opacity", 8, gray(ch(Channel::Opacity, 0))), + map("clearcoat", 8, gray(ch(Channel::CoatWeight, 0))), + map("clearcoatRoughness", 8, gray(ch(Channel::CoatRoughness, 0))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 0e696bcd..6a46f757 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -363,6 +363,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { params["reservedNames"] = job.written.iter().chain(&job.material_udim_patterns).map(|name| json!(name)).collect(); } + let directory = std::path::PathBuf::from(params["dir"].as_str().unwrap_or_default()); + // The last command writes the USD asset from the params of every command, so a canceled or failed export writes none if let Some(job) = app.ui.export.job.as_mut().filter(|job| job.usd_asset) { job.sent.push(params.clone()); @@ -382,9 +384,15 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { app.toast(warning.to_string(), true); } - let files: Vec = response_strings(&response, "files") - .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) - .collect(); + // Names relative to the output folder keep a template's folders + let relative = |file: &str| { + let path = std::path::Path::new(file); + match path.strip_prefix(&directory) { + Ok(inside) => inside.components().map(|part| part.as_os_str().to_string_lossy().into_owned()).collect::>().join("/"), + Err(_) => path.file_name().map_or_else(|| file.to_string(), |name| name.to_string_lossy().into_owned()), + } + }; + let files: Vec = response_strings(&response, "files").map(relative).collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; // The USD asset is no texture: it stays in the list of written files only for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 9cfc0071..3290256a 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -33,7 +33,7 @@ fn harness(library: &Library) -> Harness<'static, TextureCraftApp> { /// Type an invalid file name into the first output of the selected template, as the editor would. fn break_draft(h: &mut Harness<'_, TextureCraftApp>) { let draft = h.state_mut().ui.export.draft.as_mut().unwrap(); - draft.maps[0].file = "a/b".into(); + draft.maps[0].file = r"a\b".into(); assert!(draft.validate().is_err()); h.run_steps(3); } @@ -98,7 +98,7 @@ fn unfinished_edit_asks_before_selecting_another_template_and_keep_editing_stays h.get_by_label("Keep editing").click(); h.run_steps(3); assert_eq!(selected(&h), "Alpha tpl"); - assert_eq!(h.state().ui.export.draft.as_ref().unwrap().maps[0].file, "a/b", "the edit is intact"); + assert_eq!(h.state().ui.export.draft.as_ref().unwrap().maps[0].file, r"a\b", "the edit is intact"); assert!(h.state().ui.export.ask.is_none()); } @@ -118,7 +118,7 @@ fn unfinished_edit_discard_switches_to_the_other_template() { assert_eq!(draft.name, "Beta tpl"); assert!(draft.validate().is_ok(), "the dropped edit did not follow"); let alpha = h.state().session.export_preset("Alpha tpl").unwrap(); - assert_ne!(alpha.maps[0].file, "a/b", "the invalid edit was never saved"); + assert_ne!(alpha.maps[0].file, r"a\b", "the invalid edit was never saved"); } #[test] diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 1cdba31a..061c2779 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -84,6 +84,9 @@ fn drop_on(h: &mut Harness<'_, TextureCraftApp>, source: SourceRef, at: egui::Po /// Right-click the Presets list's `label` (listed before the selected one's name in the middle) fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + // The list holds more templates than it shows + h.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).scroll_to_me(); + h.run_steps(4); h.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).click_secondary(); h.run_steps(4); } diff --git a/docs/features.md b/docs/features.md index 04702ee9..42ea07a6 100644 --- a/docs/features.md +++ b/docs/features.md @@ -162,13 +162,14 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), - Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, + Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, - and share them as JSON. Right-click a preset to rename, duplicate or remove it; F2 renames. + and share them as JSON. File names may hold folders (`Roughness/$textureSet_Roughness`). + Right-click a preset to rename, duplicate or remove it; F2 renames. - **Export panel** on the right bar: *Export Mesh...* asks for the mesh export options, then for the file; *Export Textures...* opens the Export textures window (Settings, Output templates and List of exports, *Include all*, *Save settings* and the number of textures the export writes; From 0535d1ddc6ba0c4dacc0c3ab0632120e666da2d5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:11:54 +0700 Subject: [PATCH 2/6] Export templates: reject file/folder conflicts and confine writes with cap-std --- Cargo.lock | 1 + crates/formats/Cargo.toml | 1 + crates/formats/src/export/mod.rs | 58 +++-- crates/formats/src/export/tests.rs | 53 +++++ crates/formats/src/lib.rs | 357 +++++++++++++++++++++-------- 5 files changed, 356 insertions(+), 114 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 59d9a90a..d82d26f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5202,6 +5202,7 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "bytemuck", + "cap-std", "craft-cms", "craft-image-codecs", "craft-materialx", diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index fbc4138a..516e0f5d 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -39,6 +39,7 @@ rayon = { workspace = true } base64 = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +cap-std = { workspace = true } sysinfo = { workspace = true } [dev-dependencies] diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 35fe4621..235f261d 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -595,6 +595,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } let mut used = BTreeSet::new(); + let mut active_files = BTreeSet::new(); + let mut active_dirs = BTreeSet::new(); let mut out = Vec::new(); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; let grid = set.tile_grid(); @@ -697,11 +699,25 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export if k > 2 { warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); } - used.insert(name.to_ascii_lowercase()); + let lower = name.to_ascii_lowercase(); + used.insert(lower.clone()); if !enabled { continue; } + if active_dirs.contains(&lower) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); + } + let mut prefix = lower.as_str(); + while let Some((folder, _)) = prefix.rsplit_once('/') { + if active_files.contains(folder) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); + } + active_dirs.insert(folder.to_owned()); + prefix = folder; + } + active_files.insert(lower); + if color_map && requested_space != space { warnings.push(format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())); } @@ -1559,9 +1575,9 @@ fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl /// names; the folders are created inside `dir`. #[cfg(not(target_arch = "wasm32"))] pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result> { - std::fs::create_dir_all(dir)?; - let root = dir.canonicalize()?; - let mut targets = Vec::with_capacity(files.len()); + let mut seen_files = BTreeSet::new(); + let mut seen_dirs = BTreeSet::new(); + let mut rel_targets = Vec::with_capacity(files.len()); for f in files { // Cap the sanitized stem before adding the extension let (stem, ext) = f.name.rsplit_once('.').unwrap_or((&f.name, "")); @@ -1569,18 +1585,32 @@ pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result>(), ["a/x.png", "b/x.png"]); + + #[cfg(not(target_arch = "wasm32"))] + { + let dir = std::env::temp_dir().join(format!("tc-formats-conflict-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file_a = ExportedFile { name: "a.png".into(), ..valid_files[0].clone() }; + let nested_b = ExportedFile { name: "a.png/b.png".into(), ..valid_files[1].clone() }; + let upper_a = ExportedFile { name: "A.PNG".into(), ..valid_files[0].clone() }; + for pair in [[file_a, nested_b.clone()], [nested_b, upper_a]] { + assert!(write_files(&pair, &dir).is_err()); + assert!(std::fs::read_dir(&dir).unwrap().next().is_none(), "conflict must not create folders or files"); + } + std::fs::remove_dir_all(&dir).unwrap(); + } +} + +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[test] +fn folder_templates_reject_symlink_escapes_before_creating_subfolders() { + let fx = Fx::new(&default_channels()); + let files = fx.render_preset("Unreal Engine (Packed)"); + let base = std::env::temp_dir().join(format!("tc-formats-symlink-escape-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("out"); + let outside = base.join("outside"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("link")).unwrap(); + + let nested = ExportedFile { name: "link/new/map.png".into(), ..files[0].clone() }; + assert!(write_files(&[nested], &dir).is_err()); + assert!(!outside.join("new").exists(), "must not create directories through an escaping symlink"); + + let direct = ExportedFile { name: "link/map.png".into(), ..files[0].clone() }; + assert!(write_files(&[direct], &dir).is_err()); + assert!(!outside.join("map.png").exists()); + + std::fs::remove_dir_all(&base).unwrap(); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 8dc7d67e..03dc8cef 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -123,15 +123,199 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { /// Create a new temporary file beside `path`, refusing to reuse an existing (possibly symlinked) name. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> { - create_temp_with_mode(path, &std::collections::HashSet::new(), None) + let (tmp, file) = create_temp_with_mode(BatchRoot::Ambient, path, &std::collections::HashSet::new(), None)?; + match file { + BatchFile::Std(file) => Ok((tmp, file)), + BatchFile::Cap(_) => Err(FormatError::Io(std::io::Error::other("unexpected capability handle"))), + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy)] +enum BatchRoot<'a> { + Ambient, + Dir(&'a cap_std::fs::Dir), +} + +#[cfg(not(target_arch = "wasm32"))] +enum BatchFile { + Std(std::fs::File), + Cap(cap_std::fs::File), +} + +#[cfg(not(target_arch = "wasm32"))] +impl BatchFile { + fn write_and_sync(&mut self, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + match self { + Self::Std(file) => file.write_all(bytes).and_then(|()| file.sync_all()), + Self::Cap(file) => file.write_all(bytes).and_then(|()| file.sync_all()), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl BatchRoot<'_> { + fn is_dir(self, path: &std::path::Path) -> bool { + match self { + Self::Ambient => path.is_dir(), + Self::Dir(dir) => dir.is_dir(path), + } + } + + fn open_create_new(self, path: &std::path::Path, #[cfg_attr(not(unix), allow(unused_variables))] unix_mode: Option) -> std::io::Result { + match self { + Self::Ambient => { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if let Some(mode) = unix_mode { + use std::os::unix::fs::OpenOptionsExt; + options.mode(mode); + } + options.open(path).map(BatchFile::Std) + } + Self::Dir(dir) => { + let mut options = cap_std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if let Some(mode) = unix_mode { + use cap_std::fs::OpenOptionsExt; + options.mode(mode); + } + dir.open_with(path, &options).map(BatchFile::Cap) + } + } + } + + fn remove_file(self, path: &std::path::Path) -> std::io::Result<()> { + match self { + Self::Ambient => std::fs::remove_file(path), + Self::Dir(dir) => dir.remove_file(path), + } + } + + fn rename(self, from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { + match self { + Self::Ambient => std::fs::rename(from, to), + Self::Dir(dir) => dir.rename(from, dir, to), + } + } + + #[cfg(unix)] + fn restore_symlink(self, link_target: &std::path::Path, target_path: &std::path::Path) -> std::io::Result<()> { + match self { + Self::Ambient => std::fs::remove_file(target_path).and_then(|()| std::os::unix::fs::symlink(link_target, target_path)), + Self::Dir(dir) => dir.remove_file(target_path).and_then(|()| dir.symlink_contents(link_target, target_path)), + } + } + + fn target_matches_bytes(self, target_path: &std::path::Path, expected_bytes: &[u8]) -> bool { + use std::io::Read; + + let mut buf = Vec::with_capacity(expected_bytes.len().min(4096)); + let ok = match self { + Self::Ambient => { + let Ok(meta) = std::fs::symlink_metadata(target_path) else { return false }; + if !meta.file_type().is_file() { + return false; + } + let Ok(file) = std::fs::File::open(target_path) else { return false }; + let Ok(handle_meta) = file.metadata() else { return false }; + handle_meta.file_type().is_file() && file.take(expected_bytes.len() as u64 + 1).read_to_end(&mut buf).is_ok() + } + Self::Dir(dir) => { + let Ok(meta) = dir.symlink_metadata(target_path) else { return false }; + if !meta.file_type().is_file() { + return false; + } + let Ok(file) = dir.open(target_path) else { return false }; + let Ok(handle_meta) = file.metadata() else { return false }; + handle_meta.file_type().is_file() && file.take(expected_bytes.len() as u64 + 1).read_to_end(&mut buf).is_ok() + } + }; + ok && buf.as_slice() == expected_bytes + } + + fn prepare_backup( + self, + target_path: &std::path::Path, + reserved: &mut std::collections::HashSet, + ) -> std::io::Result> { + match self { + Self::Ambient => match std::fs::symlink_metadata(target_path) { + Ok(meta) => { + #[cfg(unix)] + if meta.file_type().is_symlink() { + return std::fs::read_link(target_path).map(|t| Some(RollbackBackup::Symlink(t))); + } + if !meta.file_type().is_file() { + return Err(std::io::Error::other(format!("{} is not a regular file", target_path.display()))); + } + let (backup_path, backup_file) = + create_temp_with_mode(self, target_path, reserved, Some(0o600)).map_err(|e| std::io::Error::other(e.to_string()))?; + reserved.insert(backup_path.clone()); + let copy_result = (|| -> std::io::Result<()> { + let mut src = std::fs::File::open(target_path)?; + let BatchFile::Std(mut dst) = backup_file else { + return Err(std::io::Error::other("unexpected capability handle")); + }; + std::io::copy(&mut src, &mut dst)?; + dst.set_permissions(meta.permissions())?; + dst.sync_all()?; + Ok(()) + })(); + if let Err(error) = copy_result { + let _ = std::fs::remove_file(&backup_path); + return Err(error); + } + Ok(Some(RollbackBackup::File(backup_path))) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + }, + Self::Dir(dir) => match dir.symlink_metadata(target_path) { + Ok(meta) => { + #[cfg(unix)] + if meta.file_type().is_symlink() { + return dir.read_link_contents(target_path).map(|t| Some(RollbackBackup::Symlink(t))); + } + if !meta.file_type().is_file() { + return Err(std::io::Error::other(format!("{} is not a regular file", target_path.display()))); + } + let (backup_path, backup_file) = + create_temp_with_mode(self, target_path, reserved, Some(0o600)).map_err(|e| std::io::Error::other(e.to_string()))?; + reserved.insert(backup_path.clone()); + let copy_result = (|| -> std::io::Result<()> { + let mut src = dir.open(target_path)?; + let BatchFile::Cap(mut dst) = backup_file else { + return Err(std::io::Error::other("unexpected std file handle")); + }; + std::io::copy(&mut src, &mut dst)?; + dst.set_permissions(meta.permissions())?; + dst.sync_all()?; + Ok(()) + })(); + if let Err(error) = copy_result { + let _ = dir.remove_file(&backup_path); + return Err(error); + } + Ok(Some(RollbackBackup::File(backup_path))) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + }, + } + } } #[cfg(not(target_arch = "wasm32"))] fn create_temp_with_mode( + root: BatchRoot<'_>, path: &std::path::Path, excluded: &std::collections::HashSet, - #[cfg_attr(not(unix), allow(unused_variables))] unix_mode: Option, -) -> Result<(std::path::PathBuf, std::fs::File)> { + unix_mode: Option, +) -> Result<(std::path::PathBuf, BatchFile)> { let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out"); @@ -143,14 +327,7 @@ fn create_temp_with_mode( if excluded.contains(&temporary_path) { continue; } - let mut options = std::fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - if let Some(mode) = unix_mode { - use std::os::unix::fs::OpenOptionsExt; - options.mode(mode); - } - match options.open(&temporary_path) { + match root.open_create_new(&temporary_path, unix_mode) { Ok(file) => return Ok((temporary_path, file)), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => return Err(error.into()), @@ -177,6 +354,13 @@ pub fn write_batch_atomic<'a>(entries: impl IntoIterator(root: &cap_std::fs::Dir, entries: impl IntoIterator) -> Result<()> { + write_batch_atomic_with_root(BatchRoot::Dir(root), entries, |_, _| Ok(())) +} + #[cfg(not(target_arch = "wasm32"))] enum RollbackBackup { File(std::path::PathBuf), @@ -185,32 +369,28 @@ enum RollbackBackup { } #[cfg(not(target_arch = "wasm32"))] -fn target_matches_bytes(target_path: &std::path::Path, expected_bytes: &[u8]) -> bool { - use std::io::Read; +fn write_batch_atomic_with_hook<'a>( + entries: impl IntoIterator, + before_rename: impl FnMut(usize, &std::path::Path) -> std::io::Result<()>, +) -> Result<()> { + write_batch_atomic_with_root(BatchRoot::Ambient, entries, before_rename) +} - let Ok(meta) = std::fs::symlink_metadata(target_path) else { return false }; - if !meta.file_type().is_file() { - return false; - } - let Ok(file) = std::fs::File::open(target_path) else { return false }; - let Ok(handle_meta) = file.metadata() else { return false }; - if !handle_meta.file_type().is_file() { - return false; - } - let mut buf = Vec::with_capacity(expected_bytes.len().min(4096)); - if file.take(expected_bytes.len() as u64 + 1).read_to_end(&mut buf).is_err() { - return false; - } - buf.as_slice() == expected_bytes +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn write_batch_atomic_in_dir_with_hook<'a>( + root: &cap_std::fs::Dir, + entries: impl IntoIterator, + before_rename: impl FnMut(usize, &std::path::Path) -> std::io::Result<()>, +) -> Result<()> { + write_batch_atomic_with_root(BatchRoot::Dir(root), entries, before_rename) } #[cfg(not(target_arch = "wasm32"))] -fn write_batch_atomic_with_hook<'a>( +fn write_batch_atomic_with_root<'a>( + root: BatchRoot<'_>, entries: impl IntoIterator, mut before_rename: impl FnMut(usize, &std::path::Path) -> std::io::Result<()>, ) -> Result<()> { - use std::io::Write; - // Serialize in-process batch publications so concurrent tasks cannot interleave backups/rollbacks. static BATCH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); let _guard = BATCH_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -223,16 +403,16 @@ fn write_batch_atomic_with_hook<'a>( let mut staged: Vec<(std::path::PathBuf, &std::path::Path, &[u8])> = Vec::with_capacity(entries.len()); let cleanup_staged = |staged: &[(std::path::PathBuf, &std::path::Path, &[u8])]| { for (temp_path, _, _) in staged { - let _ = std::fs::remove_file(temp_path); + let _ = root.remove_file(temp_path); } }; for (path, bytes) in entries { - if path.is_dir() { + if root.is_dir(path) { cleanup_staged(&staged); return Err(FormatError::Io(std::io::Error::other(format!("{} is a directory", path.display())))); } - let (temporary_path, mut file) = match create_temp_with_mode(path, &reserved, None) { + let (temporary_path, mut file) = match create_temp_with_mode(root, path, &reserved, None) { Ok(pair) => pair, Err(error) => { cleanup_staged(&staged); @@ -240,10 +420,10 @@ fn write_batch_atomic_with_hook<'a>( } }; reserved.insert(temporary_path.clone()); - let write_result = file.write_all(bytes).and_then(|_| file.sync_all()); + let write_result = file.write_and_sync(bytes); drop(file); if let Err(error) = write_result { - let _ = std::fs::remove_file(&temporary_path); + let _ = root.remove_file(&temporary_path); cleanup_staged(&staged); return Err(error.into()); } @@ -253,8 +433,8 @@ fn write_batch_atomic_with_hook<'a>( // Single-file writes have no earlier publications to roll back, so rename directly. if staged.len() == 1 { let (ref temporary_path, target_path, _) = staged[0]; - if let Err(error) = before_rename(0, target_path).and_then(|()| std::fs::rename(temporary_path, target_path)) { - let _ = std::fs::remove_file(temporary_path); + if let Err(error) = before_rename(0, target_path).and_then(|()| root.rename(temporary_path, target_path)) { + let _ = root.remove_file(temporary_path); return Err(error.into()); } return Ok(()); @@ -268,7 +448,7 @@ fn write_batch_atomic_with_hook<'a>( let mut incomplete = Vec::new(); for (target_path, expected_bytes, backup) in published.drain(..).rev() { // Do not overwrite if an external writer modified the target after we published it. - if !target_matches_bytes(target_path, expected_bytes) { + if !root.target_matches_bytes(target_path, expected_bytes) { if let Some(RollbackBackup::File(backup_path)) = backup { incomplete.push(format!("{} (modified by another writer; backup at {})", target_path.display(), backup_path.display())); } else { @@ -278,18 +458,18 @@ fn write_batch_atomic_with_hook<'a>( } match backup { Some(RollbackBackup::File(backup_path)) => { - if let Err(err) = std::fs::rename(&backup_path, target_path) { + if let Err(err) = root.rename(&backup_path, target_path) { incomplete.push(format!("{} (backup at {}): {err}", target_path.display(), backup_path.display())); } } #[cfg(unix)] Some(RollbackBackup::Symlink(link_target)) => { - if let Err(err) = std::fs::remove_file(target_path).and_then(|()| std::os::unix::fs::symlink(&link_target, target_path)) { + if let Err(err) = root.restore_symlink(&link_target, target_path) { incomplete.push(format!("{} (symlink -> {}): {err}", target_path.display(), link_target.display())); } } None => { - if let Err(err) = std::fs::remove_file(target_path) { + if let Err(err) = root.remove_file(target_path) { incomplete.push(format!("{}: {err}", target_path.display())); } } @@ -309,44 +489,14 @@ fn write_batch_atomic_with_hook<'a>( if let Err(error) = before_rename(index, target_path) { return Err(rollback(&mut published, &staged[index..], error)); } - let backup = match std::fs::symlink_metadata(target_path) { - Ok(meta) => { - #[cfg(unix)] - if meta.file_type().is_symlink() { - match std::fs::read_link(target_path) { - Ok(link_target) => Some(RollbackBackup::Symlink(link_target)), - Err(error) => return Err(rollback(&mut published, &staged[index..], error)), - } - } else if !meta.file_type().is_file() { - return Err(rollback(&mut published, &staged[index..], std::io::Error::other(format!("{} is not a regular file", target_path.display())))); - } else { - match stage_file_backup(target_path, &meta, &mut reserved) { - Ok(path) => Some(RollbackBackup::File(path)), - Err(error) => return Err(rollback(&mut published, &staged[index..], error)), - } - } - #[cfg(not(unix))] - { - if !meta.file_type().is_file() { - return Err(rollback( - &mut published, - &staged[index..], - std::io::Error::other(format!("{} is not a regular file", target_path.display())), - )); - } - match stage_file_backup(target_path, &meta, &mut reserved) { - Ok(path) => Some(RollbackBackup::File(path)), - Err(error) => return Err(rollback(&mut published, &staged[index..], error)), - } - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + let backup = match root.prepare_backup(target_path, &mut reserved) { + Ok(backup) => backup, Err(error) => return Err(rollback(&mut published, &staged[index..], error)), }; - if let Err(error) = std::fs::rename(&staged[index].0, target_path) { + if let Err(error) = root.rename(&staged[index].0, target_path) { if let Some(RollbackBackup::File(ref backup_path)) = backup { - let _ = std::fs::remove_file(backup_path); + let _ = root.remove_file(backup_path); } return Err(rollback(&mut published, &staged[index..], error)); } @@ -355,36 +505,13 @@ fn write_batch_atomic_with_hook<'a>( for (_, _, backup) in published { if let Some(RollbackBackup::File(backup_path)) = backup { - let _ = std::fs::remove_file(backup_path); + let _ = root.remove_file(&backup_path); } } Ok(()) } -#[cfg(not(target_arch = "wasm32"))] -fn stage_file_backup( - target_path: &std::path::Path, - meta: &std::fs::Metadata, - reserved: &mut std::collections::HashSet, -) -> std::io::Result { - let (backup_path, mut backup_file) = create_temp_with_mode(target_path, reserved, Some(0o600)).map_err(|e| std::io::Error::other(e.to_string()))?; - reserved.insert(backup_path.clone()); - let copy_result = (|| -> std::io::Result<()> { - let mut src = std::fs::File::open(target_path)?; - std::io::copy(&mut src, &mut backup_file)?; - backup_file.set_permissions(meta.permissions())?; - backup_file.sync_all()?; - Ok(()) - })(); - drop(backup_file); - if let Err(error) = copy_result { - let _ = std::fs::remove_file(&backup_path); - return Err(error); - } - Ok(backup_path) -} - #[cfg(test)] mod batch_atomic_tests { use super::{write_batch_atomic, write_batch_atomic_with_hook}; @@ -458,7 +585,7 @@ mod batch_atomic_tests { #[cfg(all(test, unix))] mod atomic_tests { - use super::{write_atomic, write_batch_atomic_with_hook}; + use super::{write_atomic, write_batch_atomic_in_dir_with_hook, write_batch_atomic_with_hook}; #[test] fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> { @@ -504,4 +631,34 @@ mod atomic_tests { let _ = std::fs::remove_dir_all(&directory); Ok(()) } + + #[test] + fn write_batch_atomic_in_dir_rejects_parent_replaced_with_symlink_mid_batch() -> std::io::Result<()> { + let base = std::env::temp_dir().join(format!("tc-dir-symlink-race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("out"); + let outside = base.join("outside"); + std::fs::create_dir_all(dir.join("sub"))?; + std::fs::create_dir_all(&outside)?; + + let root_dir = cap_std::fs::Dir::open_ambient_dir(&dir, cap_std::ambient_authority())?; + let result = write_batch_atomic_in_dir_with_hook( + &root_dir, + [(std::path::Path::new("first.png"), b"first".as_slice()), (std::path::Path::new("sub/second.png"), b"second".as_slice())], + |index, _target| { + if index == 1 { + std::fs::remove_dir(dir.join("sub"))?; + std::os::unix::fs::symlink(&outside, dir.join("sub"))?; + } + Ok(()) + }, + ); + + assert!(result.is_err()); + assert!(!dir.join("first.png").exists()); + assert!(!outside.join("second.png").exists()); + + let _ = std::fs::remove_dir_all(&base); + Ok(()) + } } From 6c72fcb34e241a56aeb4072c5df5d18f1ed6f892 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:22:16 +0700 Subject: [PATCH 3/6] Fix Windows test cfg gate for write_batch_atomic_in_dir_with_hook --- crates/formats/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 03dc8cef..4b22ddba 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -376,7 +376,7 @@ fn write_batch_atomic_with_hook<'a>( write_batch_atomic_with_root(BatchRoot::Ambient, entries, before_rename) } -#[cfg(all(test, not(target_arch = "wasm32")))] +#[cfg(all(test, unix))] pub(crate) fn write_batch_atomic_in_dir_with_hook<'a>( root: &cap_std::fs::Dir, entries: impl IntoIterator, From 0e1d9dfff1e57ab4258bb6e857d82d876cdb99f3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:43:23 +0700 Subject: [PATCH 4/6] Export templates: reject in-tree symlink folder aliases Stage capability-scoped temps in the output root so the mid-batch escape test can actually install a parent symlink, and refuse export folders that are symbolic links so two names cannot resolve to the same file. --- crates/formats/src/export/mod.rs | 28 +++++++++++++++++++++++++--- crates/formats/src/export/tests.rs | 18 ++++++++++++++++++ crates/formats/src/lib.rs | 22 +++++++++++++++++++--- 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 235f261d..f2134a0c 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -1605,13 +1605,35 @@ pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result Result<()> { + let Some(parent) = rel.parent().filter(|parent| !parent.as_os_str().is_empty()) else { + return Ok(()); + }; + + let mut prefix = std::path::PathBuf::new(); + for component in parent.components() { + prefix.push(component); + match root.symlink_metadata(&prefix) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(FormatError::Invalid(format!("\"{}\" cannot use a symbolic link as a folder", rel.display()))); + } + Ok(meta) if meta.file_type().is_dir() => {} + Ok(_) => return Err(FormatError::Invalid(format!("\"{}\" cannot use an existing file as a folder", rel.display()))), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => root.create_dir(&prefix)?, + Err(error) => return Err(error.into()), + } + } + Ok(()) +} + #[cfg(test)] mod tests; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 41c81f71..45ef06cb 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1541,3 +1541,21 @@ fn folder_templates_reject_symlink_escapes_before_creating_subfolders() { std::fs::remove_dir_all(&base).unwrap(); } + +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[test] +fn folder_templates_reject_in_tree_symlink_aliases() { + let fx = Fx::new(&default_channels()); + let files = fx.render_preset("Unreal Engine (Packed)"); + let dir = std::env::temp_dir().join(format!("tc-formats-symlink-alias-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("a")).unwrap(); + std::os::unix::fs::symlink(dir.join("a"), dir.join("b")).unwrap(); + + let one = ExportedFile { name: "a/map.png".into(), ..files[0].clone() }; + let two = ExportedFile { name: "b/map.png".into(), ..files[1].clone() }; + assert!(write_files(&[one, two], &dir).is_err()); + assert!(!dir.join("a").join("map.png").exists()); + + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 4b22ddba..7968b2d8 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -316,12 +316,24 @@ fn create_temp_with_mode( excluded: &std::collections::HashSet, unix_mode: Option, ) -> Result<(std::path::PathBuf, BatchFile)> { - let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); - let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out"); - // Bound retries when stale files, batch targets, or concurrent writers occupy candidate names const MAX_TEMP_ATTEMPTS: u32 = 256; + // Capability-scoped writes keep temporary files in the output root so a parent folder that is + // replaced after staging cannot hide the staged file, and so two maps with the same basename + // in different folders do not share a temporary name + let (parent, name) = match root { + BatchRoot::Ambient => { + let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); + let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out").to_owned(); + (parent.to_path_buf(), name) + } + BatchRoot::Dir(_) => { + let name: String = path.iter().map(|part| part.to_string_lossy()).collect::>().join("_"); + (std::path::PathBuf::from("."), if name.is_empty() { "out".into() } else { name }) + } + }; + for attempt in 0..MAX_TEMP_ATTEMPTS { let temporary_path = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id())); if excluded.contains(&temporary_path) { @@ -642,18 +654,22 @@ mod atomic_tests { std::fs::create_dir_all(&outside)?; let root_dir = cap_std::fs::Dir::open_ambient_dir(&dir, cap_std::ambient_authority())?; + let replaced = std::cell::Cell::new(false); let result = write_batch_atomic_in_dir_with_hook( &root_dir, [(std::path::Path::new("first.png"), b"first".as_slice()), (std::path::Path::new("sub/second.png"), b"second".as_slice())], |index, _target| { if index == 1 { + // Temporary files for capability-scoped writes live in the output root, so `sub` is still empty std::fs::remove_dir(dir.join("sub"))?; std::os::unix::fs::symlink(&outside, dir.join("sub"))?; + replaced.set(std::fs::symlink_metadata(dir.join("sub"))?.file_type().is_symlink()); } Ok(()) }, ); + assert!(replaced.get(), "the hook must install the escaping symlink before the second rename"); assert!(result.is_err()); assert!(!dir.join("first.png").exists()); assert!(!outside.join("second.png").exists()); From 77850f6374e334f3c0f419108e1710c8375fb329 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:54:11 +0700 Subject: [PATCH 5/6] Use a short temp name for confined export writes --- crates/formats/src/export/tests.rs | 16 ++++++++++++++++ crates/formats/src/lib.rs | 11 ++++------- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 45ef06cb..392148a1 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1559,3 +1559,19 @@ fn folder_templates_reject_in_tree_symlink_aliases() { std::fs::remove_dir_all(&dir).unwrap(); } + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn write_files_accepts_a_long_nested_folder_and_stem() { + let fx = Fx::new(&default_channels()); + let files = fx.render_preset("Unreal Engine (Packed)"); + let folder = "a".repeat(200); + let stem = "b".repeat(200); + let name = format!("{folder}/{stem}.png"); + let dir = std::env::temp_dir().join(format!("tc-formats-export-long-nested-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let paths = write_files(&[ExportedFile { name: name.clone(), ..files[0].clone() }], &dir).unwrap(); + assert_eq!(paths, [dir.join(&folder).join(format!("{stem}.png"))]); + assert!(paths[0].is_file()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 7968b2d8..a3a8a3f4 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -319,19 +319,16 @@ fn create_temp_with_mode( // Bound retries when stale files, batch targets, or concurrent writers occupy candidate names const MAX_TEMP_ATTEMPTS: u32 = 256; - // Capability-scoped writes keep temporary files in the output root so a parent folder that is - // replaced after staging cannot hide the staged file, and so two maps with the same basename - // in different folders do not share a temporary name + // Capability-scoped writes keep a short temporary name in the output root so a parent folder + // that is replaced after staging cannot hide the staged file, and so a long nested export name + // cannot overflow the filesystem name limit let (parent, name) = match root { BatchRoot::Ambient => { let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out").to_owned(); (parent.to_path_buf(), name) } - BatchRoot::Dir(_) => { - let name: String = path.iter().map(|part| part.to_string_lossy()).collect::>().join("_"); - (std::path::PathBuf::from("."), if name.is_empty() { "out".into() } else { name }) - } + BatchRoot::Dir(_) => (std::path::PathBuf::from("."), "export".into()), }; for attempt in 0..MAX_TEMP_ATTEMPTS { From f9ba93a7bee13d2e096c3049236eecfabc322e43 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:07:53 +0700 Subject: [PATCH 6/6] Give each confined export temp a unique short id A directory-scoped batch previously reused one .export.{pid}.{attempt}.tmp namespace of 256 names for every staging file and backup. Exports larger than that limit, or overwrites of about half as many existing files, failed even when every output path was valid. Each allocation now gets its own short identifier, while the collision retries stay within that namespace. --- crates/formats/src/lib.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a3a8a3f4..a46a6f62 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -321,14 +321,19 @@ fn create_temp_with_mode( // Capability-scoped writes keep a short temporary name in the output root so a parent folder // that is replaced after staging cannot hide the staged file, and so a long nested export name - // cannot overflow the filesystem name limit + // cannot overflow the filesystem name limit. Each allocation gets its own identifier so a large + // batch, including backups of existing files, does not exhaust the shared 256-name retry set let (parent, name) = match root { BatchRoot::Ambient => { let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out").to_owned(); (parent.to_path_buf(), name) } - BatchRoot::Dir(_) => (std::path::PathBuf::from("."), "export".into()), + BatchRoot::Dir(_) => { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + (std::path::PathBuf::from("."), format!("export-{id}")) + } }; for attempt in 0..MAX_TEMP_ATTEMPTS { @@ -674,4 +679,26 @@ mod atomic_tests { let _ = std::fs::remove_dir_all(&base); Ok(()) } + + #[test] + fn write_batch_atomic_in_dir_can_stage_more_files_than_the_collision_retry_limit() -> std::io::Result<()> { + let directory = std::env::temp_dir().join(format!("tc-dir-many-temps-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&directory); + std::fs::create_dir_all(&directory)?; + let names: Vec = (0..257).map(|i| std::path::PathBuf::from(format!("f{i}.png"))).collect(); + let bytes = vec![b"x".to_vec(); names.len()]; + let entries: Vec<(&std::path::Path, &[u8])> = names.iter().map(std::path::PathBuf::as_path).zip(bytes.iter().map(Vec::as_slice)).collect(); + + let root_dir = cap_std::fs::Dir::open_ambient_dir(&directory, cap_std::ambient_authority())?; + crate::write_batch_atomic_in_dir(&root_dir, entries).map_err(std::io::Error::other)?; + assert!(names.iter().all(|name| directory.join(name).is_file())); + + let bytes = vec![b"y".to_vec(); names.len()]; + let entries: Vec<(&std::path::Path, &[u8])> = names.iter().map(std::path::PathBuf::as_path).zip(bytes.iter().map(Vec::as_slice)).collect(); + crate::write_batch_atomic_in_dir(&root_dir, entries).map_err(std::io::Error::other)?; + assert!(names.iter().all(|name| std::fs::read(directory.join(name)).ok() == Some(b"y".to_vec()))); + + let _ = std::fs::remove_dir_all(&directory); + Ok(()) + } }