using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
namespace XFEToolBox.Client.Core.Search.Service;
/// <summary>All connection and trust checks run off the caller's UI thread. Missing service is a normal fallback.</summary>
public interface IIndexingServiceClient
{
Task<IndexingServiceStatus?> GetStatusAsync(CancellationToken cancellationToken = default);
Task<IndexingServiceSearchResponse?> SearchAsync(string query, string? scope, int limit, CancellationToken cancellationToken = default);
}
public sealed class IndexingServiceClient : IIndexingServiceClient
{
public Task<IndexingServiceStatus?> GetStatusAsync(CancellationToken cancellationToken = default) =>
Task.Run(async () => (await SendAsync(new(IndexingServiceProtocol.Version, "status"), cancellationToken)
.ConfigureAwait(false))?.Status, CancellationToken.None);
public Task<IndexingServiceSearchResponse?> SearchAsync(string query, string? scope, int limit,
CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var request = new IndexingServiceRequest(IndexingServiceProtocol.Version, "search", query, scope, limit);
if (!IndexingServiceProtocol.IsValid(request)) return null;
return (await SendAsync(request, cancellationToken).ConfigureAwait(false))?.Search;
}, CancellationToken.None);
private static async Task<IndexingServiceResponse?> SendAsync(IndexingServiceRequest request, CancellationToken token)
{
if (!OperatingSystem.IsWindows() || token.IsCancellationRequested) return null;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
timeout.CancelAfter(TimeSpan.FromSeconds(request.Operation == "status" ? 1 : 5));
try { return await SendWindowsAsync(request, timeout.Token).ConfigureAwait(false); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException or OperationCanceledException
or System.ComponentModel.Win32Exception or System.Text.Json.JsonException or InvalidDataException)
{ return null; }
}
[SupportedOSPlatform("windows")]
private static async Task<IndexingServiceResponse?> SendWindowsAsync(IndexingServiceRequest request, CancellationToken token)
{
// No request is written (and therefore no impersonatable token is made available)
// until the endpoint's PID has been verified against SCM's LocalSystem service.
using var pipe = await ConnectWindowsAsync(token).ConfigureAwait(false);
if (pipe is null || token.IsCancellationRequested) return null;
if (!IndexingServiceTrust.IsTrustedServer(pipe.SafePipeHandle)) return null;
await IndexingServiceProtocol.WriteAsync(pipe, request, IndexingServiceProtocol.MaximumRequestBytes, token).ConfigureAwait(false);
var response = await IndexingServiceProtocol.ReadAsync<IndexingServiceResponse>(pipe,
IndexingServiceProtocol.MaximumResponseBytes, token).ConfigureAwait(false);
if (response.Version != IndexingServiceProtocol.Version || response.Error is not null) return null;
return response;
}
[SupportedOSPlatform("windows")]
private static async Task<NamedPipeClientStream?> ConnectWindowsAsync(CancellationToken token)
{
var deadline = Environment.TickCount64 + 400;
while (true)
{
if (token.IsCancellationRequested) return null;
// FILE_READ/WRITE_DATA, attributes, EA, READ_CONTROL, SYNCHRONIZE; not
// FILE_CREATE_PIPE_INSTANCE. GENERIC_WRITE would silently include that right.
var handle = CreateFileW(@"\\.\pipe\" + IndexingServiceProtocol.PipeName, 0x0012019B,
0, IntPtr.Zero, 3, 0x40000000 | 0x00100000 | 0x00020000, IntPtr.Zero);
if (!handle.IsInvalid) return new(PipeDirection.InOut, true, true, handle);
var error = Marshal.GetLastWin32Error();
handle.Dispose();
// A missing/stopped/busy service is routine, not a first-chance
// exception on every status poll or palette cancellation.
if (error != 231 || Environment.TickCount64 >= deadline) return null;
await Task.Delay(20).ConfigureAwait(false);
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafePipeHandle CreateFileW(string name, uint access, uint share, IntPtr security,
uint creation, uint attributes, IntPtr template);
}
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
namespace XFEToolBox.Client.Core.Search.Service;
/// <summary>All connection and trust checks run off the caller's UI thread. Missing service is a normal fallback.</summary>
public interface IIndexingServiceClient
{
Task<IndexingServiceStatus?> GetStatusAsync(CancellationToken cancellationToken = default);
Task<IndexingServiceSearchResponse?> SearchAsync(string query, string? scope, int limit, CancellationToken cancellationToken = default);
}
public sealed class IndexingServiceClient : IIndexingServiceClient
{
public Task<IndexingServiceStatus?> GetStatusAsync(CancellationToken cancellationToken = default) =>
Task.Run(async () => (await SendAsync(new(IndexingServiceProtocol.Version, "status"), cancellationToken)
.ConfigureAwait(false))?.Status, CancellationToken.None);
public Task<IndexingServiceSearchResponse?> SearchAsync(string query, string? scope, int limit,
CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var request = new IndexingServiceRequest(IndexingServiceProtocol.Version, "search", query, scope, limit);
if (!IndexingServiceProtocol.IsValid(request)) return null;
return (await SendAsync(request, cancellationToken).ConfigureAwait(false))?.Search;
}, CancellationToken.None);
private static async Task<IndexingServiceResponse?> SendAsync(IndexingServiceRequest request, CancellationToken token)
{
if (!OperatingSystem.IsWindows() || token.IsCancellationRequested) return null;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
timeout.CancelAfter(TimeSpan.FromSeconds(request.Operation == "status" ? 1 : 5));
try { return await SendWindowsAsync(request, timeout.Token).ConfigureAwait(false); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException or OperationCanceledException
or System.ComponentModel.Win32Exception or System.Text.Json.JsonException or InvalidDataException)
{ return null; }
}
[SupportedOSPlatform("windows")]
private static async Task<IndexingServiceResponse?> SendWindowsAsync(IndexingServiceRequest request, CancellationToken token)
{
// No request is written (and therefore no impersonatable token is made available)
// until the endpoint's PID has been verified against SCM's LocalSystem service.
using var pipe = await ConnectWindowsAsync(token).ConfigureAwait(false);
if (pipe is null || token.IsCancellationRequested) return null;
if (!IndexingServiceTrust.IsTrustedServer(pipe.SafePipeHandle)) return null;
await IndexingServiceProtocol.WriteAsync(pipe, request, IndexingServiceProtocol.MaximumRequestBytes, token).ConfigureAwait(false);
var response = await IndexingServiceProtocol.ReadAsync<IndexingServiceResponse>(pipe,
IndexingServiceProtocol.MaximumResponseBytes, token).ConfigureAwait(false);
if (response.Version != IndexingServiceProtocol.Version || response.Error is not null) return null;
return response;
}
[SupportedOSPlatform("windows")]
private static async Task<NamedPipeClientStream?> ConnectWindowsAsync(CancellationToken token)
{
var deadline = Environment.TickCount64 + 400;
while (true)
{
if (token.IsCancellationRequested) return null;
// FILE_READ/WRITE_DATA, attributes, EA, READ_CONTROL, SYNCHRONIZE; not
// FILE_CREATE_PIPE_INSTANCE. GENERIC_WRITE would silently include that right.
var handle = CreateFileW(@"\\.\pipe\" + IndexingServiceProtocol.PipeName, 0x0012019B,
0, IntPtr.Zero, 3, 0x40000000 | 0x00100000 | 0x00020000, IntPtr.Zero);
if (!handle.IsInvalid) return new(PipeDirection.InOut, true, true, handle);
var error = Marshal.GetLastWin32Error();
handle.Dispose();
// A missing/stopped/busy service is routine, not a first-chance
// exception on every status poll or palette cancellation.
if (error != 231 || Environment.TickCount64 >= deadline) return null;
await Task.Delay(20).ConfigureAwait(false);
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafePipeHandle CreateFileW(string name, uint access, uint share, IntPtr security,
uint creation, uint attributes, IntPtr template);
}