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
22 changes: 17 additions & 5 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -535,9 +535,24 @@ private static void WriteFileAtomically(string inputPath, string outputPath, Act
{
dir = ".";
}
string tempPath = Path.Combine(dir, $".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp");
// Checked here, because creating the temporary folder would also create the missing ones above it.
if (!Directory.Exists(dir))
{
throw new DirectoryNotFoundException($"The output folder '{dir}' does not exist.");
}
// The temporary file has the output's own name in a folder of its own: IFC writes that name into its header.
string tempFolder = Path.Combine(dir, $".{Guid.NewGuid():N}.tmp");
string tempPath = Path.Combine(tempFolder, Path.GetFileName(fullPath));
Directory.CreateDirectory(tempFolder);
try
{
// The umask applies to the new folder and can leave even its owner unable to create a file in it.
if (!OperatingSystem.IsWindows())
{
const UnixFileMode ownerRights = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
UnixFileMode mode = File.GetUnixFileMode(tempFolder);
if ((mode & ownerRights) != ownerRights) File.SetUnixFileMode(tempFolder, mode | ownerRights);
}
writeAction(tempPath);
if (AreSameFile(inputPath, outputPath))
{
Expand All @@ -547,10 +562,7 @@ private static void WriteFileAtomically(string inputPath, string outputPath, Act
}
finally
{
if (File.Exists(tempPath))
{
try { File.Delete(tempPath); } catch { /* ignore temp cleanup error */ }
}
try { Directory.Delete(tempFolder, recursive: true); } catch { /* ignore temp cleanup error */ }
}
}

Expand Down
42 changes: 42 additions & 0 deletions tests/TdbIO.Tests/CliTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,48 @@ public void Export_ToIfcHtmlAndSceneJson_Succeeds()
Assert.StartsWith("ISO-10303-21;", stdoutIfc);
}

[Fact]
public void Export_IfcHeaderNamesTheOutputFile()
{
string input = File("header.db1", Gzip(Db1TablesPayload(Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2)))));
string folder = Directory.CreateDirectory(Path.Combine(_folder, "out")).FullName;
string output = Path.Combine(folder, "building.ifc");

var (exit, _, err) = Run("export", input, output);
Assert.Equal(Cli.ExitOk, exit);
Assert.Empty(err);
Assert.Contains("FILE_NAME('building.ifc',", System.IO.File.ReadAllText(output));
// Nothing of the temporary write stays next to the output.
Assert.Equal(output, Assert.Single(Directory.GetFileSystemEntries(folder)));
}

[Fact]
public void Export_IntoAMissingFolderIsAnInputErrorAndCreatesNothing()
{
string input = File("header.db1", Gzip(Db1TablesPayload(Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2)))));
string folder = Path.Combine(_folder, "missing");

var (exit, _, err) = Run("export", input, Path.Combine(folder, "building.ifc"));
Assert.Equal(Cli.ExitInput, exit);
Assert.Contains(folder, err);
Assert.False(Directory.Exists(folder));
}

[Fact]
public void Export_ThatCannotReplaceItsOutputLeavesNothingBehind()
{
string input = File("header.db1", Gzip(Db1TablesPayload(Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2)))));
string folder = Directory.CreateDirectory(Path.Combine(_folder, "out")).FullName;
// A folder stands where the output goes: the temporary file is written and then cannot be moved there.
string output = Directory.CreateDirectory(Path.Combine(folder, "taken.ifc")).FullName;

var (exit, _, err) = Run("export", input, output);
Assert.Equal(Cli.ExitInput, exit);
Assert.NotEmpty(err);
Assert.Equal(output, Assert.Single(Directory.GetFileSystemEntries(folder)));
Assert.Empty(Directory.GetFileSystemEntries(output));
}

[Fact]
public void Export_RejectsOutputPathIdenticalToInputFile()
{
Expand Down
53 changes: 53 additions & 0 deletions tests/TdbIO.Tests/CliUmaskTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Runtime.InteropServices;
using TdbIO.CommandLine;
using Xunit;
using static TdbIO.Tests.Synthetic;

namespace TdbIO.Tests;

/// <summary>For tests that change the umask. It belongs to the whole process, so no other test runs beside them.</summary>
[CollectionDefinition(nameof(ProcessUmask), DisableParallelization = true)]
public sealed class ProcessUmask
{
}

/// <summary>The <c>tdbio</c> command line under a umask that restricts what it creates.</summary>
[Collection(nameof(ProcessUmask))]
public sealed class CliUmaskTests
{
[DllImport("libc", EntryPoint = "umask")]
private static extern int SetUmask(int mask);

[Fact]
public void Export_WritesTheFileUnderAUmaskThatClosesNewFoldersToTheirOwner()
{
if (OperatingSystem.IsWindows()) return; // Windows has no umask.
string root = Directory.CreateTempSubdirectory("tdbio-umask-").FullName;
try
{
string input = Path.Combine(root, "header.db1");
File.WriteAllBytes(input, Gzip(Db1TablesPayload(Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2)))));
string folder = Directory.CreateDirectory(Path.Combine(root, "out")).FullName;
string output = Path.Combine(folder, "building.ifc");
var stderr = new StringWriter();

int previous = SetUmask(Convert.ToInt32("177", 8));
int exit;
try
{
exit = Cli.Run(["export", input, output], new StringWriter(), stderr);
}
finally
{
SetUmask(previous);
}

Assert.True(exit == Cli.ExitOk, stderr.ToString());
Assert.Equal(output, Assert.Single(Directory.GetFileSystemEntries(folder)));
}
finally
{
Directory.Delete(root, recursive: true);
}
}
}
Loading