AlexStocks commented on code in PR #1: URL: https://github.com/apache/dubbo-net/pull/1#discussion_r4431088558
########## DubboService/Native/DubboHessian2Reader.cs: ########## @@ -0,0 +1,549 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace DubboNet.DubboService.Native +{ + /// <summary> + /// 将 Hessian2 值读取为动态 .NET 列表和字典,用于 CLR 返回类型未知的 Dubbo 泛化响应。 + /// <para>EN: Reads Hessian2 values into dynamic .NET lists and dictionaries for generic Dubbo responses whose CLR result type is unknown.</para> + /// </summary> + internal sealed class DubboHessian2Reader + { + // Also used when expanding references into JSON-compatible response values. + internal const int MaxNestingDepth = 64; + private int _depth; + private sealed class ClassDefinition + { + public string TypeName { get; set; } + public string[] Fields { get; set; } + } + + private readonly byte[] _buffer; + private readonly List<object> _references = new List<object>(); + private readonly List<string> _typeReferences = new List<string>(); + private readonly List<ClassDefinition> _classDefinitions = new List<ClassDefinition>(); + private int _position; + + /// <summary> + /// 创建读取指定 Hessian2 数据的解析器。 + /// <para>EN: Creates a reader for the supplied Hessian2 payload.</para> + /// </summary> + public DubboHessian2Reader(byte[] buffer) + { + _buffer = buffer ?? throw new ArgumentNullException(nameof(buffer)); + } + + /// <summary> + /// 读取一个 Hessian2 整数。 + /// <para>EN: Reads one Hessian2 integer.</para> + /// </summary> + public int ReadInt() + { + return ReadInt(ReadByte()); + } + + /// <summary> + /// 读取一个 Hessian2 字符串。 + /// <para>EN: Reads one Hessian2 string.</para> + /// </summary> + public string ReadString() + { + return ReadString(ReadByte()); + } + + /// <summary> + /// 读取下一个动态 Hessian2 值。 + /// <para>EN: Reads the next dynamic Hessian2 value.</para> + /// </summary> + public object ReadValue() + { + if (_depth >= MaxNestingDepth) + throw new InvalidDataException($"Hessian2 nesting exceeds the limit of {MaxNestingDepth}."); + _depth++; + try { return ReadValueCore(); } + finally { _depth--; } + } + + private object ReadValueCore() + { + byte tag = ReadByte(); + if (tag == (byte)'N') return null; + if (tag == (byte)'T') return true; + if (tag == (byte)'F') return false; + + if (IsIntTag(tag)) return ReadInt(tag); + if (IsLongTag(tag)) return ReadLong(tag); + if (IsDoubleTag(tag)) return ReadDouble(tag); + + if (tag == 0x4a) + { + return DateTimeOffset.FromUnixTimeMilliseconds(ReadInt64()).UtcDateTime; + } + if (tag == 0x4b) + { + return DateTimeOffset.FromUnixTimeSeconds((long)ReadInt32() * 60).UtcDateTime; + } + + if (IsStringTag(tag)) return ReadString(tag); + if (IsBinaryTag(tag)) return ReadBinary(tag); + + if (IsListTag(tag)) return ReadList(tag); + if (tag == (byte)'C') return ReadClassDefinitionAndValue(); + if (IsMapOrObjectTag(tag)) return ReadMapOrObject(tag); + + if (tag == 0x51) + { + int reference = ReadInt(); + if (reference < 0 || reference >= _references.Count) + { + throw new InvalidDataException($"Invalid Hessian2 reference index {reference}."); + } + return _references[reference]; + } + + throw new InvalidDataException($"Unsupported Hessian2 tag 0x{tag:x2}."); + } + + private object ReadClassDefinitionAndValue() + { + string typeName = ReadString(); + int fieldCount = ReadInt(); + if (fieldCount < 0) + { + throw new InvalidDataException($"Invalid Hessian2 class field count {fieldCount}."); + } + + string[] fields = new string[fieldCount]; + for (int i = 0; i < fields.Length; i++) + { + fields[i] = ReadString(); + } + _classDefinitions.Add(new ClassDefinition + { + TypeName = typeName, + Fields = fields + }); + return ReadValue(); + } + + private object ReadMapOrObject(byte tag) + { + if (tag == (byte)'H' || tag == (byte)'M') + { + string typeName = tag == (byte)'M' ? ReadType() : null; + Dictionary<object, object> map = NewMap(typeName); + _references.Add(map); + while (PeekByte() != (byte)'Z') + { + object key = ReadValue(); + object value = ReadValue(); + map[key ?? "null"] = value; + } + _position++; + return map; + } + + int definitionIndex = tag == (byte)'O' ? ReadInt() : tag - 0x60; + if (definitionIndex < 0 || definitionIndex >= _classDefinitions.Count) + { + throw new InvalidDataException( + $"Invalid Hessian2 class definition index {definitionIndex}."); + } + + ClassDefinition definition = _classDefinitions[definitionIndex]; + Dictionary<object, object> instance = NewMap(definition.TypeName); + _references.Add(instance); + foreach (string field in definition.Fields) + { + instance[field] = ReadValue(); + } + return instance; + } + + private static Dictionary<object, object> NewMap(string typeName) + { + Dictionary<object, object> result = new Dictionary<object, object>(); + if (!string.IsNullOrWhiteSpace(typeName)) + { + result["class"] = typeName; + } + return result; + } + + private object ReadList(byte tag) + { + bool hasEnd; + int length; + + switch (tag) + { + case 0x55: + _ = ReadType(); + hasEnd = true; + length = -1; + break; + case 0x56: + _ = ReadType(); + hasEnd = false; + length = ReadInt(); + break; + case 0x57: + hasEnd = true; + length = -1; + break; + case 0x58: + hasEnd = false; + length = ReadInt(); + break; + default: + hasEnd = false; + if (tag >= 0x70 && tag <= 0x77) + { + length = tag - 0x70; + _ = ReadType(); + } + else + { + length = tag - 0x78; + } + break; + } + + if (length < -1) + { + throw new InvalidDataException($"Invalid Hessian2 list length {length}."); + } + + List<object> list = length > 0 ? new List<object>(length) : new List<object>(); + _references.Add(list); + if (hasEnd) + { + while (PeekByte() != (byte)'Z') + { + list.Add(ReadValue()); + } + _position++; + } + else + { + for (int i = 0; i < length; i++) + { + list.Add(ReadValue()); + } + } + return list; + } + + private string ReadType() + { + byte tag = PeekByte(); + if (IsIntTag(tag)) + { + int index = ReadInt(); + if (index < 0 || index >= _typeReferences.Count) + { + throw new InvalidDataException($"Invalid Hessian2 type reference index {index}."); + } + return _typeReferences[index]; + } + + string typeName = ReadString(); + _typeReferences.Add(typeName); + return typeName; + } + + private int ReadInt(byte tag) + { + if (tag >= 0x80 && tag <= 0xbf) + { + return tag - 0x90; + } + if (tag >= 0xc0 && tag <= 0xcf) + { + return ((tag - 0xc8) << 8) + ReadByte(); + } + if (tag >= 0xd0 && tag <= 0xd7) + { + return ((tag - 0xd4) << 16) + (ReadByte() << 8) + ReadByte(); + } + if (tag == (byte)'I') + { + return ReadInt32(); + } + throw new InvalidDataException($"Hessian2 tag 0x{tag:x2} is not an integer."); + } + + private long ReadLong(byte tag) + { + if (tag >= 0xd8 && tag <= 0xef) + { + return tag - 0xe0; + } + if (tag >= 0xf0) + { + return ((tag - 0xf8) << 8) + ReadByte(); + } + if (tag >= 0x38 && tag <= 0x3f) + { + return ((long)(tag - 0x3c) << 16) + (ReadByte() << 8) + ReadByte(); + } + if (tag == 0x59) + { + return ReadInt32(); + } + if (tag == (byte)'L') + { + return ReadInt64(); + } + throw new InvalidDataException($"Hessian2 tag 0x{tag:x2} is not a long."); + } + + private double ReadDouble(byte tag) + { + switch (tag) + { + case 0x5b: + return 0d; + case 0x5c: + return 1d; + case 0x5d: + return (sbyte)ReadByte(); + case 0x5e: + return unchecked((short)ReadUInt16()); + case 0x5f: + return ReadInt32() * 0.001d; + case (byte)'D': + return BitConverter.Int64BitsToDouble(ReadInt64()); + default: + throw new InvalidDataException($"Hessian2 tag 0x{tag:x2} is not a double."); + } + } + + private string ReadString(byte tag) + { + if (tag == (byte)'N') return null; + if (tag <= 0x1f) return ReadUtf8Chars(tag); + if (tag >= 0x30 && tag <= 0x33) + { + return ReadUtf8Chars(((tag - 0x30) << 8) + ReadByte()); + } + if (tag == (byte)'S') + { + return ReadUtf8Chars(ReadUInt16()); + } + if (tag == (byte)'R') + { + StringBuilder builder = new StringBuilder(); + builder.Append(ReadUtf8Chars(ReadUInt16())); + builder.Append(ReadString()); Review Comment: 🔴 **这条递归绕过了 64 层限制:分块字符串和分块二进制能直接打爆线程栈** 先更正 `DubboHessian2Reader.cs:251` 那条「ReadValue 的所有递归入口统一限制为 64 层」——`ReadList` / `ReadMapOrObject` / `ReadClassDefinitionAndValue` 确实都经 `ReadValue()`,但**这两个不是**: ```csharp // 分块字符串 'R' if (tag == (byte)'R') { StringBuilder builder = new StringBuilder(); builder.Append(ReadUtf8Chars(ReadUInt16())); builder.Append(ReadString()); // ← 这里,public ReadString() 重新读 tag,不经过 ReadValue return builder.ToString(); } ``` ```csharp // 分块二进制 'A'(第 439 行) if (tag == (byte)'A') { byte[] first = ReadBytes(ReadUInt16()); byte[] rest = ReadBinary(ReadByte()); // ← 同样不经过 ReadValue ... } ``` `_depth` 只在 `ReadValue()` 的 try/finally 里增减,所以这两条链上的嵌套深度对计数器**完全不可见**。`IsStringTag` 包含 `'R'`、`IsBinaryTag` 包含 `'A'`(519–533 行),`ReadValueCore` 会把它们直接分发进来,于是「一个 `ReadValue` 调用 + 无限深内部递归」。 **最小载荷**:每层只要 3 字节,因为长度字段可以为 0: - 分块字符串:`52 00 00` 重复 N 次(`'R'` + uint16 长度 0,`ReadUtf8Chars(0)` 立即返回,然后 `ReadString()` 读下一个 `'R'`) - 分块二进制:`41 00 00` 重复 N 次 按 .NET 默认 1MB 线程栈、单帧几百字节估,N 在几千量级就会 `StackOverflowException`,即**十几 KB 的响应体**。`DefaultMaxPayloadLength` 是 8MB,拦不住。而 .NET 的 `StackOverflowException` **无法被 try/catch 捕获**,进程直接终止——不是「这个请求失败」,是整个客户端没了。 **触发面**:`DecodeResponse`(`NativeDubboCodec.cs:176`)是 `DubboHessian2Reader` 唯一的生产消费方,解析的是 **provider 返回的 body**。`QueryDemo` / 集成测试都支持 `--host` 指向任意地址,registry 里的 provider 也可能是被攻陷的,所以这是「provider 完全控制字节流」的场景。 **Suggestion**:这两处的语义是**分块拼接,不是嵌套**,所以正确的修法不是加深度计数,而是改成迭代: ```csharp private string ReadString(byte tag) { ... if (tag == (byte)'R') { StringBuilder builder = new StringBuilder(); tag = ReadByte(); while (tag == (byte)'R') { builder.Append(ReadUtf8Chars(ReadUInt16())); tag = ReadByte(); } builder.Append(ReadString(tag)); // 收尾的非 R 字符串 return builder.ToString(); } ... } ``` `ReadBinary` 同理(`while (tag == (byte)'A')` 累加到 `MemoryStream` 后一次 `ToArray()`)。改完顺带解决了 `'A'` 那条的 O(n²) 拷贝:现在每层都 `new byte[first.Length + rest.Length]` 全量复制一次。 建议补两个用例,放在已有的 `NativeDubboCodecTest` 里:`DecodeResponse` 传入 2 万个 `52 00 00` / `41 00 00`,断言抛出 `InvalidDataException` 或正常返回,**不能崩进程**。 ########## DubboService/TripleDubboActuatorSuite.cs: ########## @@ -0,0 +1,504 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using DubboNet.Clients.DataModle; +using DubboNet.DubboService.DataModle; +using DubboNet.DubboService.Native; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace DubboNet.DubboService +{ + /// <summary> + /// 通过 Dubbo 3.3 引入的 HTTP/JSON 兼容端点调用 Dubbo Triple Java 接口一元方法。 + /// EN: Invokes Dubbo Triple Java-interface unary methods through the HTTP/JSON + /// compatibility endpoint introduced by Dubbo 3.3. + /// </summary> + /// <remarks> + /// 第一期实现仅面向使用 <c>application/json</c> 的 Java 接口一元调用,不包含 + /// Protobuf IDL、流式调用和带帧的 gRPC 线协议。 + /// EN: This first implementation intentionally targets unary Java-interface calls + /// with <c>application/json</c>. Protobuf IDL, streaming and the framed gRPC + /// wire format are outside its scope. + /// </remarks> + public sealed class TripleDubboActuatorSuite : + IDubboActuatorSuite, + IDubboGenericInvocationActuator + { + private const string ServiceVersionHeader = "tri-service-version"; + private const string ServiceGroupHeader = "tri-service-group"; + private const string ServiceTimeoutHeader = "tri-service-timeout"; + + private static readonly HashSet<string> ReservedRequestHeaders = + new HashSet<string>(StringComparer.OrdinalIgnoreCase) + { + "host", + "content-length", + "content-type", + "grpc-timeout", + ServiceVersionHeader, + ServiceGroupHeader, + ServiceTimeoutHeader + }; + + private sealed class ServiceMetadata + { + public string Version { get; set; } + public string Group { get; set; } + public int? Timeout { get; set; } + } + + private readonly HttpClient _httpClient; + private readonly bool _ownsHttpClient; + private readonly int _requestTimeoutMilliseconds; + private readonly ConcurrentDictionary<string, ServiceMetadata> _services = + new ConcurrentDictionary<string, ServiceMetadata>(StringComparer.Ordinal); + private bool _disposed; + + /// <inheritdoc/> + public DubboActuatorProtocolType ProtocolType => DubboActuatorProtocolType.Triple; + + /// <inheritdoc/> + public string ServiceFuncSpit => "/"; + + /// <inheritdoc/> + public DubboActuatorSuiteStatus ActuatorSuiteStatusInfo { get; private set; } = + new DubboActuatorSuiteStatus(); + + /// <inheritdoc/> + public DateTime LastActivateTime { get; private set; } = DateTime.Now; + + /// <summary> + /// 获取默认的 Java 服务接口名。 + /// EN: Gets the default Java service interface name. + /// </summary> + public string DefaultServiceName { get; private set; } + + /// <summary> + /// 使用指定地址和端口创建 Triple HTTP/JSON 执行器。 + /// EN: Creates a Triple HTTP/JSON actuator from an address and port. + /// </summary> + /// <param name="address">Provider 地址。EN: Provider address.</param> + /// <param name="port">Provider 端口。EN: Provider port.</param> + /// <param name="dubboActuatorSuiteConf">执行器配置。EN: Actuator configuration.</param> + public TripleDubboActuatorSuite( + string address, + int port, + DubboActuatorSuiteConf dubboActuatorSuiteConf = null) + : this( + CreateHttpClient(address, port, dubboActuatorSuiteConf), + dubboActuatorSuiteConf, + true) + { + } + + /// <summary> + /// 使用网络端点创建 Triple HTTP/JSON 执行器。 + /// EN: Creates a Triple HTTP/JSON actuator from a network endpoint. + /// </summary> + /// <param name="endPoint">Provider 网络端点。EN: Provider network endpoint.</param> + /// <param name="dubboActuatorSuiteConf">执行器配置。EN: Actuator configuration.</param> + public TripleDubboActuatorSuite( + IPEndPoint endPoint, + DubboActuatorSuiteConf dubboActuatorSuiteConf = null) + : this( + endPoint?.Address.ToString() + ?? throw new ArgumentNullException(nameof(endPoint)), + endPoint.Port, + dubboActuatorSuiteConf) + { + } + + internal TripleDubboActuatorSuite( + HttpClient httpClient, + DubboActuatorSuiteConf dubboActuatorSuiteConf = null) + : this(httpClient, dubboActuatorSuiteConf, false) + { + } + + private TripleDubboActuatorSuite( + HttpClient httpClient, + DubboActuatorSuiteConf dubboActuatorSuiteConf, + bool ownsHttpClient) + { + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + if (_httpClient.BaseAddress == null) + { + throw new ArgumentException( + "Triple HttpClient must define BaseAddress.", + nameof(httpClient)); + } + + DubboActuatorSuiteConf configuration = + dubboActuatorSuiteConf ?? new DubboActuatorSuiteConf(); + DefaultServiceName = configuration.DefaultServiceName; + _requestTimeoutMilliseconds = Math.Max(1, configuration.DubboRequestTimeout); + _ownsHttpClient = ownsHttpClient; + } + + internal void RegisterService(DubboServiceEndPointInfo endpoint) + { + if (endpoint == null) + { + throw new ArgumentNullException(nameof(endpoint)); + } + if (string.IsNullOrWhiteSpace(endpoint.Interface)) + { + return; + } + + _services[endpoint.Interface] = new ServiceMetadata + { + Version = endpoint.Version, + Group = endpoint.Group, + Timeout = endpoint.Timeout + }; + } + + /// <inheritdoc/> + public Task<DubboRequestResult> SendQuery(string endPoint) + { + return SendQuery(endPoint, string.Empty); + } + + /// <inheritdoc/> + public Task<DubboRequestResult> SendQuery(string endPoint, string req) + { + if (!string.IsNullOrWhiteSpace(DefaultServiceName) + && !string.IsNullOrWhiteSpace(endPoint) + && !endPoint.Contains("#") + && !endPoint.Contains("/") + && !endPoint.Contains(".")) + { + endPoint = $"{DefaultServiceName}.{endPoint}"; + } + + DubboInvocation invocation = NativeDubboCodec.ParseInvocation(endPoint, req); + return SendQuery(invocation); + } + + /// <inheritdoc/> + public Task<DubboRequestResult> SendQuery(DubboInvocation invocation) + { + return SendQuery(invocation, CancellationToken.None); + } + + /// <inheritdoc/> + public async Task<DubboRequestResult> SendQuery( + DubboInvocation invocation, + CancellationToken cancellationToken) + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(TripleDubboActuatorSuite)); + } + + invocation.Validate(); + LastActivateTime = DateTime.Now; + Stopwatch stopwatch = Stopwatch.StartNew(); + DubboRequestResult result = new DubboRequestResult + { + ServiceElapsed = 0, + ServiceElapsedAvailable = false + }; + + _services.TryGetValue(invocation.Service, out ServiceMetadata metadata); + string version = FirstNonBlank(invocation.Version, metadata?.Version); + string group = FirstNonBlank(invocation.Group, metadata?.Group); + int timeoutMilliseconds = Math.Max( + 1, + metadata?.Timeout ?? _requestTimeoutMilliseconds); + + string requestPath = $"/{Uri.EscapeDataString(invocation.Service)}" + + $"/{Uri.EscapeDataString(invocation.Method)}"; + string requestBody = JsonSerializer.Serialize(invocation.Arguments); + + try + { + // ResponseHeadersRead ends HttpClient.Timeout at the headers. Keep a + // single deadline alive until the complete body has been consumed. + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(timeoutMilliseconds); + using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestPath) + { + Version = HttpVersion.Version11, + VersionPolicy = HttpVersionPolicy.RequestVersionExact, + Content = new StringContent(requestBody, Encoding.UTF8, "application/json") + }; + + AddHeader(request, ServiceVersionHeader, version); + AddHeader(request, ServiceGroupHeader, group); + AddHeader(request, ServiceTimeoutHeader, timeoutMilliseconds.ToString()); + AddAttachments(request, invocation.Attachments); + + using HttpResponseMessage response = await _httpClient.SendAsync( + request, + HttpCompletionOption.ResponseHeadersRead, + timeout.Token).ConfigureAwait(false); + string responseBody = await response.Content + .ReadAsStringAsync(timeout.Token) + .ConfigureAwait(false); + + stopwatch.Stop(); + result.RequestElapsed = (int)stopwatch.ElapsedMilliseconds; + result.Result = responseBody; + result.RawResult = ParseResponseValue(responseBody); + result.ResponseAttachments = ReadResponseHeaders(response); + + if (!response.IsSuccessStatusCode) + { + result.UpdateQueryFailed(); + result.ErrorMeaasge = BuildHttpError(response, responseBody); + } + } + catch (Exception exception) + { + stopwatch.Stop(); + result.RequestElapsed = (int)stopwatch.ElapsedMilliseconds; + result.UpdateQueryFailed(); + result.ErrorMeaasge = exception.Message; + } + + ActuatorSuiteStatusInfo.LastQueryElapsed = result.RequestElapsed; + return result; + } + + /// <inheritdoc/> + public async Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp>( + string endPoint, + string req) + { + return new DubboRequestResult<T_Rsp>( + await SendQuery(endPoint, req).ConfigureAwait(false)); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp>(string endPoint) + { + return SendQuery<T_Rsp>(endPoint, string.Empty); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req>( + string endPoint, + T_Req req) + { + return SendObjects<T_Rsp>(endPoint, req); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2>( + string endPoint, T_Req1 req1, T_Req2 req2) + { + return SendObjects<T_Rsp>(endPoint, req1, req2); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2, T_Req3>( + string endPoint, T_Req1 req1, T_Req2 req2, T_Req3 req3) + { + return SendObjects<T_Rsp>(endPoint, req1, req2, req3); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2, T_Req3, T_Req4>( + string endPoint, T_Req1 req1, T_Req2 req2, T_Req3 req3, T_Req4 req4) + { + return SendObjects<T_Rsp>(endPoint, req1, req2, req3, req4); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2, T_Req3, T_Req4, T_Req5>( + string endPoint, T_Req1 req1, T_Req2 req2, T_Req3 req3, T_Req4 req4, T_Req5 req5) + { + return SendObjects<T_Rsp>(endPoint, req1, req2, req3, req4, req5); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2, T_Req3, T_Req4, T_Req5, T_Req6>( + string endPoint, T_Req1 req1, T_Req2 req2, T_Req3 req3, T_Req4 req4, T_Req5 req5, T_Req6 req6) + { + return SendObjects<T_Rsp>(endPoint, req1, req2, req3, req4, req5, req6); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2, T_Req3, T_Req4, T_Req5, T_Req6, T_Req7>( + string endPoint, T_Req1 req1, T_Req2 req2, T_Req3 req3, T_Req4 req4, T_Req5 req5, T_Req6 req6, T_Req7 req7) + { + return SendObjects<T_Rsp>(endPoint, req1, req2, req3, req4, req5, req6, req7); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2, T_Req3, T_Req4, T_Req5, T_Req6, T_Req7, T_Req8>( + string endPoint, T_Req1 req1, T_Req2 req2, T_Req3 req3, T_Req4 req4, T_Req5 req5, T_Req6 req6, T_Req7 req7, T_Req8 req8) + { + return SendObjects<T_Rsp>(endPoint, req1, req2, req3, req4, req5, req6, req7, req8); + } + + /// <inheritdoc/> + public Task<DubboRequestResult<T_Rsp>> SendQuery<T_Rsp, T_Req1, T_Req2, T_Req3, T_Req4, T_Req5, T_Req6, T_Req7, T_Req8, T_Req9>( + string endPoint, T_Req1 req1, T_Req2 req2, T_Req3 req3, T_Req4 req4, T_Req5 req5, T_Req6 req6, T_Req7 req7, T_Req8 req8, T_Req9 req9) + { + return SendObjects<T_Rsp>(endPoint, req1, req2, req3, req4, req5, req6, req7, req8, req9); + } + + private async Task<DubboRequestResult<T_Rsp>> SendObjects<T_Rsp>( + string endPoint, + params object[] arguments) + { + string request = JsonSerializer.Serialize(arguments); + return new DubboRequestResult<T_Rsp>( + await SendQuery(endPoint, request).ConfigureAwait(false)); + } + + private static HttpClient CreateHttpClient( + string address, + int port, + DubboActuatorSuiteConf configuration) + { + if (string.IsNullOrWhiteSpace(address)) + { + throw new ArgumentException("Provider address cannot be empty.", nameof(address)); + } + + DubboActuatorSuiteConf effectiveConfiguration = + configuration ?? new DubboActuatorSuiteConf(); + int maxConnections = Math.Max(1, effectiveConfiguration.MaxConnections); + SocketsHttpHandler handler = new SocketsHttpHandler + { + MaxConnectionsPerServer = maxConnections, + PooledConnectionIdleTimeout = effectiveConfiguration.MasterConnectionAliveTime > 0 + ? TimeSpan.FromSeconds(effectiveConfiguration.MasterConnectionAliveTime) + : Timeout.InfiniteTimeSpan + }; + + HttpClient client = new HttpClient(handler) + { + BaseAddress = new Uri($"http://{address}:{port}"), Review Comment: 🟡 **IPv6 字面量走到这里必抛 `UriFormatException`:`http://::1:8080` 不是合法 URI** 这个 PR 新增的端点参数是**明确支持 IPv6** 的: - `TestEndpointOptions.Host()` 会 `Trim('[', ']')` 后接受 `::1`(`Uri.CheckHostName` 返回 `IPv6`,不是 `Unknown`),`TestEndpointOptionsTest` 里也有对应用例; - `ResolveProviderAddressesAsync` 保留 `AddressFamily.InterNetworkV6`,只是把 IPv4 排在前面; - 同一个文件里给 registry 拼地址时**已经处理了方括号**:`effectiveHost.Contains(':') ? $"[{effectiveHost}]" : effectiveHost`。 但这里直接字符串插值: ```csharp BaseAddress = new Uri($"http://{address}:{port}"), ``` `address = "::1"` → `http://::1:8080`。RFC 3986 要求 IPv6 字面量必须带方括号,所以 `Uri` 构造器抛 `UriFormatException: Invalid URI: The hostname could not be parsed`。而且 `port` 也会被吞进冒号里,即使不抛也解释错了。 两个入口都中: - `TripleDubboActuatorSuite("::1", 50051)` 直接构造; - `TripleDubboActuatorSuite(IPEndPoint)` 走 `endPoint.Address.ToString()`,IPv6 的 `ToString()` 就是无括号的 `::1`,同样抛。 而 Native 侧用的是 `IPEndPoint` / `IPAddress`(`NativeDubboConnection(IPEndPoint ...)`),不经过字符串,所以「`--host ::1` 时 Native 能用、Triple 不能用」——同一个参数在两个 suite 上一个通一个炸,这个不一致本身也说明问题出在拼接方式而不是参数校验。 **Suggestion**:抽一个和 registry 那边一致的辅助方法,或直接用 `UriBuilder`(它会对 IPv6 自动加方括号): ```csharp string host = address.Contains(':') ? $"[{address.Trim('[', ']')}]" : address; BaseAddress = new Uri($"http://{host}:{port}"); ``` 顺手加一个单测:`new TripleDubboActuatorSuite("::1", 50051)` 不抛,且 `BaseAddress.Host` 是 `::1`;再补一个 `IPEndPoint(IPAddress.IPv6Loopback, 50051)` 的用例覆盖第二个构造器。 如果这个 PR 不打算支持 IPv6 的 Triple 路径,那至少要在 `Host()` 里拒绝 IPv6,并让 `--host` 的帮助文本说明只支持 IPv4/hostname——现在的状态是「校验放行、构造必炸」,用户看到的是一个莫名的 `UriFormatException`。 ########## DubboService/Native/NativeDubboCodec.cs: ########## @@ -0,0 +1,788 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using DubboNet.DubboService.DataModle; +using NHessian.IO; +using System; +using System.Buffers.Binary; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.Encodings.Web; +using System.Text.Unicode; + +namespace DubboNet.DubboService.Native +{ + /// <summary> + /// 编解码 Dubbo2 16 字节帧头、Hessian2 泛化调用请求和响应。 + /// <para>EN: Encodes and decodes Dubbo2 16-byte frames and Hessian2 generic invocation payloads.</para> + /// </summary> + internal static class NativeDubboCodec + { + internal const int HeaderLength = 16; + internal const int DefaultMaxPayloadLength = 8 * 1024 * 1024; + internal const byte Hessian2SerializationId = 2; + internal const byte OkStatus = 20; + internal const string ProtocolVersion = "2.0.2"; + internal const string GenericParameterDescriptor = + "Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;"; + + private const byte RequestFlag = 0x80; + private const byte TwoWayFlag = 0x40; + private const byte EventFlag = 0x20; + private const byte SerializationMask = 0x1f; + + private static readonly JsonSerializerOptions ResultJsonOptions = + new JsonSerializerOptions + { + // 保留中文等 Unicode 字符的可读形式,同时继续转义 JSON/HTML 敏感字符。 + // EN: Keep Chinese and other Unicode characters readable while retaining + // the encoder's escaping of JSON/HTML-sensitive characters. + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) + }; + + private static readonly JsonSerializerOptions ArgumentJsonOptions = + new JsonSerializerOptions + { + IncludeFields = true + }; + + /// <summary> + /// 将泛化调用编码为完整的双向 Dubbo2 请求帧。 + /// <para>EN: Encodes a generic invocation as a complete two-way Dubbo2 request frame.</para> + /// </summary> + internal static byte[] EncodeGenericRequest( + long requestId, + DubboInvocation invocation, + string serviceVersion, + string group, + int timeoutMilliseconds) + { + invocation.Validate(); + byte[] body = EncodeGenericRequestBody( + invocation, + serviceVersion, + group, + timeoutMilliseconds); + + byte[] frame = new byte[HeaderLength + body.Length]; + frame[0] = 0xda; + frame[1] = 0xbb; + frame[2] = RequestFlag | TwoWayFlag | Hessian2SerializationId; + frame[3] = 0; + BinaryPrimitives.WriteInt64BigEndian(frame.AsSpan(4, 8), requestId); + BinaryPrimitives.WriteInt32BigEndian(frame.AsSpan(12, 4), body.Length); + body.CopyTo(frame, HeaderLength); + return frame; + } + + /// <summary> + /// 编码客户端心跳请求帧。 + /// <para>EN: Encodes a client heartbeat request frame.</para> + /// </summary> + internal static byte[] EncodeHeartbeat(long requestId) + { + byte[] frame = new byte[HeaderLength + 1]; + frame[0] = 0xda; + frame[1] = 0xbb; + frame[2] = RequestFlag | TwoWayFlag | EventFlag | Hessian2SerializationId; + BinaryPrimitives.WriteInt64BigEndian(frame.AsSpan(4, 8), requestId); + BinaryPrimitives.WriteInt32BigEndian(frame.AsSpan(12, 4), 1); + frame[HeaderLength] = (byte)'N'; + return frame; + } + + /// <summary> + /// 编码服务端双向事件所需的心跳响应帧。 + /// <para>EN: Encodes the heartbeat response required by a server two-way event.</para> + /// </summary> + internal static byte[] EncodeHeartbeatResponse(long requestId, byte serializationId) + { + byte[] frame = new byte[HeaderLength + 1]; + frame[0] = 0xda; + frame[1] = 0xbb; + frame[2] = (byte)(EventFlag | (serializationId & SerializationMask)); + frame[3] = OkStatus; + BinaryPrimitives.WriteInt64BigEndian(frame.AsSpan(4, 8), requestId); + BinaryPrimitives.WriteInt32BigEndian(frame.AsSpan(12, 4), 1); + frame[HeaderLength] = (byte)'N'; + return frame; + } + + /// <summary> + /// 按 <c>GenericService.$invoke</c> 参数顺序编码 Hessian2 请求体。 + /// <para>EN: Encodes a Hessian2 request body in <c>GenericService.$invoke</c> argument order.</para> + /// </summary> + internal static byte[] EncodeGenericRequestBody( + DubboInvocation invocation, + string serviceVersion, + string group, + int timeoutMilliseconds) + { + using MemoryStream stream = new MemoryStream(); + using HessianStreamWriter streamWriter = new HessianStreamWriter(stream, true); + HessianOutputV2 output = new HessianOutputV2(streamWriter, TypeBindings.Java); + + string effectiveVersion = invocation.Version ?? serviceVersion; + string effectiveGroup = invocation.Group ?? group; + object[] arguments = new object[invocation.Arguments.Count]; + Dictionary<object, object> normalizedReferences = + new Dictionary<object, object>(ReferenceEqualityComparer.Instance); + for (int i = 0; i < arguments.Length; i++) + { + object prepared = PrepareArgument( + invocation.Arguments[i], + invocation.ParameterTypes[i]); + arguments[i] = NormalizeHessianArgument(prepared, normalizedReferences); + } + + output.WriteString(ProtocolVersion); + output.WriteString(invocation.Service); + output.WriteString(effectiveVersion); + output.WriteString("$invoke"); + output.WriteString(GenericParameterDescriptor); + output.WriteString(invocation.Method); + output.WriteObject(invocation.ParameterTypes.ToArray()); + output.WriteObject(arguments); + output.WriteObject(BuildAttachments( + invocation, + effectiveVersion, + effectiveGroup, + timeoutMilliseconds)); + + return stream.ToArray(); + } + + /// <summary> + /// 解码 Hessian2 响应标志、返回值、异常和 attachments。 + /// <para>EN: Decodes Hessian2 response flags, values, exceptions, and attachments.</para> + /// </summary> + internal static NativeDubboResponse DecodeResponse(NativeDubboFrame frame) + { + NativeDubboResponse response = new NativeDubboResponse + { + RequestId = frame.RequestId, + Status = frame.Status, + SerializationId = frame.SerializationId, + IsEvent = frame.IsEvent + }; + + if (frame.SerializationId != Hessian2SerializationId) + { + throw new NotSupportedException( + $"Dubbo response serialization id {frame.SerializationId} is not supported. " + + "NativeDubboActuatorSuite currently supports Hessian2 (id 2) only."); + } + + DubboHessian2Reader input = new DubboHessian2Reader(frame.Body); + + if (frame.Status != OkStatus) + { + response.ErrorMessage = input.ReadString(); + return response; + } + + if (frame.IsEvent) + { + response.Value = input.ReadValue(); + return response; + } + + response.ResultKind = input.ReadInt(); + switch (response.ResultKind) + { + case 0: + response.Exception = ToJsonCompatible(input.ReadValue()); + break; + case 1: + response.Value = ToJsonCompatible(input.ReadValue()); + break; + case 2: + break; + case 3: + response.Exception = ToJsonCompatible(input.ReadValue()); + response.Attachments = ReadAttachments(input); + break; + case 4: + response.Value = ToJsonCompatible(input.ReadValue()); + response.Attachments = ReadAttachments(input); + break; + case 5: + response.Attachments = ReadAttachments(input); + break; + default: + throw new InvalidDataException( + $"Unknown Dubbo response result kind {response.ResultKind}; expected 0 through 5."); + } + return response; + } + + /// <summary> + /// 校验并解析 Dubbo2 帧头。 + /// <para>EN: Validates and parses a Dubbo2 frame header.</para> + /// </summary> + internal static NativeDubboFrame DecodeFrameHeader(byte[] header, byte[] body) + { + if (header == null || header.Length != HeaderLength) + { + throw new InvalidDataException($"Dubbo header must contain exactly {HeaderLength} bytes."); + } + if (header[0] != 0xda || header[1] != 0xbb) + { + throw new InvalidDataException( + $"Invalid Dubbo magic 0x{header[0]:x2}{header[1]:x2}; expected 0xdabb."); + } + + int declaredLength = BinaryPrimitives.ReadInt32BigEndian(header.AsSpan(12, 4)); + if (body == null || declaredLength != body.Length) + { + throw new InvalidDataException( + $"Dubbo body length mismatch. Header declares {declaredLength}, received {body?.Length ?? 0}."); + } + + byte flags = header[2]; + return new NativeDubboFrame + { + Flags = flags, + Status = header[3], + RequestId = BinaryPrimitives.ReadInt64BigEndian(header.AsSpan(4, 8)), + SerializationId = (byte)(flags & SerializationMask), + IsRequest = (flags & RequestFlag) != 0, + IsTwoWay = (flags & TwoWayFlag) != 0, + IsEvent = (flags & EventFlag) != 0, + Body = body + }; + } + + /// <summary> + /// 将旧式 endpoint 与 JSON 请求转换为泛化调用;类型推断仅用于兼容入口。 + /// <para>EN: Converts a legacy endpoint and JSON request into a generic invocation; inference here exists for compatibility only.</para> + /// </summary> + internal static DubboInvocation ParseInvocation(string endPoint, string request) + { + (string service, string method) = SplitEndPoint(endPoint); + JsonElement[] jsonArguments = ParseJsonArguments(request); + string[] parameterTypes = new string[jsonArguments.Length]; + object[] arguments = new object[jsonArguments.Length]; + + for (int i = 0; i < jsonArguments.Length; i++) + { + parameterTypes[i] = InferJavaType(jsonArguments[i]); + arguments[i] = jsonArguments[i].Clone(); + } + + return new DubboInvocation(service, method, parameterTypes, arguments); + } + + internal static string SerializeJson(object value) + { + return JsonSerializer.Serialize(ToJsonCompatible(value), ResultJsonOptions); + } + + internal static string DescribeException(object exception) + { + if (exception is IDictionary<string, object> stringMap) + { + foreach (string key in new[] { "detailMessage", "message", "exceptionMessage" }) + { + if (stringMap.TryGetValue(key, out object value) && value != null) + { + return value.ToString(); + } + } + } + return exception?.ToString() ?? "The Dubbo provider returned an exception."; + } + + private static Dictionary<string, object> BuildAttachments( + DubboInvocation invocation, + string serviceVersion, + string group, + int timeoutMilliseconds) + { + Dictionary<string, object> attachments = new Dictionary<string, object>(StringComparer.Ordinal) + { + ["path"] = invocation.Service, + ["interface"] = invocation.Service, + ["dubbo"] = ProtocolVersion, + ["generic"] = "true", + ["timeout"] = Math.Max(1, timeoutMilliseconds).ToString() + }; + + if (!string.IsNullOrEmpty(serviceVersion)) + { + attachments["version"] = serviceVersion; + } + if (!string.IsNullOrEmpty(group)) + { + attachments["group"] = group; + } + if (invocation.Attachments != null) + { + foreach (KeyValuePair<string, string> attachment in invocation.Attachments) + { + attachments[attachment.Key] = attachment.Value; + } + } + return attachments; + } + + private static IReadOnlyDictionary<string, object> ReadAttachments(DubboHessian2Reader input) + { + object value = ToJsonCompatible(input.ReadValue()); + return value as IReadOnlyDictionary<string, object> + ?? new Dictionary<string, object>(); + } + + private static object PrepareArgument(object value, string javaType) + { + if (value is JsonDocument document) + { + value = document.RootElement; + } + if (value is JsonElement element) + { + value = FromJsonElement(element, javaType); + } + + switch (javaType) + { + case "byte": + case "java.lang.Byte": + case "short": + case "java.lang.Short": + case "int": + case "java.lang.Integer": + return value == null ? null : Convert.ToInt32(value); + case "long": + case "java.lang.Long": + return value == null ? null : Convert.ToInt64(value); + case "float": + case "java.lang.Float": + case "double": + case "java.lang.Double": + return value == null ? null : Convert.ToDouble(value); + case "boolean": + case "java.lang.Boolean": + return value == null ? null : Convert.ToBoolean(value); + case "char": + case "java.lang.Character": + case "java.lang.String": + return value?.ToString(); + default: + if (value != null && value is not string && IsPojoType(javaType)) + { + JsonElement serialized = JsonSerializer.SerializeToElement( + value, + ArgumentJsonOptions); + if (serialized.ValueKind == JsonValueKind.Object) + { + return FromJsonElement(serialized, javaType); + } + } + return AddPojoClass(value, javaType); + } + } + + private static object FromJsonElement(JsonElement element, string javaType = null) + { + switch (element.ValueKind) + { + case JsonValueKind.Null: + case JsonValueKind.Undefined: + return null; + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Number: + if (IsLongType(javaType) && element.TryGetInt64(out long longValue)) + { + return longValue; + } + if (IsFloatingPointType(javaType)) + { + return element.GetDouble(); + } + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long inferredLong)) + { + return inferredLong; + } + return element.GetDouble(); + case JsonValueKind.Array: + return element.EnumerateArray() + .Select(item => FromJsonElement(item)) + .ToArray(); + case JsonValueKind.Object: + Dictionary<string, object> map = new Dictionary<string, object>(StringComparer.Ordinal); + foreach (JsonProperty property in element.EnumerateObject()) + { + map[property.Name] = FromJsonElement(property.Value); + } + return AddPojoClass(map, javaType); + default: + throw new NotSupportedException($"Unsupported JSON value kind {element.ValueKind}."); + } + } + + private static object NormalizeHessianArgument( + object value, + Dictionary<object, object> normalizedReferences) + { + if (value == null + || value is string + || value is bool + || value is int + || value is long + || value is float + || value is double + || value is DateTime + || value is byte[] + || value is Enum) + { + return value; + } + + // NHessian 0.4.3 only writes int, long, float and double as native + // Hessian numbers. Unsupported CLR numeric structs are otherwise + // reflected as POJOs; decimal/UInt64 can then recurse through their + // own backing fields until a StackOverflowException occurs. + if (value is decimal decimalValue) + { + return Convert.ToDouble(decimalValue); + } + if (value is byte + || value is sbyte + || value is short + || value is ushort) + { + return Convert.ToInt32(value); + } + if (value is uint uintValue) + { + return Convert.ToInt64(uintValue); + } + if (value is ulong ulongValue) + { + if (ulongValue > long.MaxValue) + { + throw new ArgumentOutOfRangeException( + nameof(value), + ulongValue, + "UInt64 values greater than Int64.MaxValue cannot be encoded by Hessian2."); + } + return Convert.ToInt64(ulongValue); + } + if (value is char character) + { + return character.ToString(); + } + if (value is DateTimeOffset dateTimeOffset) + { + return dateTimeOffset.UtcDateTime; + } + if (value is Guid guid) + { + return guid.ToString(); + } + if (value is JsonDocument document) + { + return NormalizeHessianArgument( + FromJsonElement(document.RootElement), + normalizedReferences); + } + if (value is JsonElement element) + { + return NormalizeHessianArgument( + FromJsonElement(element), + normalizedReferences); + } + + if (normalizedReferences.TryGetValue(value, out object existing)) + { + return existing; + } + + if (value is IDictionary dictionary) + { + Dictionary<object, object> normalized = + new Dictionary<object, object>(); + normalizedReferences[value] = normalized; + foreach (DictionaryEntry entry in dictionary) + { + object key = NormalizeHessianArgument(entry.Key, normalizedReferences); + if (key == null) + { + throw new ArgumentException( + "Hessian request maps cannot contain a null key.", + nameof(value)); + } + normalized[key] = NormalizeHessianArgument( + entry.Value, + normalizedReferences); + } + return normalized; + } + + if (value is IEnumerable enumerable) + { + List<object> normalized = new List<object>(); + normalizedReferences[value] = normalized; + foreach (object item in enumerable) + { + normalized.Add(NormalizeHessianArgument(item, normalizedReferences)); + } + return normalized; + } + + JsonElement serialized = JsonSerializer.SerializeToElement( + value, + ArgumentJsonOptions); + object normalizedPojo = FromJsonElement(serialized); + object normalizedValue = NormalizeHessianArgument( + normalizedPojo, + normalizedReferences); + normalizedReferences[value] = normalizedValue; + return normalizedValue; + } + + private static object AddPojoClass(object value, string javaType) + { + if (value is IDictionary<string, object> map && IsPojoType(javaType)) + { + if (!map.ContainsKey("class")) + { + map["class"] = javaType; + } + } + return value; + } + + private static bool IsPojoType(string javaType) + { + if (string.IsNullOrWhiteSpace(javaType) || javaType.StartsWith("[", StringComparison.Ordinal)) + { + return false; + } + return javaType != "java.lang.Object" + && javaType != "java.util.Map" + && javaType != "java.util.HashMap" + && javaType != "java.util.List" + && javaType != "java.util.Collection"; + } + + private static bool IsLongType(string javaType) + { + return javaType == "long" || javaType == "java.lang.Long"; + } + + private static bool IsFloatingPointType(string javaType) + { + return javaType == "float" + || javaType == "java.lang.Float" + || javaType == "double" + || javaType == "java.lang.Double"; + } + + private static JsonElement[] ParseJsonArguments(string request) + { + if (string.IsNullOrWhiteSpace(request)) + { + return Array.Empty<JsonElement>(); + } + + string trimmed = request.Trim(); + string json = trimmed.StartsWith("[", StringComparison.Ordinal) + && trimmed.EndsWith("]", StringComparison.Ordinal) + ? trimmed + : $"[{trimmed}]"; + + using JsonDocument document = JsonDocument.Parse(json); + return document.RootElement.EnumerateArray() + .Select(item => item.Clone()) + .ToArray(); + } + + private static string InferJavaType(JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return "java.lang.String"; + case JsonValueKind.True: + case JsonValueKind.False: + return "boolean"; + case JsonValueKind.Number: + if (element.TryGetInt32(out _)) + { + return "int"; + } + if (element.TryGetInt64(out _)) + { + return "long"; + } + return "double"; + case JsonValueKind.Object: + if (element.TryGetProperty("class", out JsonElement classElement) + && classElement.ValueKind == JsonValueKind.String + && !string.IsNullOrWhiteSpace(classElement.GetString())) + { + return classElement.GetString(); + } + return "java.util.Map"; + case JsonValueKind.Array: + return "java.util.List"; + case JsonValueKind.Null: + case JsonValueKind.Undefined: + return "java.lang.Object"; + default: + throw new NotSupportedException( + $"Cannot infer a Java parameter type from JSON kind {element.ValueKind}."); + } + } + + private static (string Service, string Method) SplitEndPoint(string endPoint) + { + if (string.IsNullOrWhiteSpace(endPoint)) + { + throw new ArgumentException("Dubbo endpoint cannot be empty.", nameof(endPoint)); + } + + int separator = Math.Max(endPoint.LastIndexOf('#'), endPoint.LastIndexOf('/')); + if (separator < 0) + { + separator = endPoint.LastIndexOf('.'); + } + if (separator <= 0 || separator == endPoint.Length - 1) + { + throw new ArgumentException( + $"Dubbo endpoint '{endPoint}' must contain both service and method names.", + nameof(endPoint)); + } + return (endPoint.Substring(0, separator), endPoint.Substring(separator + 1)); + } + + private static object ToJsonCompatible(object value) + { + return ToJsonCompatible( + value, + new HashSet<object>(ReferenceEqualityComparer.Instance)); + } + + private static object ToJsonCompatible(object value, HashSet<object> activeReferences, int depth = 0) + { + if (depth >= DubboHessian2Reader.MaxNestingDepth) Review Comment: 🟡 **深度上限挡不住内存放大:`activeReferences` 是路径式环检测,DAG 共享会指数展开** 这条和我上轮在 `DubboHessian2Reader.cs:33` 留的 💭 是**两件不同的事**:那条讲 64 这个数字同时约束了两种语义;这条讲在 64 层之内,内存依然可以翻到几百 MB。 关键在于这里的 `activeReferences` 是「进作用域 `Add`、出作用域 `Remove`」: ```csharp if (!activeReferences.Add(value)) return "[Circular reference]"; try { ...递归... } finally { activeReferences.Remove(value); } // ← 退出就摘掉 ``` 它只能识别**环**(同一个对象出现在自己的祖先链上),识别不了**同一个对象被兄弟节点重复引用**。而 Hessian2 的引用(`0x51` + index)本来就允许一个实例被多处引用——这是正常编码方式,不是畸形数据。 于是构造一个 DAG:`L0 = [0]`,`L_k = [ref L_{k-1}, ref L_{k-1}]`。展开后节点数是 `2^k`,但**读出来的对象图只有一个节点**(`_references` 里存的是同一个实例),`_depth` 也只有 k 层,60 层以内随便过。 **载荷有多小**:Hessian2 定长 list 是 `0x78 + n`,小整数是 `0x90 + v`,ref 是 `0x51` + int。所以: - `L0` = `79 90`(list[1], int 0) - `L1` = `7a 51 90 51 90`(list[2], ref 0, ref 0)→ 2 个节点 - `L2` = `7a 51 91 51 91` → 4 个节点 - 每层 5 字节,`L20` → 2^20 ≈ 100 万节点 **总共约 100 字节的响应体,归一化时分配 2^20~2^21 个 `List<object>`(每层还会重新 `new List<object>()` 和装箱),量级在几十到上百 MB**,21 层就到 128MB 左右。8MB 的 `DefaultMaxPayloadLength` 完全不构成约束,`depth >= 64` 也不构成约束——深度的平方根才是字节数。 **Suggestion**:在深度之外再加一个**节点预算**,这是防这类放大的通用做法: ```csharp private const int MaxNormalizedNodes = 100_000; private static object ToJsonCompatible(object value, HashSet<object> activeReferences, int depth = 0, ref int budget) // 或用一个 int[] / class Budget 承载 { if (--budget < 0) throw new InvalidDataException($"Hessian2 value expands beyond {MaxNormalizedNodes} nodes."); ... } ``` 预算用 `ref` 或小 class 在整棵树间共享,每访问一个节点减一,超了就抛 `InvalidDataException`(和现有的深度超限行为一致)。这样无论攻击者用深度、广度还是 DAG 共享放大,都收敛到一个常数上界。 如果不想引入可变状态,另一个方向是给每个实例记「被展开次数」,超过阈值(比如 3)就退化成 `"[Shared reference]"` 占位——但这会改变正常业务数据的 JSON 形态,不如预算稳妥。 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
