using System.Buffers.Binary; using System.Text; namespace XFEToolBox.Indexing.Service.Engine; public sealed record EngineStatus(bool IsIndexing, int IndexedFiles, int Volumes, int ReadyVolumes, string? Error) { public IReadOnlyList VolumeStatuses { get; init; } = []; public IReadOnlyList IndexedRoots { get; init; } = []; public IReadOnlyList UnavailableRoots { get; init; } = []; } public sealed record VolumeIndexStatus(string Root, string Phase, int IndexedFiles, ulong JournalId, long NextUsn, string? Error); internal sealed record NtfsName(ulong ParentId, string Name); internal sealed record NtfsNode(ulong FileId, uint Attributes, NtfsName[] Names) { public bool IsDirectory => (Attributes & 0x10) != 0; } internal sealed record NtfsVolume(string Root, string VolumeId, uint SerialNumber); internal readonly record struct NtfsJournal(ulong Id, long FirstUsn, long NextUsn, long LowestValidUsn) { public bool CanResume(ulong id, long cursor) => id == Id && cursor >= Math.Max(FirstUsn, LowestValidUsn) && cursor <= NextUsn; } internal readonly record struct NtfsChange(ulong FileId, uint Reason); internal interface INtfsMetadataSource : IDisposable { bool IsOpen { get; } string? OpenError { get; } bool TryGetJournal(out NtfsJournal journal, out string? error); bool TryEnumerate(Action accept, CancellationToken token, out string? error); bool TryReadNodes(IReadOnlyList ids, Action accept, CancellationToken token, out string? error); bool TryReadChanges(NtfsJournal journal, long cursor, out long nextUsn, out NtfsChange[] changes, out string? error); } /// Bounds-checked parsers for the documented Windows SDK layouts, also usable by synthetic tests. internal static class NtfsMetadataParser { public static NtfsNode[] ParseLayout(ReadOnlySpan data) { Require(data.Length >= 16, "Truncated file layout header."); var count = U32(data, 0); Require(count <= (uint)(data.Length / 40), "Invalid file layout count."); var offset = checked((int)U32(data, 4)); var result = new NtfsNode[count]; for (var index = 0; index < count; index++) { Require(offset >= 16 && offset <= data.Length - 40, "Invalid file layout offset."); Require(U32(data, offset) == 1, "Unsupported file layout version."); var next = checked((int)U32(data, offset + 4)); var end = next == 0 ? data.Length : checked(offset + next); Require(end > offset && end <= data.Length, "Invalid next file layout offset."); var nameOffset = checked((int)U32(data, offset + 24)); var names = new List(); var position = nameOffset == 0 ? 0 : checked(offset + nameOffset); while (position != 0) { Require(position >= offset + 40 && position <= end - 24, "Invalid file name offset."); var length = checked((int)U32(data, position + 16)); Require(length > 0 && (length & 1) == 0 && length <= 65534 && position + 24 <= end - length, "Invalid UTF-16 file name length."); var flags = U32(data, position + 4); // Pure DOS aliases are not additional real filenames. PRIMARY|DOS is a real 8.3 name. if ((flags & 3) != 2) { var name = Encoding.Unicode.GetString(data.Slice(position + 24, length)); Require(!name.Contains('\\') && !name.Contains('/') && !name.Contains('\0'), "Invalid basename in file layout."); names.Add(new(U64(data, position + 8), name)); } var advance = checked((int)U32(data, position)); if (advance == 0) break; Require(advance >= 24 + length, "Cyclic file name offsets."); position = checked(position + advance); } result[index] = new(U64(data, offset + 16), U32(data, offset + 12), names.Distinct().ToArray()); if (index + 1 < count) Require(next >= 40, "Missing next file layout entry."); offset = end; } return result; } public static (long NextUsn, NtfsChange[] Changes) ParseJournal(ReadOnlySpan data) { Require(data.Length >= 8, "Truncated USN header."); var changes = new List(); for (var offset = 8; offset < data.Length;) { Require(offset <= data.Length - 8, "Truncated USN record."); var length = checked((int)U32(data, offset)); Require(length >= 60 && length <= data.Length - offset, "Invalid USN record length."); Require(BinaryPrimitives.ReadUInt16LittleEndian(data[(offset + 4)..]) == 2, "Unsupported USN record version on NTFS volume."); var nameLength = BinaryPrimitives.ReadUInt16LittleEndian(data[(offset + 56)..]); var nameOffset = BinaryPrimitives.ReadUInt16LittleEndian(data[(offset + 58)..]); Require(nameOffset >= 60 && nameOffset <= length - nameLength && (nameLength & 1) == 0, "Invalid USN name bounds."); changes.Add(new(U64(data, offset + 8), U32(data, offset + 40))); offset += length; } return (BinaryPrimitives.ReadInt64LittleEndian(data), changes.ToArray()); } private static uint U32(ReadOnlySpan data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data[offset..]); private static ulong U64(ReadOnlySpan data, int offset) => BinaryPrimitives.ReadUInt64LittleEndian(data[offset..]); private static void Require(bool condition, string message) { if (!condition) throw new InvalidDataException(message); } }