XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers;
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;

[assembly: InternalsVisibleTo("XFEToolBox.Client.Test")]

namespace XFEToolBox.Client.Core.Search;

/// <summary>
/// Read-only, opportunistic NTFS MFT enumeration. This never elevates the process,
/// enables token privileges, creates a USN journal, or changes a volume.
/// </summary>
/// <remarks>
/// The caller must run this on a background worker. False means that ordinary
/// directory enumeration is required; some valid batches may already have been
/// published. Even a successful pass needs subsequent directory reconciliation:
/// MFT records identify files, not all of their hard-link names, and are not an
/// atomic snapshot. Raw MFT names must never bypass the caller's directory ACLs.
/// </remarks>
public static class NtfsVolumeScanner
{
    private const uint FsctlEnumUsnData = 0x000900b3;
    private const uint GenericRead = 0x80000000;
    private const uint ListDirectory = 0x00000001;
    private const uint ReadAttributes = 0x00000080;
    private const uint ShareAll = 0x00000007;
    private const uint OpenExisting = 3;
    private const uint BackupSemantics = 0x02000000;
    private const uint OpenReparsePoint = 0x00200000;
    private const uint DirectoryAttribute = 0x10;
    private const uint ReparseAttribute = 0x400;
    private const int ErrorHandleEof = 38;
    private const int ErrorMoreData = 234;
    private const int BufferSize = 1024 * 1024;
    private const int BatchSize = 256;

    /// <summary>Attempts a volume-root scan using only the current token's existing access.</summary>
    public static bool TryScan(string volumeRoot, Action<IReadOnlyList<FileSearchEntry>> publishBatch,
        CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(volumeRoot);
        ArgumentNullException.ThrowIfNull(publishBatch);
        cancellationToken.ThrowIfCancellationRequested();
        if (!OperatingSystem.IsWindows() || !TryNormalizeVolumeRoot(volumeRoot, out var root))
            return false;

        // FILE_FLAG_BACKUP_SEMANTICS is necessary to open directories, but an
        // already-enabled backup/restore privilege could override their DACLs.
        // Do not use this backend in that case, rather than changing the token.
        if (!NativeMethods.CanPerformOrdinaryDirectoryAccess())
            return false;

        using var volume = NativeMethods.CreateFileW(@"\\.\" + root[..2], GenericRead,
            ShareAll, IntPtr.Zero, OpenExisting, 0, IntPtr.Zero);
        if (volume.IsInvalid)
            return false;

        using var rootHandle = OpenDirectory(root);
        if (rootHandle.IsInvalid || !NativeMethods.GetFileInformationByHandle(rootHandle, out var rootInfo) ||
            (rootInfo.FileAttributes & (DirectoryAttribute | ReparseAttribute)) != DirectoryAttribute)
            return false;
        var fileSystemName = new StringBuilder(32);
        if (!NativeMethods.GetVolumeInformationByHandleW(rootHandle, IntPtr.Zero, 0, IntPtr.Zero,
                IntPtr.Zero, IntPtr.Zero, fileSystemName, fileSystemName.Capacity) ||
            !fileSystemName.ToString().Equals("NTFS", StringComparison.OrdinalIgnoreCase))
            return false;
        var rootId = new NtfsFileId(((ulong)rootInfo.FileIndexHigh << 32) | rootInfo.FileIndexLow, 0);

        var directories = new Dictionary<NtfsFileId, NtfsDirectoryNode>();
        directories[rootId] = new(rootId, rootId, string.Empty, DirectoryAttribute) { Path = root, Resolved = true };
        var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
        try
        {
            // Retain only directory topology, not a million temporary file nodes.
            if (!Enumerate(volume, buffer, directoriesOnly: true, record =>
                {
                    if (record.Id != rootId && !record.IsNtfsMetadata)
                        directories[record.Id] = new(record.Id, record.ParentId, record.Name, record.Attributes);
                }, cancellationToken))
                return false;

            var resolver = new NtfsDirectoryResolver(root, rootId, directories, CanListDirectory);
            var batch = new List<FileSearchEntry>(BatchSize);
            void Publish(NtfsUsnRecord record)
            {
                if (record.Id == rootId || record.IsNtfsMetadata)
                    return;
                var parent = resolver.Resolve(record.ParentId, cancellationToken);
                if (parent is null)
                    return;
                batch.Add(new FileSearchEntry(Combine(parent, record.Name), record.IsDirectory));
                if (batch.Count < BatchSize)
                    return;
                publishBatch(batch.ToArray());
                batch.Clear();
            }

            batch.Add(new FileSearchEntry(root, true));
            if (!Enumerate(volume, buffer, directoriesOnly: false, Publish, cancellationToken))
                return false;
            if (batch.Count != 0)
                publishBatch(batch.ToArray());
            return true;
        }
        finally
        {
            // Returned buffer contains filenames. Do not leave them in a shared pool.
            ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
        }
    }

