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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Core.Search.Service;

namespace XFEToolBox.Indexing.Service.IPC;

/// <summary>Must be used synchronously inside RunAsClient; never cache grants across requests.</summary>
public sealed class CallerFileAccess
{
    private readonly Dictionary<string, bool> directories = new(StringComparer.OrdinalIgnoreCase);
    private readonly string? scope;
    private readonly string? scopePrefix;

    public CallerFileAccess(string? scope = null)
    {
        this.scope = scope is null ? null : Path.TrimEndingDirectorySeparator(Path.GetFullPath(scope));
        scopePrefix = this.scope is null ? null : Path.EndsInDirectorySeparator(this.scope) ? this.scope : this.scope + Path.DirectorySeparatorChar;
    }

    public bool IsAccessible(FileSearchEntry entry)
    {
        if (!OperatingSystem.IsWindows() || !IndexingServiceProtocol.IsLocalPath(entry.FullPath)) return false;
        string path;
        try { path = Path.GetFullPath(entry.FullPath); }
        catch (Exception error) when (error is ArgumentException or NotSupportedException or PathTooLongException) { return false; }
        if (scope is not null && !string.Equals(path, scope, StringComparison.OrdinalIgnoreCase)
            && !path.StartsWith(scopePrefix!, StringComparison.OrdinalIgnoreCase)) return false;
        var parent = entry.IsDirectory ? path : Path.GetDirectoryName(path);
        if (parent is null || !CanEnumerate(parent)) return false;
        // Directory enumeration reveals basenames even when the child has an
        // independent deny-read ACL. Do not stat/open each child as SYSTEM or
        // require content rights just to disclose a name the caller may list.
        // Opening/reading a result is performed only by the ordinary client.
        return true;
    }

    public bool IsWithinScope(FileSearchEntry entry)
    {
        if (scope is null) return true;
        var path = entry.FullPath;
        return string.Equals(path, scope, StringComparison.OrdinalIgnoreCase)
            || path.StartsWith(scopePrefix!, StringComparison.OrdinalIgnoreCase);
    }

    private bool CanEnumerate(string path)
    {
        if (directories.TryGetValue(path, out var allowed)) return allowed;
        // Ancestors are checked before the target; a traversable directory alone
        // must not disclose children of a parent the caller cannot enumerate.
        var pending = new List<string>();
        string? current = path;
        allowed = true;
        while (current is not null)
        {
            if (directories.TryGetValue(current, out var cached)) { allowed = cached; break; }
            if (pending.Count >= 1024) return false;
            pending.Add(current);
            current = Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(current));
        }
        for (var index = pending.Count - 1; index >= 0; index--)
        {
            allowed = allowed && OpenWithoutReparse(pending[index], true);
            directories[pending[index]] = allowed;
        }
        return allowed;
    }

    private static bool OpenWithoutReparse(string path, bool directory)
    {
        using var handle = CreateFileW(@"\\?\" + path, directory ? 0x81u : 0x80u, 7, IntPtr.Zero, 3,
            0x02000000u | 0x00200000u, IntPtr.Zero);
        return !handle.IsInvalid && GetFileInformationByHandle(handle, out var information)
            && (information.Attributes & 0x400) == 0
            && ((information.Attributes & 0x10) != 0) == directory;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct FileInformation
    {
        public uint Attributes;
        public System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Write;
        public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
    }
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security,
        uint creation, uint attributes, IntPtr template);
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out FileInformation information);
}