using System.Text; using System.Text.Json.Nodes; namespace UCVL.VPNPlus; // Expand the documented GeoSite/Domain protobuf before batching. Otherwise a // short geosite token can become a >4 MiB RoutingService request in xray api. internal static class RoutingRuleBatches { internal const string OwnedPrefix = "ucvl-"; internal static void TagInitialRules(JsonObject root) { if (root["routing"]?["rules"] is not JsonArray rules) return; for (var i = 0; i < rules.Count; i++) rules[i]!["ruleTag"] = $"{OwnedPrefix}base-{i}"; } internal static List Build(string routingJson, string dataDirectory, string generation) { var routing = JsonNode.Parse(routingJson)?["routing"]?.AsObject() ?? throw new InvalidDataException("缺少路由更新内容。"); if (routing["balancers"] is JsonArray { Count: > 0 }) throw new InvalidDataException("动态负载器更新尚不支持,现有规则保持不变。"); var cache = new Dictionary>(StringComparer.OrdinalIgnoreCase); var result = new List(); foreach (var item in routing["rules"]!.AsArray()) { var rule = item!.AsObject(); if (rule["domain"] is not JsonArray matchers) { Add(rule.DeepClone().AsObject()); continue; } var domains = new List(); foreach (var node in matchers) { var matcher = node!.GetValue(); if (!matcher.StartsWith("geosite:", StringComparison.OrdinalIgnoreCase)) { domains.Add(matcher); continue; } var code = matcher[8..]; if (code.Contains('@')) throw new InvalidDataException("带属性的 geosite 规则暂不能热更新,现有规则保持不变。"); if (!cache.TryGetValue(code, out var expanded)) cache[code] = expanded = LoadSite(Path.Combine(dataDirectory, "geosite.dat"), code); domains.AddRange(expanded); } var chunk = new List(); var bytes = 0; foreach (var domain in domains) { var cost = Encoding.UTF8.GetByteCount(domain) + 32; if (chunk.Count > 0 && bytes + cost > 384 * 1024) Flush(); chunk.Add(domain); bytes += cost; } if (chunk.Count > 0) Flush(); else if (domains.Count == 0) throw new InvalidDataException("空域名规则不能热更新。"); void Flush() { var copy = rule.DeepClone().AsObject(); copy["domain"] = new JsonArray(chunk.Select(d => (JsonNode?)JsonValue.Create(d)).ToArray()); Add(copy); chunk.Clear(); bytes = 0; } } if (result.Count == 0) throw new InvalidDataException("拒绝用空规则替换当前线路。"); return result; void Add(JsonObject rule) { // Domain chunks are OR alternatives; preserve every other AND // condition and the original rule priority. rule["ruleTag"] = $"{OwnedPrefix}{generation}-{result.Count}"; result.Add(rule); } } private static List LoadSite(string path, string code) { var bytes = File.ReadAllBytes(path); foreach (var entry in Fields(bytes).Where(f => f.Number == 1 && f.Wire == 2)) { var fields = Fields(entry.Value); var country = fields.FirstOrDefault(f => f.Number == 1 && f.Wire == 2); if (country is null || !Encoding.UTF8.GetString(country.Value.Span).Equals(code, StringComparison.OrdinalIgnoreCase)) continue; var result = new List(); foreach (var domain in fields.Where(f => f.Number == 2 && f.Wire == 2)) { var parts = Fields(domain.Value); var type = parts.FirstOrDefault(f => f.Number == 1)?.Scalar ?? 0; var value = parts.FirstOrDefault(f => f.Number == 2 && f.Wire == 2) ?? throw new InvalidDataException("geosite 域名内容缺失。"); var prefix = type switch { 0 => "keyword:", 1 => "regexp:", 2 => "domain:", 3 => "full:", _ => throw new InvalidDataException("未知 geosite 域名匹配类型。") }; result.Add(prefix + Encoding.UTF8.GetString(value.Value.Span)); } return result; } throw new InvalidDataException($"本地 geosite 没有 {code},现有路由保持不变。"); } private sealed record Field(int Number, int Wire, ulong Scalar, ReadOnlyMemory Value); private static List Fields(ReadOnlyMemory input) { var fields = new List(); var offset = 0; while (offset < input.Length) { var tag = Varint(input.Span, ref offset); var wire = (int)(tag & 7); var number = checked((int)(tag >> 3)); if (number == 0) throw new InvalidDataException("无效 protobuf 字段。"); if (wire == 0) { fields.Add(new Field(number, wire, Varint(input.Span, ref offset), default)); continue; } var length = wire switch { 1 => 8, 5 => 4, 2 => checked((int)Varint(input.Span, ref offset)), _ => throw new InvalidDataException("未知 protobuf 编码。") }; if (length < 0 || length > input.Length - offset) throw new InvalidDataException("截断的 geosite 数据。"); fields.Add(new Field(number, wire, 0, input.Slice(offset, length))); offset += length; } return fields; } private static ulong Varint(ReadOnlySpan bytes, ref int offset) { ulong value = 0; for (var shift = 0; shift < 64 && offset < bytes.Length; shift += 7) { var next = bytes[offset++]; value |= (ulong)(next & 127) << shift; if ((next & 128) == 0) return value; } throw new InvalidDataException("无效 protobuf 整数。"); } }