    internal static bool TryNormalizeVolumeRoot(string value, out string root)
    {
        root = string.Empty;
        if (value.Length is < 2 or > 3 || !char.IsAsciiLetter(value[0]) || value[1] != ':' ||
            (value.Length == 3 && value[2] is not ('\\' or '/')))
            return false;
        root = char.ToUpperInvariant(value[0]) + @":\";
        return true;
    }

    private static string Combine(string parent, string name) => parent.EndsWith('\\')
        ? parent + name : parent + "\\" + name;

    private static SafeFileHandle OpenDirectory(string path) => NativeMethods.CreateFileW(
        @"\\?\" + path, ListDirectory | ReadAttributes, ShareAll, IntPtr.Zero,
        OpenExisting, BackupSemantics | OpenReparsePoint, IntPtr.Zero);

    private static bool CanListDirectory(string path, NtfsFileId expectedId)
    {
        using var handle = OpenDirectory(path);
        return !handle.IsInvalid && NativeMethods.GetFileInformationByHandle(handle, out var information) &&
            (information.FileAttributes & (DirectoryAttribute | ReparseAttribute)) == DirectoryAttribute &&
            expectedId.High == 0 && expectedId.Low == (((ulong)information.FileIndexHigh << 32) | information.FileIndexLow);
    }

