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

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
namespace XFESystem.Browser;

/// <summary>Finite HTTP field validation shared by the script boundary and transports.</summary>
public static class BrowserRequestHeaders
{
    private static readonly HashSet<string> Forbidden = new(StringComparer.OrdinalIgnoreCase)
    { "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "set-cookie", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" };
    public static bool Allowed(string name, string value)
    {
        if (name.Length is 0 or > 128 || name.Any(c => !char.IsAsciiLetterOrDigit(c) && !"!#$%&'*+-.^_`|~".Contains(c)) || value.Length > 2048 || value.Any(c => c < 32 && c != '\t' || c == 127 || c > 255))
            throw new ArgumentException("Invalid HTTP request field.");
        return !Forbidden.Contains(name) && !name.StartsWith("proxy-", StringComparison.OrdinalIgnoreCase) && !name.StartsWith("sec-", StringComparison.OrdinalIgnoreCase);
    }
    public static IReadOnlyDictionary<string, string> Copy(IReadOnlyDictionary<string, string> headers)
    {
        if (headers.Count > 32) throw new BrowserLimitException("The script request header count limit was reached.");
        var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); int characters = 0;
        foreach (var pair in headers)
        {
            if (!Allowed(pair.Key, pair.Value)) continue;
            if ((characters += pair.Key.Length + pair.Value.Length) > 8192) throw new BrowserLimitException("The script request headers exceed their character limit.");
            result[pair.Key] = pair.Value;
        }
        return result;
    }
}