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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using XFEToolBox.Client.Core.Search;

namespace XFEToolBox.Indexing.Service.Engine;

internal sealed class NtfsCatalog
{
    private const int CacheVersion = 1;
    private const uint CacheMagic = 0x58464d46; // XFMF
    private const ulong FileIdMask = 0x0000ffffffffffff;
    public Dictionary<ulong, NtfsNode> Nodes { get; } = [];
    private Dictionary<ulong, HashSet<ulong>>? children;
    public ulong JournalId { get; set; }
    public long NextUsn { get; set; }

    public Dictionary<ulong, string> ResolveDirectories(string root, CancellationToken token,
        Dictionary<ulong, string>? existing = null, IEnumerable<ulong>? affected = null)
    {
        var paths = existing ?? new Dictionary<ulong, string>();
        var nodes = affected is null ? Nodes.Values : affected.Where(Nodes.ContainsKey).Select(id => Nodes[id]);
        foreach (var node in nodes)
        {
            if (!node.IsDirectory)
                continue;
            token.ThrowIfCancellationRequested();
            Resolve(node.FileId, root, paths);
        }
        return paths;
    }

    public HashSet<ulong> GetDescendants(IEnumerable<ulong> roots, CancellationToken token)
    {
        EnsureParentIndex();
        var result = new HashSet<ulong>(roots);
        var queue = new Queue<ulong>(result);
        while (queue.TryDequeue(out var parent))
        {
            token.ThrowIfCancellationRequested();
            if (!children!.TryGetValue(parent, out var descendants))
                continue;
            foreach (var descendant in descendants)
                if (result.Add(descendant)) queue.Enqueue(descendant);
        }
        return result;
    }

    public void UpdateNode(ulong id, NtfsNode? replacement)
    {
        EnsureParentIndex();
        if (Nodes.TryGetValue(id, out var previous))
            foreach (var name in previous.Names)
                if (children!.TryGetValue(name.ParentId, out var descendants))
                {
                    descendants.Remove(id);
                    if (descendants.Count == 0) children.Remove(name.ParentId);
                }
        if (replacement is null)
            Nodes.Remove(id);
        else
        {
            Nodes[id] = replacement;
            IndexParents(replacement);
        }
    }

    private void EnsureParentIndex()
    {
        if (children is not null) return;
        children = [];
        foreach (var node in Nodes.Values) IndexParents(node);
    }

    private void IndexParents(NtfsNode node)
    {
        foreach (var name in node.Names)
        {
            if (!children!.TryGetValue(name.ParentId, out var descendants))
                children[name.ParentId] = descendants = [];
            descendants.Add(node.FileId);
        }
    }

    private string? Resolve(ulong id, string root, Dictionary<ulong, string> paths)
    {
        if ((id & FileIdMask) == 5)
            return root;
        if (paths.TryGetValue(id, out var cached))
            return cached.Length == 0 ? null : cached;
        var chain = new List<(ulong Id, string Name)>();
        var visiting = new HashSet<ulong>();
        string? parentPath = null;
        while (true)
        {
            if ((id & FileIdMask) == 5)
            {
                parentPath = root;
                break;
            }
            if (paths.TryGetValue(id, out cached))
            {
                parentPath = cached.Length == 0 ? null : cached;
                break;
            }
            if (chain.Count > 4096 || !visiting.Add(id) || !Nodes.TryGetValue(id, out var node)
                || !node.IsDirectory || node.Names.Length == 0)
                break;
            var name = node.Names[0];
            chain.Add((id, name.Name));
            id = name.ParentId;
        }
        for (var index = chain.Count - 1; index >= 0; index--)
        {
            if (parentPath is not null)
                parentPath = Combine(parentPath, chain[index].Name);
            paths[chain[index].Id] = parentPath ?? string.Empty;
        }
        return parentPath;
    }

    public static IEnumerable<FileSearchEntry> GetEntries(NtfsNode node, string root,
        IReadOnlyDictionary<ulong, string> directories)
    {
        if ((node.FileId & FileIdMask) == 5)
            yield break;
        foreach (var name in node.Names)
        {
            string? parent = (name.ParentId & FileIdMask) == 5 ? root : directories.GetValueOrDefault(name.ParentId);
            if (string.IsNullOrEmpty(parent) || name.Name is "." or "..")
                continue;
            yield return new FileSearchEntry(Combine(parent, name.Name), node.IsDirectory);
        }
    }

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

