-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathSocketAsyncEventArgs.Windows.cs
1278 lines (1129 loc) · 60 KB
/
SocketAsyncEventArgs.Windows.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
/// <summary>
/// Value used to indicate whether the thread starting an async operation or invoking the callback owns completion and cleanup,
/// and potentially a packed result when ownership is transferred from the overlapped callback to the initial thread.
/// </summary>
/// <remarks>
/// An async operation may complete asynchronously so quickly that the overlapped callback may be invoked even while the thread
/// launching the operation is still in the process of launching it, including setting up state that's only configured after
/// the Winsock call has been made, e.g. registering with a cancellation token. In order to ensure that cleanup and announcement
/// of completion happen only once all work related to launching the operation has quiesced, the launcher and the callback
/// coordinate via this flag. It's initially set to 0. When either the launcher completes its work or the callback is invoked,
/// they each try to transition the flag to non-0, and if successful, the other entity owns completion and cleanup; if unsuccessful,
/// they themselves own cleanup and completion. For cases where the operation frequently completes asynchronously but quickly,
/// e.g. accepts with an already pending connection, this also helps to turn what would otherwise be treated as asynchronous completion
/// into a synchronous completion, which can help with performance for the caller, e.g. an async method awaiting the operation simply
/// continues its execution synchronously rather than needing to hook up a continuation and go through the async completion path.
/// If the overlapped callback succeeds in transferring ownership, the value is a combination of the error code (bottom 32-bits) and
/// the number of bytes transferred (bits 33-63); the top bit is also set just in case both the error code and number of bytes
/// transferred are 0.
/// </remarks>
private ulong _asyncCompletionOwnership;
/// <summary>Pinned handle for a single buffer.</summary>
/// <remarks>
/// This should only be set in <see cref="ProcessIOCPResult"/> when <see cref="_asyncCompletionOwnership"/> is also being
/// set to non-0, and then cleaned up in <see cref="CompleteCore"/>. If it's set and <see cref="_asyncCompletionOwnership"/>
/// remains 0, it may not get cleaned up correctly.
/// </remarks>
private MemoryHandle _singleBufferHandle;
// BufferList property variables.
// Note that these arrays are allocated and then grown as necessary, but never shrunk.
// Thus the actual in-use length is defined by _bufferListInternal.Count, not the length of these arrays.
private WSABuffer[]? _wsaBufferArrayPinned;
private MemoryHandle[]? _multipleBufferMemoryHandles;
// Internal buffers for WSARecvMsg
private byte[]? _wsaMessageBufferPinned;
private byte[]? _controlBufferPinned;
private WSABuffer[]? _wsaRecvMsgWSABufferArrayPinned;
// SocketAddress buffer
private IntPtr _socketAddressPtr;
// SendPacketsElements property variables.
private SafeFileHandle[]? _sendPacketsFileHandles;
// Overlapped object related variables.
private PreAllocatedOverlapped _preAllocatedOverlapped;
private readonly StrongBox<SocketAsyncEventArgs?> _strongThisRef = new StrongBox<SocketAsyncEventArgs?>(); // state for _preAllocatedOverlapped; .Value set to this while operations in flight
/// <summary>Registration with a cancellation token for an asynchronous operation.</summary>
/// <remarks>
/// This should only be set in <see cref="ProcessIOCPResult"/> when <see cref="_asyncCompletionOwnership"/> is also being
/// set to non-0, and then cleaned up in <see cref="CompleteCore"/>. If it's set and <see cref="_asyncCompletionOwnership"/>
/// remains 0, it may not get cleaned up correctly.
/// </remarks>
private CancellationTokenRegistration _registrationToCancelPendingIO;
private unsafe NativeOverlapped* _pendingOverlappedForCancellation;
private PinState _pinState;
private enum PinState : byte
{
None = 0,
MultipleBuffer,
SendPackets
}
[MemberNotNull(nameof(_preAllocatedOverlapped))]
private void InitializeInternals()
{
Debug.Assert(OperatingSystem.IsWindows());
_preAllocatedOverlapped = PreAllocatedOverlapped.UnsafeCreate(s_completionPortCallback, _strongThisRef, null);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"new PreAllocatedOverlapped {_preAllocatedOverlapped}");
}
private void FreeInternals()
{
FreePinHandles();
FreeOverlapped();
}
private unsafe NativeOverlapped* AllocateNativeOverlapped()
{
Debug.Assert(OperatingSystem.IsWindows());
Debug.Assert(_operating == OperationState.InProgress, $"Expected {nameof(_operating)} == {nameof(OperationState.InProgress)}, got {_operating}");
Debug.Assert(_currentSocket != null, "_currentSocket is null");
Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null");
Debug.Assert(_preAllocatedOverlapped != null, "_preAllocatedOverlapped is null");
ThreadPoolBoundHandle boundHandle = _currentSocket.GetOrAllocateThreadPoolBoundHandle();
return boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped);
}
private unsafe void FreeNativeOverlapped(ref NativeOverlapped* overlapped)
{
Debug.Assert(OperatingSystem.IsWindows());
Debug.Assert(overlapped != null, "overlapped is null");
Debug.Assert(_operating == OperationState.InProgress, $"Expected _operating == OperationState.InProgress, got {_operating}");
Debug.Assert(_currentSocket != null, "_currentSocket is null");
Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null");
Debug.Assert(_currentSocket.SafeHandle.IOCPBoundHandle != null, "_currentSocket.SafeHandle.IOCPBoundHandle is null");
Debug.Assert(_preAllocatedOverlapped != null, "_preAllocatedOverlapped is null");
_currentSocket.SafeHandle.IOCPBoundHandle.FreeNativeOverlapped(overlapped);
overlapped = null;
}
partial void StartOperationCommonCore()
{
// Store the reference to this instance so that it's kept alive by the preallocated
// overlapped during the asynchronous operation and so that it's available in the
// I/O completion callback. Once the operation completes, we null this out so
// that the SocketAsyncEventArgs instance isn't kept alive unnecessarily.
_strongThisRef.Value = this;
}
/// <summary>Gets the result of an IOCP operation and determines how it should be handled (synchronously or asynchronously).</summary>
/// <param name="success">true if the IOCP operation indicated synchronous success; otherwise, false.</param>
/// <param name="overlapped">The overlapped that was used for this operation. Will be freed if the operation result will be handled synchronously.</param>
/// <returns>The SocketError for the operation. This will be SocketError.IOPending if the operation will be handled asynchronously.</returns>
private unsafe SocketError GetIOCPResult(bool success, ref NativeOverlapped* overlapped)
{
// Note: We need to dispose of the overlapped iff the operation result will be handled synchronously.
if (success)
{
// Synchronous success.
if (_currentSocket!.SafeHandle.SkipCompletionPortOnSuccess)
{
// The socket handle is configured to skip completion on success, so we can handle the result synchronously.
FreeNativeOverlapped(ref overlapped);
return SocketError.Success;
}
// Completed synchronously, but the handle wasn't marked as skip completion port on success,
// so we still need to behave as if the IO was pending and wait for the completion to come through on the IOCP.
return SocketError.IOPending;
}
else
{
// Get the socket error (which may be IOPending)
SocketError socketError = SocketPal.GetLastSocketError();
Debug.Assert(socketError != SocketError.Success);
if (socketError != SocketError.IOPending)
{
// Completed synchronously with a failure.
// No IOCP completion will occur.
FreeNativeOverlapped(ref overlapped);
return socketError;
}
// The completion will arrive on the IOCP when the operation is done.
return SocketError.IOPending;
}
}
/// <summary>Handles the result of an IOCP operation for which we have deferred async processing logic (buffer pinning or cancellation).</summary>
/// <param name="success">true if the IOCP operation indicated synchronous success; otherwise, false.</param>
/// <param name="bytesTransferred">The number of bytes transferred, if the operation completed synchronously and successfully.</param>
/// <param name="overlapped">The overlapped that was used for this operation. Will be freed if the operation result will be handled synchronously.</param>
/// <param name="bufferToPin">The buffer to pin. May be Memory.Empty if no buffer should be pinned.
/// Note this buffer (if not empty) should already be pinned locally using `fixed` prior to the OS async call and until after this method returns.</param>
/// <param name="cancellationToken">The cancellation token to use to cancel the operation.</param>
/// <returns>The result status of the operation.</returns>
private unsafe SocketError ProcessIOCPResult(bool success, int bytesTransferred, ref NativeOverlapped* overlapped, Memory<byte> bufferToPin, CancellationToken cancellationToken)
{
SocketError socketError = GetIOCPResult(success, ref overlapped);
SocketFlags socketFlags = SocketFlags.None;
if (socketError == SocketError.IOPending)
{
// Perform any required setup of the asynchronous operation. Everything set up here needs to be undone in CompleteCore.CleanupIOCPResult.
if (cancellationToken.CanBeCanceled)
{
Debug.Assert(_pendingOverlappedForCancellation == null);
_pendingOverlappedForCancellation = overlapped;
_registrationToCancelPendingIO = cancellationToken.UnsafeRegister(static s =>
{
// Try to cancel the I/O. We ignore the return value (other than for logging), as cancellation
// is opportunistic and we don't want to fail the operation because we couldn't cancel it.
var thisRef = (SocketAsyncEventArgs)s!;
SafeSocketHandle handle = thisRef._currentSocket!.SafeHandle;
if (!handle.IsClosed)
{
try
{
bool canceled = Interop.Kernel32.CancelIoEx(handle, thisRef._pendingOverlappedForCancellation);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(thisRef, canceled ?
"Socket operation canceled." :
$"CancelIoEx failed with error '{Marshal.GetLastPInvokeError()}'.");
}
}
catch (ObjectDisposedException)
{
// Ignore errors resulting from the SafeHandle being closed concurrently.
}
}
}, this);
}
if (!bufferToPin.Equals(default))
{
_singleBufferHandle = bufferToPin.Pin();
}
// We've finished setting up and launching the operation. Coordinate with the callback.
// The expectation is that in the majority of cases either the operation will have completed
// synchronously (in which case we won't be here) or the operation will complete asynchronously
// and this function will typically win the race condition with the callback.
ulong packedResult = Interlocked.Exchange(ref _asyncCompletionOwnership, 1);
if (packedResult == 0)
{
// We won the race condition with the callback. It now owns completion and clean up.
return SocketError.IOPending;
}
// The callback was already invoked and transferred ownership to us, so now behave as if the operation completed synchronously.
// Since the success/bytesTransferred arguments passed into this method are stale, we need to retrieve the actual status info
// from the overlapped directly. It's also now our responsibility to clean up as GetIOCPResult would have, so free the overlapped.
Debug.Assert((packedResult & 0x8000000000000000) != 0, "Top bit should have been set");
bytesTransferred = (int)((packedResult >> 32) & 0x7FFFFFFF);
socketError = (SocketError)(packedResult & 0xFFFFFFFF);
if (socketError != SocketError.Success)
{
GetOverlappedResultOnError(ref socketError, ref *(uint*)&bytesTransferred, ref socketFlags, overlapped);
}
FreeNativeOverlapped(ref overlapped);
}
// The operation completed, either synchronously and the callback won't be invoked, or asynchronously
// but so fast the callback has already executed and left clean up to us.
FinishOperationSync(socketError, bytesTransferred, socketFlags);
return socketError;
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
bool userBuffer = _count != 0;
Debug.Assert(!userBuffer || (!_buffer.Equals(default) && _count >= _acceptAddressBufferCount));
Memory<byte> buffer = userBuffer ? _buffer : _acceptBuffer;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool success = socket.AcceptEx(
handle,
acceptHandle,
(IntPtr)(userBuffer ? (bufferPtr + _offset) : bufferPtr),
userBuffer ? _count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out int bytesTransferred,
overlapped);
return ProcessIOCPResult(success, bytesTransferred, ref overlapped, buffer, cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
}
internal SocketError DoOperationConnect(SafeSocketHandle handle)
{
// Called for connectionless protocols.
SocketError socketError = SocketPal.Connect(handle, _socketAddress!.Buffer);
FinishOperationSync(socketError, 0, SocketFlags.None);
return socketError;
}
internal unsafe SocketError DoOperationConnectEx(Socket socket, SafeSocketHandle handle)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
// ConnectEx uses a sockaddr buffer containing the remote address to which to connect.
// It can also optionally take a single buffer of data to send after the connection is complete.
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool success = socket.ConnectEx(
handle,
_socketAddress!.Buffer.Span,
(IntPtr)(bufferPtr + _offset),
_count,
out int bytesTransferred,
overlapped);
return ProcessIOCPResult(success, bytesTransferred, ref overlapped, _buffer, cancellationToken: default);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool success = socket.DisconnectEx(
handle,
overlapped,
(int)(DisconnectReuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0);
return ProcessIOCPResult(success, 0, ref overlapped, bufferToPin: default, cancellationToken: cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
internal SocketError DoOperationReceive(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList == null ?
DoOperationReceiveSingleBuffer(handle, cancellationToken) :
DoOperationReceiveMultiBuffer(handle);
internal unsafe SocketError DoOperationReceiveSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecv(
handle,
&wsaBuffer,
1,
out int bytesTransferred,
ref flags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, _buffer, cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationReceiveMultiBuffer(SafeSocketHandle handle)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecv(
handle,
_wsaBufferArrayPinned,
_bufferListInternal!.Count,
out int bytesTransferred,
ref flags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, bufferToPin: default, cancellationToken: default);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle, CancellationToken cancellationToken)
{
// WSARecvFrom uses a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
// WSARecvFrom also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is allocated from NativeMemory and reused multiple time when possible.
AllocateSocketAddressBuffer();
return _bufferList == null ?
DoOperationReceiveFromSingleBuffer(handle, cancellationToken) :
DoOperationReceiveFromMultiBuffer(handle);
}
internal unsafe SocketError DoOperationReceiveFromSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecvFrom(
handle,
ref wsaBuffer,
1,
out int bytesTransferred,
ref flags,
PtrSocketAddressBuffer(),
PtrSocketAddressSize(),
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, _buffer, cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationReceiveFromMultiBuffer(SafeSocketHandle handle)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecvFrom(
handle,
_wsaBufferArrayPinned!,
_bufferListInternal!.Count,
out int bytesTransferred,
ref flags,
PtrSocketAddressBuffer(),
PtrSocketAddressSize(),
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, bufferToPin: default, cancellationToken: default);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
// WSARecvMsg uses a WSAMsg descriptor.
// The WSAMsg buffer is a pinned array to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a sockaddr that is allocated from NativeMemory
// and reused multiple time when possible.
// WSAMsg also contains a pointer to a WSABuffer array describing data buffers.
// WSAMsg also contains a single WSABuffer describing a control buffer.
AllocateSocketAddressBuffer();
// Create a WSAMessageBuffer if none exists yet.
_wsaMessageBufferPinned ??= GC.AllocateUninitializedArray<byte>(sizeof(Interop.Winsock.WSAMsg), pinned: true);
// Create and pin an appropriately sized control buffer if none already
IPAddress? ipAddress = (_socketAddress!.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
bool ipv4 = (_currentSocket!.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6;
if (ipv6 && (_controlBufferPinned == null || _controlBufferPinned.Length != sizeof(Interop.Winsock.ControlDataIPv6)))
{
_controlBufferPinned = GC.AllocateUninitializedArray<byte>(sizeof(Interop.Winsock.ControlDataIPv6), pinned: true);
}
else if (ipv4 && (_controlBufferPinned == null || _controlBufferPinned.Length != sizeof(Interop.Winsock.ControlData)))
{
_controlBufferPinned = GC.AllocateUninitializedArray<byte>(sizeof(Interop.Winsock.ControlData), pinned: true);
}
// If single buffer we need a single element WSABuffer.
WSABuffer[] wsaRecvMsgWSABufferArray;
uint wsaRecvMsgWSABufferCount;
if (_bufferList == null)
{
_wsaRecvMsgWSABufferArrayPinned ??= GC.AllocateUninitializedArray<WSABuffer>(1, pinned: true);
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
_wsaRecvMsgWSABufferArrayPinned[0].Pointer = (IntPtr)bufferPtr + _offset;
_wsaRecvMsgWSABufferArrayPinned[0].Length = _count;
wsaRecvMsgWSABufferArray = _wsaRecvMsgWSABufferArrayPinned;
wsaRecvMsgWSABufferCount = 1;
return Core();
}
}
else
{
// Use the multi-buffer WSABuffer.
wsaRecvMsgWSABufferArray = _wsaBufferArrayPinned!;
wsaRecvMsgWSABufferCount = (uint)_bufferListInternal!.Count;
return Core();
}
// Fill in WSAMessageBuffer, run WSARecvMsg and process the IOCP result.
// Logic is in a separate method so we can share code between the (pinned) single buffer and the multi-buffer case
SocketError Core()
{
// Fill in WSAMessageBuffer.
Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBufferPinned, 0);
pMessage->socketAddress = PtrSocketAddressBuffer();
pMessage->addressLength = (uint)SocketAddress.GetMaximumAddressSize(_socketAddress!.Family);
fixed (void* ptrWSARecvMsgWSABufferArray = &wsaRecvMsgWSABufferArray[0])
{
pMessage->buffers = (IntPtr)ptrWSARecvMsgWSABufferArray;
}
pMessage->count = wsaRecvMsgWSABufferCount;
if (_controlBufferPinned != null)
{
Debug.Assert(_controlBufferPinned.Length > 0);
fixed (void* ptrControlBuffer = &_controlBufferPinned[0])
{
pMessage->controlBuffer.Pointer = (IntPtr)ptrControlBuffer;
}
pMessage->controlBuffer.Length = _controlBufferPinned.Length;
}
pMessage->flags = _socketFlags;
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketError socketError = socket.WSARecvMsg(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBufferPinned, 0),
out int bytesTransferred,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, _bufferList == null ? _buffer : default, cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList == null ?
DoOperationSendSingleBuffer(handle, cancellationToken) :
DoOperationSendMultiBuffer(handle);
internal unsafe SocketError DoOperationSendSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketError socketError = Interop.Winsock.WSASend(
handle,
&wsaBuffer,
1,
out int bytesTransferred,
_socketFlags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, _buffer, cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationSendMultiBuffer(SafeSocketHandle handle)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketError socketError = Interop.Winsock.WSASend(
handle,
_wsaBufferArrayPinned,
_bufferListInternal!.Count,
out int bytesTransferred,
_socketFlags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, bufferToPin: default, cancellationToken: default);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
// Cache copy to avoid problems with concurrent manipulation during the async operation.
Debug.Assert(_sendPacketsElements != null);
SendPacketsElement[] sendPacketsElementsCopy = (SendPacketsElement[])_sendPacketsElements.Clone();
// TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as
// descriptors for buffers and files to be sent. It also takes a send size
// and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle.
// Opens the files to get the file handles, pin down any buffers specified and builds the
// native TRANSMIT_PACKET_ELEMENT array that will be passed to TransmitPackets.
// Scan the elements to count files and buffers.
int sendPacketsElementsFileCount = 0, sendPacketsElementsFileStreamCount = 0, sendPacketsElementsBufferCount = 0;
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe != null)
{
if (spe.FilePath != null)
{
sendPacketsElementsFileCount++;
}
else if (spe.FileStream != null)
{
sendPacketsElementsFileStreamCount++;
}
else if (spe.MemoryBuffer != null && spe.Count > 0)
{
sendPacketsElementsBufferCount++;
}
}
}
if (sendPacketsElementsFileCount + sendPacketsElementsFileStreamCount + sendPacketsElementsBufferCount == 0)
{
FinishOperationSyncSuccess(0, SocketFlags.None);
return SocketError.Success;
}
// Attempt to open the files if any were given.
if (sendPacketsElementsFileCount > 0)
{
// Loop through the elements attempting to open each files and get its handle.
int index = 0;
_sendPacketsFileHandles = new SafeFileHandle[sendPacketsElementsFileCount];
try
{
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe?.FilePath != null)
{
// Create a FileStream to open the file.
_sendPacketsFileHandles[index] =
File.OpenHandle(spe.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
// Get the file handle from the stream.
index++;
}
}
}
catch
{
// Got an exception opening a file - close any open streams, then throw.
for (int i = index - 1; i >= 0; i--)
_sendPacketsFileHandles[i].Dispose();
_sendPacketsFileHandles = null;
throw;
}
}
Interop.Winsock.TransmitPacketsElement[] sendPacketsDescriptorPinned =
SetupPinHandlesSendPackets(sendPacketsElementsCopy, sendPacketsElementsFileCount,
sendPacketsElementsFileStreamCount, sendPacketsElementsBufferCount);
Debug.Assert(sendPacketsDescriptorPinned != null);
Debug.Assert(sendPacketsDescriptorPinned.Length > 0);
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool result = socket.TransmitPackets(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(sendPacketsDescriptorPinned, 0),
sendPacketsDescriptorPinned.Length,
_sendPacketsSendSize,
overlapped,
_sendPacketsFlags);
return ProcessIOCPResult(result, 0, ref overlapped, bufferToPin: default, cancellationToken: cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
internal unsafe SocketError DoOperationSendTo(SafeSocketHandle handle, CancellationToken cancellationToken)
{
// WSASendTo uses a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
return _bufferList == null ?
DoOperationSendToSingleBuffer(handle, cancellationToken) :
DoOperationSendToMultiBuffer(handle);
}
internal unsafe SocketError DoOperationSendToSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketError socketError = Interop.Winsock.WSASendTo(
handle,
ref wsaBuffer,
1,
out int bytesTransferred,
_socketFlags,
_socketAddress!.Buffer.Span,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, _buffer, cancellationToken);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationSendToMultiBuffer(SafeSocketHandle handle)
{
Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketError socketError = Interop.Winsock.WSASendTo(
handle,
_wsaBufferArrayPinned!,
_bufferListInternal!.Count,
out int bytesTransferred,
_socketFlags,
_socketAddress!.Buffer.Span,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, bufferToPin: default, cancellationToken: default);
}
catch when (overlapped is not null)
{
FreeNativeOverlapped(ref overlapped);
throw;
}
}
// Ensures Overlapped object exists with appropriate multiple buffers pinned.
private void SetupMultipleBuffers()
{
if (_bufferListInternal == null || _bufferListInternal.Count == 0)
{
// No buffer list is set so unpin any existing multiple buffer pinning.
if (_pinState == PinState.MultipleBuffer)
{
FreePinHandles();
}
}
else
{
// Need to setup a new Overlapped.
FreePinHandles();
try
{
int bufferCount = _bufferListInternal.Count;
// Number of things to pin is number of buffers.
// Ensure we have properly sized object array.
if (_multipleBufferMemoryHandles == null || (_multipleBufferMemoryHandles.Length < bufferCount))
{
_multipleBufferMemoryHandles = new MemoryHandle[bufferCount];
}
// Pin the buffers.
for (int i = 0; i < bufferCount; i++)
{
_multipleBufferMemoryHandles[i] = _bufferListInternal[i].Array.AsMemory().Pin();
}
if (_wsaBufferArrayPinned == null || _wsaBufferArrayPinned.Length < bufferCount)
{
_wsaBufferArrayPinned = GC.AllocateUninitializedArray<WSABuffer>(bufferCount, pinned: true);
}
for (int i = 0; i < bufferCount; i++)
{
ArraySegment<byte> localCopy = _bufferListInternal[i];
_wsaBufferArrayPinned[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array!, localCopy.Offset);
_wsaBufferArrayPinned[i].Length = localCopy.Count;
}
_pinState = PinState.MultipleBuffer;
}
catch (Exception)
{
FreePinHandles();
throw;
}
}
}
// Ensures appropriate SocketAddress buffer is allocated.
private unsafe void AllocateSocketAddressBuffer()
{
//_socketAddress!.Size = SocketAddress.GetMaximumAddressSize(_socketAddress!.Family);
int size = SocketAddress.GetMaximumAddressSize(_socketAddress!.Family);
if (_socketAddressPtr == IntPtr.Zero)
{
_socketAddressPtr = (IntPtr)NativeMemory.Alloc((uint)(_socketAddress!.Size + sizeof(IntPtr)));
}
*((int*)_socketAddressPtr) = size;
}
private unsafe IntPtr PtrSocketAddressBuffer()
{
Debug.Assert(_socketAddressPtr != IntPtr.Zero);
return _socketAddressPtr + sizeof(IntPtr);
}
private IntPtr PtrSocketAddressSize()
{
Debug.Assert(_socketAddressPtr != IntPtr.Zero);
return _socketAddressPtr;
}
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped()
{
// Free the preallocated overlapped object. This in turn will unpin
// any pinned buffers.
if (_preAllocatedOverlapped != null)
{
Debug.Assert(OperatingSystem.IsWindows());
_preAllocatedOverlapped.Dispose();
_preAllocatedOverlapped = null!;
}
}
private unsafe void FreePinHandles()
{
_pinState = PinState.None;
if (_multipleBufferMemoryHandles != null)
{
for (int i = 0; i < _multipleBufferMemoryHandles.Length; i++)
{
_multipleBufferMemoryHandles[i].Dispose();
_multipleBufferMemoryHandles[i] = default;
}
}
if (_socketAddressPtr != IntPtr.Zero)
{
NativeMemory.Free((void*)_socketAddressPtr);
_socketAddressPtr = IntPtr.Zero;
}
Debug.Assert(_singleBufferHandle.Equals(default(MemoryHandle)));
}
// Sets up an Overlapped object for SendPacketsAsync.
private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPackets(
SendPacketsElement[] sendPacketsElementsCopy, int sendPacketsElementsFileCount, int sendPacketsElementsFileStreamCount, int sendPacketsElementsBufferCount)
{
if (_pinState != PinState.None)
{
FreePinHandles();
}
// Alloc native descriptor.
var sendPacketsDescriptorPinned = GC.AllocateUninitializedArray<Interop.Winsock.TransmitPacketsElement>(
sendPacketsElementsFileCount + sendPacketsElementsFileStreamCount + sendPacketsElementsBufferCount,
pinned: true);
// Number of things to pin is number of buffers + 1 (native descriptor).
// Ensure we have properly sized object array.
if (_multipleBufferMemoryHandles == null || (_multipleBufferMemoryHandles.Length < sendPacketsElementsBufferCount))
{
_multipleBufferMemoryHandles = new MemoryHandle[sendPacketsElementsBufferCount];
}
// Pin user specified buffers.
int index = 0;
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe?.MemoryBuffer != null && spe.Count > 0)
{
_multipleBufferMemoryHandles[index] = spe.MemoryBuffer.Value.Pin();
index++;
}
}
// Fill in native descriptor.
int bufferIndex = 0;
int descriptorIndex = 0;
int fileIndex = 0;
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe != null)
{
if (spe.MemoryBuffer != null && spe.Count > 0)
{
// This element is a buffer.
sendPacketsDescriptorPinned[descriptorIndex].buffer = (IntPtr)_multipleBufferMemoryHandles[bufferIndex].Pointer;
sendPacketsDescriptorPinned[descriptorIndex].length = (uint)spe.Count;
sendPacketsDescriptorPinned[descriptorIndex].flags =
Interop.Winsock.TransmitPacketsElementFlags.Memory | (spe.EndOfPacket
? Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket
: 0);
bufferIndex++;
descriptorIndex++;
}
else if (spe.FilePath != null)
{
// This element is a file.
sendPacketsDescriptorPinned[descriptorIndex].fileHandle = _sendPacketsFileHandles![fileIndex].DangerousGetHandle();
sendPacketsDescriptorPinned[descriptorIndex].fileOffset = spe.OffsetLong;
sendPacketsDescriptorPinned[descriptorIndex].length = (uint)spe.Count;
sendPacketsDescriptorPinned[descriptorIndex].flags =
Interop.Winsock.TransmitPacketsElementFlags.File | (spe.EndOfPacket
? Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket
: 0);
fileIndex++;
descriptorIndex++;
}
else if (spe.FileStream != null)
{
// This element is a file stream. SendPacketsElement throws if the FileStream is not opened asynchronously;
// Synchronously opened FileStream can't be used concurrently (e.g. multiple SendPacketsElements with the same
// FileStream).
sendPacketsDescriptorPinned[descriptorIndex].fileHandle = spe.FileStream.SafeFileHandle.DangerousGetHandle();
sendPacketsDescriptorPinned[descriptorIndex].fileOffset = spe.OffsetLong;
sendPacketsDescriptorPinned[descriptorIndex].length = (uint)spe.Count;
sendPacketsDescriptorPinned[descriptorIndex].flags =
Interop.Winsock.TransmitPacketsElementFlags.File | (spe.EndOfPacket