Terraria v1.4.4.9
Terraria source code documentation
Loading...
Searching...
No Matches
SocketAsyncEventArgs.cs
Go to the documentation of this file.
4using System.IO;
12
13namespace System.Net.Sockets;
14
16{
18 {
20
21 private int _isCompleted;
22
23 public short Version => _mrvtsc.Version;
24
29
30 public void GetResult(short token)
31 {
32 _mrvtsc.GetResult(token);
33 }
34
35 public ValueTaskSourceStatus GetStatus(short token)
36 {
37 return _mrvtsc.GetStatus(token);
38 }
39
41 {
42 _mrvtsc.OnCompleted(continuation, state, token, flags);
43 }
44
45 public void Reset()
46 {
47 _mrvtsc.Reset();
48 }
49
50 protected override void OnCompleted(SocketAsyncEventArgs e)
51 {
52 _mrvtsc.SetResult(result: true);
53 }
54
56 {
57 return Interlocked.Exchange(ref _isCompleted, 1) == 0;
58 }
59 }
60
61 private enum AsyncProcessingState : byte
62 {
63 None,
65 Set
66 }
67
68 private enum PinState : byte
69 {
70 None,
73 }
74
76
78
80
81 private int _offset;
82
83 private int _count;
84
86
88
90
91 private int _bytesTransferred;
92
94
96
98
100
102
104
106
108
110
112
113 private object _userToken;
114
115 private byte[] _acceptBuffer;
116
118
120
121 private readonly bool _flowExecutionContext;
122
124
126
128
129 private bool _userSocket;
130
131 private bool _disposeCalled;
132
133 private int _operating;
134
136
138
140
142
144
146
147 private byte[] _controlBufferPinned;
148
150
152
154
156
158
160
162
164
166
168 {
171 if (errorCode == 0)
172 {
173 value.FreeNativeOverlapped(nativeOverlapped);
174 value.FinishOperationAsyncSuccess((int)numBytes, SocketFlags.None);
175 }
176 else
177 {
178 value.HandleCompletionPortCallbackError(errorCode, numBytes, nativeOverlapped);
179 }
180 };
181
183 {
184 get
185 {
186 return _acceptSocket;
187 }
188 set
189 {
191 }
192 }
193
195
196 public byte[]? Buffer
197 {
198 get
199 {
201 {
203 bool flag = MemoryMarshal.TryGetArray((ReadOnlyMemory<byte>)_buffer, out segment);
204 return segment.Array;
205 }
206 return null;
207 }
208 }
209
211
212 public int Offset => _offset;
213
214 public int Count => _count;
215
217 {
218 get
219 {
220 return _sendPacketsFlags;
221 }
222 set
223 {
225 }
226 }
227
229 {
230 get
231 {
232 return _bufferList;
233 }
234 set
235 {
237 try
238 {
239 if (value != null)
240 {
241 if (!_buffer.Equals(default(Memory<byte>)))
242 {
244 }
245 int count = value.Count;
246 if (_bufferListInternal == null)
247 {
249 }
250 else
251 {
253 }
254 for (int i = 0; i < count; i++)
255 {
259 }
260 }
261 else
262 {
264 }
267 }
268 finally
269 {
270 Complete();
271 }
272 }
273 }
274
276
278 {
279 get
280 {
282 }
283 set
284 {
286 }
287 }
288
290
292
294 {
295 get
296 {
297 return _remoteEndPoint;
298 }
299 set
300 {
302 }
303 }
304
306 {
307 get
308 {
310 }
311 set
312 {
314 try
315 {
317 }
318 finally
319 {
320 Complete();
321 }
322 }
323 }
324
326 {
327 get
328 {
330 }
331 set
332 {
334 }
335 }
336
338 {
339 get
340 {
341 return _socketError;
342 }
343 set
344 {
346 }
347 }
348
350
352 {
353 get
354 {
355 return _socketFlags;
356 }
357 set
358 {
360 }
361 }
362
363 public object? UserToken
364 {
365 get
366 {
367 return _userToken;
368 }
369 set
370 {
372 }
373 }
374
375 internal bool HasMultipleBuffers => _bufferList != null;
376
378 {
379 get
380 {
381 fixed (byte* ptr = &_pinnedSocketAddress.Buffer[0])
382 {
383 void* ptr2 = ptr;
384 return (IntPtr)ptr2;
385 }
386 }
387 }
388
390
392
397
403
404 private void OnCompletedInternal()
405 {
406 if (SocketsTelemetry.Log.IsEnabled())
407 {
409 }
410 OnCompleted(this);
411 }
412
413 protected virtual void OnCompleted(SocketAsyncEventArgs e)
414 {
415 this.Completed?.Invoke(e._currentSocket, e);
416 }
417
419 {
420 switch (LastOperation)
421 {
422 case SocketAsyncOperation.Accept:
423 SocketsTelemetry.Log.AfterAccept(SocketError);
424 break;
425 case SocketAsyncOperation.Connect:
426 SocketsTelemetry.Log.AfterConnect(SocketError);
427 break;
428 }
429 }
430
431 public void SetBuffer(int offset, int count)
432 {
434 try
435 {
436 if (!_buffer.Equals(default(Memory<byte>)))
437 {
438 if ((uint)offset > _buffer.Length)
439 {
440 throw new ArgumentOutOfRangeException("offset");
441 }
442 if ((uint)count > _buffer.Length - offset)
443 {
444 throw new ArgumentOutOfRangeException("count");
445 }
447 {
449 }
450 _offset = offset;
451 _count = count;
452 }
453 }
454 finally
455 {
456 Complete();
457 }
458 }
459
461 {
463 try
464 {
465 _buffer = source._buffer;
466 _offset = source._offset;
467 _count = source._count;
468 _bufferIsExplicitArray = source._bufferIsExplicitArray;
469 }
470 finally
471 {
472 Complete();
473 }
474 }
475
476 public void SetBuffer(byte[]? buffer, int offset, int count)
477 {
479 try
480 {
481 if (buffer == null)
482 {
483 _buffer = default(Memory<byte>);
484 _offset = 0;
485 _count = 0;
487 return;
488 }
489 if (_bufferList != null)
490 {
492 }
493 if ((uint)offset > buffer.Length)
494 {
495 throw new ArgumentOutOfRangeException("offset");
496 }
497 if ((uint)count > buffer.Length - offset)
498 {
499 throw new ArgumentOutOfRangeException("count");
500 }
501 _buffer = buffer;
502 _offset = offset;
503 _count = count;
505 }
506 finally
507 {
508 Complete();
509 }
510 }
511
513 {
515 try
516 {
517 if (buffer.Length != 0 && _bufferList != null)
518 {
520 }
521 _buffer = buffer;
522 _offset = 0;
523 _count = buffer.Length;
525 }
526 finally
527 {
528 Complete();
529 }
530 }
531
539
541 {
544 _socketFlags = flags;
545 if (exception == null)
546 {
547 _socketError = SocketError.Success;
548 }
550 {
551 _socketError = ex.SocketErrorCode;
552 }
553 else
554 {
555 _socketError = SocketError.SocketError;
556 }
557 }
558
559 private static void ExecutionCallback(object state)
560 {
562 socketAsyncEventArgs.OnCompletedInternal();
563 }
564
565 internal void Complete()
566 {
567 CompleteCore();
568 _context = null;
569 _operating = 0;
570 if (_disposeCalled)
571 {
572 Dispose();
573 }
574 }
575
576 public void Dispose()
577 {
578 _disposeCalled = true;
580 {
583 GC.SuppressFinalize(this);
584 }
585 }
586
588 {
590 {
592 }
593 }
594
595 private void StartConfiguring()
596 {
597 int num = Interlocked.CompareExchange(ref _operating, -1, 0);
598 if (num != 0)
599 {
601 }
602 }
603
604 private void ThrowForNonFreeStatus(int status)
605 {
607 }
608
624
626 {
627 _strongThisRef.Value = this;
628 }
629
630 internal void StartOperationAccept()
631 {
633 if (!_buffer.Equals(default(Memory<byte>)))
634 {
636 {
638 }
639 }
640 else if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount)
641 {
643 }
644 }
645
652
653 internal void CancelConnectAsync()
654 {
656 {
658 if (multipleConnectCancellation != null)
659 {
661 }
662 else
663 {
665 }
666 }
667 }
668
670 {
673 if (currentSocket != null)
674 {
675 currentSocket.UpdateStatusAfterSocketError(socketError);
677 {
678 currentSocket.Dispose();
679 _currentSocket = null;
680 }
681 }
683 if (completedOperation == SocketAsyncOperation.SendPackets)
684 {
686 }
687 Complete();
688 }
689
691 {
692 ExecutionContext context = _context;
694 if (context == null)
695 {
697 }
698 else
699 {
701 }
702 }
703
705 {
709 multiConnectSocketAsyncEventArgs.CopyBufferFrom(this);
711 return multiConnectSocketAsyncEventArgs.ReachedCoordinationPointFirst();
713 {
714 Socket tempSocketIPv4 = null;
715 Socket tempSocketIPv5 = null;
717 try
718 {
721 foreach (IPAddress iPAddress in array)
722 {
723 Socket socket = null;
724 if (_currentSocket != null)
725 {
726 if (!_currentSocket.CanTryAddressFamily(iPAddress.AddressFamily))
727 {
728 continue;
729 }
731 }
732 else
733 {
734 if (iPAddress.AddressFamily == AddressFamily.InterNetworkV6)
735 {
737 if (socket2 == null)
738 {
740 tempSocketIPv5 = (socket3 = (Socket.OSSupportsIPv6 ? new Socket(AddressFamily.InterNetworkV6, socketType, protocolType) : null));
742 }
743 socket = socket2;
744 if (socket != null && iPAddress.IsIPv4MappedToIPv6)
745 {
746 socket.DualMode = true;
747 }
748 }
749 else if (iPAddress.AddressFamily == AddressFamily.InterNetwork)
750 {
752 if (socket4 == null)
753 {
755 tempSocketIPv4 = (socket3 = (Socket.OSSupportsIPv4 ? new Socket(AddressFamily.InterNetwork, socketType, protocolType) : null));
757 }
758 socket = socket4;
759 }
760 if (socket == null)
761 {
762 continue;
763 }
764 }
765 socket.ReplaceHandleIfNecessaryAfterFailedConnect();
766 if (internalArgs.RemoteEndPoint is IPEndPoint iPEndPoint)
767 {
768 iPEndPoint.Address = iPAddress;
769 }
770 else
771 {
772 internalArgs.RemoteEndPoint = new IPEndPoint(iPAddress, port);
773 }
774 if (socket.ConnectAsync(internalArgs))
775 {
776 using (cancellationToken.UnsafeRegister(delegate(object s)
777 {
779 }, internalArgs))
780 {
782 }
783 }
784 if (internalArgs.SocketError == SocketError.Success)
785 {
786 return;
787 }
788 if (cancellationToken.IsCancellationRequested)
789 {
790 throw new SocketException(995);
791 }
792 lastError = internalArgs.SocketError;
793 internalArgs.Reset();
794 }
796 }
798 {
799 caughtException = (Exception)(object)new SocketException(995);
800 }
801 catch (Exception ex2)
802 {
804 }
805 finally
806 {
807 if (tempSocketIPv4 != null && !tempSocketIPv4.Connected)
808 {
809 tempSocketIPv4.Dispose();
810 }
811 if (tempSocketIPv5 != null && !tempSocketIPv5.Connected)
812 {
813 tempSocketIPv5.Dispose();
814 }
815 if (_currentSocket != null && ((!_userSocket && !_currentSocket.Connected) || caughtException is OperationCanceledException || caughtException is SocketException { SocketErrorCode: SocketError.OperationAborted }))
816 {
818 }
819 if (caughtException != null)
820 {
823 }
824 else
825 {
826 SetResults(SocketError.Success, internalArgs.BytesTransferred, internalArgs.SocketFlags);
827 _connectSocket = (_currentSocket = internalArgs.ConnectSocket);
828 }
829 if (SocketsTelemetry.Log.IsEnabled())
830 {
832 }
833 Complete();
834 internalArgs.Dispose();
835 if (!internalArgs.ReachedCoordinationPointFirst())
836 {
837 OnCompleted(this);
838 }
839 }
840 }
841 }
842
844 {
845 SetResults(SocketError.Success, bytesTransferred, flags);
846 if (System.Net.NetEventSource.Log.IsEnabled() && bytesTransferred > 0)
847 {
849 }
851 switch (_completedOperation)
852 {
853 case SocketAsyncOperation.Accept:
854 {
857 if (socketError == SocketError.Success)
858 {
860 if (System.Net.NetEventSource.Log.IsEnabled())
861 {
862 try
863 {
865 }
867 {
868 }
869 }
870 }
871 else
872 {
874 _acceptSocket = null;
876 }
877 break;
878 }
879 case SocketAsyncOperation.Connect:
881 if (socketError == SocketError.Success)
882 {
883 if (System.Net.NetEventSource.Log.IsEnabled())
884 {
885 try
886 {
888 }
890 {
891 }
892 }
895 }
896 else
897 {
900 }
901 break;
902 case SocketAsyncOperation.Disconnect:
904 _currentSocket._remoteEndPoint = null;
905 break;
906 case SocketAsyncOperation.ReceiveFrom:
907 {
908 _socketAddress.InternalSize = GetSocketAddressSize();
910 if (!socketAddress.Equals(_socketAddress))
911 {
912 try
913 {
915 }
916 catch
917 {
918 }
919 }
920 break;
921 }
922 case SocketAsyncOperation.ReceiveMessageFrom:
923 {
924 _socketAddress.InternalSize = GetSocketAddressSize();
926 if (!socketAddress.Equals(_socketAddress))
927 {
928 try
929 {
931 }
932 catch
933 {
934 }
935 }
937 break;
938 }
939 case SocketAsyncOperation.SendPackets:
941 break;
942 }
943 if (SocketsTelemetry.Log.IsEnabled())
944 {
946 }
947 Complete();
948 }
949
951 {
952 ExecutionContext context = _context;
954 if (context == null)
955 {
957 }
958 else
959 {
961 }
962 }
963
965 {
966 if (socketError == SocketError.Success)
967 {
969 }
970 else
971 {
973 }
974 if (SocketsTelemetry.Log.IsEnabled())
975 {
977 }
978 }
979
981 {
982 switch (operation)
983 {
984 case SocketAsyncOperation.Accept:
985 case SocketAsyncOperation.Receive:
986 case SocketAsyncOperation.ReceiveFrom:
987 case SocketAsyncOperation.ReceiveMessageFrom:
989 if (socketType == SocketType.Dgram)
990 {
991 SocketsTelemetry.Log.DatagramReceived();
992 }
993 break;
994 case SocketAsyncOperation.Connect:
995 case SocketAsyncOperation.Send:
996 case SocketAsyncOperation.SendPackets:
997 case SocketAsyncOperation.SendTo:
999 if (socketType == SocketType.Dgram)
1000 {
1001 SocketsTelemetry.Log.DatagramSent();
1002 }
1003 break;
1004 case SocketAsyncOperation.Disconnect:
1005 break;
1006 }
1007 }
1008
1009 [MemberNotNull("_preAllocatedOverlapped")]
1010 private void InitializeInternals()
1011 {
1013 if (System.Net.NetEventSource.Log.IsEnabled())
1014 {
1015 System.Net.NetEventSource.Info(this, $"new PreAllocatedOverlapped {_preAllocatedOverlapped}", "InitializeInternals");
1016 }
1017 }
1018
1019 private void FreeInternals()
1020 {
1023 }
1024
1030
1035
1037 {
1040 {
1042 SafeSocketHandle safeHandle = socketAsyncEventArgs._currentSocket.SafeHandle;
1043 if (!safeHandle.IsClosed)
1044 {
1045 try
1046 {
1047 bool flag = global::Interop.Kernel32.CancelIoEx(safeHandle, socketAsyncEventArgs._pendingOverlappedForCancellation);
1048 if (System.Net.NetEventSource.Log.IsEnabled())
1049 {
1050 System.Net.NetEventSource.Info(socketAsyncEventArgs, flag ? "Socket operation canceled." : $"CancelIoEx failed with error '{Marshal.GetLastWin32Error()}'.", "RegisterToCancelPendingIO");
1051 }
1052 }
1054 {
1055 }
1056 }
1057 }, this);
1058 }
1059
1061 {
1062 if (success)
1063 {
1065 {
1067 return SocketError.Success;
1068 }
1069 return SocketError.IOPending;
1070 }
1072 if (lastSocketError != SocketError.IOPending)
1073 {
1075 return lastSocketError;
1076 }
1077 return SocketError.IOPending;
1078 }
1079
1089
1106
1108 {
1109 bool flag = _count != 0;
1111 fixed (byte* ptr = &MemoryMarshal.GetReference(bufferToPin.Span))
1112 {
1114 try
1115 {
1117 int bytesReceived;
1118 bool success = socket.AcceptEx(handle, acceptHandle, (IntPtr)(flag ? (ptr + _offset) : ptr), flag ? (_count - _acceptAddressBufferCount) : 0, _acceptAddressBufferCount / 2, _acceptAddressBufferCount / 2, out bytesReceived, overlapped);
1120 }
1121 catch
1122 {
1125 throw;
1126 }
1127 }
1128 }
1129
1136
1157
1174
1183
1209
1226
1236
1262
1279
1281 {
1283 if (_wsaMessageBufferPinned == null)
1284 {
1285 _wsaMessageBufferPinned = GC.AllocateUninitializedArray<byte>(sizeof(global::Interop.Winsock.WSAMsg), pinned: true);
1286 }
1287 IPAddress iPAddress = ((_socketAddress.Family == AddressFamily.InterNetworkV6) ? _socketAddress.GetIPAddress() : null);
1288 bool flag = _currentSocket.AddressFamily == AddressFamily.InterNetwork || (iPAddress?.IsIPv4MappedToIPv6 ?? false);
1289 if (_currentSocket.AddressFamily == AddressFamily.InterNetworkV6 && (_controlBufferPinned == null || _controlBufferPinned.Length != sizeof(global::Interop.Winsock.ControlDataIPv6)))
1290 {
1291 _controlBufferPinned = GC.AllocateUninitializedArray<byte>(sizeof(global::Interop.Winsock.ControlDataIPv6), pinned: true);
1292 }
1293 else if (flag && (_controlBufferPinned == null || _controlBufferPinned.Length != sizeof(global::Interop.Winsock.ControlData)))
1294 {
1295 _controlBufferPinned = GC.AllocateUninitializedArray<byte>(sizeof(global::Interop.Winsock.ControlData), pinned: true);
1296 }
1299 if (_bufferList == null)
1300 {
1302 {
1303 _wsaRecvMsgWSABufferArrayPinned = GC.AllocateUninitializedArray<WSABuffer>(1, pinned: true);
1304 }
1305 fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.Span))
1306 {
1312 return Core();
1313 }
1314 }
1317 return Core();
1318 unsafe SocketError Core()
1319 {
1320 global::Interop.Winsock.WSAMsg* ptr2 = (global::Interop.Winsock.WSAMsg*)(void*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBufferPinned, 0);
1321 ptr2->socketAddress = PtrSocketAddressBuffer;
1322 ptr2->addressLength = (uint)_socketAddress.Size;
1324 {
1325 void* ptr4 = ptr3;
1326 ptr2->buffers = (IntPtr)ptr4;
1327 }
1329 if (_controlBufferPinned != null)
1330 {
1331 fixed (byte* ptr5 = &_controlBufferPinned[0])
1332 {
1333 void* ptr6 = ptr5;
1334 ptr2->controlBuffer.Pointer = (IntPtr)ptr6;
1335 }
1336 ptr2->controlBuffer.Length = _controlBufferPinned.Length;
1337 }
1338 ptr2->flags = _socketFlags;
1340 try
1341 {
1342 int bytesTransferred;
1345 }
1346 catch
1347 {
1350 throw;
1351 }
1352 }
1353 }
1354
1363
1365 {
1366 fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.Span))
1367 {
1369 try
1370 {
1372 WSABuffer wSABuffer = default(WSABuffer);
1373 wSABuffer.Length = _count;
1374 wSABuffer.Pointer = (IntPtr)(ptr + _offset);
1376 int bytesTransferred;
1377 SocketError socketError = global::Interop.Winsock.WSASend(handle, &wSABuffer2, 1, out bytesTransferred, _socketFlags, overlapped, IntPtr.Zero);
1379 }
1380 catch
1381 {
1384 throw;
1385 }
1386 }
1387 }
1388
1404
1406 {
1408 int num = 0;
1409 int num2 = 0;
1410 int num3 = 0;
1413 {
1414 if (sendPacketsElement != null)
1415 {
1416 if (sendPacketsElement.FilePath != null)
1417 {
1418 num++;
1419 }
1420 else if (sendPacketsElement.FileStream != null)
1421 {
1422 num2++;
1423 }
1424 else if (sendPacketsElement.MemoryBuffer.HasValue && sendPacketsElement.Count > 0)
1425 {
1426 num3++;
1427 }
1428 }
1429 }
1430 if (num + num2 + num3 == 0)
1431 {
1433 return SocketError.Success;
1434 }
1435 if (num > 0)
1436 {
1437 int num4 = 0;
1439 try
1440 {
1443 {
1444 if (sendPacketsElement2 != null && sendPacketsElement2.FilePath != null)
1445 {
1447 num4++;
1448 }
1449 }
1450 }
1451 catch
1452 {
1453 for (int num5 = num4 - 1; num5 >= 0; num5--)
1454 {
1456 }
1458 throw;
1459 }
1460 }
1461 global::Interop.Winsock.TransmitPacketsElement[] array4 = SetupPinHandlesSendPackets(array, num, num2, num3);
1463 try
1464 {
1468 }
1469 catch
1470 {
1473 throw;
1474 }
1475 }
1476
1486
1488 {
1489 fixed (byte* ptr = &MemoryMarshal.GetReference(_buffer.Span))
1490 {
1492 try
1493 {
1495 WSABuffer wSABuffer = default(WSABuffer);
1496 wSABuffer.Length = _count;
1497 wSABuffer.Pointer = (IntPtr)(ptr + _offset);
1499 int bytesTransferred;
1502 }
1503 catch
1504 {
1507 throw;
1508 }
1509 }
1510 }
1511
1527
1529 {
1530 if (_bufferListInternal == null || _bufferListInternal.Count == 0)
1531 {
1532 if (_pinState == PinState.MultipleBuffer)
1533 {
1535 }
1536 return;
1537 }
1539 try
1540 {
1543 {
1545 }
1546 for (int i = 0; i < count; i++)
1547 {
1548 _multipleBufferMemoryHandles[i] = _bufferListInternal[i].Array.AsMemory().Pin();
1549 }
1551 {
1552 _wsaBufferArrayPinned = GC.AllocateUninitializedArray<WSABuffer>(count, pinned: true);
1553 }
1554 for (int j = 0; j < count; j++)
1555 {
1559 }
1560 _pinState = PinState.MultipleBuffer;
1561 }
1562 catch (Exception)
1563 {
1565 throw;
1566 }
1567 }
1568
1570 {
1572 {
1574 {
1576 }
1578 _socketAddress.CopyAddressSizeIntoBuffer();
1580 }
1581 }
1582
1583 private void FreeOverlapped()
1584 {
1585 if (_preAllocatedOverlapped != null)
1586 {
1589 }
1590 }
1591
1592 private void FreePinHandles()
1593 {
1594 _pinState = PinState.None;
1595 if (_asyncProcessingState != 0)
1596 {
1599 }
1600 if (_multipleBufferMemoryHandles != null)
1601 {
1602 for (int i = 0; i < _multipleBufferMemoryHandles.Length; i++)
1603 {
1606 }
1607 }
1609 {
1611 _pinnedSocketAddress = null;
1612 }
1613 }
1614
1616 {
1617 if (_pinState != 0)
1618 {
1620 }
1621 global::Interop.Winsock.TransmitPacketsElement[] array = GC.AllocateUninitializedArray<global::Interop.Winsock.TransmitPacketsElement>(sendPacketsElementsFileCount + sendPacketsElementsFileStreamCount + sendPacketsElementsBufferCount, pinned: true);
1623 {
1625 }
1626 int num = 0;
1628 {
1629 if (sendPacketsElement != null && sendPacketsElement.MemoryBuffer.HasValue && sendPacketsElement.Count > 0)
1630 {
1631 _multipleBufferMemoryHandles[num] = sendPacketsElement.MemoryBuffer.Value.Pin();
1632 num++;
1633 }
1634 }
1635 int num2 = 0;
1636 int num3 = 0;
1637 int num4 = 0;
1639 {
1640 if (sendPacketsElement2 != null)
1641 {
1642 if (sendPacketsElement2.MemoryBuffer.HasValue && sendPacketsElement2.Count > 0)
1643 {
1645 array[num3].length = (uint)sendPacketsElement2.Count;
1646 array[num3].flags = global::Interop.Winsock.TransmitPacketsElementFlags.Memory | (sendPacketsElement2.EndOfPacket ? global::Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket : global::Interop.Winsock.TransmitPacketsElementFlags.None);
1647 num2++;
1648 num3++;
1649 }
1650 else if (sendPacketsElement2.FilePath != null)
1651 {
1653 array[num3].fileOffset = sendPacketsElement2.OffsetLong;
1654 array[num3].length = (uint)sendPacketsElement2.Count;
1655 array[num3].flags = global::Interop.Winsock.TransmitPacketsElementFlags.File | (sendPacketsElement2.EndOfPacket ? global::Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket : global::Interop.Winsock.TransmitPacketsElementFlags.None);
1656 num4++;
1657 num3++;
1658 }
1659 else if (sendPacketsElement2.FileStream != null)
1660 {
1661 array[num3].fileHandle = sendPacketsElement2.FileStream.SafeFileHandle.DangerousGetHandle();
1662 array[num3].fileOffset = sendPacketsElement2.OffsetLong;
1663 array[num3].length = (uint)sendPacketsElement2.Count;
1664 array[num3].flags = global::Interop.Winsock.TransmitPacketsElementFlags.File | (sendPacketsElement2.EndOfPacket ? global::Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket : global::Interop.Winsock.TransmitPacketsElementFlags.None);
1665 num3++;
1666 }
1667 }
1668 }
1669 _pinState = PinState.SendPackets;
1670 return array;
1671 }
1672
1673 internal void LogBuffer(int size)
1674 {
1675 if (_bufferList != null)
1676 {
1677 for (int i = 0; i < _bufferListInternal.Count; i++)
1678 {
1680 System.Net.NetEventSource.DumpBuffer(this, wSABuffer.Pointer, Math.Min(wSABuffer.Length, size), "LogBuffer");
1681 if ((size -= wSABuffer.Length) <= 0)
1682 {
1683 break;
1684 }
1685 }
1686 }
1687 else if (_buffer.Length != 0)
1688 {
1689 System.Net.NetEventSource.DumpBuffer(this, _buffer, _offset, size, "LogBuffer");
1690 }
1691 }
1692
1694 {
1695 bool success = false;
1698 try
1699 {
1700 safeHandle.DangerousAddRef(ref success);
1701 IntPtr pointer = safeHandle.DangerousGetHandle();
1702 bool flag = _count != 0;
1704 fixed (byte* ptr = &MemoryMarshal.GetReference(memory.Span))
1705 {
1708 }
1709 socketError = global::Interop.Winsock.setsockopt(_acceptSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateAcceptContext, ref pointer, IntPtr.Size);
1710 if (socketError == SocketError.SocketError)
1711 {
1713 }
1714 }
1716 {
1717 socketError = SocketError.OperationAborted;
1718 }
1719 finally
1720 {
1721 if (success)
1722 {
1723 safeHandle.DangerousRelease();
1724 }
1725 }
1726 return socketError;
1727 }
1728
1730 {
1731 try
1732 {
1733 if (_currentSocket.SocketType != SocketType.Stream)
1734 {
1735 return SocketError.Success;
1736 }
1737 SocketError socketError = global::Interop.Winsock.setsockopt(_currentSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateConnectContext, null, 0);
1738 return (socketError == SocketError.SocketError) ? SocketPal.GetLastSocketError() : socketError;
1739 }
1741 {
1742 return SocketError.OperationAborted;
1743 }
1744 }
1745
1746 private unsafe int GetSocketAddressSize()
1747 {
1748 return *(int*)(void*)PtrSocketAddressBufferSize;
1749 }
1750
1751 private void CompleteCore()
1752 {
1753 _strongThisRef.Value = null;
1754 if (_asyncProcessingState != 0)
1755 {
1757 }
1758 unsafe void CompleteCoreSpin()
1759 {
1760 SpinWait spinWait = default(SpinWait);
1761 while (_asyncProcessingState == AsyncProcessingState.InProcess)
1762 {
1763 spinWait.SpinOnce();
1764 }
1770 }
1771 }
1772
1774 {
1775 global::Interop.Winsock.WSAMsg* ptr = (global::Interop.Winsock.WSAMsg*)(void*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBufferPinned, 0);
1776 if (_controlBufferPinned.Length == sizeof(global::Interop.Winsock.ControlData))
1777 {
1778 _receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((global::Interop.Winsock.ControlData*)(void*)ptr->controlBuffer.Pointer);
1779 }
1780 else if (_controlBufferPinned.Length == sizeof(global::Interop.Winsock.ControlDataIPv6))
1781 {
1782 _receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((global::Interop.Winsock.ControlDataIPv6*)(void*)ptr->controlBuffer.Pointer);
1783 }
1784 else
1785 {
1787 }
1788 }
1789
1791 {
1792 if (_sendPacketsFileHandles != null)
1793 {
1794 for (int i = 0; i < _sendPacketsFileHandles.Length; i++)
1795 {
1797 }
1799 }
1800 }
1801
1803 {
1806 if (socketError != SocketError.OperationAborted)
1807 {
1809 {
1810 socketError = SocketError.OperationAborted;
1811 }
1812 else
1813 {
1814 try
1815 {
1816 global::Interop.Winsock.WSAGetOverlappedResult(_currentSocket.SafeHandle, nativeOverlapped, out numBytes, wait: false, out socketFlags);
1818 }
1819 catch
1820 {
1821 socketError = SocketError.OperationAborted;
1822 }
1823 }
1824 }
1827 }
1828}
void Add(TKey key, TValue value)
static bool HasShutdownStarted
static void SuppressFinalize(object obj)
Definition GC.cs:202
Definition GC.cs:8
static SafeFileHandle OpenHandle(string path, FileMode mode=FileMode.Open, FileAccess access=FileAccess.Read, FileShare share=FileShare.Read, FileOptions options=FileOptions.None, long preallocationSize=0L)
Definition File.cs:1009
static byte Min(byte val1, byte val2)
Definition Math.cs:912
static Task< IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress)
Definition Dns.cs:205
virtual EndPoint Create(SocketAddress socketAddress)
Definition EndPoint.cs:20
override bool Equals(object comparand)
static readonly System.Net.NetEventSource Log
static void Info(object thisOrContextObject, FormattableString formattableString=null, [CallerMemberName] string memberName=null)
static void Connected(Socket socket, object localEp, object remoteEp)
static void Accepted(Socket socket, object remoteEp, object localEp)
static void DumpBuffer(object thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string memberName=null)
static void ValidateSegment(ArraySegment< byte > segment)
static System.Net.Internals.SocketAddress Serialize(EndPoint endpoint)
ThreadPoolBoundHandle? IOCPBoundHandle
void OnCompleted(Action< object > continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
unsafe SocketError DoOperationConnectEx(Socket socket, SafeSocketHandle handle)
void SetBuffer(byte[]? buffer, int offset, int count)
unsafe SocketError DoOperationReceiveFromMultiBuffer(SafeSocketHandle handle)
unsafe SocketError ProcessIOCPResult(bool success, int bytesTransferred, NativeOverlapped *overlapped)
unsafe SocketError DoOperationReceiveFromSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
bool DnsConnectAsync(DnsEndPoint endPoint, SocketType socketType, ProtocolType protocolType)
void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
unsafe SocketError DoOperationSendToMultiBuffer(SafeSocketHandle handle)
unsafe SocketError DoOperationReceiveSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
unsafe NativeOverlapped * AllocateNativeOverlapped()
void FinishOperationAsyncSuccess(int bytesTransferred, SocketFlags flags)
unsafe void RegisterToCancelPendingIO(NativeOverlapped *overlapped, CancellationToken cancellationToken)
unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken)
static void LogBytesTransferEvents(SocketType? socketType, SocketAsyncOperation operation, int bytesTransferred)
void FinishOperationSyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
volatile AsyncProcessingState _asyncProcessingState
void SetResults(Exception exception, int bytesTransferred, SocketFlags flags)
unsafe SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken)
unsafe SocketError FinishOperationAccept(System.Net.Internals.SocketAddress remoteSocketAddress)
unsafe void FreeNativeOverlapped(NativeOverlapped *overlapped)
System.Net.Internals.SocketAddress _pinnedSocketAddress
unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle, CancellationToken cancellationToken)
void StartOperationCommon(Socket socket, SocketAsyncOperation operation)
void FinishOperationSync(SocketError socketError, int bytesTransferred, SocketFlags flags)
unsafe SocketError DoOperationReceiveMultiBuffer(SafeSocketHandle handle)
void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags)
static unsafe readonly IOCompletionCallback s_completionPortCallback
readonly StrongBox< SocketAsyncEventArgs > _strongThisRef
List< ArraySegment< byte > > _bufferListInternal
unsafe SocketError DoOperationSendMultiBuffer(SafeSocketHandle handle)
unsafe SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken)
SocketError DoOperationSend(SafeSocketHandle handle, CancellationToken cancellationToken)
unsafe SocketError DoOperationSendToSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
unsafe SocketError ProcessIOCPResultWithDeferredAsyncHandling(bool success, int bytesTransferred, NativeOverlapped *overlapped, Memory< byte > bufferToPin, CancellationToken cancellationToken=default(CancellationToken))
virtual void OnCompleted(SocketAsyncEventArgs e)
EventHandler< SocketAsyncEventArgs >? Completed
void FinishOperationSyncSuccess(int bytesTransferred, SocketFlags flags)
SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle)
IList< ArraySegment< byte > >? BufferList
unsafe void HandleCompletionPortCallbackError(uint errorCode, uint numBytes, NativeOverlapped *nativeOverlapped)
System.Net.Internals.SocketAddress _socketAddress
unsafe SocketError DoOperationSendSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
CancellationTokenRegistration _registrationToCancelPendingIO
SocketAsyncEventArgs(bool unsafeSuppressExecutionContextFlow)
IList< ArraySegment< byte > > _bufferList
SocketError DoOperationReceive(SafeSocketHandle handle, CancellationToken cancellationToken)
void StartOperationConnect(bool saeaMultiConnectCancelable, bool userSocket)
SocketError DoOperationReceiveFrom(SafeSocketHandle handle, CancellationToken cancellationToken)
unsafe global::Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPackets(SendPacketsElement[] sendPacketsElementsCopy, int sendPacketsElementsFileCount, int sendPacketsElementsFileStreamCount, int sendPacketsElementsBufferCount)
unsafe SocketError GetIOCPResult(bool success, NativeOverlapped *overlapped)
void CopyBufferFrom(SocketAsyncEventArgs source)
unsafe NativeOverlapped * _pendingOverlappedForCancellation
static readonly ContextCallback s_executionCallback
SocketError DoOperationSendTo(SafeSocketHandle handle, CancellationToken cancellationToken)
static SocketError Connect(SafeSocketHandle handle, byte[] peerAddress, int peerAddressLen)
Definition SocketPal.cs:174
static SocketError GetLastSocketError()
Definition SocketPal.cs:22
static unsafe IPPacketInformation GetIPPacketInformation(global::Interop.Winsock.ControlData *controlBuffer)
Definition SocketPal.cs:370
AddressFamily AddressFamily
Definition Socket.cs:748
SafeSocketHandle SafeHandle
Definition Socket.cs:685
virtual void Dispose(bool disposing)
Definition Socket.cs:3294
unsafe? EndPoint LocalEndPoint
Definition Socket.cs:615
void GetAcceptExSockaddrs(IntPtr buffer, int receiveDataLength, int localAddressLength, int remoteAddressLength, out IntPtr localSocketAddress, out int localSocketAddressLength, out IntPtr remoteSocketAddress, out int remoteSocketAddressLength)
Definition Socket.cs:4458
Socket UpdateAcceptSocket(Socket socket, EndPoint remoteEP)
Definition Socket.cs:3636
void Connect(EndPoint remoteEP)
Definition Socket.cs:1206
static int GetAddressSize(EndPoint endPoint)
Definition Socket.cs:3215
void UpdateStatusAfterSocketError(SocketException socketException)
Definition Socket.cs:3726
static void CancelConnectAsync(SocketAsyncEventArgs e)
Definition Socket.cs:2966
bool CanTryAddressFamily(AddressFamily family)
Definition Socket.cs:1159
ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle()
Definition Socket.cs:4599
static readonly SocketsTelemetry Log
static void Copy(int[] source, int startIndex, IntPtr destination, int length)
Definition Marshal.cs:800
static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
Definition Marshal.cs:775
static string net_buffercounttoosmall
Definition SR.cs:86
static string Format(string resourceFormat, object p1)
Definition SR.cs:118
static string InvalidOperation_BufferNotExplicitArray
Definition SR.cs:104
static string net_ambiguousbuffers
Definition SR.cs:90
static string net_socketopinprogress
Definition SR.cs:84
Definition SR.cs:7
static ? ExecutionContext Capture()
static void Run(ExecutionContext executionContext, ContextCallback callback, object? state)
static int CompareExchange(ref int location1, int value, int comparand)
static int Exchange(ref int location1, int value)
static PreAllocatedOverlapped UnsafeCreate(IOCompletionCallback callback, object? state, object? pinData)
unsafe void FreeNativeOverlapped(NativeOverlapped *overlapped)
static unsafe? object GetNativeOverlappedState(NativeOverlapped *overlapped)
delegate void ContextCallback(object? state)
unsafe delegate void IOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped *pOVERLAP)
static int Size
Definition IntPtr.cs:21
static readonly IntPtr Zero
Definition IntPtr.cs:18
unsafe MemoryHandle Pin()
Definition Memory.cs:223
override bool Equals([NotNullWhen(true)] object? obj)
Definition Memory.cs:255
unsafe Span< T > Span
Definition Memory.cs:28
static GCHandle Alloc(object? value)
Definition GCHandle.cs:81
void OnCompleted(Action< object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
Definition ValueTask.cs:312