| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.IO.Pipelines; |
| | | 7 | | using System.IO.Pipes; |
| | | 8 | | using System.Runtime.InteropServices; |
| | | 9 | | using System.Threading; |
| | | 10 | | using System.Threading.Tasks; |
| | | 11 | | using CoreWCF.Runtime; |
| | | 12 | | using Microsoft.AspNetCore.Connections; |
| | | 13 | | using PipeOptions = System.IO.Pipelines.PipeOptions; |
| | | 14 | | |
| | | 15 | | namespace CoreWCF.Channels |
| | | 16 | | { |
| | | 17 | | // When we eventually move to .NET 6, implement IThreadPoolWorkItem |
| | | 18 | | internal class NamedPipeConnectionContext : DefaultConnectionContext, IAsyncDisposable |
| | | 19 | | { |
| | 0 | 20 | | private static readonly ConnectionAbortedException s_sendGracefullyCompletedException = new ConnectionAbortedExc |
| | | 21 | | |
| | | 22 | | private NamedPipeServerStream _pipe; |
| | | 23 | | private string _connectionId; |
| | | 24 | | private IDuplexPipe _originalTransport; |
| | | 25 | | private int _connectionBufferSize; |
| | | 26 | | private byte[] _readBuffer; |
| | | 27 | | |
| | 0 | 28 | | private readonly CancellationTokenSource _connectionClosedTokenSource = new CancellationTokenSource(); |
| | | 29 | | private bool _connectionShutdown; |
| | | 30 | | private bool _connectionClosed; |
| | | 31 | | private Exception _shutdownReason; |
| | | 32 | | private bool _streamDisconnected; |
| | 0 | 33 | | private readonly object _shutdownLock = new object(); |
| | 0 | 34 | | internal Task _receivingTask = Task.CompletedTask; |
| | 0 | 35 | | internal Task _sendingTask = Task.CompletedTask; |
| | | 36 | | private byte[] _writeBuffer; |
| | | 37 | | |
| | 0 | 38 | | internal NamedPipeConnectionContext(NamedPipeServerStream pipe, PipeOptions inputOptions, PipeOptions outputOpti |
| | | 39 | | { |
| | 0 | 40 | | _pipe = pipe; |
| | 0 | 41 | | var input = new Pipe(inputOptions); |
| | 0 | 42 | | var output = new Pipe(outputOptions); |
| | 0 | 43 | | Transport = _originalTransport = DuplexPipe.CreateTransport(input, output); |
| | 0 | 44 | | Application = DuplexPipe.CreateApplication(input, output); |
| | 0 | 45 | | _connectionBufferSize = connectionBufferSize; |
| | 0 | 46 | | } |
| | | 47 | | |
| | | 48 | | public override string ConnectionId |
| | | 49 | | { |
| | 0 | 50 | | get => _connectionId ??= CorrelationIdGenerator.GetNextId(); |
| | 0 | 51 | | set => _connectionId = value; |
| | | 52 | | } |
| | | 53 | | |
| | 0 | 54 | | public PipeWriter Input => Application.Output; |
| | 0 | 55 | | public PipeReader Output => Application.Input; |
| | | 56 | | |
| | 0 | 57 | | public NetNamedPipeTrace Logger { get; internal set; } |
| | | 58 | | |
| | | 59 | | public void Start() |
| | | 60 | | { |
| | | 61 | | try |
| | | 62 | | { |
| | | 63 | | // Spawn send and receive logic |
| | 0 | 64 | | _receivingTask = DoReceiveAsync(); |
| | 0 | 65 | | _sendingTask = DoSendAsync(); |
| | 0 | 66 | | } |
| | 0 | 67 | | catch (Exception ex) |
| | | 68 | | { |
| | 0 | 69 | | Logger.LogConnectionError(0, ex, $"Unexpected exception in {nameof(NamedPipeConnection)}.{nameof(Start)} |
| | 0 | 70 | | } |
| | 0 | 71 | | } |
| | | 72 | | |
| | | 73 | | private async Task DoReceiveAsync() |
| | | 74 | | { |
| | 0 | 75 | | Exception error = null; |
| | | 76 | | |
| | | 77 | | try |
| | | 78 | | { |
| | 0 | 79 | | var input = Input; |
| | 0 | 80 | | while (true) |
| | | 81 | | { |
| | | 82 | | // Ensure we have some reasonable amount of buffer space |
| | 0 | 83 | | var buffer = input.GetMemory(_connectionBufferSize); |
| | | 84 | | int bytesReceived; |
| | 0 | 85 | | if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> byteArray)) |
| | | 86 | | { |
| | 0 | 87 | | bytesReceived = await _pipe.ReadAsync(byteArray.Array, byteArray.Offset, byteArray.Count); |
| | | 88 | | } |
| | | 89 | | else |
| | | 90 | | { |
| | 0 | 91 | | _readBuffer ??= Fx.AllocateByteArray(_connectionBufferSize); |
| | 0 | 92 | | bytesReceived = await _pipe.ReadAsync(_readBuffer, 0, _readBuffer.Length); |
| | 0 | 93 | | new Memory<byte>(_readBuffer, 0, bytesReceived).CopyTo(buffer); |
| | | 94 | | } |
| | | 95 | | |
| | 0 | 96 | | if (bytesReceived == 0) |
| | | 97 | | { |
| | | 98 | | // Read completed. |
| | 0 | 99 | | Logger.ConnectionReadEnd(ConnectionId); |
| | 0 | 100 | | break; |
| | | 101 | | } |
| | | 102 | | |
| | 0 | 103 | | input.Advance(bytesReceived); |
| | | 104 | | |
| | 0 | 105 | | var flushTask = Input.FlushAsync(); |
| | | 106 | | |
| | 0 | 107 | | var paused = !flushTask.IsCompleted; |
| | | 108 | | |
| | 0 | 109 | | if (paused) |
| | | 110 | | { |
| | 0 | 111 | | Logger.ConnectionPause(ConnectionId); |
| | | 112 | | } |
| | | 113 | | |
| | 0 | 114 | | var result = await flushTask; |
| | | 115 | | |
| | 0 | 116 | | if (paused) |
| | | 117 | | { |
| | 0 | 118 | | Logger.ConnectionResume(ConnectionId); |
| | | 119 | | } |
| | | 120 | | |
| | 0 | 121 | | if (result.IsCompleted || result.IsCanceled) |
| | | 122 | | { |
| | | 123 | | // Pipe consumer is shut down, do we stop writing |
| | | 124 | | break; |
| | | 125 | | } |
| | 0 | 126 | | } |
| | 0 | 127 | | } |
| | 0 | 128 | | catch (ObjectDisposedException ex) |
| | | 129 | | { |
| | | 130 | | // This exception should always be ignored because _shutdownReason should be set. |
| | 0 | 131 | | error = ex; |
| | | 132 | | |
| | 0 | 133 | | if (!_connectionShutdown) |
| | | 134 | | { |
| | | 135 | | // This is unexpected if the socket hasn't been disposed yet. |
| | 0 | 136 | | Logger.ConnectionError(ConnectionId, error); |
| | | 137 | | } |
| | 0 | 138 | | } |
| | 0 | 139 | | catch (Exception ex) |
| | | 140 | | { |
| | | 141 | | // This is unexpected. |
| | 0 | 142 | | error = ex; |
| | 0 | 143 | | Logger.ConnectionError(ConnectionId, error); |
| | 0 | 144 | | } |
| | | 145 | | finally |
| | | 146 | | { |
| | | 147 | | // If Shutdown() has already been called, assume that was the reason ProcessReceives() exited. |
| | 0 | 148 | | Input.Complete(_shutdownReason ?? error); |
| | | 149 | | |
| | 0 | 150 | | FireConnectionClosed(); |
| | | 151 | | } |
| | 0 | 152 | | } |
| | | 153 | | |
| | | 154 | | private async Task DoSendAsync() |
| | | 155 | | { |
| | 0 | 156 | | Exception shutdownReason = null; |
| | 0 | 157 | | Exception unexpectedError = null; |
| | | 158 | | |
| | | 159 | | try |
| | | 160 | | { |
| | 0 | 161 | | while (true) |
| | | 162 | | { |
| | 0 | 163 | | var result = await Output.ReadAsync(); |
| | | 164 | | |
| | 0 | 165 | | if (result.IsCanceled) |
| | | 166 | | { |
| | | 167 | | break; |
| | | 168 | | } |
| | 0 | 169 | | var buffer = result.Buffer; |
| | | 170 | | |
| | 0 | 171 | | if (buffer.IsSingleSegment) |
| | | 172 | | { |
| | | 173 | | // Fast path when the buffer is a single segment. |
| | 0 | 174 | | await WriteAsync(buffer.First); |
| | | 175 | | } |
| | | 176 | | else |
| | | 177 | | { |
| | 0 | 178 | | foreach (var segment in buffer) |
| | | 179 | | { |
| | 0 | 180 | | await WriteAsync(segment); |
| | | 181 | | } |
| | | 182 | | } |
| | | 183 | | |
| | 0 | 184 | | Output.AdvanceTo(buffer.End); |
| | | 185 | | |
| | 0 | 186 | | if (result.IsCompleted) |
| | | 187 | | { |
| | | 188 | | break; |
| | | 189 | | } |
| | 0 | 190 | | } |
| | 0 | 191 | | } |
| | 0 | 192 | | catch (ObjectDisposedException ex) |
| | | 193 | | { |
| | | 194 | | // This should always be ignored since Shutdown() must have already been called by Abort(). |
| | 0 | 195 | | shutdownReason = ex; |
| | 0 | 196 | | } |
| | 0 | 197 | | catch (Exception ex) |
| | | 198 | | { |
| | 0 | 199 | | shutdownReason = ex; |
| | 0 | 200 | | unexpectedError = ex; |
| | 0 | 201 | | Logger.ConnectionError(ConnectionId, unexpectedError); |
| | 0 | 202 | | } |
| | | 203 | | finally |
| | | 204 | | { |
| | 0 | 205 | | Shutdown(shutdownReason); |
| | | 206 | | |
| | | 207 | | // Complete the output after disposing the socket |
| | 0 | 208 | | Output.Complete(unexpectedError); |
| | | 209 | | |
| | | 210 | | // Cancel any pending flushes so that the input loop is un-paused |
| | 0 | 211 | | Input.CancelPendingFlush(); |
| | | 212 | | } |
| | 0 | 213 | | } |
| | | 214 | | |
| | | 215 | | private async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer) |
| | | 216 | | { |
| | 0 | 217 | | if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> byteArray)) |
| | | 218 | | { |
| | 0 | 219 | | await _pipe.WriteAsync(byteArray.Array, byteArray.Offset, byteArray.Count); |
| | | 220 | | } |
| | | 221 | | else |
| | | 222 | | { |
| | 0 | 223 | | _writeBuffer ??= Fx.AllocateByteArray(_connectionBufferSize); |
| | 0 | 224 | | if (buffer.Length <= _connectionBufferSize) |
| | | 225 | | { |
| | 0 | 226 | | buffer.CopyTo(_writeBuffer); |
| | 0 | 227 | | await _pipe.WriteAsync(_writeBuffer, 0, buffer.Length); |
| | | 228 | | } |
| | | 229 | | else |
| | | 230 | | { |
| | 0 | 231 | | while(buffer.Length > _connectionBufferSize) |
| | | 232 | | { |
| | 0 | 233 | | buffer.Slice(0, _connectionBufferSize).CopyTo(_writeBuffer); |
| | 0 | 234 | | await _pipe.WriteAsync(_writeBuffer, 0, _connectionBufferSize); |
| | 0 | 235 | | buffer = buffer.Slice(_connectionBufferSize); |
| | | 236 | | } |
| | 0 | 237 | | buffer.CopyTo(_writeBuffer); |
| | 0 | 238 | | await _pipe.WriteAsync(_writeBuffer, 0, buffer.Length); |
| | | 239 | | } |
| | | 240 | | } |
| | 0 | 241 | | } |
| | | 242 | | |
| | | 243 | | private void Shutdown(Exception shutdownReason) |
| | | 244 | | { |
| | 0 | 245 | | lock (_shutdownLock) |
| | | 246 | | { |
| | 0 | 247 | | if (_connectionShutdown) |
| | | 248 | | { |
| | 0 | 249 | | return; |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | // Make sure to close the connection only after the _aborted flag is set. |
| | | 253 | | // Without this, the RequestsCanBeAbortedMidRead test will sometimes fail when |
| | | 254 | | // a BadHttpRequestException is thrown instead of a TaskCanceledException. |
| | 0 | 255 | | _connectionShutdown = true; |
| | | 256 | | |
| | | 257 | | // shutdownReason should only be null if the output was completed gracefully, so no one should ever |
| | | 258 | | // ever observe the nondescript ConnectionAbortedException except for connection middleware attempting |
| | | 259 | | // to half close the connection which is currently unsupported. |
| | 0 | 260 | | _shutdownReason = shutdownReason ?? s_sendGracefullyCompletedException; |
| | 0 | 261 | | Logger.ConnectionDisconnect(ConnectionId, _shutdownReason.Message); |
| | | 262 | | |
| | | 263 | | try |
| | | 264 | | { |
| | 0 | 265 | | _pipe.Disconnect(); |
| | 0 | 266 | | _streamDisconnected = true; |
| | 0 | 267 | | } |
| | 0 | 268 | | catch |
| | | 269 | | { |
| | | 270 | | // Ignore any errors from NamedPipeStream.Disconnect() since we're tearing down the connection anywa |
| | 0 | 271 | | } |
| | | 272 | | } |
| | 0 | 273 | | } |
| | | 274 | | |
| | | 275 | | private void FireConnectionClosed() |
| | | 276 | | { |
| | | 277 | | // Guard against scheduling this multiple times |
| | 0 | 278 | | lock (_shutdownLock) |
| | | 279 | | { |
| | 0 | 280 | | if (_connectionClosed) |
| | | 281 | | { |
| | 0 | 282 | | return; |
| | | 283 | | } |
| | | 284 | | |
| | 0 | 285 | | _connectionClosed = true; |
| | 0 | 286 | | } |
| | | 287 | | |
| | 0 | 288 | | CancelConnectionClosedToken(); |
| | 0 | 289 | | } |
| | | 290 | | |
| | | 291 | | private void CancelConnectionClosedToken() |
| | | 292 | | { |
| | | 293 | | try |
| | | 294 | | { |
| | 0 | 295 | | _connectionClosedTokenSource.Cancel(); |
| | 0 | 296 | | } |
| | 0 | 297 | | catch (Exception ex) |
| | | 298 | | { |
| | 0 | 299 | | Logger.LogConnectionError(0, ex, $"Unexpected exception in {nameof(NamedPipeConnectionContext)}.{nameof( |
| | 0 | 300 | | } |
| | 0 | 301 | | } |
| | | 302 | | |
| | | 303 | | public async ValueTask DisposeAsync() |
| | | 304 | | { |
| | 0 | 305 | | _originalTransport.Input.Complete(); |
| | 0 | 306 | | _originalTransport.Output.Complete(); |
| | | 307 | | |
| | | 308 | | try |
| | | 309 | | { |
| | | 310 | | // Now wait for both to complete |
| | 0 | 311 | | await _receivingTask; |
| | 0 | 312 | | await _sendingTask; |
| | 0 | 313 | | } |
| | 0 | 314 | | catch (Exception ex) |
| | | 315 | | { |
| | 0 | 316 | | Logger.LogConnectionError(0, ex, $"Unexpected exception in {nameof(NamedPipeConnection)}.{nameof(Start)} |
| | 0 | 317 | | _pipe.Dispose(); |
| | 0 | 318 | | return; |
| | | 319 | | } |
| | | 320 | | |
| | | 321 | | // TODO: Consider pooling NamedPipeServerStream instances |
| | 0 | 322 | | _pipe.Dispose(); |
| | 0 | 323 | | } |
| | | 324 | | |
| | | 325 | | public override void Abort(ConnectionAbortedException abortReason) |
| | | 326 | | { |
| | | 327 | | Debug.Assert(Application != null); |
| | 0 | 328 | | Application.Input.CancelPendingRead(); |
| | 0 | 329 | | } |
| | | 330 | | |
| | | 331 | | private class DuplexPipe : IDuplexPipe |
| | | 332 | | { |
| | | 333 | | public static IDuplexPipe CreateTransport(Pipe input, Pipe output) |
| | | 334 | | { |
| | 0 | 335 | | return new DuplexPipe { Input = input.Reader, Output = output.Writer }; |
| | | 336 | | } |
| | | 337 | | |
| | | 338 | | public static IDuplexPipe CreateApplication(Pipe input, Pipe output) |
| | | 339 | | { |
| | 0 | 340 | | return new DuplexPipe { Input = output.Reader, Output = input.Writer }; |
| | | 341 | | } |
| | | 342 | | |
| | 0 | 343 | | public PipeReader Input { get; private set; } |
| | 0 | 344 | | public PipeWriter Output { get; private set; } |
| | | 345 | | } |
| | | 346 | | } |
| | | 347 | | } |