using System.Buffers.Binary;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace XFEToolBox.Indexing.Service.Engine;
/// <summary>Read-only bulk NTFS metadata access; never opens file contents or modifies the USN journal.</summary>
internal sealed class NtfsNativeVolume : INtfsMetadataSource
{
// CTL_CODE(FILE_DEVICE_FILE_SYSTEM=9, function=157, METHOD_NEITHER=3, FILE_ANY_ACCESS=0).
private const uint QueryFileLayout = (9u << 16) | (157u << 2) | 3u;
private const uint QueryUsnJournal = 0x000900f4;
private const uint ReadUsnJournal = 0x000900bb;
private readonly SafeFileHandle handle;
private readonly byte[] output = new byte[4 * 1024 * 1024];
public NtfsVolume Volume { get; }
public bool IsOpen => !handle.IsInvalid;
public string? OpenError { get; }
public NtfsNativeVolume(NtfsVolume volume)
{
Volume = volume;
handle = CreateFileW(volume.VolumeId.TrimEnd('\\'), 0x80000000, 7, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!IsOpen)
OpenError = DescribeError(Marshal.GetLastWin32Error());
}
public static NtfsVolume[] GetVolumes()
{
var volumes = new List<NtfsVolume>();
var volumeName = new StringBuilder(1024);
var iterator = FindFirstVolumeW(volumeName, volumeName.Capacity);
if (iterator == new IntPtr(-1))
return [];
try
{
do
{
var id = volumeName.ToString();
// Includes mounted-folder volumes, not only volumes that have a drive letter.
// No-content metadata calls return false rather than throwing for unavailable disks.
if (GetDriveTypeW(id) != 3)
continue;
var fileSystem = new StringBuilder(32);
if (!GetVolumeInformationW(id, null, 0, out var serial, out _, out _, fileSystem, 32)
|| !fileSystem.ToString().Equals("NTFS", StringComparison.OrdinalIgnoreCase))
continue;
var paths = new char[32768];
if (!GetVolumePathNamesForVolumeNameW(id, paths, (uint)paths.Length, out _))
continue;
var roots = new string(paths).Split('\0', StringSplitOptions.RemoveEmptyEntries);
var root = roots.OrderBy(path => path.Length).FirstOrDefault();
if (root is not null)
volumes.Add(new(root, id, serial));
} while (FindNextVolumeW(iterator, volumeName, volumeName.Capacity));
}
finally { FindVolumeClose(iterator); }
return volumes.DistinctBy(volume => volume.VolumeId, StringComparer.OrdinalIgnoreCase).ToArray();
}
public bool TryGetJournal(out NtfsJournal journal, out string? error)
{
journal = default;
if (!Call(QueryUsnJournal, [], out var length, out var code) || length < 56)
{
error = code == 1179 ? "此 NTFS 卷没有 USN 日志;服务不会创建日志,请使用普通扫描。" : DescribeError(code);
return false;
}
journal = new(BinaryPrimitives.ReadUInt64LittleEndian(output),
BinaryPrimitives.ReadInt64LittleEndian(output.AsSpan(8)),
BinaryPrimitives.ReadInt64LittleEndian(output.AsSpan(16)),
BinaryPrimitives.ReadInt64LittleEndian(output.AsSpan(24)));
error = null;
return true;
}
public bool TryEnumerate(Action<NtfsNode[]> accept, CancellationToken token, out string? error)
=> TryLayout(null, accept, token, out error);
public bool TryReadNodes(IReadOnlyList<ulong> ids, Action<NtfsNode[]> accept, CancellationToken token,
out string? error) => TryLayout(ids, accept, token, out error);
private bool TryLayout(IReadOnlyList<ulong>? ids, Action<NtfsNode[]> accept, CancellationToken token,
out string? error)
{
var count = ids?.Count ?? 0;
var input = new byte[Math.Max(32, 16 + 16 * count)];
BinaryPrimitives.WriteUInt32LittleEndian(input, (uint)count);
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(4), 3); // RESTART | INCLUDE_NAMES
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(8), count == 0 ? 0u : 2u); // FILEID filter
for (var index = 0; index < count; index++)
{
BinaryPrimitives.WriteUInt64LittleEndian(input.AsSpan(16 + index * 16), ids![index]);
BinaryPrimitives.WriteUInt64LittleEndian(input.AsSpan(24 + index * 16), ids[index]);
}
while (true)
{
token.ThrowIfCancellationRequested();
var ok = Call(QueryFileLayout, input, out var length, out var code);
if (length >= 16 && (ok || code == 234))
accept(NtfsMetadataParser.ParseLayout(output.AsSpan(0, length)));
if (!ok && code is 38 or 18 or 2)
break;
if (!ok && code != 234)
{
error = code is 1 or 50 or 87
? "系统不支持批量 NTFS 文件布局查询(需要 Windows 10 1809 或更新版本)。"
: DescribeError(code);
return false;
}
if (length < 16 || BinaryPrimitives.ReadUInt32LittleEndian(output) == 0)
break;
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(4), 2); // Continue native cursor.
}
error = null;
return true;
}
public bool TryReadChanges(NtfsJournal journal, long cursor, out long nextUsn,
out NtfsChange[] changes, out string? error)
{
var input = new byte[40];
BinaryPrimitives.WriteInt64LittleEndian(input, cursor);
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(8), uint.MaxValue);
BinaryPrimitives.WriteUInt64LittleEndian(input.AsSpan(32), journal.Id);
// BytesToWaitFor=0: return immediately; there is never a blocking kernel wait to cancel.
if (!Call(ReadUsnJournal, input, out var length, out var code))
{
nextUsn = cursor;
changes = [];
error = code is 1178 or 1181 ? "USN 日志已截断或重建,必须重新建立本卷索引。" : DescribeError(code);
return false;
}
(nextUsn, changes) = NtfsMetadataParser.ParseJournal(output.AsSpan(0, length));
error = null;
return true;
}
private bool Call(uint control, byte[] input, out int length, out int error)
{
using var priority = new NtfsIoPriority();
var success = DeviceIoControl(handle, control, input, input.Length, output, output.Length, out length, IntPtr.Zero);
error = success ? 0 : Marshal.GetLastWin32Error();
return success;
}
private static string DescribeError(int code) => code switch
{
5 => "无法只读访问 NTFS 卷;请确认独立索引服务已由安装程序安装并运行。",
21 => "卷尚未就绪。",
1167 => "卷已断开。",
1178 => "USN 日志正在删除。",
_ => $"NTFS 元数据操作失败(Windows 错误 {code})。"
};
public void Dispose() => handle.Dispose();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security,
uint creation, uint flags, IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeviceIoControl(SafeFileHandle device, uint control, byte[] input, int inputSize,
byte[] output, int outputSize, out int returned, IntPtr overlapped);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetDriveTypeW(string root);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetVolumeInformationW(string root, StringBuilder? name, int nameSize,
out uint serial, out uint maximumComponent, out uint flags, StringBuilder fileSystem, int fileSystemSize);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr FindFirstVolumeW(StringBuilder name, int length);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FindNextVolumeW(IntPtr iterator, StringBuilder name, int length);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FindVolumeClose(IntPtr iterator);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetVolumePathNamesForVolumeNameW(string volumeName, [Out] char[] paths,
uint length, out uint required);
}
using System.Buffers.Binary;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace XFEToolBox.Indexing.Service.Engine;
/// <summary>Read-only bulk NTFS metadata access; never opens file contents or modifies the USN journal.</summary>
internal sealed class NtfsNativeVolume : INtfsMetadataSource
{
// CTL_CODE(FILE_DEVICE_FILE_SYSTEM=9, function=157, METHOD_NEITHER=3, FILE_ANY_ACCESS=0).
private const uint QueryFileLayout = (9u << 16) | (157u << 2) | 3u;
private const uint QueryUsnJournal = 0x000900f4;
private const uint ReadUsnJournal = 0x000900bb;
private readonly SafeFileHandle handle;
private readonly byte[] output = new byte[4 * 1024 * 1024];
public NtfsVolume Volume { get; }
public bool IsOpen => !handle.IsInvalid;
public string? OpenError { get; }
public NtfsNativeVolume(NtfsVolume volume)
{
Volume = volume;
handle = CreateFileW(volume.VolumeId.TrimEnd('\\'), 0x80000000, 7, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!IsOpen)
OpenError = DescribeError(Marshal.GetLastWin32Error());
}
public static NtfsVolume[] GetVolumes()
{
var volumes = new List<NtfsVolume>();
var volumeName = new StringBuilder(1024);
var iterator = FindFirstVolumeW(volumeName, volumeName.Capacity);
if (iterator == new IntPtr(-1))
return [];
try
{
do
{
var id = volumeName.ToString();
// Includes mounted-folder volumes, not only volumes that have a drive letter.
// No-content metadata calls return false rather than throwing for unavailable disks.
if (GetDriveTypeW(id) != 3)
continue;
var fileSystem = new StringBuilder(32);
if (!GetVolumeInformationW(id, null, 0, out var serial, out _, out _, fileSystem, 32)
|| !fileSystem.ToString().Equals("NTFS", StringComparison.OrdinalIgnoreCase))
continue;
var paths = new char[32768];
if (!GetVolumePathNamesForVolumeNameW(id, paths, (uint)paths.Length, out _))
continue;
var roots = new string(paths).Split('\0', StringSplitOptions.RemoveEmptyEntries);
var root = roots.OrderBy(path => path.Length).FirstOrDefault();
if (root is not null)
volumes.Add(new(root, id, serial));
} while (FindNextVolumeW(iterator, volumeName, volumeName.Capacity));
}
finally { FindVolumeClose(iterator); }
return volumes.DistinctBy(volume => volume.VolumeId, StringComparer.OrdinalIgnoreCase).ToArray();
}
public bool TryGetJournal(out NtfsJournal journal, out string? error)
{
journal = default;
if (!Call(QueryUsnJournal, [], out var length, out var code) || length < 56)
{
error = code == 1179 ? "此 NTFS 卷没有 USN 日志;服务不会创建日志,请使用普通扫描。" : DescribeError(code);
return false;
}
journal = new(BinaryPrimitives.ReadUInt64LittleEndian(output),
BinaryPrimitives.ReadInt64LittleEndian(output.AsSpan(8)),
BinaryPrimitives.ReadInt64LittleEndian(output.AsSpan(16)),
BinaryPrimitives.ReadInt64LittleEndian(output.AsSpan(24)));
error = null;
return true;
}
public bool TryEnumerate(Action<NtfsNode[]> accept, CancellationToken token, out string? error)
=> TryLayout(null, accept, token, out error);
public bool TryReadNodes(IReadOnlyList<ulong> ids, Action<NtfsNode[]> accept, CancellationToken token,
out string? error) => TryLayout(ids, accept, token, out error);
private bool TryLayout(IReadOnlyList<ulong>? ids, Action<NtfsNode[]> accept, CancellationToken token,
out string? error)
{
var count = ids?.Count ?? 0;
var input = new byte[Math.Max(32, 16 + 16 * count)];
BinaryPrimitives.WriteUInt32LittleEndian(input, (uint)count);
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(4), 3); // RESTART | INCLUDE_NAMES
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(8), count == 0 ? 0u : 2u); // FILEID filter
for (var index = 0; index < count; index++)
{
BinaryPrimitives.WriteUInt64LittleEndian(input.AsSpan(16 + index * 16), ids![index]);
BinaryPrimitives.WriteUInt64LittleEndian(input.AsSpan(24 + index * 16), ids[index]);
}
while (true)
{
token.ThrowIfCancellationRequested();
var ok = Call(QueryFileLayout, input, out var length, out var code);
if (length >= 16 && (ok || code == 234))
accept(NtfsMetadataParser.ParseLayout(output.AsSpan(0, length)));
if (!ok && code is 38 or 18 or 2)
break;
if (!ok && code != 234)
{
error = code is 1 or 50 or 87
? "系统不支持批量 NTFS 文件布局查询(需要 Windows 10 1809 或更新版本)。"
: DescribeError(code);
return false;
}
if (length < 16 || BinaryPrimitives.ReadUInt32LittleEndian(output) == 0)
break;
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(4), 2); // Continue native cursor.
}
error = null;
return true;
}
public bool TryReadChanges(NtfsJournal journal, long cursor, out long nextUsn,
out NtfsChange[] changes, out string? error)
{
var input = new byte[40];
BinaryPrimitives.WriteInt64LittleEndian(input, cursor);
BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(8), uint.MaxValue);
BinaryPrimitives.WriteUInt64LittleEndian(input.AsSpan(32), journal.Id);
// BytesToWaitFor=0: return immediately; there is never a blocking kernel wait to cancel.
if (!Call(ReadUsnJournal, input, out var length, out var code))
{
nextUsn = cursor;
changes = [];
error = code is 1178 or 1181 ? "USN 日志已截断或重建,必须重新建立本卷索引。" : DescribeError(code);
return false;
}
(nextUsn, changes) = NtfsMetadataParser.ParseJournal(output.AsSpan(0, length));
error = null;
return true;
}
private bool Call(uint control, byte[] input, out int length, out int error)
{
using var priority = new NtfsIoPriority();
var success = DeviceIoControl(handle, control, input, input.Length, output, output.Length, out length, IntPtr.Zero);
error = success ? 0 : Marshal.GetLastWin32Error();
return success;
}
private static string DescribeError(int code) => code switch
{
5 => "无法只读访问 NTFS 卷;请确认独立索引服务已由安装程序安装并运行。",
21 => "卷尚未就绪。",
1167 => "卷已断开。",
1178 => "USN 日志正在删除。",
_ => $"NTFS 元数据操作失败(Windows 错误 {code})。"
};
public void Dispose() => handle.Dispose();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security,
uint creation, uint flags, IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeviceIoControl(SafeFileHandle device, uint control, byte[] input, int inputSize,
byte[] output, int outputSize, out int returned, IntPtr overlapped);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetDriveTypeW(string root);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetVolumeInformationW(string root, StringBuilder? name, int nameSize,
out uint serial, out uint maximumComponent, out uint flags, StringBuilder fileSystem, int fileSystemSize);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr FindFirstVolumeW(StringBuilder name, int length);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FindNextVolumeW(IntPtr iterator, StringBuilder name, int length);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FindVolumeClose(IntPtr iterator);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetVolumePathNamesForVolumeNameW(string volumeName, [Out] char[] paths,
uint length, out uint required);
}