    public static string GetCachePath(string directory, NtfsVolume volume)
    {
        var identity = SHA256.HashData(Encoding.UTF8.GetBytes(volume.VolumeId.ToUpperInvariant()));
        return Path.Combine(directory, Convert.ToHexString(identity) + ".ntfs.gz");
    }

    public static NtfsCatalog? TryLoad(string path, NtfsVolume volume, NtfsJournal journal)
    {
        if (!File.Exists(path))
            return null;
        try
        {
            using var priority = new NtfsIoPriority();
            using var stream = File.OpenRead(path);
            using var gzip = new GZipStream(stream, CompressionMode.Decompress);
            using var reader = new BinaryReader(gzip, Encoding.UTF8);
            if (reader.ReadUInt32() != CacheMagic || reader.ReadInt32() != CacheVersion
                || ReadBoundedString(reader, 1024) != volume.VolumeId || reader.ReadUInt32() != volume.SerialNumber)
                return null;
            var catalog = new NtfsCatalog { JournalId = reader.ReadUInt64(), NextUsn = reader.ReadInt64() };
            if (!journal.CanResume(catalog.JournalId, catalog.NextUsn))
                return null;
            var count = reader.ReadInt32();
            if (count < 0 || count > 30_000_000)
                return null;
            for (var index = 0; index < count; index++)
            {
                var id = reader.ReadUInt64();
                var attributes = reader.ReadUInt32();
                var nameCount = reader.ReadInt32();
                if (nameCount < 0 || nameCount > 1024)
                    return null;
                var names = new NtfsName[nameCount];
                for (var nameIndex = 0; nameIndex < names.Length; nameIndex++)
                {
                    var parent = reader.ReadUInt64();
                    var name = ReadBoundedString(reader, 131068);
                    if (name.Length > 32767 || name.Contains('\\') || name.Contains('/') || name.Contains('\0'))
                        return null;
                    names[nameIndex] = new(parent, name);
                }
                catalog.Nodes.Add(id, new(id, attributes, names));
            }
            // Force validation of the gzip checksum/trailer before trusting a checkpoint.
            if (gzip.ReadByte() != -1)
                return null;
            return catalog;
        }
        catch (Exception exception) when (exception is IOException or InvalidDataException or ArgumentException)
        {
            return null;
        }
    }

    private static string ReadBoundedString(BinaryReader reader, int maximumBytes)
    {
        var length = reader.Read7BitEncodedInt();
        if (length < 0 || length > maximumBytes)
            throw new InvalidDataException("Invalid cached string length.");
        var bytes = reader.ReadBytes(length);
        if (bytes.Length != length)
            throw new EndOfStreamException();
        return Encoding.UTF8.GetString(bytes);
    }

    public void SaveAtomic(string path, NtfsVolume volume, CancellationToken token)
    {
        using var priority = new NtfsIoPriority();
        Directory.CreateDirectory(Path.GetDirectoryName(path)!);
        // Nodes and the USN cursor are serialized together by the sole catalog writer. A crash can
        // leave an unused .pending file, never a newer checkpoint paired with older index data.
        var pending = path + ".pending";
        using (var stream = new FileStream(pending, FileMode.Create, FileAccess.Write, FileShare.None, 256 * 1024,
                   FileOptions.SequentialScan))
        {
            using (var gzip = new GZipStream(stream, CompressionLevel.Fastest, leaveOpen: true))
            using (var writer = new BinaryWriter(gzip, Encoding.UTF8, leaveOpen: true))
            {
                writer.Write(CacheMagic);
                writer.Write(CacheVersion);
                writer.Write(volume.VolumeId);
                writer.Write(volume.SerialNumber);
                writer.Write(JournalId);
                writer.Write(NextUsn);
                writer.Write(Nodes.Count);
                foreach (var node in Nodes.Values)
                {
                    token.ThrowIfCancellationRequested();
                    writer.Write(node.FileId);
                    writer.Write(node.Attributes);
                    writer.Write(node.Names.Length);
                    foreach (var name in node.Names)
                    {
                        writer.Write(name.ParentId);
                        writer.Write(name.Name);
                    }
                }
            }
            stream.Flush(flushToDisk: true);
        }
        File.Move(pending, path, overwrite: true);
    }
}