| | 1 | | using System.Buffers; |
| | 2 | | using System.Net.Sockets; |
| | 3 | | using Microsoft.Extensions.Logging; |
| | 4 | |
|
| | 5 | | namespace NLightning.Infrastructure.Transport.Services; |
| | 6 | |
|
| | 7 | | using Crypto.Interfaces; |
| | 8 | | using Domain.Crypto.ValueObjects; |
| | 9 | | using Domain.Exceptions; |
| | 10 | | using Domain.Protocol.Interfaces; |
| | 11 | | using Domain.Serialization.Interfaces; |
| | 12 | | using Domain.Transport; |
| | 13 | | using Exceptions; |
| | 14 | | using Interfaces; |
| | 15 | | using Protocol.Constants; |
| | 16 | |
|
| | 17 | | internal sealed class TransportService : ITransportService |
| | 18 | | { |
| 12 | 19 | | private readonly CancellationTokenSource _cts = new(); |
| | 20 | | private readonly ILogger _logger; |
| | 21 | | private readonly IMessageSerializer _messageSerializer; |
| | 22 | | private readonly TimeSpan _networkTimeout; |
| 12 | 23 | | private readonly SemaphoreSlim _networkWriteSemaphore = new(1, 1); |
| | 24 | | private readonly TcpClient _tcpClient; |
| 12 | 25 | | private readonly TaskCompletionSource<bool> _tcs = new(); |
| | 26 | |
|
| | 27 | | private IHandshakeService? _handshakeService; |
| | 28 | | private ITransport? _transport; |
| | 29 | | private bool _disposed; |
| | 30 | |
|
| | 31 | | // event that will be called when a message is received |
| | 32 | | public event EventHandler<MemoryStream>? MessageReceived; |
| | 33 | | public event EventHandler<Exception>? ExceptionRaised; |
| | 34 | |
|
| 0 | 35 | | public bool IsInitiator { get; } |
| 0 | 36 | | public bool IsConnected => _tcpClient.Connected; |
| 8 | 37 | | public CompactPubKey? RemoteStaticPublicKey { get; private set; } |
| | 38 | |
|
| | 39 | | public TransportService(IEcdh ecdh, ILogger logger, IMessageSerializer messageSerializer, TimeSpan networkTimeout, |
| | 40 | | bool isInitiator, ReadOnlySpan<byte> s, ReadOnlySpan<byte> rs, TcpClient tcpClient) |
| 0 | 41 | | : this(logger, messageSerializer, networkTimeout, new HandshakeService(isInitiator, s, rs, null, ecdh), |
| 0 | 42 | | tcpClient) |
| | 43 | | { |
| 0 | 44 | | _messageSerializer = messageSerializer; |
| 0 | 45 | | _networkTimeout = networkTimeout; |
| 0 | 46 | | } |
| | 47 | |
|
| 12 | 48 | | internal TransportService(ILogger logger, IMessageSerializer messageSerializer, TimeSpan networkTimeout, |
| 12 | 49 | | IHandshakeService handshakeService, TcpClient tcpClient) |
| | 50 | | { |
| 12 | 51 | | _handshakeService = handshakeService; |
| 12 | 52 | | _logger = logger; |
| 12 | 53 | | _messageSerializer = messageSerializer; |
| 12 | 54 | | _networkTimeout = networkTimeout; |
| 12 | 55 | | _tcpClient = tcpClient; |
| | 56 | |
|
| 12 | 57 | | IsInitiator = handshakeService.IsInitiator; |
| 12 | 58 | | } |
| | 59 | |
|
| | 60 | | public async Task InitializeAsync() |
| | 61 | | { |
| 12 | 62 | | if (_handshakeService == null) |
| 0 | 63 | | throw new NullReferenceException(nameof(_handshakeService)); |
| | 64 | |
|
| 12 | 65 | | if (!_tcpClient.Connected) |
| 4 | 66 | | throw new InvalidOperationException("TcpClient is not connected"); |
| | 67 | |
|
| 8 | 68 | | var writeBuffer = ArrayPool<byte>.Shared.Rent(66); |
| 8 | 69 | | var readBuffer = ArrayPool<byte>.Shared.Rent(50); |
| 8 | 70 | | var stream = _tcpClient.GetStream(); |
| | 71 | |
|
| 8 | 72 | | CancellationTokenSource networkTimeoutCancellationTokenSource = new(); |
| | 73 | |
|
| 8 | 74 | | var host = _tcpClient.Client.RemoteEndPoint?.ToString() ?? "unknown"; |
| | 75 | |
|
| 8 | 76 | | if (_handshakeService.IsInitiator) |
| | 77 | | { |
| | 78 | | try |
| | 79 | | { |
| 8 | 80 | | _logger.LogTrace("We're initiator, writing Act One for {host}", host); |
| | 81 | |
|
| | 82 | | // Write Act One |
| 8 | 83 | | var len = _handshakeService.PerformStep(ProtocolConstants.EmptyMessage, writeBuffer.AsSpan()[..50], |
| 8 | 84 | | out _); |
| 8 | 85 | | await stream.WriteAsync(writeBuffer.AsMemory()[..len], networkTimeoutCancellationTokenSource.Token); |
| 8 | 86 | | await stream.FlushAsync(networkTimeoutCancellationTokenSource.Token); |
| | 87 | |
|
| | 88 | | // Read exactly 50 bytes |
| 8 | 89 | | _logger.LogTrace("Reading Act Two from {host}", host); |
| 8 | 90 | | networkTimeoutCancellationTokenSource = new CancellationTokenSource(_networkTimeout); |
| 8 | 91 | | await stream.ReadExactlyAsync(readBuffer.AsMemory()[..50], networkTimeoutCancellationTokenSource.Token); |
| 4 | 92 | | networkTimeoutCancellationTokenSource.Dispose(); |
| | 93 | |
|
| | 94 | | // Read Act Two and Write Act Three |
| 4 | 95 | | _logger.LogTrace("Writing Act Three for {host}", host); |
| 4 | 96 | | len = _handshakeService.PerformStep(readBuffer.AsSpan()[..50], writeBuffer.AsSpan()[..66], |
| 4 | 97 | | out _transport); |
| 4 | 98 | | await stream.WriteAsync(writeBuffer.AsMemory()[..len], CancellationToken.None); |
| 4 | 99 | | await stream.FlushAsync(CancellationToken.None); |
| 4 | 100 | | } |
| 4 | 101 | | catch (Exception e) |
| | 102 | | { |
| 4 | 103 | | throw new ConnectionTimeoutException($"Timeout while reading Handshake's Act 2 from host {host}", e); |
| | 104 | | } |
| | 105 | | finally |
| | 106 | | { |
| 8 | 107 | | ArrayPool<byte>.Shared.Return(writeBuffer); |
| 8 | 108 | | ArrayPool<byte>.Shared.Return(readBuffer); |
| | 109 | | } |
| | 110 | | } |
| | 111 | | else |
| | 112 | | { |
| 0 | 113 | | var act = 1; |
| 0 | 114 | | _logger.LogTrace("We're responder, waiting for Act One from {host}", host); |
| | 115 | |
|
| | 116 | | try |
| | 117 | | { |
| | 118 | | // Read exactly 50 bytes |
| 0 | 119 | | networkTimeoutCancellationTokenSource = new CancellationTokenSource(_networkTimeout); |
| 0 | 120 | | if (!IsSocketConnected()) |
| 0 | 121 | | throw new ConnectionException($"TcpClient disconnected before reading Act One from host {host}"); |
| | 122 | |
|
| 0 | 123 | | await stream.ReadExactlyAsync(readBuffer.AsMemory()[..50], networkTimeoutCancellationTokenSource.Token); |
| | 124 | |
|
| | 125 | | // Read Act One and Write Act Two |
| 0 | 126 | | _logger.LogTrace("Writing Act Two for {host}", host); |
| 0 | 127 | | var len = _handshakeService.PerformStep(readBuffer.AsSpan()[..50], writeBuffer.AsSpan()[..50], out _); |
| | 128 | |
|
| 0 | 129 | | if (!IsSocketConnected()) |
| 0 | 130 | | throw new ConnectionException($"TcpClient disconnected before writing Act Two to host {host}"); |
| | 131 | |
|
| 0 | 132 | | await stream.WriteAsync(writeBuffer.AsMemory()[..len], CancellationToken.None); |
| 0 | 133 | | await stream.FlushAsync(CancellationToken.None); |
| | 134 | |
|
| | 135 | | // Read exactly 66 bytes |
| 0 | 136 | | _logger.LogTrace("Reading Act Three from {host}", host); |
| 0 | 137 | | act = 3; |
| 0 | 138 | | networkTimeoutCancellationTokenSource = new CancellationTokenSource(_networkTimeout); |
| 0 | 139 | | if (!IsSocketConnected()) |
| 0 | 140 | | throw new ConnectionException($"TcpClient disconnected before reading Act Three from host {host}"); |
| 0 | 141 | | await stream.ReadExactlyAsync(readBuffer.AsMemory()[..66], networkTimeoutCancellationTokenSource.Token); |
| 0 | 142 | | networkTimeoutCancellationTokenSource.Dispose(); |
| | 143 | |
|
| | 144 | | // Read Act Three |
| 0 | 145 | | _ = _handshakeService.PerformStep(readBuffer.AsSpan()[..66], writeBuffer.AsSpan()[..50], |
| 0 | 146 | | out _transport); |
| 0 | 147 | | } |
| 0 | 148 | | catch (TaskCanceledException tce) |
| | 149 | | { |
| 0 | 150 | | _tcs.SetResult(true); |
| 0 | 151 | | throw new ConnectionTimeoutException( |
| 0 | 152 | | $"Timeout while reading Handshake's Act {act} from host {host}", tce); |
| | 153 | | } |
| 0 | 154 | | catch (Exception e) |
| | 155 | | { |
| 0 | 156 | | _tcs.SetResult(true); |
| 0 | 157 | | throw new ConnectionException($"Host {host} closed the connection", e); |
| | 158 | | } |
| | 159 | | finally |
| | 160 | | { |
| 0 | 161 | | ArrayPool<byte>.Shared.Return(writeBuffer); |
| 0 | 162 | | ArrayPool<byte>.Shared.Return(readBuffer); |
| | 163 | | } |
| | 164 | | } |
| | 165 | |
|
| | 166 | | // Handshake completed |
| 4 | 167 | | if (_transport is null) |
| 0 | 168 | | throw new InvalidOperationException($"Handshake not completed for host {host}"); |
| | 169 | |
|
| 4 | 170 | | RemoteStaticPublicKey = _handshakeService.RemoteStaticPublicKey |
| 4 | 171 | | ?? throw new InvalidOperationException($"RemoteStaticPublicKey is null for host {host}"); |
| | 172 | |
|
| | 173 | | // Listen to messages and raise event |
| 4 | 174 | | _logger.LogTrace("Handshake completed with host {host}, listening to messages from peer {peer}", host, |
| 4 | 175 | | RemoteStaticPublicKey); |
| 4 | 176 | | _ = Task.Run(ReadResponseAsync, _cts.Token).ContinueWith(task => |
| 4 | 177 | | { |
| 0 | 178 | | if (task.Exception?.InnerExceptions.Count > 0) |
| 0 | 179 | | ExceptionRaised?.Invoke(this, task.Exception.InnerExceptions[0]); |
| 4 | 180 | | }, _cts.Token); |
| | 181 | |
|
| | 182 | | // Dispose of the handshake service |
| 4 | 183 | | _handshakeService.Dispose(); |
| 4 | 184 | | _handshakeService = null; |
| 4 | 185 | | } |
| | 186 | |
|
| | 187 | | public async Task WriteMessageAsync(IMessage message, CancellationToken cancellationToken = default) |
| | 188 | | { |
| 0 | 189 | | if (_tcpClient is null) |
| 0 | 190 | | throw new ConnectionException("TcpClient was null while trying to write a message", |
| 0 | 191 | | new NullReferenceException(nameof(_tcpClient))); |
| | 192 | |
|
| 0 | 193 | | if (!IsSocketConnected()) |
| 0 | 194 | | throw new ConnectionException("TcpClient was not connected while trying to write a message"); |
| | 195 | |
|
| 0 | 196 | | if (_transport is null) |
| 0 | 197 | | throw new ConnectionException("Handshake not completed while trying to write a message"); |
| | 198 | |
|
| | 199 | | // Serialize the message |
| 0 | 200 | | using var messageStream = new MemoryStream(); |
| 0 | 201 | | await _messageSerializer.SerializeAsync(message, messageStream); |
| | 202 | |
|
| | 203 | | // Encrypt message |
| 0 | 204 | | var buffer = ArrayPool<byte>.Shared.Rent(ProtocolConstants.MaxMessageLength); |
| 0 | 205 | | var size = _transport.WriteMessage(messageStream.ToArray(), |
| 0 | 206 | | buffer.AsSpan()[..ProtocolConstants.MaxMessageLength]); |
| | 207 | |
|
| | 208 | | // Write the message to stream |
| 0 | 209 | | await _networkWriteSemaphore.WaitAsync(cancellationToken); |
| | 210 | | try |
| | 211 | | { |
| 0 | 212 | | var stream = _tcpClient.GetStream(); |
| 0 | 213 | | await stream.WriteAsync(buffer.AsMemory()[..size], cancellationToken); |
| 0 | 214 | | await stream.FlushAsync(cancellationToken); |
| 0 | 215 | | } |
| 0 | 216 | | catch (Exception e) |
| | 217 | | { |
| 0 | 218 | | throw new ConnectionException("Error writing message", e); |
| | 219 | | } |
| | 220 | | finally |
| | 221 | | { |
| 0 | 222 | | ArrayPool<byte>.Shared.Return(buffer); |
| 0 | 223 | | _networkWriteSemaphore.Release(); |
| | 224 | | } |
| 0 | 225 | | } |
| | 226 | |
|
| | 227 | | private bool IsSocketConnected() |
| | 228 | | { |
| | 229 | | try |
| | 230 | | { |
| 4 | 231 | | if (_tcpClient.Client.Connected) |
| | 232 | | { |
| | 233 | | // This is how you can determine if a socket is still connected. |
| 4 | 234 | | return _tcpClient.Client.Connected && |
| 4 | 235 | | (!_tcpClient.Client.Poll(1, SelectMode.SelectRead) || _tcpClient.Client.Available != 0); |
| | 236 | | } |
| | 237 | |
|
| 0 | 238 | | return false; |
| | 239 | | } |
| 0 | 240 | | catch (SocketException) |
| | 241 | | { |
| 0 | 242 | | return false; |
| | 243 | | } |
| 0 | 244 | | catch (ObjectDisposedException) |
| | 245 | | { |
| 0 | 246 | | return false; |
| | 247 | | } |
| 4 | 248 | | } |
| | 249 | |
|
| | 250 | | private async Task ReadResponseAsync() |
| | 251 | | { |
| 4 | 252 | | while (!_cts.IsCancellationRequested) |
| | 253 | | { |
| 4 | 254 | | var buffer = ArrayPool<byte>.Shared.Rent(ProtocolConstants.MaxMessageLength); |
| 4 | 255 | | var memoryBuffer = buffer.AsMemory(); |
| | 256 | |
|
| | 257 | | try |
| | 258 | | { |
| 4 | 259 | | if (_transport == null) |
| 0 | 260 | | throw new InvalidOperationException("Handshake not completed while trying to read a message"); |
| | 261 | |
|
| 4 | 262 | | if (_tcpClient is null || !IsSocketConnected()) |
| 0 | 263 | | throw new InvalidOperationException("TcpClient is not connected while trying to read a message"); |
| | 264 | |
|
| | 265 | | // Read response |
| 4 | 266 | | var stream = _tcpClient.GetStream(); |
| 4 | 267 | | var lenRead = await stream.ReadAsync(memoryBuffer[..ProtocolConstants.MessageHeaderSize], _cts.Token); |
| 0 | 268 | | if (_cts.IsCancellationRequested) |
| 0 | 269 | | break; |
| | 270 | |
|
| 0 | 271 | | if (lenRead != ProtocolConstants.MessageHeaderSize) |
| | 272 | | { |
| 0 | 273 | | if (!IsSocketConnected() || lenRead == 0) |
| 0 | 274 | | throw new ConnectionException( |
| 0 | 275 | | "TcpClient is not connected while trying to read a message header"); |
| | 276 | |
|
| 0 | 277 | | throw new ConnectionException("Peer sent wrong length"); |
| | 278 | | } |
| | 279 | |
|
| 0 | 280 | | var messageLen = |
| 0 | 281 | | _transport.ReadMessageLength(memoryBuffer[..ProtocolConstants.MessageHeaderSize].Span); |
| 0 | 282 | | if (_cts.IsCancellationRequested) |
| 0 | 283 | | break; |
| | 284 | |
|
| 0 | 285 | | if (messageLen > ProtocolConstants.MaxMessageLength) |
| 0 | 286 | | throw new ConnectionException("Peer sent message too long"); |
| | 287 | |
|
| 0 | 288 | | if (!IsSocketConnected()) |
| 0 | 289 | | throw new ConnectionException("TcpClient is not connected while trying to read a message body"); |
| | 290 | |
|
| 0 | 291 | | lenRead = await stream.ReadAsync(memoryBuffer[..messageLen], _cts.Token); |
| 0 | 292 | | if (_cts.IsCancellationRequested) |
| 0 | 293 | | break; |
| | 294 | |
|
| 0 | 295 | | if (lenRead != messageLen) |
| 0 | 296 | | throw new ConnectionException("Peer sent wrong body length"); |
| | 297 | |
|
| 0 | 298 | | messageLen = _transport.ReadMessagePayload(memoryBuffer[..lenRead].Span, buffer); |
| | 299 | |
|
| | 300 | | // Raise event |
| 0 | 301 | | var messageStream = new MemoryStream(buffer[..messageLen]); |
| 0 | 302 | | MessageReceived?.Invoke(this, messageStream); |
| 0 | 303 | | } |
| 0 | 304 | | catch (OperationCanceledException) |
| | 305 | | { |
| | 306 | | // Ignore cancellation |
| 0 | 307 | | } |
| 0 | 308 | | catch (ConnectionException) |
| | 309 | | { |
| 0 | 310 | | throw; |
| | 311 | | } |
| 0 | 312 | | catch (Exception e) |
| | 313 | | { |
| 0 | 314 | | if (!_cts.IsCancellationRequested) |
| | 315 | | { |
| 0 | 316 | | if (_tcpClient is null || !_tcpClient.Connected) |
| 0 | 317 | | throw new ConnectionException("Peer closed the connection"); |
| | 318 | |
|
| 0 | 319 | | throw new ConnectionException("Error reading response", e); |
| | 320 | | } |
| 0 | 321 | | } |
| | 322 | | finally |
| | 323 | | { |
| 0 | 324 | | ArrayPool<byte>.Shared.Return(buffer, true); |
| | 325 | | } |
| 0 | 326 | | } |
| | 327 | |
|
| 0 | 328 | | _tcs.TrySetResult(true); |
| 0 | 329 | | } |
| | 330 | |
|
| | 331 | | #region Dispose Pattern |
| | 332 | |
|
| | 333 | | public void Dispose() |
| | 334 | | { |
| 0 | 335 | | Dispose(true); |
| 0 | 336 | | GC.SuppressFinalize(this); |
| 0 | 337 | | } |
| | 338 | |
|
| | 339 | | private void Dispose(bool disposing) |
| | 340 | | { |
| 2 | 341 | | if (_disposed) |
| 0 | 342 | | return; |
| | 343 | |
|
| 2 | 344 | | if (disposing) |
| | 345 | | { |
| | 346 | | // Cancel and wait for an elegant shutdown |
| 0 | 347 | | _cts.Cancel(); |
| 0 | 348 | | _tcs.Task.Wait(TimeSpan.FromSeconds(5)); |
| | 349 | |
|
| 0 | 350 | | _handshakeService?.Dispose(); |
| 0 | 351 | | _transport?.Dispose(); |
| 0 | 352 | | _tcpClient.Dispose(); |
| | 353 | | } |
| | 354 | |
|
| 2 | 355 | | _disposed = true; |
| 2 | 356 | | } |
| | 357 | |
|
| | 358 | | ~TransportService() |
| | 359 | | { |
| 2 | 360 | | Dispose(false); |
| 4 | 361 | | } |
| | 362 | |
|
| | 363 | | #endregion |
| | 364 | | } |