| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using IceRpc.Ice.Codec; |
| | | 4 | | using IceRpc.Ice.Internal; |
| | | 5 | | using IceRpc.Ice.Operations.Internal; |
| | | 6 | | using IceRpc.Internal; |
| | | 7 | | using System.Buffers; |
| | | 8 | | using System.Collections.Immutable; |
| | | 9 | | using System.Diagnostics; |
| | | 10 | | using System.Globalization; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | using System.Text; |
| | | 13 | | |
| | | 14 | | namespace IceRpc.Ice.Operations; |
| | | 15 | | |
| | | 16 | | /// <summary>Provides extension methods for <see cref="IceDecoder" /> to decode proxies.</summary> |
| | | 17 | | public static class IceProxyIceDecoderExtensions |
| | | 18 | | { |
| | | 19 | | // The printable ASCII range. Characters outside this range must be percent-escaped in a service address parameter |
| | | 20 | | // value. |
| | | 21 | | private const char FirstValidChar = '\x21'; |
| | | 22 | | private const char LastValidChar = '\x7E'; |
| | | 23 | | |
| | | 24 | | // Same as ServiceAddress's _notValidInParamValue, plus '%' which must be escaped to make the percent-escaped |
| | | 25 | | // value unambiguously decodable. |
| | 2 | 26 | | private static readonly SearchValues<char> _mustEscapeInAdapterId = SearchValues.Create("\"<>#%&\\^`{|}"); |
| | | 27 | | |
| | | 28 | | /// <summary>Decodes a proxy struct.</summary> |
| | | 29 | | /// <typeparam name="TProxy">The type of the proxy struct to decode.</typeparam> |
| | | 30 | | /// <param name="decoder">The Ice decoder.</param> |
| | | 31 | | /// <returns>The decoded proxy, or <see langword="null" />.</returns> |
| | | 32 | | public static TProxy? DecodeProxy<TProxy>(this ref IceDecoder decoder) where TProxy : struct, IIceProxy => |
| | 61 | 33 | | decoder.DecodeServiceAddress() is ServiceAddress serviceAddress ? |
| | 61 | 34 | | CreateProxy<TProxy>(serviceAddress, decoder.DecodingContext) : null; |
| | | 35 | | |
| | | 36 | | private static TProxy CreateProxy<TProxy>(ServiceAddress serviceAddress, object? decodingContext) |
| | | 37 | | where TProxy : struct, IIceProxy |
| | 49 | 38 | | { |
| | 49 | 39 | | Debug.Assert(serviceAddress.Protocol is not null, "The Ice encoding does not support relative proxies."); |
| | | 40 | | |
| | 49 | 41 | | if (decodingContext is null) |
| | 38 | 42 | | { |
| | 38 | 43 | | return new TProxy { Invoker = InvalidInvoker.Instance, ServiceAddress = serviceAddress }; |
| | | 44 | | } |
| | | 45 | | else |
| | 11 | 46 | | { |
| | 11 | 47 | | var baseProxy = (IIceProxy)decodingContext; |
| | 11 | 48 | | return new TProxy |
| | 11 | 49 | | { |
| | 11 | 50 | | EncodeOptions = baseProxy.EncodeOptions, |
| | 11 | 51 | | Invoker = baseProxy.Invoker, |
| | 11 | 52 | | ServiceAddress = serviceAddress |
| | 11 | 53 | | }; |
| | | 54 | | } |
| | 49 | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <summary>Decodes a service address.</summary> |
| | | 58 | | /// <param name="decoder">The Ice decoder.</param> |
| | | 59 | | /// <returns>The decoded service address, or <see langword="null" />.</returns> |
| | | 60 | | private static ServiceAddress? DecodeServiceAddress(this ref IceDecoder decoder) |
| | 61 | 61 | | { |
| | 61 | 62 | | string path = new Identity(ref decoder).ToPath(); |
| | 61 | 63 | | return path != "/" ? decoder.DecodeServiceAddressCore(path) : null; |
| | 57 | 64 | | } |
| | | 65 | | |
| | | 66 | | /// <summary>Decodes a server address.</summary> |
| | | 67 | | /// <param name="decoder">The Ice decoder.</param> |
| | | 68 | | /// <param name="protocol">The protocol of this server address.</param> |
| | | 69 | | /// <returns>The server address decoded by this decoder.</returns> |
| | | 70 | | private static ServerAddress DecodeServerAddress(this ref IceDecoder decoder, Protocol protocol) |
| | 37 | 71 | | { |
| | | 72 | | // With the Ice encoding, the ice server addresses are transport-specific, with a transport-specific encoding. |
| | | 73 | | |
| | 37 | 74 | | ServerAddress? serverAddress = null; |
| | 37 | 75 | | var transportCode = (TransportCode)decoder.DecodeShort(); |
| | | 76 | | |
| | 37 | 77 | | int size = decoder.DecodeInt(); |
| | 37 | 78 | | if (size < 6) |
| | 0 | 79 | | { |
| | 0 | 80 | | throw new InvalidDataException($"The Ice encapsulation's size ({size}) is too small."); |
| | | 81 | | } |
| | | 82 | | |
| | | 83 | | // Remove 6 bytes from the encapsulation size (4 for encapsulation size, 2 for encoding). |
| | 37 | 84 | | size -= 6; |
| | | 85 | | |
| | 37 | 86 | | byte encodingMajor = decoder.DecodeByte(); |
| | 37 | 87 | | byte encodingMinor = decoder.DecodeByte(); |
| | | 88 | | |
| | 37 | 89 | | if (decoder.Remaining < size) |
| | 0 | 90 | | { |
| | 0 | 91 | | throw new InvalidDataException($"The Ice encapsulation's size ({size}) is too big."); |
| | | 92 | | } |
| | | 93 | | |
| | 37 | 94 | | if (encodingMajor == 1 && encodingMinor <= 1) |
| | 37 | 95 | | { |
| | 37 | 96 | | long oldPos = decoder.Consumed; |
| | | 97 | | |
| | 37 | 98 | | if (protocol == Protocol.Ice) |
| | 18 | 99 | | { |
| | 18 | 100 | | switch (transportCode) |
| | | 101 | | { |
| | | 102 | | case TransportCode.Tcp: |
| | 11 | 103 | | serverAddress = decoder.DecodeTcpServerAddressBody(IceProxyIceEncoderExtensions.TcpName); |
| | 11 | 104 | | break; |
| | | 105 | | |
| | | 106 | | case TransportCode.Ssl: |
| | 2 | 107 | | serverAddress = decoder.DecodeTcpServerAddressBody(IceProxyIceEncoderExtensions.SslName); |
| | 2 | 108 | | break; |
| | | 109 | | |
| | | 110 | | case TransportCode.Uri: |
| | 3 | 111 | | serverAddress = DecodeUriServerAddress(decoder.DecodeString()); |
| | 1 | 112 | | if (serverAddress.Value.Protocol != protocol) |
| | 0 | 113 | | { |
| | 0 | 114 | | throw new InvalidDataException( |
| | 0 | 115 | | $"Expected {protocol} server address but received '{serverAddress.Value}'."); |
| | | 116 | | } |
| | 1 | 117 | | break; |
| | | 118 | | |
| | | 119 | | default: |
| | | 120 | | // Create a server address for transport opaque |
| | 2 | 121 | | ImmutableDictionary<string, string>.Builder builder = |
| | 2 | 122 | | ImmutableDictionary.CreateBuilder<string, string>(); |
| | | 123 | | |
| | 2 | 124 | | if (encodingMinor == 0) |
| | 1 | 125 | | { |
| | 1 | 126 | | builder.Add("e", "1.0"); |
| | 1 | 127 | | } |
| | | 128 | | // else no e |
| | | 129 | | |
| | 2 | 130 | | builder.Add("t", ((short)transportCode).ToString(CultureInfo.InvariantCulture)); |
| | 2 | 131 | | { |
| | 2 | 132 | | using IMemoryOwner<byte> memoryOwner = MemoryPool<byte>.Shared.Rent(size); |
| | 2 | 133 | | Span<byte> span = memoryOwner.Memory.Span[0..size]; |
| | 2 | 134 | | decoder.CopyTo(span); |
| | 2 | 135 | | string value = Convert.ToBase64String(span); |
| | 2 | 136 | | builder.Add("v", value); |
| | 2 | 137 | | decoder.IncreaseCollectionAllocation(value.Length, Unsafe.SizeOf<char>()); |
| | 2 | 138 | | } |
| | | 139 | | |
| | 2 | 140 | | serverAddress = new ServerAddress( |
| | 2 | 141 | | Protocol.Ice, |
| | 2 | 142 | | host: "opaque", // not a real host obviously |
| | 2 | 143 | | port: Protocol.Ice.DefaultPort, |
| | 2 | 144 | | transport: IceProxyIceEncoderExtensions.OpaqueName, |
| | 2 | 145 | | builder.ToImmutable()); |
| | 2 | 146 | | break; |
| | | 147 | | } |
| | 16 | 148 | | } |
| | 19 | 149 | | else if (transportCode == TransportCode.Uri) |
| | 19 | 150 | | { |
| | | 151 | | // The server addresses of an Ice-encoded icerpc proxies only use TransportCode.Uri. |
| | 19 | 152 | | serverAddress = DecodeUriServerAddress(decoder.DecodeString()); |
| | 17 | 153 | | if (serverAddress.Value.Protocol != protocol) |
| | 0 | 154 | | { |
| | 0 | 155 | | throw new InvalidDataException( |
| | 0 | 156 | | $"Expected {protocol} server address but received '{serverAddress.Value}'."); |
| | | 157 | | } |
| | 17 | 158 | | } |
| | | 159 | | |
| | 33 | 160 | | if (serverAddress is not null) |
| | 33 | 161 | | { |
| | | 162 | | // Make sure we read the full encapsulation. |
| | 33 | 163 | | if (decoder.Consumed != oldPos + size) |
| | 0 | 164 | | { |
| | 0 | 165 | | throw new InvalidDataException( |
| | 0 | 166 | | $"There are {oldPos + size - decoder.Consumed} bytes left in server address encapsulation."); |
| | | 167 | | } |
| | 33 | 168 | | } |
| | 33 | 169 | | } |
| | | 170 | | |
| | 33 | 171 | | if (serverAddress is null) |
| | 0 | 172 | | { |
| | 0 | 173 | | throw new InvalidDataException( |
| | 0 | 174 | | $"Cannot decode server address for protocol '{protocol}' and transport '{transportCode.ToString().ToLowe |
| | | 175 | | } |
| | | 176 | | |
| | 33 | 177 | | return serverAddress.Value; |
| | | 178 | | |
| | | 179 | | static ServerAddress DecodeUriServerAddress(string uriString) |
| | 22 | 180 | | { |
| | | 181 | | try |
| | 22 | 182 | | { |
| | 22 | 183 | | return new ServerAddress(new Uri(uriString)); |
| | | 184 | | } |
| | 4 | 185 | | catch (Exception exception) when (exception is UriFormatException or ArgumentException) |
| | 4 | 186 | | { |
| | 4 | 187 | | throw new InvalidDataException( |
| | 4 | 188 | | $"Received invalid server address URI '{uriString}'.", |
| | 4 | 189 | | exception); |
| | | 190 | | } |
| | 18 | 191 | | } |
| | 33 | 192 | | } |
| | | 193 | | |
| | | 194 | | /// <summary>Decodes a service address encoded with the Ice encoding.</summary> |
| | | 195 | | /// <param name="decoder">The Ice decoder.</param> |
| | | 196 | | /// <param name="path">The decoded path.</param> |
| | | 197 | | /// <returns>The decoded service address.</returns> |
| | | 198 | | private static ServiceAddress DecodeServiceAddressCore(this ref IceDecoder decoder, string path) |
| | 53 | 199 | | { |
| | | 200 | | // With the Ice encoding, a service address is encoded as a kind of discriminated union with: |
| | | 201 | | // - Identity |
| | | 202 | | // - If Identity is not the null identity: |
| | | 203 | | // - the fragment, invocation mode, secure, protocol major and minor, and the encoding major and minor |
| | | 204 | | // - a sequence of server addresses (can be empty) |
| | | 205 | | // - an adapter ID string present only when the sequence of server addresses is empty |
| | | 206 | | |
| | 53 | 207 | | string fragment = decoder.DecodeFacet().ToFragment(); |
| | 53 | 208 | | _ = decoder.DecodeInvocationMode(); |
| | 53 | 209 | | _ = decoder.DecodeBool(); |
| | 53 | 210 | | byte protocolMajor = decoder.DecodeByte(); |
| | 53 | 211 | | byte protocolMinor = decoder.DecodeByte(); |
| | 53 | 212 | | decoder.Skip(2); // skip encoding major and minor |
| | | 213 | | |
| | 53 | 214 | | if (protocolMajor == 0) |
| | 0 | 215 | | { |
| | 0 | 216 | | throw new InvalidDataException("Received service address with protocol set to 0."); |
| | | 217 | | } |
| | 53 | 218 | | if (protocolMinor != 0) |
| | 0 | 219 | | { |
| | 0 | 220 | | throw new InvalidDataException( |
| | 0 | 221 | | $"Received service address with invalid protocolMinor value: {protocolMinor}."); |
| | | 222 | | } |
| | | 223 | | |
| | 53 | 224 | | int count = decoder.DecodeSize(); |
| | | 225 | | |
| | 53 | 226 | | ServerAddress? serverAddress = null; |
| | 53 | 227 | | IEnumerable<ServerAddress> altServerAddresses = ImmutableList<ServerAddress>.Empty; |
| | 53 | 228 | | var protocol = Protocol.FromByteValue(protocolMajor); |
| | 53 | 229 | | ImmutableDictionary<string, string> serviceAddressParams = ImmutableDictionary<string, string>.Empty; |
| | | 230 | | |
| | 53 | 231 | | if (count == 0) |
| | 17 | 232 | | { |
| | 17 | 233 | | if (decoder.DecodeString() is string adapterId && adapterId.Length > 0) |
| | 10 | 234 | | { |
| | 10 | 235 | | serviceAddressParams = |
| | 10 | 236 | | serviceAddressParams.Add("adapter-id", EscapeAdapterId(adapterId)); |
| | 10 | 237 | | } |
| | 17 | 238 | | } |
| | | 239 | | else |
| | 36 | 240 | | { |
| | 36 | 241 | | serverAddress = decoder.DecodeServerAddress(protocol); |
| | 32 | 242 | | if (count >= 2) |
| | 1 | 243 | | { |
| | | 244 | | // An Ice-encoded server address consumes at least 8 bytes (2 bytes for the server address type and 6 |
| | | 245 | | // bytes for the encapsulation header). SizeOf ServerAddress is large but less than 8 * 8. |
| | 1 | 246 | | decoder.IncreaseCollectionAllocation(count, Unsafe.SizeOf<ServerAddress>()); |
| | | 247 | | |
| | 1 | 248 | | var serverAddressArray = new ServerAddress[count - 1]; |
| | 4 | 249 | | for (int i = 0; i < count - 1; ++i) |
| | 1 | 250 | | { |
| | 1 | 251 | | serverAddressArray[i] = decoder.DecodeServerAddress(protocol); |
| | 1 | 252 | | } |
| | 1 | 253 | | altServerAddresses = serverAddressArray; |
| | 1 | 254 | | } |
| | 32 | 255 | | } |
| | | 256 | | |
| | | 257 | | try |
| | 49 | 258 | | { |
| | 49 | 259 | | if (!protocol.HasFragment && fragment.Length > 0) |
| | 0 | 260 | | { |
| | 0 | 261 | | throw new InvalidDataException($"Unexpected fragment in {protocol} service address."); |
| | | 262 | | } |
| | | 263 | | |
| | 49 | 264 | | return new ServiceAddress( |
| | 49 | 265 | | protocol, |
| | 49 | 266 | | path, |
| | 49 | 267 | | serverAddress, |
| | 49 | 268 | | altServerAddresses.ToImmutableList(), |
| | 49 | 269 | | serviceAddressParams, |
| | 49 | 270 | | fragment); |
| | | 271 | | } |
| | 0 | 272 | | catch (InvalidDataException) |
| | 0 | 273 | | { |
| | 0 | 274 | | throw; |
| | | 275 | | } |
| | 0 | 276 | | catch (Exception exception) |
| | 0 | 277 | | { |
| | 0 | 278 | | throw new InvalidDataException("Received invalid service address.", exception); |
| | | 279 | | } |
| | 49 | 280 | | } |
| | | 281 | | |
| | | 282 | | /// <summary>Decodes the body of a tcp or ssl server address.</summary> |
| | | 283 | | private static ServerAddress DecodeTcpServerAddressBody(this ref IceDecoder decoder, string transport) |
| | 13 | 284 | | { |
| | 13 | 285 | | var body = new TcpServerAddressBody(ref decoder); |
| | | 286 | | |
| | 13 | 287 | | if (Uri.CheckHostName(body.Host) == UriHostNameType.Unknown) |
| | 0 | 288 | | { |
| | 0 | 289 | | throw new InvalidDataException($"Received service address with invalid host '{body.Host}'."); |
| | | 290 | | } |
| | | 291 | | |
| | 13 | 292 | | ImmutableDictionary<string, string> parameters = ImmutableDictionary<string, string>.Empty; |
| | 13 | 293 | | if (body.Timeout != IceProxyIceEncoderExtensions.DefaultTcpTimeout) |
| | 4 | 294 | | { |
| | 4 | 295 | | parameters = parameters.Add("t", body.Timeout.ToString(CultureInfo.InvariantCulture)); |
| | 4 | 296 | | } |
| | 13 | 297 | | if (body.Compress) |
| | 1 | 298 | | { |
| | 1 | 299 | | parameters = parameters.Add("z", ""); |
| | 1 | 300 | | } |
| | | 301 | | |
| | | 302 | | try |
| | 13 | 303 | | { |
| | 13 | 304 | | return new ServerAddress(Protocol.Ice, body.Host, checked((ushort)body.Port), transport, parameters); |
| | | 305 | | } |
| | 0 | 306 | | catch (OverflowException exception) |
| | 0 | 307 | | { |
| | 0 | 308 | | throw new InvalidDataException( |
| | 0 | 309 | | "Cannot decode a server address with a port number larger than 65,535.", |
| | 0 | 310 | | exception); |
| | | 311 | | } |
| | 13 | 312 | | } |
| | | 313 | | |
| | | 314 | | /// <summary>Percent-encodes only the characters that are invalid in a service address parameter value: characters |
| | | 315 | | /// outside the printable ASCII range <c>\x21..\x7E</c>, characters in |
| | | 316 | | /// <see cref="_mustEscapeInAdapterId" />, and the <c>%</c> character itself (which must be escaped to make the |
| | | 317 | | /// result unambiguously decodable).</summary> |
| | | 318 | | /// <param name="value">The raw adapter ID, as decoded from the wire.</param> |
| | | 319 | | /// <returns>An escaped string suitable for use as the value of the <c>adapter-id</c> service address parameter. |
| | | 320 | | /// </returns> |
| | | 321 | | /// <remarks>This is intentionally narrower than <see cref="Uri.EscapeDataString(string)" />, which over-escapes |
| | | 322 | | /// characters that are valid in service address parameter values such as <c>/</c>, <c>:</c>, and <c>@</c>. |
| | | 323 | | /// </remarks> |
| | | 324 | | private static string EscapeAdapterId(string value) |
| | 10 | 325 | | { |
| | 10 | 326 | | ReadOnlySpan<char> span = value.AsSpan(); |
| | | 327 | | |
| | | 328 | | // Fast path: nothing to escape. Adapter IDs are usually pure ASCII so we almost always take this path. |
| | 10 | 329 | | if (span.IndexOfAnyExceptInRange(FirstValidChar, LastValidChar) == -1 && |
| | 10 | 330 | | span.IndexOfAny(_mustEscapeInAdapterId) == -1) |
| | 5 | 331 | | { |
| | 5 | 332 | | return value; |
| | | 333 | | } |
| | | 334 | | |
| | | 335 | | // Slow path. Encode the whole string to UTF-8 bytes, then percent-escape every byte that is not a valid |
| | | 336 | | // unescaped char. UTF-8 continuation bytes (>= 0x80) naturally fall in the escape branch, so multi-byte |
| | | 337 | | // code points are handled without any surrogate-pair logic here. |
| | 5 | 338 | | byte[] utf8 = Encoding.UTF8.GetBytes(value); |
| | 5 | 339 | | var sb = new StringBuilder(utf8.Length + 8); |
| | 111 | 340 | | foreach (byte b in utf8) |
| | 48 | 341 | | { |
| | 48 | 342 | | if (b >= FirstValidChar && b <= LastValidChar && !_mustEscapeInAdapterId.Contains((char)b)) |
| | 40 | 343 | | { |
| | 40 | 344 | | sb.Append((char)b); |
| | 40 | 345 | | } |
| | | 346 | | else |
| | 8 | 347 | | { |
| | 8 | 348 | | sb.Append('%').Append(b.ToString("X2", CultureInfo.InvariantCulture)); |
| | 8 | 349 | | } |
| | 48 | 350 | | } |
| | 5 | 351 | | return sb.ToString(); |
| | 10 | 352 | | } |
| | | 353 | | } |