-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathSocketPal.Windows.cs
1091 lines (943 loc) · 46.7 KB
/
SocketPal.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.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
#if BIGENDIAN
using System.Buffers.Binary;
#endif
namespace System.Net.Sockets
{
internal static class SocketPal
{
public const bool SupportsMultipleConnectAttempts = true;
public static readonly int MaximumAddressSize = UnixDomainSocketEndPoint.MaxAddressSize;
private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime)
{
const int microcnv = 1000000;
socketTime.Seconds = (int)(microseconds / microcnv);
socketTime.Microseconds = (int)(microseconds % microcnv);
}
public static SocketError GetLastSocketError()
{
int win32Error = Marshal.GetLastWin32Error();
Debug.Assert(win32Error != 0, "Expected non-0 error");
return (SocketError)win32Error;
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeSocketHandle socket)
{
Interop.Winsock.EnsureInitialized();
IntPtr handle = Interop.Winsock.WSASocketW(addressFamily, socketType, protocolType, IntPtr.Zero, 0, Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED |
Interop.Winsock.SocketConstructorFlags.WSA_FLAG_NO_HANDLE_INHERIT);
socket = new SafeSocketHandle(handle, ownsHandle: true);
if (socket.IsInvalid)
{
SocketError error = GetLastSocketError();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"WSASocketW failed with error {error}");
socket.Dispose();
return error;
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, socket);
return SocketError.Success;
}
public static unsafe SocketError CreateSocket(
SocketInformation socketInformation,
out SafeSocketHandle socket,
ref AddressFamily addressFamily,
ref SocketType socketType,
ref ProtocolType protocolType)
{
if (socketInformation.ProtocolInformation == null || socketInformation.ProtocolInformation.Length < sizeof(Interop.Winsock.WSAPROTOCOL_INFOW))
{
throw new ArgumentException(SR.net_sockets_invalid_socketinformation, nameof(socketInformation));
}
Interop.Winsock.EnsureInitialized();
fixed (byte* protocolInfoBytes = socketInformation.ProtocolInformation)
{
// Sockets are non-inheritable in .NET Core.
// Handle properties like HANDLE_FLAG_INHERIT are not cloned with socket duplication, therefore
// we need to disable handle inheritance when constructing the new socket handle from Protocol Info.
// Additionally, it looks like WSA_FLAG_NO_HANDLE_INHERIT has no effect when being used with the Protocol Info
// variant of WSASocketW, so it is being passed to that call only for consistency.
// Inheritance is being disabled with SetHandleInformation(...) after the WSASocketW call.
IntPtr handle = Interop.Winsock.WSASocketW(
(AddressFamily)(-1),
(SocketType)(-1),
(ProtocolType)(-1),
(IntPtr)protocolInfoBytes,
0,
Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED |
Interop.Winsock.SocketConstructorFlags.WSA_FLAG_NO_HANDLE_INHERIT);
socket = new SafeSocketHandle(handle, ownsHandle: true);
if (socket.IsInvalid)
{
SocketError error = GetLastSocketError();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"WSASocketW failed with error {error}");
socket.Dispose();
return error;
}
if (!Interop.Kernel32.SetHandleInformation(socket, Interop.Kernel32.HandleFlags.HANDLE_FLAG_INHERIT, 0))
{
// Returning SocketError for consistency, since the call site can deal with conversion, and
// the most common SetHandleInformation error (AccessDenied) is included in SocketError anyways:
SocketError error = GetLastSocketError();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, $"SetHandleInformation failed with error {error}");
socket.Dispose();
return error;
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, socket);
Interop.Winsock.WSAPROTOCOL_INFOW* protocolInfo = (Interop.Winsock.WSAPROTOCOL_INFOW*)protocolInfoBytes;
addressFamily = protocolInfo->iAddressFamily;
socketType = protocolInfo->iSocketType;
protocolType = protocolInfo->iProtocol;
return SocketError.Success;
}
}
public static SocketError SetBlocking(SafeSocketHandle handle, bool shouldBlock, out bool willBlock)
{
int intBlocking = shouldBlock ? 0 : -1;
SocketError errorCode;
errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref intBlocking);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
willBlock = intBlocking == 0;
return errorCode;
}
public static unsafe SocketError GetSockName(SafeSocketHandle handle, byte* buffer, int* nameLen)
{
SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetAvailable(SafeSocketHandle handle, out int available)
{
int value = 0;
SocketError errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONREAD,
ref value);
available = value;
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError GetPeerName(SafeSocketHandle handle, Span<byte> buffer, ref int nameLen)
{
fixed (byte* rawBuffer = buffer)
{
SocketError errorCode = Interop.Winsock.getpeername(handle, rawBuffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
}
public static SocketError Bind(SafeSocketHandle handle, ProtocolType socketProtocolType, byte[] buffer, int nameLen)
{
SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Listen(SafeSocketHandle handle, int backlog)
{
SocketError errorCode = Interop.Winsock.listen(handle, backlog);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Accept(SafeSocketHandle listenSocket, byte[] socketAddress, ref int socketAddressSize, out SafeSocketHandle socket)
{
IntPtr handle = Interop.Winsock.accept(listenSocket, socketAddress, ref socketAddressSize);
socket = new SafeSocketHandle(handle, ownsHandle: true);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, socket);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Connect(SafeSocketHandle handle, byte[] peerAddress, int peerAddressLen)
{
SocketError errorCode = Interop.Winsock.WSAConnect(
handle,
peerAddress,
peerAddressLen,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Send(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[]? leasedWSA = null;
GCHandle[]? leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array!, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSASend(
handle,
WSABuffers,
count,
out bytesTransferred,
socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA!);
ArrayPool<GCHandle>.Shared.Return(leasedGC!);
}
}
}
public static unsafe SocketError Send(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Send(handle, new ReadOnlySpan<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Send(SafeSocketHandle handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesSent;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesSent = Interop.Winsock.send(handle, bufferPtr, buffer.Length, socketFlags);
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle? fileHandle, ReadOnlySpan<byte> preBuffer, ReadOnlySpan<byte> postBuffer, TransmitFileOptions flags)
{
fixed (byte* prePinnedBuffer = preBuffer)
fixed (byte* postPinnedBuffer = postBuffer)
{
bool success = TransmitFileHelper(handle, fileHandle, null, (IntPtr)prePinnedBuffer, preBuffer.Length, (IntPtr)postPinnedBuffer, postBuffer.Length, flags);
return success ? SocketError.Success : GetLastSocketError();
}
}
public static SocketError SendTo(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred) =>
SendTo(handle, buffer.AsSpan(offset, size), socketFlags, peerAddress, peerAddressSize, out bytesTransferred);
public static unsafe SocketError SendTo(SafeSocketHandle handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred)
{
int bytesSent;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesSent = Interop.Winsock.sendto(handle, bufferPtr, buffer.Length, socketFlags, peerAddress, peerAddressSize);
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static SocketError Receive(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[]? leasedWSA = null;
GCHandle[]? leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array!, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSARecv(
handle,
WSABuffers,
count,
out bytesTransferred,
ref socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA!);
ArrayPool<GCHandle>.Shared.Return(leasedGC!);
}
}
}
public static unsafe SocketError Receive(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Receive(handle, new Span<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Receive(SafeSocketHandle handle, Span<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesReceived;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesReceived = Interop.Winsock.recv(handle, bufferPtr, buffer.Length, socketFlags);
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlData* controlBuffer)
{
IPAddress address = controlBuffer->length == UIntPtr.Zero ? IPAddress.None : new IPAddress((long)controlBuffer->address);
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlDataIPv6* controlBuffer)
{
if (controlBuffer->length == (UIntPtr)sizeof(Interop.Winsock.ControlData))
{
// IPv4 client connectiong to dual mode socket.
return GetIPPacketInformation((Interop.Winsock.ControlData*)controlBuffer);
}
IPAddress address = controlBuffer->length != UIntPtr.Zero ?
new IPAddress(new ReadOnlySpan<byte>(controlBuffer->address, Interop.Winsock.IPv6AddressLength)) :
IPAddress.IPv6None;
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
return ReceiveMessageFrom(socket, handle, new Span<byte>(buffer, offset, size), ref socketFlags, socketAddress, out receiveAddress, out ipPacketInformation, out bytesTransferred);
}
public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeSocketHandle handle, Span<byte> buffer, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
bool ipv4, ipv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out ipv4, out ipv6);
bytesTransferred = 0;
receiveAddress = socketAddress;
ipPacketInformation = default(IPPacketInformation);
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
fixed (byte* ptrSocketAddress = socketAddress.Buffer)
{
Interop.Winsock.WSAMsg wsaMsg;
wsaMsg.socketAddress = (IntPtr)ptrSocketAddress;
wsaMsg.addressLength = (uint)socketAddress.Size;
wsaMsg.flags = socketFlags;
WSABuffer wsaBuffer;
wsaBuffer.Length = buffer.Length;
wsaBuffer.Pointer = (IntPtr)bufferPtr;
wsaMsg.buffers = (IntPtr)(&wsaBuffer);
wsaMsg.count = 1;
if (ipv4)
{
Interop.Winsock.ControlData controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlData);
if (socket.WSARecvMsgBlocking(
handle,
(IntPtr)(&wsaMsg),
out bytesTransferred) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else if (ipv6)
{
Interop.Winsock.ControlDataIPv6 controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlDataIPv6);
if (socket.WSARecvMsgBlocking(
handle,
(IntPtr)(&wsaMsg),
out bytesTransferred) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else
{
wsaMsg.controlBuffer.Pointer = IntPtr.Zero;
wsaMsg.controlBuffer.Length = 0;
if (socket.WSARecvMsgBlocking(
handle,
(IntPtr)(&wsaMsg),
out bytesTransferred) == SocketError.SocketError)
{
return GetLastSocketError();
}
}
socketFlags = wsaMsg.flags;
}
return SocketError.Success;
}
public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred) =>
ReceiveFrom(handle, buffer.AsSpan(offset, size), SocketFlags.None, socketAddress, ref addressLength, out bytesTransferred);
public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, Span<byte> buffer, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred)
{
int bytesReceived;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesReceived = Interop.Winsock.recvfrom(handle, bufferPtr, buffer.Length, socketFlags, socketAddress, ref addressLength);
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue, out int optionLength)
{
if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
throw new InvalidOperationException(SR.net_sockets_useblocking);
}
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
handle,
ioControlCode,
optionInValue,
optionInValue != null ? optionInValue.Length : 0,
optionOutValue,
optionOutValue != null ? optionOutValue.Length : 0,
out optionLength,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue);
}
else
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
}
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
return IOControlKeepAlive.Set(handle, optionName, optionValue);
}
fixed (byte* optionValuePtr = optionValue)
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValuePtr,
optionValue != null ? optionValue.Length : 0);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
}
public static unsafe SocketError SetRawSockOpt(SafeSocketHandle handle, int optionLevel, int optionName, ReadOnlySpan<byte> optionValue)
{
fixed (byte* optionValuePtr = optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
(SocketOptionLevel)optionLevel,
(SocketOptionName)optionName,
optionValuePtr,
optionValue.Length);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
public static SocketError SetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = default;
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address);
#pragma warning restore CS0618
if (optionValue.LocalAddress != null)
{
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.Address);
#pragma warning restore CS0618
}
else
{ //this structure works w/ interfaces as well
int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex);
ipmr.InterfaceAddress = unchecked((int)ifIndex);
}
#if BIGENDIAN
ipmr.MulticastAddress = BinaryPrimitives.ReverseEndianness(ipmr.MulticastAddress);
if (optionValue.LocalAddress != null)
{
ipmr.InterfaceAddress = BinaryPrimitives.ReverseEndianness(ipmr.InterfaceAddress);
}
#endif
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IP,
optionName,
ref ipmr,
Interop.Winsock.IPMulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = default;
ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex);
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IPv6,
optionName,
ref ipmr,
Interop.Winsock.IPv6MulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetLingerOption(SafeSocketHandle handle, LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = default;
lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
lngopt.Time = (ushort)optionValue.LingerTime;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
ref lngopt,
4);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetIPProtectionLevel(Socket socket, SocketOptionLevel optionLevel, int protectionLevel)
{
socket.SetSocketOption(optionLevel, SocketOptionName.IPProtectionLevel, protectionLevel);
}
public static unsafe SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
optionValue = IOControlKeepAlive.Get(handle, optionName);
return SocketError.Success;
}
int optionLength = sizeof(int);
int tmpOptionValue = 0;
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
(byte*)&tmpOptionValue,
ref optionLength);
optionValue = tmpOptionValue;
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
return IOControlKeepAlive.Get(handle, optionName, optionValue, ref optionLength);
}
fixed (byte* optionValuePtr = optionValue)
{
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
optionValuePtr,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
}
public static unsafe SocketError GetRawSockOpt(SafeSocketHandle handle, int optionLevel, int optionName, Span<byte> optionValue, ref int optionLength)
{
Debug.Assert((uint)optionLength <= optionValue.Length);
SocketError errorCode;
fixed (byte* optionValuePtr = optionValue)
{
errorCode = Interop.Winsock.getsockopt(
handle,
(SocketOptionLevel)optionLevel,
(SocketOptionName)optionName,
optionValuePtr,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
}
public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption? optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = default;
int optlen = Interop.Winsock.IPMulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(MulticastOption);
return GetLastSocketError();
}
#if BIGENDIAN
ipmr.MulticastAddress = BinaryPrimitives.ReverseEndianness(ipmr.MulticastAddress);
ipmr.InterfaceAddress = BinaryPrimitives.ReverseEndianness(ipmr.InterfaceAddress);
#endif // BIGENDIAN
IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress);
IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress);
optionValue = new MulticastOption(multicastAddr, multicastIntr);
return SocketError.Success;
}
public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption? optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = default;
int optlen = Interop.Winsock.IPv6MulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(IPv6MulticastOption);
return GetLastSocketError();
}
optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex);
return SocketError.Success;
}
public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption? optionValue)
{
Interop.Winsock.Linger lngopt = default;
int optlen = 4;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
out lngopt,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(LingerOption);
return GetLastSocketError();
}
optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time);
return SocketError.Success;
}
public static unsafe SocketError Poll(SafeSocketHandle handle, int microseconds, SelectMode mode, out bool status)
{
bool refAdded = false;
try
{
handle.DangerousAddRef(ref refAdded);
IntPtr rawHandle = handle.DangerousGetHandle();
IntPtr* fileDescriptorSet = stackalloc IntPtr[2] { (IntPtr)1, rawHandle };
Interop.Winsock.TimeValue IOwait = default;
// A negative timeout value implies an indefinite wait.
int socketCount;
if (microseconds != -1)
{
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
IntPtr.Zero);
}
if ((SocketError)socketCount == SocketError.SocketError)
{
status = false;
return GetLastSocketError();
}
status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle;
return SocketError.Success;
}
finally
{
if (refAdded)
{
handle.DangerousRelease();
}
}
}
public static unsafe SocketError Select(IList? checkRead, IList? checkWrite, IList? checkError, int microseconds)
{
const int StackThreshold = 64; // arbitrary limit to avoid too much space on stack
static bool ShouldStackAlloc(IList? list, ref IntPtr[]? lease, out Span<IntPtr> span)
{
int count;
if (list == null || (count = list.Count) == 0)
{
span = default;
return false;
}
if (count >= StackThreshold) // note on >= : the first element is reserved for internal length
{
span = lease = ArrayPool<IntPtr>.Shared.Rent(count + 1);
return false;
}
span = default;
return true;
}
IntPtr[]? leaseRead = null, leaseWrite = null, leaseError = null;
int refsAdded = 0;
try
{
// In case we can't increase the reference count for each Socket,
// we'll unref refAdded Sockets in the finally block ordered: [checkRead, checkWrite, checkError].
Span<IntPtr> readfileDescriptorSet = ShouldStackAlloc(checkRead, ref leaseRead, out var tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkRead, readfileDescriptorSet, ref refsAdded);
Span<IntPtr> writefileDescriptorSet = ShouldStackAlloc(checkWrite, ref leaseWrite, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkWrite, writefileDescriptorSet, ref refsAdded);
Span<IntPtr> errfileDescriptorSet = ShouldStackAlloc(checkError, ref leaseError, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkError, errfileDescriptorSet, ref refsAdded);
// This code used to erroneously pass a non-null timeval structure containing zeroes
// to select() when the caller specified (-1) for the microseconds parameter. That
// caused select to actually have a *zero* timeout instead of an infinite timeout
// turning the operation into a non-blocking poll.
//
// Now we pass a null timeval struct when microseconds is (-1).
//
// Negative microsecond values that weren't exactly (-1) were originally successfully
// converted to a timeval struct containing unsigned non-zero integers. This code
// retains that behavior so that any app working around the original bug with,
// for example, (-2) specified for microseconds, will continue to get the same behavior.
int socketCount;
fixed (IntPtr* readPtr = &MemoryMarshal.GetReference(readfileDescriptorSet))
fixed (IntPtr* writePtr = &MemoryMarshal.GetReference(writefileDescriptorSet))
fixed (IntPtr* errPtr = &MemoryMarshal.GetReference(errfileDescriptorSet))
{
if (microseconds != -1)
{
Interop.Winsock.TimeValue IOwait = default;
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
IntPtr.Zero);
}
}
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(null, $"Interop.Winsock.select returns socketCount:{socketCount}");
if ((SocketError)socketCount == SocketError.SocketError)
{
return GetLastSocketError();
}
// Remove from the lists any entries which weren't set
Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet, ref refsAdded);
Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet, ref refsAdded);
Socket.SelectFileDescriptor(checkError, errfileDescriptorSet, ref refsAdded);
return SocketError.Success;
}
finally
{
if (leaseRead != null) ArrayPool<IntPtr>.Shared.Return(leaseRead);
if (leaseWrite != null) ArrayPool<IntPtr>.Shared.Return(leaseWrite);
if (leaseError != null) ArrayPool<IntPtr>.Shared.Return(leaseError);
// This order matches with the AddToPollArray calls
// to release only the handles that were ref'd.
Socket.SocketListDangerousReleaseRefs(checkRead, ref refsAdded);
Socket.SocketListDangerousReleaseRefs(checkWrite, ref refsAdded);
Socket.SocketListDangerousReleaseRefs(checkError, ref refsAdded);
Debug.Assert(refsAdded == 0);
}
}
public static SocketError Shutdown(SafeSocketHandle handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
SocketError err = Interop.Winsock.shutdown(handle, (int)how);
if (err != SocketError.SocketError)
{
handle.TrackShutdown(how);
return SocketError.Success;
}