504 lines
16 KiB
PowerShell
504 lines
16 KiB
PowerShell
function Assert-DxNoReparsePath {
|
|
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$Value,
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$Name
|
|
)
|
|
|
|
$absolute = [IO.Path]::GetFullPath($Value)
|
|
$driveRoot = [IO.Path]::GetPathRoot($absolute)
|
|
if ([string]::IsNullOrWhiteSpace($driveRoot) -or
|
|
$driveRoot -notmatch '^[A-Za-z]:\\$') {
|
|
throw "$Name must use a local drive: $absolute"
|
|
}
|
|
|
|
$current = $driveRoot
|
|
$remaining = $absolute.Substring($driveRoot.Length)
|
|
$parts = $remaining.Split(
|
|
[char[]]@('\', '/'),
|
|
[StringSplitOptions]::RemoveEmptyEntries
|
|
)
|
|
foreach ($part in $parts) {
|
|
$current = Join-Path $current $part
|
|
try {
|
|
$attributes = [IO.File]::GetAttributes($current)
|
|
}
|
|
catch {
|
|
$pathFailure = $_.Exception
|
|
while ($null -ne $pathFailure.InnerException) {
|
|
$pathFailure = $pathFailure.InnerException
|
|
}
|
|
if ($pathFailure -is [IO.FileNotFoundException] -or
|
|
$pathFailure -is [IO.DirectoryNotFoundException]) {
|
|
return
|
|
}
|
|
throw "$Name cannot be validated at: $current"
|
|
}
|
|
if (($attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
|
|
throw "$Name contains a reparse point: $current"
|
|
}
|
|
}
|
|
}
|
|
|
|
if (-not ("DxProductivity.PathSafetyNative" -as [type])) {
|
|
Add-Type -TypeDefinition @'
|
|
using System;
|
|
using System.ComponentModel;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
|
|
namespace DxProductivity
|
|
{
|
|
public static class PathSafetyNative
|
|
{
|
|
private const uint FileReadAttributes = 0x00000080;
|
|
private const uint GenericRead = 0x80000000;
|
|
private const uint GenericWrite = 0x40000000;
|
|
private const uint DeleteAccess = 0x00010000;
|
|
private const uint FileShareRead = 0x00000001;
|
|
private const uint FileShareWrite = 0x00000002;
|
|
private const uint FileShareDelete = 0x00000004;
|
|
private const uint CreateNew = 1;
|
|
private const uint OpenExisting = 3;
|
|
private const uint FileAttributeNormal = 0x00000080;
|
|
private const uint FileFlagBackupSemantics = 0x02000000;
|
|
private const uint FileFlagOpenReparsePoint = 0x00200000;
|
|
private const int FileDispositionInfo = 4;
|
|
private const int NativeFileRenameInformation = 10;
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct IoStatusBlock
|
|
{
|
|
public IntPtr Status;
|
|
public UIntPtr Information;
|
|
}
|
|
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
private static extern IntPtr CreateFile(
|
|
string fileName,
|
|
uint desiredAccess,
|
|
uint shareMode,
|
|
IntPtr securityAttributes,
|
|
uint creationDisposition,
|
|
uint flagsAndAttributes,
|
|
IntPtr templateFile
|
|
);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
public static extern bool CloseHandle(IntPtr handle);
|
|
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
private static extern uint GetFinalPathNameByHandle(
|
|
IntPtr handle,
|
|
StringBuilder path,
|
|
uint pathLength,
|
|
uint flags
|
|
);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
private static extern bool WriteFile(
|
|
IntPtr handle,
|
|
byte[] buffer,
|
|
uint bytesToWrite,
|
|
out uint bytesWritten,
|
|
IntPtr overlapped
|
|
);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
private static extern bool FlushFileBuffers(IntPtr handle);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
private static extern bool SetFileInformationByHandle(
|
|
IntPtr handle,
|
|
int informationClass,
|
|
IntPtr information,
|
|
uint bufferSize
|
|
);
|
|
|
|
[DllImport("ntdll.dll")]
|
|
private static extern int NtSetInformationFile(
|
|
IntPtr handle,
|
|
out IoStatusBlock ioStatus,
|
|
IntPtr information,
|
|
uint length,
|
|
int informationClass
|
|
);
|
|
|
|
[DllImport("ntdll.dll")]
|
|
private static extern uint RtlNtStatusToDosError(int status);
|
|
|
|
public static IntPtr OpenDirectory(string path, bool denyRename)
|
|
{
|
|
uint access = FileReadAttributes;
|
|
if (denyRename)
|
|
{
|
|
access |= DeleteAccess;
|
|
}
|
|
return CreateFile(
|
|
path,
|
|
access,
|
|
FileShareRead | FileShareWrite,
|
|
IntPtr.Zero,
|
|
OpenExisting,
|
|
FileFlagBackupSemantics | FileFlagOpenReparsePoint,
|
|
IntPtr.Zero
|
|
);
|
|
}
|
|
|
|
public static IntPtr OpenStagedFile(string path)
|
|
{
|
|
IntPtr handle = CreateFile(
|
|
path,
|
|
GenericRead | GenericWrite | DeleteAccess,
|
|
FileShareRead | FileShareDelete,
|
|
IntPtr.Zero,
|
|
CreateNew,
|
|
FileAttributeNormal,
|
|
IntPtr.Zero
|
|
);
|
|
if (handle == new IntPtr(-1))
|
|
{
|
|
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
}
|
|
return handle;
|
|
}
|
|
|
|
public static void WriteStagedFile(IntPtr handle, byte[] bytes)
|
|
{
|
|
if (bytes.LongLength > UInt32.MaxValue)
|
|
{
|
|
throw new IOException("Atomic publication payload is too large");
|
|
}
|
|
uint written;
|
|
if (!WriteFile(handle, bytes, (uint)bytes.Length, out written,
|
|
IntPtr.Zero))
|
|
{
|
|
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
}
|
|
if (written != bytes.Length)
|
|
{
|
|
throw new IOException("Atomic publication staging write was incomplete");
|
|
}
|
|
if (!FlushFileBuffers(handle))
|
|
{
|
|
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
}
|
|
}
|
|
|
|
public static void PublishStagedFile(
|
|
IntPtr stagedHandle,
|
|
IntPtr parentHandle,
|
|
string destinationName
|
|
)
|
|
{
|
|
if (String.IsNullOrEmpty(destinationName) ||
|
|
destinationName == "." || destinationName == ".." ||
|
|
destinationName.IndexOf('\\') >= 0 ||
|
|
destinationName.IndexOf('/') >= 0)
|
|
{
|
|
throw new ArgumentException("Invalid atomic publication name");
|
|
}
|
|
byte[] name = Encoding.Unicode.GetBytes(destinationName);
|
|
int pointerSize = IntPtr.Size;
|
|
int rootOffset = (sizeof(uint) + pointerSize - 1) & -pointerSize;
|
|
int lengthOffset = rootOffset + pointerSize;
|
|
int nameOffset = lengthOffset + sizeof(uint);
|
|
int bufferSize = nameOffset + name.Length + sizeof(char);
|
|
IntPtr information = Marshal.AllocHGlobal(bufferSize);
|
|
try
|
|
{
|
|
for (int index = 0; index < bufferSize; index++)
|
|
{
|
|
Marshal.WriteByte(information, index, 0);
|
|
}
|
|
Marshal.WriteByte(information, 0, 1);
|
|
Marshal.WriteIntPtr(information, rootOffset, parentHandle);
|
|
Marshal.WriteInt32(information, lengthOffset, name.Length);
|
|
Marshal.Copy(name, 0, IntPtr.Add(information, nameOffset),
|
|
name.Length);
|
|
IoStatusBlock ioStatus;
|
|
int status = NtSetInformationFile(
|
|
stagedHandle,
|
|
out ioStatus,
|
|
information,
|
|
(uint)bufferSize,
|
|
NativeFileRenameInformation
|
|
);
|
|
if (status < 0)
|
|
{
|
|
throw new Win32Exception(
|
|
(int)RtlNtStatusToDosError(status)
|
|
);
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
Marshal.FreeHGlobal(information);
|
|
}
|
|
}
|
|
|
|
public static void DeleteStagedFile(IntPtr stagedHandle)
|
|
{
|
|
IntPtr disposition = Marshal.AllocHGlobal(1);
|
|
try
|
|
{
|
|
Marshal.WriteByte(disposition, 1);
|
|
if (!SetFileInformationByHandle(
|
|
stagedHandle,
|
|
FileDispositionInfo,
|
|
disposition,
|
|
1))
|
|
{
|
|
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
Marshal.FreeHGlobal(disposition);
|
|
}
|
|
}
|
|
|
|
public static string FinalPath(IntPtr handle)
|
|
{
|
|
uint capacity = 512;
|
|
while (true)
|
|
{
|
|
StringBuilder buffer = new StringBuilder((int)capacity);
|
|
uint result = GetFinalPathNameByHandle(
|
|
handle,
|
|
buffer,
|
|
capacity,
|
|
0
|
|
);
|
|
if (result == 0)
|
|
{
|
|
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
}
|
|
if (result < capacity)
|
|
{
|
|
return buffer.ToString();
|
|
}
|
|
capacity = result + 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
'@
|
|
}
|
|
|
|
function Convert-DxHandlePath {
|
|
param([string]$Value)
|
|
$text = $Value
|
|
if ($text.StartsWith("\\?\UNC\", [StringComparison]::OrdinalIgnoreCase)) {
|
|
$text = "\\" + $text.Substring(8)
|
|
}
|
|
elseif ($text.StartsWith("\\?\", [StringComparison]::OrdinalIgnoreCase)) {
|
|
$text = $text.Substring(4)
|
|
}
|
|
return ([IO.Path]::GetFullPath($text)).TrimEnd('\')
|
|
}
|
|
|
|
function Close-DxPublicationLock {
|
|
param([object]$Lock)
|
|
if ($null -eq $Lock) {
|
|
return
|
|
}
|
|
for ($index = $Lock.Handles.Count - 1; $index -ge 0; $index--) {
|
|
[void][DxProductivity.PathSafetyNative]::CloseHandle(
|
|
$Lock.Handles[$index]
|
|
)
|
|
}
|
|
}
|
|
|
|
function Remove-DxStagedIdentity {
|
|
param([IntPtr]$Handle)
|
|
[DxProductivity.PathSafetyNative]::DeleteStagedFile($Handle)
|
|
}
|
|
|
|
function Open-DxDirectoryLock {
|
|
param(
|
|
[string]$Path,
|
|
[bool]$DenyRename,
|
|
[string]$Name
|
|
)
|
|
$handle = [DxProductivity.PathSafetyNative]::OpenDirectory(
|
|
$Path,
|
|
$DenyRename
|
|
)
|
|
if ($handle -eq [IntPtr](-1)) {
|
|
$errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
|
|
throw "$Name cannot lock directory: $Path (Windows error $errorCode)"
|
|
}
|
|
try {
|
|
$expected = ([IO.Path]::GetFullPath($Path)).TrimEnd('\')
|
|
$actual = Convert-DxHandlePath (
|
|
[DxProductivity.PathSafetyNative]::FinalPath($handle)
|
|
)
|
|
if (-not [string]::Equals(
|
|
$expected,
|
|
$actual,
|
|
[StringComparison]::OrdinalIgnoreCase
|
|
)) {
|
|
throw "$Name directory handle resolves outside its lexical path: $Path"
|
|
}
|
|
Assert-DxNoReparsePath $Path $Name
|
|
return $handle
|
|
}
|
|
catch {
|
|
[void][DxProductivity.PathSafetyNative]::CloseHandle($handle)
|
|
throw
|
|
}
|
|
}
|
|
|
|
function Enter-DxPublicationLock {
|
|
param([string]$Destination, [string]$Name)
|
|
$absolute = [IO.Path]::GetFullPath($Destination)
|
|
$directory = Split-Path -Parent $absolute
|
|
$driveRoot = [IO.Path]::GetPathRoot($directory)
|
|
Assert-DxNoReparsePath $absolute $Name
|
|
if ([string]::IsNullOrWhiteSpace($driveRoot) -or
|
|
[string]::Equals(
|
|
$directory.TrimEnd('\'),
|
|
$driveRoot.TrimEnd('\'),
|
|
[StringComparison]::OrdinalIgnoreCase
|
|
)) {
|
|
throw "$Name destination parent must be below a local drive root"
|
|
}
|
|
if (-not (Test-Path -LiteralPath $directory -PathType Container)) {
|
|
throw "$Name destination directory does not exist: $directory"
|
|
}
|
|
|
|
$handles = New-Object 'Collections.Generic.List[IntPtr]'
|
|
$publicationLock = [pscustomobject]@{
|
|
Handles = $handles
|
|
Directory = $directory
|
|
}
|
|
try {
|
|
$current = $driveRoot
|
|
$handles.Add((Open-DxDirectoryLock $current $false $Name))
|
|
$remaining = $directory.Substring($driveRoot.Length)
|
|
$parts = $remaining.Split(
|
|
[char[]]@('\', '/'),
|
|
[StringSplitOptions]::RemoveEmptyEntries
|
|
)
|
|
for ($index = 0; $index -lt $parts.Count; $index++) {
|
|
$current = Join-Path $current $parts[$index]
|
|
$denyRename = $index -eq $parts.Count - 1
|
|
$handles.Add((
|
|
Open-DxDirectoryLock $current $denyRename $Name
|
|
))
|
|
}
|
|
Assert-DxNoReparsePath $absolute $Name
|
|
return $publicationLock
|
|
}
|
|
catch {
|
|
Close-DxPublicationLock $publicationLock
|
|
throw
|
|
}
|
|
}
|
|
|
|
function Write-DxBytesAtomic {
|
|
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$Destination,
|
|
[Parameter(Mandatory = $true)]
|
|
[byte[]]$Bytes,
|
|
[scriptblock]$AfterValidation
|
|
)
|
|
$absolute = [IO.Path]::GetFullPath($Destination)
|
|
$publicationLock = $null
|
|
$temporary = $null
|
|
$stagedHandle = [IntPtr](-1)
|
|
$published = $false
|
|
$primaryError = $null
|
|
$cleanupError = $null
|
|
try {
|
|
$publicationLock = Enter-DxPublicationLock $absolute `
|
|
"atomic publication"
|
|
$temporary = Join-Path $publicationLock.Directory (
|
|
"." + [IO.Path]::GetFileName($absolute) + "." +
|
|
[guid]::NewGuid().ToString("N") + ".tmp"
|
|
)
|
|
$stagedHandle = [DxProductivity.PathSafetyNative]::OpenStagedFile(
|
|
$temporary
|
|
)
|
|
[DxProductivity.PathSafetyNative]::WriteStagedFile(
|
|
$stagedHandle,
|
|
$Bytes
|
|
)
|
|
$expectedTemporary = ([IO.Path]::GetFullPath($temporary)).TrimEnd('\')
|
|
$actualTemporary = Convert-DxHandlePath (
|
|
[DxProductivity.PathSafetyNative]::FinalPath($stagedHandle)
|
|
)
|
|
if (-not [string]::Equals(
|
|
$expectedTemporary,
|
|
$actualTemporary,
|
|
[StringComparison]::OrdinalIgnoreCase
|
|
)) {
|
|
throw "atomic publication staging handle changed identity"
|
|
}
|
|
Assert-DxNoReparsePath $temporary "atomic publication temporary file"
|
|
Assert-DxNoReparsePath $absolute "atomic publication destination"
|
|
if ($null -ne $AfterValidation) {
|
|
& $AfterValidation $absolute $temporary
|
|
}
|
|
$parentHandle = $publicationLock.Handles[
|
|
$publicationLock.Handles.Count - 1
|
|
]
|
|
[DxProductivity.PathSafetyNative]::PublishStagedFile(
|
|
$stagedHandle,
|
|
$parentHandle,
|
|
[IO.Path]::GetFileName($absolute)
|
|
)
|
|
$published = $true
|
|
}
|
|
catch {
|
|
$primaryError = $_.Exception
|
|
}
|
|
finally {
|
|
try {
|
|
if ($stagedHandle -ne [IntPtr](-1) -and -not $published) {
|
|
try {
|
|
Remove-DxStagedIdentity $stagedHandle
|
|
}
|
|
catch {
|
|
$cleanupError = $_.Exception
|
|
}
|
|
}
|
|
}
|
|
finally {
|
|
try {
|
|
if ($stagedHandle -ne [IntPtr](-1)) {
|
|
[void][DxProductivity.PathSafetyNative]::CloseHandle(
|
|
$stagedHandle
|
|
)
|
|
}
|
|
}
|
|
finally {
|
|
Close-DxPublicationLock $publicationLock
|
|
}
|
|
}
|
|
}
|
|
if ($null -ne $primaryError) {
|
|
throw $primaryError
|
|
}
|
|
if ($null -ne $cleanupError) {
|
|
throw $cleanupError
|
|
}
|
|
}
|
|
|
|
function Write-DxUtf8Atomic {
|
|
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$Destination,
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$Text,
|
|
[scriptblock]$AfterValidation
|
|
)
|
|
$utf8 = New-Object Text.UTF8Encoding($false)
|
|
Write-DxBytesAtomic -Destination $Destination -Bytes $utf8.GetBytes($Text) `
|
|
-AfterValidation $AfterValidation
|
|
}
|