    private static bool Enumerate(SafeFileHandle volume, byte[] buffer, bool directoriesOnly,
        Action<NtfsUsnRecord> accept, CancellationToken cancellationToken)
    {
        var request = new MftEnumData { LowUsn = 0, HighUsn = long.MaxValue };
        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var success = NativeMethods.DeviceIoControl(volume, FsctlEnumUsnData, ref request,
                Marshal.SizeOf<MftEnumData>(), buffer, BufferSize, out var returned, IntPtr.Zero);
            var error = success ? 0 : Marshal.GetLastWin32Error();
            if (!success && error == ErrorHandleEof)
                return true;
            if ((!success && error != ErrorMoreData) || returned < sizeof(ulong) || returned > BufferSize)
                return false;
            var next = BinaryPrimitives.ReadUInt64LittleEndian(buffer);
            if (next <= request.StartFileReferenceNumber ||
                !ParseBuffer(buffer.AsSpan(8, returned - 8), directoriesOnly, accept, cancellationToken))
                return false;
            request.StartFileReferenceNumber = next;
        }
    }

    internal static bool ParseBuffer(ReadOnlySpan<byte> bytes, bool directoriesOnly,
        Action<NtfsUsnRecord> accept, CancellationToken cancellationToken = default)
    {
        var count = 0;
        while (!bytes.IsEmpty)
        {
            if ((count++ & 127) == 0)
                cancellationToken.ThrowIfCancellationRequested();
            if (bytes.Length < 8)
                return false;
            var length = BinaryPrimitives.ReadUInt32LittleEndian(bytes);
            if (length < 8 || length > (uint)bytes.Length)
                return false;
            var record = bytes[..(int)length];
            var major = BinaryPrimitives.ReadUInt16LittleEndian(record[4..]);
            var attributesOffset = major switch { 2 => 52, 3 => 68, _ => -1 };
            if (attributesOffset < 0 || record.Length < attributesOffset + 8)
                return false;
            // Do not allocate a filename for every file in the topology pass.
            if (!directoriesOnly || (BinaryPrimitives.ReadUInt32LittleEndian(record[attributesOffset..]) & DirectoryAttribute) != 0)
            {
                if (!TryReadRecord(record, out var parsed))
                    return false;
                accept(parsed);
            }
            bytes = bytes[(int)length..];
        }
        return true;
    }

    internal static bool TryReadRecord(ReadOnlySpan<byte> bytes, out NtfsUsnRecord record)
    {
        record = default;
        if (bytes.Length < 8)
            return false;
        var length = BinaryPrimitives.ReadUInt32LittleEndian(bytes);
        var major = BinaryPrimitives.ReadUInt16LittleEndian(bytes[4..]);
        var attributesOffset = major switch { 2 => 52, 3 => 68, _ => -1 };
        if (attributesOffset < 0 || length > (uint)bytes.Length || length < attributesOffset + 8)
            return false;
        var nameLength = BinaryPrimitives.ReadUInt16LittleEndian(bytes[(attributesOffset + 4)..]);
        var nameOffset = BinaryPrimitives.ReadUInt16LittleEndian(bytes[(attributesOffset + 6)..]);
        if (nameLength == 0 || (nameLength & 1) != 0 || nameOffset < attributesOffset + 8 ||
            (nameOffset & 1) != 0 || (uint)nameOffset + nameLength > length)
            return false;
        var id = new NtfsFileId(BinaryPrimitives.ReadUInt64LittleEndian(bytes[8..]),
            major == 3 ? BinaryPrimitives.ReadUInt64LittleEndian(bytes[16..]) : 0);
        var parentOffset = major == 3 ? 24 : 16;
        var parent = new NtfsFileId(BinaryPrimitives.ReadUInt64LittleEndian(bytes[parentOffset..]),
            major == 3 ? BinaryPrimitives.ReadUInt64LittleEndian(bytes[(parentOffset + 8)..]) : 0);
        var attributes = BinaryPrimitives.ReadUInt32LittleEndian(bytes[attributesOffset..]);
        var name = Encoding.Unicode.GetString(bytes.Slice(nameOffset, nameLength));
        // NTFS's self-parented root may be named '.', but no other record may
        // introduce a path separator, ADS, or traversal component.
        if ((name == "." && (id != parent || (attributes & DirectoryAttribute) == 0)) || name == ".." ||
            name.AsSpan().IndexOfAny('\\', '/', ':') >= 0 || name.Contains('\0'))
            return false;
        record = new(id, parent, name, attributes);
        return true;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct MftEnumData
    {
        public ulong StartFileReferenceNumber;
        public long LowUsn;
        public long HighUsn;
    }

    // FILETIME consists of two DWORDs and is aligned to 4, unlike a C# long.
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    private struct ByHandleFileInformation
    {
        public uint FileAttributes;
        public long CreationTime;
        public long LastAccessTime;
        public long LastWriteTime;
        public uint VolumeSerialNumber;
        public uint FileSizeHigh;
        public uint FileSizeLow;
        public uint NumberOfLinks;
        public uint FileIndexHigh;
        public uint FileIndexLow;
    }

    private static class NativeMethods
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal 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)]
        internal static extern bool DeviceIoControl(SafeFileHandle device, uint controlCode,
            ref MftEnumData input, int inputSize, [Out] byte[] output, int outputSize,
            out int returned, IntPtr overlapped);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetFileInformationByHandle(SafeFileHandle file, out ByHandleFileInformation information);

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetVolumeInformationByHandleW(SafeFileHandle file, IntPtr volumeName, int volumeNameSize,
            IntPtr volumeSerialNumber, IntPtr maximumComponentLength, IntPtr fileSystemFlags,
            [Out] StringBuilder fileSystemName, int fileSystemNameSize);

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetCurrentProcess();

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetCurrentThread();

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool OpenThreadToken(IntPtr thread, uint access, bool openAsSelf, out SafeFileHandle token);

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool OpenProcessToken(IntPtr process, uint access, out SafeFileHandle token);

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetTokenInformation(SafeFileHandle token, int informationClass,
            [Out] byte[]? information, int informationLength, out int returnLength);

        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool LookupPrivilegeValueW(string? systemName, string name, out long luid);

        internal static bool CanPerformOrdinaryDirectoryAccess()
        {
            const uint tokenQuery = 8;
            const int noThreadToken = 1008;
            const int insufficientBuffer = 122;
            const int tokenPrivileges = 3;
            SafeFileHandle token;
            if (!OpenThreadToken(GetCurrentThread(), tokenQuery, true, out token))
            {
                var error = Marshal.GetLastWin32Error();
                token.Dispose();
                if (error != noThreadToken)
                    return false;
                if (!OpenProcessToken(GetCurrentProcess(), tokenQuery, out token))
                {
                    token.Dispose();
                    return false;
                }
            }
            using (token)
            {
                if (!LookupPrivilegeValueW(null, "SeBackupPrivilege", out var backup) ||
                    !LookupPrivilegeValueW(null, "SeRestorePrivilege", out var restore))
                    return false;
                _ = GetTokenInformation(token, tokenPrivileges, null, 0, out var size);
                if (Marshal.GetLastWin32Error() != insufficientBuffer || size is < 4 or > 1024 * 1024)
                    return false;
                var privileges = new byte[size];
                if (!GetTokenInformation(token, tokenPrivileges, privileges, size, out var actual) || actual < 4 || actual > size)
                    return false;
                var count = BinaryPrimitives.ReadUInt32LittleEndian(privileges);
                if (count > (uint)(actual - 4) / 12)
                    return false;
                for (var offset = 4; offset < 4 + count * 12; offset += 12)
                {
                    var luid = BinaryPrimitives.ReadInt64LittleEndian(privileges.AsSpan(offset));
                    var attributes = BinaryPrimitives.ReadUInt32LittleEndian(privileges.AsSpan(offset + 8));
                    if ((attributes & 2) != 0 && (luid == backup || luid == restore))
                        return false;
                }
                return true;
            }
        }
    }
}

