Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/DwgIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
15 changes: 15 additions & 0 deletions src/DwgIO/DwgDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,21 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20
/// <summary>Best-effort parse failures collected while opening (section name → message).</summary>
public IReadOnlyList<string> Diagnostics { get; } = [];

/// <summary>Creates an in-memory document over a file header and a fixed entity list (tests).</summary>
internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList<DwgEntity> entities)
{
Path = path;
_fileBytes = [];
FileHeader = fileHeader;
Version = fileHeader.Version;
Sections = [];
Diagnostics = _diagnostics;
Entities = entities;
}

/// <summary>Records a non-fatal problem found after the document was opened (e.g. by an exporter).</summary>
internal void ReportDiagnostic(string message) => _diagnostics.Add(message);

/// <summary>Opens and parses a DWG file.</summary>
/// <exception cref="FileNotFoundException">The file does not exist.</exception>
/// <exception cref="DwgUnsupportedVersionException">The file's container is not implemented yet
Expand Down
144 changes: 141 additions & 3 deletions src/DwgIO/Json/DwgJsonExporter.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Security.AccessControl;
using System.Text.Json;

namespace DwgIO.Json;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -196,8 +211,131 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio
/// <summary>Writes <paramref name="document"/> as JSON to a new file at <paramref name="path"/>.</summary>
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) =>
Expand Down
Loading
Loading