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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Core.Search.Service;
using XFEToolBox.Indexing.Service.Engine;
using XFEToolBox.Indexing.Service.IPC;

namespace XFEToolBox.Indexing.Service.Host;

internal sealed class IndexingServiceHost : IAsyncDisposable
{
    private readonly NtfsIndexEngine engine;
    private readonly List<NamedPipeServerStream> listeners = [];
    private readonly CancellationTokenSource lifetime = new();
    private Task[] workers = [];

    public IndexingServiceHost(string dataDirectory) => engine = new(dataDirectory, Environment.ProcessorCount);

    public async Task RunAsync(CancellationToken token)
    {
        using var cancellation = token.Register(() => _ = lifetime.CancelAsync());
        // Retain/reuse these handles for the entire service lifetime. There is no
        // last-connection-close interval in which another user could claim the name.
        for (var index = 0; index < Math.Clamp(Environment.ProcessorCount, 2, 4); index++)
            listeners.Add(SecurePipeFactory.Create(index == 0));
        workers = listeners.Select(pipe => Task.Run(() => ListenAsync(pipe, lifetime.Token))).ToArray();
        await engine.StartAsync(lifetime.Token).ConfigureAwait(false);
        await Task.WhenAll(workers).ConfigureAwait(false);
    }

    private async Task ListenAsync(NamedPipeServerStream pipe, CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            try
            {
                await pipe.WaitForConnectionAsync(token).ConfigureAwait(false);
                using var requestTimeout = CancellationTokenSource.CreateLinkedTokenSource(token);
                requestTimeout.CancelAfter(TimeSpan.FromSeconds(4));
                var request = await IndexingServiceProtocol.ReadAsync<IndexingServiceRequest>(pipe,
                    IndexingServiceProtocol.MaximumRequestBytes, requestTimeout.Token).ConfigureAwait(false);
                if (!IndexingServiceProtocol.IsValid(request)) continue;
                var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                var disconnected = ObserveClientDisconnectAsync(pipe, requestTimeout, completed.Task);
                try
                {
                    IndexingServiceResponse? response = null;
                    pipe.RunAsClient(() =>
                    {
                        using var identity = WindowsIdentity.GetCurrent(true);
                        if (identity is null || !identity.IsAuthenticated || identity.ImpersonationLevel
                            is not (TokenImpersonationLevel.Impersonation or TokenImpersonationLevel.Delegation)) return;
                        var status = ClientStatus();
                        if (request.Operation == "status")
                        {
                            response = new(IndexingServiceProtocol.Version, status);
                            return;
                        }
                        var query = FileSearchQuery.Parse(request.Query);
                        if (query.Error is not null)
                        {
                            response = new(IndexingServiceProtocol.Version, status,
                                new([], false, TimeSpan.Zero, status, query.Error));
                            return;
                        }
                        // Keep this entire call synchronous: Task.Run/async here would
                        // lose the caller's thread token and evaluate ACLs as LocalSystem.
                        var access = new CallerFileAccess(request.Scope);
                        var watch = Stopwatch.StartNew();
                        var results = SearchVisible(request.Limit, access, request.Scope is not null,
                            (offset, limit, filter) => engine.TrySearch(request.Query, offset, limit, requestTimeout.Token, filter),
                            requestTimeout.Token);
                        if (results is null) return;
                        response = new(IndexingServiceProtocol.Version, status,
                            new(results.Items.Take(request.Limit).ToArray(), results.TotalMatches > request.Limit,
                                watch.Elapsed, status));
                    });
                    if (response is not null && !requestTimeout.IsCancellationRequested)
                    {
                        await IndexingServiceProtocol.WriteAsync(pipe, response,
                            IndexingServiceProtocol.MaximumResponseBytes, requestTimeout.Token).ConfigureAwait(false);
                        await WaitForClientCloseAsync(pipe, requestTimeout.Token).ConfigureAwait(false);
                    }
                }
                finally
                {
                    completed.TrySetResult();
                    await disconnected.ConfigureAwait(false);
                }
            }
            catch (Exception error) when (error is IOException or UnauthorizedAccessException or OperationCanceledException
                or InvalidDataException or System.Text.Json.JsonException or ArgumentException
                or System.ComponentModel.Win32Exception or System.Security.SecurityException)
            {
                // Invalid/abandoned requests are isolated, with no privileged paths
                // or per-volume errors sent back to the unprivileged caller.
                // A persistent native error must never turn this into a tight
                // exception loop that competes with indexing and valid clients.
                if (!token.IsCancellationRequested) await Task.Delay(20).ConfigureAwait(false);
            }
            finally
            {
                ResetClientConnection(pipe);
            }
        }
    }

    internal static void ResetClientConnection(NamedPipeServerStream pipe)
    {
        // An EOF before the request is written marks the managed stream Broken,
        // so IsConnected is false while the native instance is still occupied.
        // Disconnect is explicitly valid in the Broken state and must not be
        // conditional on IsConnected, or all listeners become permanently busy.
        try { pipe.Disconnect(); }
        catch (InvalidOperationException) { /* Still waiting/already disconnected, e.g. shutdown. */ }
        catch (IOException) { /* Cancellation/shutdown may already have closed the native endpoint. */ }
    }

    internal static async Task WaitForClientCloseAsync(NamedPipeServerStream pipe, CancellationToken token)
    {
        // PipeStream.FlushAsync does not drain the peer's unread kernel buffer.
        // DisconnectNamedPipe discards that buffer. Our one-request client closes
        // its handle immediately after reading the complete response, so await
        // EOF before reusing the server instance. A stalled peer is still bounded
        // by the request deadline; no synchronous WaitForPipeDrain/FlushFileBuffers.
        _ = await pipe.ReadAsync(new byte[1], token).ConfigureAwait(false);
    }

    internal static async Task ObserveClientDisconnectAsync(NamedPipeServerStream pipe,
        CancellationTokenSource request, Task completed)
    {
        while (!request.IsCancellationRequested)
        {
            if (await Task.WhenAny(completed, Task.Delay(50)).ConfigureAwait(false) == completed) return;
            // Peek on an overlapped byte pipe is non-blocking. Unlike a pending
            // ReadAsync it neither consumes another message nor needs exception-
            // based cancellation on every successful request.
            if (!PeekNamedPipe(pipe.SafePipeHandle, IntPtr.Zero, 0, IntPtr.Zero, out var pending, IntPtr.Zero)
                || pending != 0)
            {
                await request.CancelAsync().ConfigureAwait(false);
                return;
            }
        }
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool PeekNamedPipe(SafePipeHandle handle, IntPtr buffer, uint size,
        IntPtr read, out uint available, IntPtr remaining);

    internal static FileSearchResults? SearchVisible(int limit, CallerFileAccess access, bool scoped,
        Func<int, int, Func<FileSearchEntry, bool>?, FileSearchResults?> search, CancellationToken token)
    {
        var visible = new List<FileSearchMatch>(Math.Min(limit + 1, 2048));
        var batchSize = Math.Clamp(limit + 1, 1024, 2048);
        var offset = 0;
        // Ranking is in memory. Validate only the leading candidates until enough
        // caller-listable names are found instead of issuing a stat for every match.
        while (offset < 8192)
        {
            var candidates = search(offset, batchSize, scoped ? access.IsWithinScope : null);
            if (candidates is null) return null;
            foreach (var candidate in candidates.Items)
            {
                if (token.IsCancellationRequested) return null;
                if (!access.IsAccessible(candidate.Entry)) continue;
                visible.Add(candidate);
                if (visible.Count > limit)
                    return new(visible, visible.Count, candidates.Elapsed);
            }
            offset += candidates.Items.Count;
            if (candidates.Items.Count == 0 || offset >= candidates.TotalMatches)
                return new(visible, visible.Count, candidates.Elapsed);
        }
        // A large inaccessible prefix must not hide later allowed results. The
        // fallback reuses this request's directory grants, never another user's.
        return search(0, limit + 1, access.IsAccessible);
    }

    private IndexingServiceStatus ClientStatus()
    {
        var state = engine.GetStatus();
        return new(state.IsIndexing, 0, state.Volumes, state.ReadyVolumes,
            state.Error is null ? null : "部分磁盘索引暂不可用,请查看服务诊断。")
        {
            IndexedRoots = state.IndexedRoots,
            UnavailableRoots = state.UnavailableRoots
        };
    }

    public async ValueTask DisposeAsync()
    {
        await lifetime.CancelAsync().ConfigureAwait(false);
        try { await Task.WhenAll(workers).ConfigureAwait(false); }
        catch (OperationCanceledException) { }
        foreach (var pipe in listeners) pipe.Dispose();
        await engine.DisposeAsync().ConfigureAwait(false);
        lifetime.Dispose();
    }
}