internal readonly record struct NtfsFileId(ulong Low, ulong High);

internal readonly record struct NtfsUsnRecord(NtfsFileId Id, NtfsFileId ParentId, string Name, uint Attributes)
{
    public bool IsDirectory => (Attributes & 0x10) != 0;
    public bool IsNtfsMetadata => Id.High == 0 && (Id.Low & 0x0000ffffffffffffUL) < 16;
}

internal sealed class NtfsDirectoryNode(NtfsFileId id, NtfsFileId parent, string name, uint attributes)
{
    public NtfsFileId Id { get; } = id;
    public NtfsFileId Parent { get; } = parent;
    public string Name { get; } = name;
    public uint Attributes { get; } = attributes;
    public string? Path { get; set; }
    public bool Resolved { get; set; }
    public bool Resolving { get; set; }
}

/// <summary>Iterative, memoized resolution validates every directory ancestor before exposing children.</summary>
internal sealed class NtfsDirectoryResolver(string root, NtfsFileId rootId,
    Dictionary<NtfsFileId, NtfsDirectoryNode> directories, Func<string, NtfsFileId, bool> canList)
{
    private readonly List<NtfsDirectoryNode> trail = [];

    public string? Resolve(NtfsFileId id, CancellationToken cancellationToken = default)
    {
        trail.Clear();
        string? parent = null;
        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (id == rootId)
            {
                parent = root;
                break;
            }
            if (!directories.TryGetValue(id, out var node) || node.Resolving)
                break;
            if (node.Resolved)
            {
                parent = node.Path;
                break;
            }
            node.Resolving = true;
            trail.Add(node);
            if ((node.Attributes & (0x10 | 0x400)) != 0x10)
                break;
            id = node.Parent;
        }
        for (var index = trail.Count - 1; index >= 0; index--)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var node = trail[index];
            if (parent is not null && (node.Attributes & (0x10 | 0x400)) == 0x10)
            {
                var path = parent.EndsWith('\\') ? parent + node.Name : parent + "\\" + node.Name;
                parent = canList(path, node.Id) ? path : null;
            }
            else
                parent = null;
            node.Path = parent;
            node.Resolving = false;
            node.Resolved = true;
        }
        return parent;
    }
}