< Summary

Information
Class: IceRpc.Transports.Tcp.Internal.TcpClientConnection
Assembly: IceRpc
File(s): /home/runner/work/icerpc-csharp/icerpc-csharp/src/IceRpc/Transports/Tcp/Internal/TcpConnection.cs
Tag: 2300_35243572715
Line coverage
85%
Covered lines: 46
Uncovered lines: 8
Coverable lines: 54
Total lines: 442
Line coverage: 85.1%
Branch coverage
85%
Covered branches: 12
Total branches: 14
Branch coverage: 85.7%
Method coverage
100%
Covered methods: 4
Fully covered methods: 3
Total methods: 4
Method coverage: 100%
Full method coverage: 75%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_Socket()100%11100%
get_SslStream()100%11100%
.ctor(...)80%131068%
ConnectAsyncCore()100%44100%

File(s)

/home/runner/work/icerpc-csharp/icerpc-csharp/src/IceRpc/Transports/Tcp/Internal/TcpConnection.cs

#LineLine coverage
 1// Copyright (c) ZeroC, Inc.
 2
 3using System.Buffers;
 4using System.Diagnostics;
 5using System.Net;
 6using System.Net.Security;
 7using System.Net.Sockets;
 8using System.Runtime.InteropServices;
 9
 10namespace IceRpc.Transports.Tcp.Internal;
 11
 12/// <summary>Implements <see cref="IDuplexConnection" /> for tcp with or without TLS.</summary>
 13/// <remarks>Unlike Coloc, the Tcp transport is not a "checked" transport, which means it does not need to detect
 14/// violations of the duplex transport contract or report such violations. It assumes its clients are sufficiently well
 15/// tested to never violate this contract. As a result, this implementation does not throw
 16/// <see cref="InvalidOperationException" />.</remarks>
 17internal abstract class TcpConnection : IDuplexConnection
 18{
 19    internal abstract Socket Socket { get; }
 20
 21    internal abstract SslStream? SslStream { get; }
 22
 23    private protected volatile bool _isDisposed;
 24
 25    // The MaxDataSize of the SSL implementation.
 26    private const int MaxSslDataSize = 16 * 1024;
 27
 28    private bool _isShutdown;
 29    private readonly int _maxSslBufferSize;
 30    private readonly List<ArraySegment<byte>> _segments = new();
 31    private readonly IMemoryOwner<byte>? _writeBufferOwner;
 32
 33    public Task<TransportConnectionInformation> ConnectAsync(CancellationToken cancellationToken)
 34    {
 35        ObjectDisposedException.ThrowIf(_isDisposed, this);
 36        return ConnectAsyncCore(cancellationToken);
 37    }
 38
 39    public void Dispose()
 40    {
 41        _isDisposed = true;
 42
 43        if (SslStream is SslStream sslStream)
 44        {
 45            sslStream.Dispose();
 46        }
 47
 48        // If shutdown was called, we can just dispose the connection to complete the graceful TCP closure. Otherwise,
 49        // we abort the TCP connection to ensure the connection doesn't end up in the TIME_WAIT state.
 50        if (_isShutdown)
 51        {
 52            Socket.Dispose();
 53        }
 54        else
 55        {
 56            Socket.Close(0);
 57        }
 58        _writeBufferOwner?.Dispose();
 59    }
 60
 61    public ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
 62    {
 63        ObjectDisposedException.ThrowIf(_isDisposed, this);
 64
 65        return buffer.Length > 0 ? PerformReadAsync() :
 66            throw new ArgumentException($"The {nameof(buffer)} cannot be empty.", nameof(buffer));
 67
 68        async ValueTask<int> PerformReadAsync()
 69        {
 70            try
 71            {
 72                return SslStream is SslStream sslStream ?
 73                    await SslStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false) :
 74                    await Socket.ReceiveAsync(buffer, SocketFlags.None, cancellationToken).ConfigureAwait(false);
 75            }
 76            catch (IOException exception)
 77            {
 78                throw exception.ToIceRpcException();
 79            }
 80            catch (SocketException exception)
 81            {
 82                throw exception.ToIceRpcException();
 83            }
 84        }
 85    }
 86
 87    public Task ShutdownWriteAsync(CancellationToken cancellationToken)
 88    {
 89        ObjectDisposedException.ThrowIf(_isDisposed, this);
 90
 91        return PerformShutdownAsync();
 92
 93        async Task PerformShutdownAsync()
 94        {
 95            try
 96            {
 97                if (SslStream is SslStream sslStream)
 98                {
 99                    Task shutdownTask = sslStream.ShutdownAsync();
 100
 101                    try
 102                    {
 103                        await shutdownTask.WaitAsync(cancellationToken).ConfigureAwait(false);
 104                    }
 105                    catch (OperationCanceledException)
 106                    {
 107                        await AbortAndObserveAsync(shutdownTask).ConfigureAwait(false);
 108                        throw;
 109                    }
 110                }
 111
 112                // Shutdown the socket send side to send a TCP FIN packet. We don't close the read side because we want
 113                // to be notified when the peer shuts down it's side of the socket (through the ReceiveAsync call).
 114                Socket.Shutdown(SocketShutdown.Send);
 115
 116                // If shutdown is successful mark the connection as shutdown to ensure Dispose won't reset the TCP
 117                // connection.
 118                _isShutdown = true;
 119            }
 120            catch (IOException exception)
 121            {
 122                throw exception.ToIceRpcException();
 123            }
 124            catch (SocketException exception)
 125            {
 126                throw exception.ToIceRpcException();
 127            }
 128        }
 129    }
 130
 131    public ValueTask WriteAsync(ReadOnlySequence<byte> buffer, CancellationToken cancellationToken)
 132    {
 133        ObjectDisposedException.ThrowIf(_isDisposed, this);
 134
 135        if (buffer.IsEmpty)
 136        {
 137            throw new ArgumentException($"The {nameof(buffer)} cannot be empty.", nameof(buffer));
 138        }
 139
 140        return PerformWriteAsync();
 141
 142        async ValueTask PerformWriteAsync()
 143        {
 144            try
 145            {
 146                if (SslStream is SslStream sslStream)
 147                {
 148                    if (buffer.IsSingleSegment)
 149                    {
 150                        await sslStream.WriteAsync(buffer.First, cancellationToken).ConfigureAwait(false);
 151                    }
 152                    else
 153                    {
 154                        // Coalesce leading segments up to _maxSslBufferSize. We don't coalesce trailing segments as we
 155                        // assume these segments are large enough.
 156                        int leadingSize = 0;
 157                        int leadingSegmentCount = 0;
 158                        foreach (ReadOnlyMemory<byte> memory in buffer)
 159                        {
 160                            if (leadingSize + memory.Length <= _maxSslBufferSize)
 161                            {
 162                                leadingSize += memory.Length;
 163                                leadingSegmentCount++;
 164                            }
 165                            else
 166                            {
 167                                break;
 168                            }
 169                        }
 170
 171                        if (leadingSegmentCount > 1)
 172                        {
 173                            ReadOnlySequence<byte> leading = buffer.Slice(0, leadingSize);
 174                            buffer = buffer.Slice(leadingSize); // buffer can become empty
 175
 176                            Debug.Assert(_writeBufferOwner is not null);
 177                            Memory<byte> writeBuffer = _writeBufferOwner.Memory[0..leadingSize];
 178                            leading.CopyTo(writeBuffer.Span);
 179
 180                            // Send the "coalesced" leading segments
 181                            await sslStream.WriteAsync(writeBuffer, cancellationToken).ConfigureAwait(false);
 182                        }
 183                        // else no need to coalesce (copy) a single segment
 184
 185                        // Send the remaining segments one by one
 186                        if (buffer.IsEmpty)
 187                        {
 188                            // done
 189                        }
 190                        else if (buffer.IsSingleSegment)
 191                        {
 192                            await sslStream.WriteAsync(buffer.First, cancellationToken).ConfigureAwait(false);
 193                        }
 194                        else
 195                        {
 196                            foreach (ReadOnlyMemory<byte> memory in buffer)
 197                            {
 198                                await sslStream.WriteAsync(memory, cancellationToken).ConfigureAwait(false);
 199                            }
 200                        }
 201                    }
 202                }
 203                else
 204                {
 205                    if (buffer.IsSingleSegment)
 206                    {
 207                        int bytesSent = await Socket.SendAsync(
 208                            buffer.First,
 209                            SocketFlags.None,
 210                            cancellationToken).ConfigureAwait(false);
 211
 212                        if (bytesSent != buffer.First.Length)
 213                        {
 214                            // This should never happen.
 215                            throw new IceRpcException(
 216                                IceRpcError.IceRpcError,
 217                                $"Short write on TCP socket: expected {buffer.First.Length} bytes but sent {bytesSent}."
 218                        }
 219                    }
 220                    else
 221                    {
 222                        _segments.Clear();
 223                        long totalBytes = buffer.Length;
 224                        foreach (ReadOnlyMemory<byte> memory in buffer)
 225                        {
 226                            if (MemoryMarshal.TryGetArray(memory, out ArraySegment<byte> segment))
 227                            {
 228                                _segments.Add(segment);
 229                            }
 230                            else
 231                            {
 232                                throw new ArgumentException(
 233                                    $"The {nameof(buffer)} must be backed by arrays.",
 234                                    nameof(buffer));
 235                            }
 236                        }
 237
 238                        Task<int> sendTask = Socket.SendAsync(_segments, SocketFlags.None);
 239
 240                        int bytesSent;
 241                        try
 242                        {
 243                            bytesSent = await sendTask.WaitAsync(cancellationToken).ConfigureAwait(false);
 244                        }
 245                        catch (OperationCanceledException)
 246                        {
 247                            await AbortAndObserveAsync(sendTask).ConfigureAwait(false);
 248                            throw;
 249                        }
 250
 251                        if (bytesSent != totalBytes)
 252                        {
 253                            // This should never happen.
 254                            throw new IceRpcException(
 255                                IceRpcError.IceRpcError,
 256                                $"Short write on TCP socket: expected {totalBytes} bytes but sent {bytesSent}.");
 257                        }
 258                    }
 259                }
 260            }
 261            catch (IOException exception)
 262            {
 263                throw exception.ToIceRpcException();
 264            }
 265            catch (SocketException exception)
 266            {
 267                throw exception.ToIceRpcException();
 268            }
 269        }
 270    }
 271
 272    private protected TcpConnection(IMemoryOwner<byte>? memoryOwner)
 273    {
 274        _writeBufferOwner = memoryOwner;
 275        // When coalescing leading buffers in WriteAsync (SSL only), the upper size limit is the lesser of the size of
 276        // the buffer we rented from the memory pool (typically 4K) and MaxSslDataSize (16K).
 277        _maxSslBufferSize = Math.Min(memoryOwner?.Memory.Length ?? 0, MaxSslDataSize);
 278    }
 279
 280    private protected abstract Task<TransportConnectionInformation> ConnectAsyncCore(
 281        CancellationToken cancellationToken);
 282
 283    /// <summary>Aborts the connection and then observes the exception of the provided task.</summary>
 284    private async Task AbortAndObserveAsync(Task task)
 285    {
 286        Socket.Close(0);
 287        try
 288        {
 289            await task.ConfigureAwait(false);
 290        }
 291        catch
 292        {
 293            // observe exception
 294        }
 295    }
 296}
 297
 298internal class TcpClientConnection : TcpConnection
 299{
 951300    internal override Socket Socket { get; }
 301
 306302    internal override SslStream? SslStream => _sslStream;
 303
 304    private readonly EndPoint _address;
 305    private readonly SslClientAuthenticationOptions? _authenticationOptions;
 306
 307    private SslStream? _sslStream;
 308
 309    internal TcpClientConnection(
 310        TransportAddress transportAddress,
 311        SslClientAuthenticationOptions? authenticationOptions,
 312        MemoryPool<byte> pool,
 313        int minimumSegmentSize,
 314        TcpClientTransportOptions options)
 139315        : base(authenticationOptions is not null ? pool.Rent(minimumSegmentSize) : null)
 139316    {
 139317        _address = IPAddress.TryParse(transportAddress.Host, out IPAddress? ipAddress) ?
 139318            new IPEndPoint(ipAddress, transportAddress.Port) :
 139319            new DnsEndPoint(transportAddress.Host, transportAddress.Port);
 320
 139321        _authenticationOptions = authenticationOptions;
 322
 323        // When using IPv6 address family we use the socket constructor without AddressFamily parameter to ensure
 324        // dual-mode socket are used in platforms that support them.
 139325        Socket = ipAddress?.AddressFamily == AddressFamily.InterNetwork ?
 139326            new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp) :
 139327            new Socket(SocketType.Stream, ProtocolType.Tcp);
 328
 329        try
 139330        {
 139331            if (options.LocalNetworkAddress is IPEndPoint localNetworkAddress)
 1332            {
 1333                Socket.Bind(localNetworkAddress);
 1334            }
 335
 139336            Socket.Configure(options);
 139337        }
 0338        catch (SocketException exception)
 0339        {
 0340            Dispose();
 0341            throw exception.ToIceRpcException();
 342        }
 0343        catch
 0344        {
 0345            Dispose();
 0346            throw;
 347        }
 139348    }
 349
 350    private protected override async Task<TransportConnectionInformation> ConnectAsyncCore(
 351        CancellationToken cancellationToken)
 130352    {
 130353        bool isConnected = false;
 354        try
 130355        {
 130356            Debug.Assert(Socket is not null);
 357
 358            // Connect to the peer.
 130359            await Socket.ConnectAsync(_address, cancellationToken).ConfigureAwait(false);
 122360            isConnected = true;
 361
 122362            if (_authenticationOptions is not null)
 31363            {
 31364                _sslStream = new SslStream(new NetworkStream(Socket, false), false);
 365
 31366                await _sslStream.AuthenticateAsClientAsync(
 31367                    _authenticationOptions,
 31368                    cancellationToken).ConfigureAwait(false);
 25369            }
 370
 116371            return new TransportConnectionInformation(
 116372                localNetworkAddress: Socket.LocalEndPoint!,
 116373                remoteNetworkAddress: Socket.RemoteEndPoint!,
 116374                _sslStream?.RemoteCertificate);
 375        }
 2376        catch (IOException exception)
 2377        {
 2378            throw exception.ToIceRpcException();
 379        }
 5380        catch (SocketException exception) when (isConnected)
 1381        {
 382            // This can happen if the peer closes the connection immediately after accepting it, which can cause the
 383            // endpoint information to be unavailable. Any SocketException at this point means the connection is no
 384            // longer usable.
 1385            throw new IceRpcException(IceRpcError.ConnectionAborted, exception);
 386        }
 4387        catch (SocketException exception)
 4388        {
 4389            throw exception.ToIceRpcException();
 390        }
 115391    }
 392}
 393
 394internal class TcpServerConnection : TcpConnection
 395{
 396    internal override Socket Socket { get; }
 397
 398    internal override SslStream? SslStream => _sslStream;
 399
 400    private readonly SslServerAuthenticationOptions? _authenticationOptions;
 401    private SslStream? _sslStream;
 402
 403    internal TcpServerConnection(
 404        Socket socket,
 405        SslServerAuthenticationOptions? authenticationOptions,
 406        MemoryPool<byte> pool,
 407        int minimumSegmentSize)
 408        : base(authenticationOptions is not null ? pool.Rent(minimumSegmentSize) : null)
 409    {
 410        Socket = socket;
 411        _authenticationOptions = authenticationOptions;
 412    }
 413
 414    private protected override async Task<TransportConnectionInformation> ConnectAsyncCore(
 415        CancellationToken cancellationToken)
 416    {
 417        try
 418        {
 419            if (_authenticationOptions is not null)
 420            {
 421                // This can only be created with a connected socket.
 422                _sslStream = new SslStream(new NetworkStream(Socket, false), false);
 423                await _sslStream.AuthenticateAsServerAsync(
 424                    _authenticationOptions,
 425                    cancellationToken).ConfigureAwait(false);
 426            }
 427
 428            return new TransportConnectionInformation(
 429                localNetworkAddress: Socket.LocalEndPoint!,
 430                remoteNetworkAddress: Socket.RemoteEndPoint!,
 431                _sslStream?.RemoteCertificate);
 432        }
 433        catch (IOException exception)
 434        {
 435            throw exception.ToIceRpcException();
 436        }
 437        catch (SocketException exception)
 438        {
 439            throw exception.ToIceRpcException();
 440        }
 441    }
 442}