diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index 9d65583..f2e48aa 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -47,7 +47,7 @@ private static int Main(string[] args) } catch (Exception ex) { - Console.Error.WriteLine($"unexpected error: {ex}"); + Console.Error.WriteLine($"unexpected error: {ex.Message}"); return ExitParseError; } } diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 3c3c448..87fa187 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -92,6 +92,21 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Best-effort parse failures collected while opening (section name → message). public IReadOnlyList Diagnostics { get; } = []; + /// Creates an in-memory document over a file header and a fixed entity list (tests). + internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities) + { + Path = path; + _fileBytes = []; + FileHeader = fileHeader; + Version = fileHeader.Version; + Sections = []; + Diagnostics = _diagnostics; + Entities = entities; + } + + /// Records a non-fatal problem found after the document was opened (e.g. by an exporter). + internal void ReportDiagnostic(string message) => _diagnostics.Add(message); + /// Opens and parses a DWG file. /// The file does not exist. /// The file's container is not implemented yet diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index ae2e3fd..ca2ab32 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -1,3 +1,4 @@ +using System.Security.AccessControl; using System.Text.Json; namespace DwgIO.Json; @@ -143,12 +144,26 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio if (entity.Geometry is { } geometry) { writer.WriteStartArray("geometry"); + int nonFiniteValues = 0; foreach (var value in geometry) { - writer.WriteNumberValue(Math.Round(value, 6)); + if (double.IsFinite(value)) + { + writer.WriteNumberValue(Math.Round(value, 6)); + } + else + { + writer.WriteNullValue(); + nonFiniteValues++; + } } writer.WriteEndArray(); + if (nonFiniteValues > 0) + { + document.ReportDiagnostic( + $"entity {entity.Handle:X}: {nonFiniteValues} non-finite geometry value(s) written as null"); + } } if (entity.ColorIndex != 0) @@ -196,8 +211,131 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio /// Writes as JSON to a new file at . public static void WriteFile(DwgDocument document, string path, DwgJsonExportOptions options) { - using var stream = File.Create(path); - Write(document, stream, options); + var fullPath = Path.GetFullPath(path); + var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); + + // Preserve the destination's access rights across the atomic replace: a fresh + // temporary file inherits the directory ACL, which may be more permissive than + // the file being overwritten. Copy the existing rights onto the temporary file + // before any JSON bytes are written; the same-directory move preserves them. + // Reading or applying the rights is mandatory: failures abort the export + // before the destination is touched, instead of silently widening access. + FileSecurity? savedWindowsAcl = null; + UnixFileMode? savedUnixMode = null; + bool destinationExists = File.Exists(fullPath); + if (destinationExists) + { + if (OperatingSystem.IsWindows()) + { + try + { + savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); + } + catch (PlatformNotSupportedException) + { + savedWindowsAcl = null; + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + try + { + savedUnixMode = File.GetUnixFileMode(fullPath); + } + catch (PlatformNotSupportedException) + { + savedUnixMode = null; + } + } + } + + try + { + // Create the temporary file empty first so its rights can be tightened + // before any document content hits the disk. + using (var _ = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + } + + ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); + + using (var stream = new FileStream(tempPath, FileMode.Truncate, FileAccess.Write, FileShare.None)) + { + Write(document, stream, options); + } + + File.Move(tempPath, fullPath, overwrite: true); + } + catch + { + TryDelete(tempPath); + throw; + } + } + + private static void ApplyTempSecurity( + string filePath, + FileSecurity? windowsAcl, + UnixFileMode? unixMode, + bool destinationExists) + { + if (!destinationExists) + { + return; + } + + if (OperatingSystem.IsWindows()) + { + if (windowsAcl is null) + { + return; + } + + // Copy only the DACL and its protection flag. Persisting the whole + // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, + // when unmodified, persists nothing — the temporary file would keep + // the directory's inherited rules. + new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); + return; + } + + if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + if (unixMode.HasValue) + { + File.SetUnixFileMode(filePath, unixMode.Value); + } + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static FileSecurity CloneDacl(FileSecurity source) + { + var clone = new FileSecurity(); + clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); + foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) + { + clone.AddAccessRule(rule); + } + + return clone; + } + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } } private static bool IsIncluded(DwgDocument document, string name, DwgJsonExportOptions options) => diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs new file mode 100644 index 0000000..7ab59d9 --- /dev/null +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -0,0 +1,247 @@ +using System.Text.Json; +using DwgIO.Json; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +public class JsonExporterTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgEntity CreateEntity(double[] geometry) => + new() + { + Handle = 0x2A, + TypeCode = 0x04, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = geometry, + }; + + [Fact] + public void Write_NonFiniteGeometry_WritesNullAndRecordsDiagnostic() + { + var document = CreateDocument(CreateEntity( + [double.NaN, double.PositiveInfinity, 1.5, double.NegativeInfinity, -2.25, 0.0])); + + using var stream = new MemoryStream(); + DwgJsonExporter.Write(document, stream, DwgJsonExportOptions.Default); + + using var json = JsonDocument.Parse(stream.ToArray()); + var geometry = json.RootElement.GetProperty("entities")[0].GetProperty("geometry"); + Assert.Equal(JsonValueKind.Null, geometry[0].ValueKind); + Assert.Equal(JsonValueKind.Null, geometry[1].ValueKind); + Assert.Equal(1.5, geometry[2].GetDouble()); + Assert.Equal(JsonValueKind.Null, geometry[3].ValueKind); + Assert.Equal(-2.25, geometry[4].GetDouble()); + Assert.Equal(0.0, geometry[5].GetDouble()); + Assert.Contains(document.Diagnostics, d => d.StartsWith("entity 2A:", StringComparison.Ordinal)); + } + + [Fact] + public void Write_FiniteGeometry_RoundsWithoutDiagnostics() + { + var document = CreateDocument(CreateEntity([1.12345678, 2.0, 3.0, 4.0, 5.0, 6.0])); + + using var stream = new MemoryStream(); + DwgJsonExporter.Write(document, stream, DwgJsonExportOptions.Default); + + using var json = JsonDocument.Parse(stream.ToArray()); + var geometry = json.RootElement.GetProperty("entities")[0].GetProperty("geometry"); + Assert.Equal(1.123457, geometry[0].GetDouble()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void WriteFile_WritesFileAndLeavesNoTemporaryFile() + { + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var target = Path.Combine(directory, "out.json"); + + DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default); + + Assert.True(File.Exists(target)); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + using var json = JsonDocument.Parse(File.ReadAllBytes(target)); + Assert.Equal(1, json.RootElement.GetProperty("entityCount").GetInt32()); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WriteFile_Overwrite_PreservesExistingAccessRules(bool denyAclChanges) + { + if (!OperatingSystem.IsWindows()) + { + return; + } + + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var target = Path.Combine(directory, "out.json"); + DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default); + + var acl = new FileInfo(target).GetAccessControl(); + acl.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + System.Security.Principal.WindowsIdentity.GetCurrent().User!, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); + if (denyAclChanges) + { + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + System.Security.Principal.WindowsIdentity.GetCurrent().User!, + System.Security.AccessControl.FileSystemRights.ChangePermissions, + System.Security.AccessControl.AccessControlType.Deny)); + // OWNER RIGHTS suppresses the owner's implicit permission to change the ACL. + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + new System.Security.Principal.SecurityIdentifier("S-1-3-4"), + System.Security.AccessControl.FileSystemRights.ReadPermissions, + System.Security.AccessControl.AccessControlType.Allow)); + } + + new FileInfo(target).SetAccessControl(acl); + var expectedAcl = new FileInfo(target).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access); + + DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default); + + Assert.Equal(expectedAcl, new FileInfo(target).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access)); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + using var json = JsonDocument.Parse(File.ReadAllBytes(target)); + Assert.Equal(1, json.RootElement.GetProperty("entityCount").GetInt32()); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void WriteFile_UnreadableAcl_AbortsWithoutReplacing() + { + if (!OperatingSystem.IsWindows()) + { + return; + } + + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + var target = Path.Combine(directory, "out.json"); + File.WriteAllText(target, "KEEP ORIGINAL"); + var fileInfo = new FileInfo(target); + + var deny = new System.Security.AccessControl.FileSecurity(); + deny.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + var user = System.Security.Principal.WindowsIdentity.GetCurrent().User!; + deny.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + user, + System.Security.AccessControl.FileSystemRights.ReadPermissions, + System.Security.AccessControl.AccessControlType.Deny)); + deny.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + user, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); + deny.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + new System.Security.Principal.SecurityIdentifier("S-1-3-4"), + System.Security.AccessControl.FileSystemRights.ChangePermissions, + System.Security.AccessControl.AccessControlType.Allow)); + fileInfo.SetAccessControl(deny); + + try + { + bool readDenied; + try + { + fileInfo.GetAccessControl(); + readDenied = false; + } + catch (UnauthorizedAccessException) + { + readDenied = true; + } + + Assert.True(readDenied, "probe invalid: reading the ACL was not denied"); + + var exception = Record.Exception(() => DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default)); + + Assert.NotNull(exception); + Assert.True(exception is UnauthorizedAccessException or IOException, exception.ToString()); + // READ_CONTROL is denied, so contents cannot be opened for reading + // (GENERIC_READ includes READ_CONTROL); the directory-reported length + // still proves the original 13-byte file was not replaced. + Assert.Equal(13, new FileInfo(target).Length); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + } + finally + { + // The deny ACL blocks READ_CONTROL, so it cannot be restored in-process; + // deleting only needs DELETE, which FullControl still allows. + try + { + File.Delete(target); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void WriteFile_FailedMove_LeavesNoTargetFileOrTemporaryFile() + { + var document = CreateDocument(CreateEntity([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])); + var directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var target = Path.Combine(directory, "out.json"); + // A directory at the target path makes the final move fail after the temporary file was written. + Directory.CreateDirectory(target); + + var exception = Record.Exception(() => DwgJsonExporter.WriteFile(document, target, DwgJsonExportOptions.Default)); + + Assert.NotNull(exception); + Assert.True(exception is IOException or UnauthorizedAccessException, exception.ToString()); + Assert.False(File.Exists(target)); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } +}