/
Socket.cs
10332 lines (8641 loc) · 425 KB
/
Socket.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
//------------------------------------------------------------------------------
// <copyright file="Socket.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.Sockets {
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Configuration;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.ComponentModel;
/// <devdoc>
/// <para>The <see cref='Sockets.Socket'/> class implements the Berkeley sockets
/// interface.</para>
/// </devdoc>
public partial class Socket : IDisposable
{
internal const int DefaultCloseTimeout = -1; // don't change for default, otherwise breaking change
// AcceptQueue - queued list of accept requests for BeginAccept or async Result for Begin Connect
private object m_AcceptQueueOrConnectResult;
// Async connect operation integrity check.
private int asyncConnectOperationLock = 0;
// the following 8 members represent the state of the socket
private SafeCloseSocket m_Handle;
// m_RightEndPoint is null if the socket has not been bound. Otherwise, it is any EndPoint of the
// correct type (IPEndPoint, etc).
internal EndPoint m_RightEndPoint;
internal EndPoint m_RemoteEndPoint;
// this flags monitor if the socket was ever connected at any time and if it still is.
private bool m_IsConnected; // = false;
private bool m_IsDisconnected; // = false;
// when the socket is created it will be in blocking mode
// we'll only be able to Accept or Connect, so we only need
// to handle one of these cases at a time
private bool willBlock = true; // desired state of the socket for the user
private bool willBlockInternal = true; // actual win32 state of the socket
private bool isListening = false;
// Our internal state doesn't automatically get updated after a non-blocking connect
// completes. Keep track of whether we're doing a non-blocking connect, and make sure
// to poll for the real state until we're done connecting.
private bool m_NonBlockingConnectInProgress;
// Keep track of the kind of endpoint used to do a non-blocking connect, so we can set
// it to m_RightEndPoint when we discover we're connected.
private EndPoint m_NonBlockingConnectRightEndPoint;
// These are constants initialized by constructor
private AddressFamily addressFamily;
private SocketType socketType;
private ProtocolType protocolType;
// These caches are one degree off of Socket since they're not used in the sync case/when disabled in config.
private CacheSet m_Caches;
private class CacheSet
{
internal CallbackClosure ConnectClosureCache;
internal CallbackClosure AcceptClosureCache;
internal CallbackClosure SendClosureCache;
internal CallbackClosure ReceiveClosureCache;
internal OverlappedCache SendOverlappedCache;
internal OverlappedCache ReceiveOverlappedCache;
}
//
// Overlapped constants.
//
#if !FEATURE_PAL || CORIOLIS
internal static volatile bool UseOverlappedIO;
#else
// Disable the I/O completion port for Rotor
internal static volatile bool UseOverlappedIO = true;
#endif // !FEATURE_PAL || CORIOLIS
private bool useOverlappedIO;
// Bool marked true if the native socket m_Handle was bound to the ThreadPool
private bool m_BoundToThreadPool; // = false;
// Bool marked true if the native socket option IP_PKTINFO or IPV6_PKTINFO has been set
private bool m_ReceivingPacketInformation;
// Event used for async Connect/Accept calls
private ManualResetEvent m_AsyncEvent;
private RegisteredWaitHandle m_RegisteredWait;
private AsyncEventBits m_BlockEventBits = AsyncEventBits.FdNone;
//These members are to cache permission checks
private SocketAddress m_PermittedRemoteAddress;
private DynamicWinsockMethods m_DynamicWinsockMethods;
private static object s_InternalSyncObject;
private int m_CloseTimeout = Socket.DefaultCloseTimeout;
private int m_IntCleanedUp; // 0 if not completed >0 otherwise.
private const int microcnv = 1000000;
private readonly static int protocolInformationSize = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO));
internal static volatile bool s_SupportsIPv4;
internal static volatile bool s_SupportsIPv6;
internal static volatile bool s_OSSupportsIPv6;
internal static volatile bool s_Initialized;
private static volatile WaitOrTimerCallback s_RegisteredWaitCallback;
private static volatile bool s_LoggingEnabled;
#if !FEATURE_PAL // perfcounter
internal static volatile bool s_PerfCountersEnabled;
#endif
//************* constructors *************************
//------------------------------------
// Creates a Dual Mode socket for working with both IPv4 and IPv6
public Socket(SocketType socketType, ProtocolType protocolType)
: this(AddressFamily.InterNetworkV6, socketType, protocolType) {
DualMode = true;
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='Sockets.Socket'/> class.
/// </para>
/// </devdoc>
public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) {
s_LoggingEnabled = Logging.On;
if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
InitializeSockets();
m_Handle = SafeCloseSocket.CreateWSASocket(
addressFamily,
socketType,
protocolType);
if (m_Handle.IsInvalid) {
//
// failed to create the win32 socket, throw
//
throw new SocketException();
}
this.addressFamily = addressFamily;
this.socketType = socketType;
this.protocolType = protocolType;
IPProtectionLevel defaultProtectionLevel = SettingsSectionInternal.Section.IPProtectionLevel;
if (defaultProtectionLevel != IPProtectionLevel.Unspecified) {
SetIPProtectionLevel(defaultProtectionLevel);
}
if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
}
public Socket(SocketInformation socketInformation) {
s_LoggingEnabled = Logging.On;
if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
ExceptionHelper.UnrestrictedSocketPermission.Demand();
InitializeSockets();
if(socketInformation.ProtocolInformation == null || socketInformation.ProtocolInformation.Length < protocolInformationSize){
throw new ArgumentException(SR.GetString(SR.net_sockets_invalid_socketinformation), "socketInformation.ProtocolInformation");
}
unsafe{
fixed(byte * pinnedBuffer = socketInformation.ProtocolInformation){
m_Handle = SafeCloseSocket.CreateWSASocket(pinnedBuffer);
UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO protocolInfo = (UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO)Marshal.PtrToStructure((IntPtr)pinnedBuffer, typeof(UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO));
addressFamily = protocolInfo.iAddressFamily;
socketType = (SocketType)protocolInfo.iSocketType;
protocolType = (ProtocolType)protocolInfo.iProtocol;
}
}
if (m_Handle.IsInvalid) {
SocketException e = new SocketException();
if(e.ErrorCode == (int)SocketError.InvalidArgument){
throw new ArgumentException(SR.GetString(SR.net_sockets_invalid_socketinformation), "socketInformation");
}
else {
throw e;
}
}
if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6) {
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
m_IsConnected = socketInformation.IsConnected;
willBlock = !socketInformation.IsNonBlocking;
InternalSetBlocking(willBlock);
isListening = socketInformation.IsListening;
UseOnlyOverlappedIO = socketInformation.UseOnlyOverlappedIO;
//are we bound? if so, what's the local endpoint?
if (socketInformation.RemoteEndPoint != null) {
m_RightEndPoint = socketInformation.RemoteEndPoint;
m_RemoteEndPoint = socketInformation.RemoteEndPoint;
}
else {
EndPoint ep = null;
if (addressFamily == AddressFamily.InterNetwork ) {
ep = IPEndPoint.Any;
}
else if(addressFamily == AddressFamily.InterNetworkV6) {
ep = IPEndPoint.IPv6Any;
}
SocketAddress socketAddress = ep.Serialize();
SocketError errorCode;
try
{
errorCode = UnsafeNclNativeMethods.OSSOCK.getsockname(
m_Handle,
socketAddress.m_Buffer,
ref socketAddress.m_Size);
}
catch (ObjectDisposedException)
{
errorCode = SocketError.NotSocket;
}
if (errorCode == SocketError.Success) {
try {
//we're bound
m_RightEndPoint = ep.Create(socketAddress);
}
catch {
}
}
}
if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
}
/// <devdoc>
/// <para>
/// Called by the class to create a socket to accept an
/// incoming request.
/// </para>
/// </devdoc>
private Socket(SafeCloseSocket fd) {
s_LoggingEnabled = Logging.On;
if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Socket", null);
InitializeSockets();
// ExceptionHelper.UnmanagedPermission.Demand();
//<
//
// this should never happen, let's check anyway
//
if (fd == null || fd.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.net_InvalidSocketHandle));
}
m_Handle = fd;
addressFamily = Sockets.AddressFamily.Unknown;
socketType = Sockets.SocketType.Unknown;
protocolType = Sockets.ProtocolType.Unknown;
if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
}
//************* properties *************************
/// <devdoc>
/// <para>Indicates whether IPv4 support is available and enabled on this machine.</para>
/// </devdoc>
[Obsolete("SupportsIPv4 is obsoleted for this type, please use OSSupportsIPv4 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static bool SupportsIPv4 {
get {
InitializeSockets();
return s_SupportsIPv4;
}
}
// Renamed to be consistent with OSSupportsIPv6
public static bool OSSupportsIPv4 {
get {
InitializeSockets();
return s_SupportsIPv4;
}
}
/// <devdoc>
/// <para>Indicates whether IPv6 support is available and enabled on this machine.</para>
/// </devdoc>
[Obsolete("SupportsIPv6 is obsoleted for this type, please use OSSupportsIPv6 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static bool SupportsIPv6 {
get {
InitializeSockets();
return s_SupportsIPv6;
}
}
internal static bool LegacySupportsIPv6 {
get {
InitializeSockets();
return s_SupportsIPv6;
}
}
public static bool OSSupportsIPv6 {
get {
InitializeSockets();
return s_OSSupportsIPv6;
}
}
/// <devdoc>
/// <para>
/// Gets the amount of data pending in the network's input buffer that can be
/// read from the socket.
/// </para>
/// </devdoc>
public int Available {
get {
if (CleanedUp) {
throw new ObjectDisposedException(this.GetType().FullName);
}
int argp = 0;
// This may throw ObjectDisposedException.
SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.ioctlsocket(
m_Handle,
IoctlSocketConstants.FIONREAD,
ref argp);
GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Available_get() UnsafeNclNativeMethods.OSSOCK.ioctlsocket returns errorCode:" + errorCode);
//
// if the native call fails we'll throw a SocketException
//
if (errorCode==SocketError.SocketError) {
//
// update our internal state after this socket error and throw
//
SocketException socketException = new SocketException();
UpdateStatusAfterSocketError(socketException);
if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "Available", socketException);
throw socketException;
}
return argp;
}
}
/// <devdoc>
/// <para>
/// Gets the local end point.
/// </para>
/// </devdoc>
public EndPoint LocalEndPoint {
get {
if (CleanedUp) {
throw new ObjectDisposedException(this.GetType().FullName);
}
if (m_NonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
{
// update the state if we've become connected after a non-blocking connect
m_IsConnected = true;
m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
m_NonBlockingConnectInProgress = false;
}
if (m_RightEndPoint == null) {
return null;
}
SocketAddress socketAddress = m_RightEndPoint.Serialize();
// This may throw ObjectDisposedException.
SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.getsockname(
m_Handle,
socketAddress.m_Buffer,
ref socketAddress.m_Size);
if (errorCode!=SocketError.Success) {
//
// update our internal state after this socket error and throw
//
SocketException socketException = new SocketException();
UpdateStatusAfterSocketError(socketException);
if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "LocalEndPoint", socketException);
throw socketException;
}
return m_RightEndPoint.Create(socketAddress);
}
}
/// <devdoc>
/// <para>
/// Gets the remote end point
/// </para>
/// </devdoc>
public EndPoint RemoteEndPoint {
get {
if (CleanedUp) {
throw new ObjectDisposedException(this.GetType().FullName);
}
if (m_RemoteEndPoint==null) {
if (m_NonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
{
// update the state if we've become connected after a non-blocking connect
m_IsConnected = true;
m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
m_NonBlockingConnectInProgress = false;
}
if (m_RightEndPoint==null) {
return null;
}
SocketAddress socketAddress = m_RightEndPoint.Serialize();
// This may throw ObjectDisposedException.
SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.getpeername(
m_Handle,
socketAddress.m_Buffer,
ref socketAddress.m_Size);
if (errorCode!=SocketError.Success) {
//
// update our internal state after this socket error and throw
//
SocketException socketException = new SocketException();
UpdateStatusAfterSocketError(socketException);
if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "RemoteEndPoint", socketException);
throw socketException;
}
try {
m_RemoteEndPoint = m_RightEndPoint.Create(socketAddress);
}
catch {
}
}
return m_RemoteEndPoint;
}
}
/// <devdoc>
/// <para>
/// Gets the operating system m_Handle for the socket.
///YUKON: should we cut this method off, who are the users?
/// </para>
/// </devdoc>
public IntPtr Handle {
get {
ExceptionHelper.UnmanagedPermission.Demand();
return m_Handle.DangerousGetHandle();
}
}
internal SafeCloseSocket SafeHandle {
get {
return m_Handle;
}
}
// Non-blocking I/O control
/// <devdoc>
/// <para>
/// Gets and sets the blocking mode of a socket.
/// </para>
/// </devdoc>
public bool Blocking {
get {
//
// return the user's desired blocking behaviour (not the actual win32 state)
//
return willBlock;
}
set {
if (CleanedUp) {
throw new ObjectDisposedException(this.GetType().FullName);
}
GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::set_Blocking() value:" + value.ToString() + " willBlock:" + willBlock.ToString() + " willBlockInternal:" + willBlockInternal.ToString());
bool current;
SocketError errorCode = InternalSetBlocking(value, out current);
if (errorCode!=SocketError.Success) {
//
// update our internal state after this socket error and throw
SocketException socketException = new SocketException(errorCode);
UpdateStatusAfterSocketError(socketException);
if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "Blocking", socketException);
throw socketException;
}
//
// win32 call succeeded, update desired state
//
willBlock = current;
}
}
public bool UseOnlyOverlappedIO{
get {
//
// return the user's desired blocking behaviour (not the actual win32 state)
//
return useOverlappedIO;
}
set {
if (m_BoundToThreadPool) {
throw new InvalidOperationException(SR.GetString(SR.net_io_completionportwasbound));
}
useOverlappedIO = value;
}
}
/// <devdoc>
/// <para>
/// Gets the connection state of the Socket. This property will return the latest
/// known state of the Socket. When it returns false, the Socket was either never connected
/// or it is not connected anymore. When it returns true, though, there's no guarantee that the Socket
/// is still connected, but only that it was connected at the time of the last IO operation.
/// </para>
/// </devdoc>
public bool Connected {
get {
GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Connected() m_IsConnected:"+m_IsConnected);
if (m_NonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
{
// update the state if we've become connected after a non-blocking connect
m_IsConnected = true;
m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
m_NonBlockingConnectInProgress = false;
}
return m_IsConnected;
}
}
/// <devdoc>
/// <para>
/// Gets the socket's address family.
/// </para>
/// </devdoc>
public AddressFamily AddressFamily {
get {
return addressFamily;
}
}
/// <devdoc>
/// <para>
/// Gets the socket's socketType.
/// </para>
/// </devdoc>
public SocketType SocketType {
get {
return socketType;
}
}
/// <devdoc>
/// <para>
/// Gets the socket's protocol socketType.
/// </para>
/// </devdoc>
public ProtocolType ProtocolType {
get {
return protocolType;
}
}
public bool IsBound{
get{
return (m_RightEndPoint != null);
}
}
public bool ExclusiveAddressUse{
get {
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse) != 0 ? true : false;
}
set {
if (IsBound) {
throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustnotbebound));
}
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value ? 1 : 0);
}
}
public int ReceiveBufferSize {
get {
return (int)GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer);
}
set {
if (value<0) {
throw new ArgumentOutOfRangeException("value");
}
SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer, value);
}
}
public int SendBufferSize {
get {
return (int)GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendBuffer);
}
set {
if (value<0) {
throw new ArgumentOutOfRangeException("value");
}
SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendBuffer, value);
}
}
public int ReceiveTimeout {
get {
return (int)GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout);
}
set {
if (value< -1) {
throw new ArgumentOutOfRangeException("value");
}
if (value == -1) {
value = 0;
}
SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, value);
}
}
public int SendTimeout {
get {
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
}
set {
if (value< -1) {
throw new ArgumentOutOfRangeException("value");
}
if (value == -1) {
value = 0;
}
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
}
}
public LingerOption LingerState {
get {
return (LingerOption)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
}
set {
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value);
}
}
public bool NoDelay {
get {
return (int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false;
}
set {
SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
}
}
public short Ttl{
get {
if (addressFamily == AddressFamily.InterNetwork) {
return (short)(int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive);
}
else if (addressFamily == AddressFamily.InterNetworkV6) {
return (short)(int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive);
}
else{
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
}
set {
// valid values are from 0 to 255 since Ttl is really just a byte value on the wire
if (value < 0 || value > 255) {
throw new ArgumentOutOfRangeException("value");
}
if (addressFamily == AddressFamily.InterNetwork) {
SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
}
else if (addressFamily == AddressFamily.InterNetworkV6) {
SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive, value);
}
else{
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
}
}
public bool DontFragment{
get {
if (addressFamily == AddressFamily.InterNetwork) {
return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment) != 0 ? true : false;
}
else{
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
}
set {
if (addressFamily == AddressFamily.InterNetwork) {
SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, value ? 1 : 0);
}
else{
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
}
}
public bool MulticastLoopback{
get {
if (addressFamily == AddressFamily.InterNetwork) {
return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback) != 0 ? true : false;
}
else if (addressFamily == AddressFamily.InterNetworkV6) {
return (int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback) != 0 ? true : false;
}
else{
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
}
set {
if (addressFamily == AddressFamily.InterNetwork) {
SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value ? 1 : 0);
}
else if (addressFamily == AddressFamily.InterNetworkV6) {
SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value ? 1 : 0);
}
else{
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
}
}
public bool EnableBroadcast{
get {
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast) != 0 ? true : false;
}
set {
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
}
}
public bool DualMode {
get {
if (AddressFamily != AddressFamily.InterNetworkV6) {
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only) == 0);
}
set {
if (AddressFamily != AddressFamily.InterNetworkV6) {
throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
}
SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, value ? 0 : 1);
}
}
private bool IsDualMode {
get {
return AddressFamily == AddressFamily.InterNetworkV6 && DualMode;
}
}
internal bool CanTryAddressFamily(AddressFamily family) {
return (family == addressFamily) || (family == AddressFamily.InterNetwork && IsDualMode);
}
//************* public methods *************************
/// <devdoc>
/// <para>Associates a socket with an end point.</para>
/// </devdoc>
public void Bind(EndPoint localEP) {
if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Bind", localEP);
if (CleanedUp) {
throw new ObjectDisposedException(this.GetType().FullName);
}
//
// parameter validation
//
if (localEP==null) {
throw new ArgumentNullException("localEP");
}
GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Bind() localEP:" + localEP.ToString());
EndPoint endPointSnapshot = localEP;
IPEndPoint ipSnapshot = localEP as IPEndPoint;
//
// for now security is implemented only on IPEndPoint
// If EndPoint is of other type - unmanaged code permisison is demanded
//
if (ipSnapshot != null)
{
// Take a snapshot that will make it immutable and not derived.
ipSnapshot = ipSnapshot.Snapshot();
// DualMode: Do the security check on the users IPv4 address, but map to IPv6 before binding.
endPointSnapshot = RemapIPEndPoint(ipSnapshot);
//
// create the permissions the user would need for the call
//
SocketPermission socketPermission
= new SocketPermission(
NetworkAccess.Accept,
Transport,
ipSnapshot.Address.ToString(),
ipSnapshot.Port);
//
// demand for them
//
socketPermission.Demand();
// Here the permission check has succeded.
// NB: if local port is 0, then winsock will assign some>1024,
// so assuming that this is safe. We will not check the
// NetworkAccess.Accept permissions in Receive.
}
else {
//<
ExceptionHelper.UnmanagedPermission.Demand();
}
//
// ask the EndPoint to generate a SocketAddress that we
// can pass down to winsock
//
SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPointSnapshot);
DoBind(endPointSnapshot, socketAddress);
if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Bind", "");
}
internal void InternalBind(EndPoint localEP)
{
if (s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "InternalBind", localEP);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::InternalBind() localEP:" + localEP.ToString());
GlobalLog.Assert(!(localEP is DnsEndPoint), "Calling InternalBind with a DnsEndPoint, about to get NotImplementedException");
//
// ask the EndPoint to generate a SocketAddress that we
// can pass down to winsock
//
EndPoint endPointSnapshot = localEP;
SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
DoBind(endPointSnapshot, socketAddress);
if (s_LoggingEnabled) Logging.Exit(Logging.Sockets, this, "InternalBind", "");
}
private void DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
{
// Mitigation for Blue Screen of Death (Win7, maybe others)
IPEndPoint ipEndPoint = endPointSnapshot as IPEndPoint;
if (!OSSupportsIPv4 && ipEndPoint != null && ipEndPoint.Address.IsIPv4MappedToIPv6)
{
SocketException socketException = new SocketException(SocketError.InvalidArgument);
UpdateStatusAfterSocketError(socketException);
if (s_LoggingEnabled) Logging.Exception(Logging.Sockets, this, "DoBind", socketException);
throw socketException;
}
// This may throw ObjectDisposedException.
SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.bind(
m_Handle,
socketAddress.m_Buffer,
socketAddress.m_Size);
#if TRAVE
try
{
GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Bind() SRC:" + ValidationHelper.ToString(LocalEndPoint) + " UnsafeNclNativeMethods.OSSOCK.bind returns errorCode:" + errorCode);
}
catch (ObjectDisposedException) { }
#endif
//
// if the native call fails we'll throw a SocketException
//
if (errorCode != SocketError.Success)
{
//
// update our internal state after this socket error and throw
//
SocketException socketException = new SocketException();
UpdateStatusAfterSocketError(socketException);
if (s_LoggingEnabled) Logging.Exception(Logging.Sockets, this, "DoBind", socketException);
throw socketException;
}
if (m_RightEndPoint == null)
{
//
// save a copy of the EndPoint so we can use it for Create()
//
m_RightEndPoint = endPointSnapshot;
}
}
/// <devdoc>
/// <para>Establishes a connection to a remote system.</para>
/// </devdoc>
public void Connect(EndPoint remoteEP) {
if (CleanedUp) {
throw new ObjectDisposedException(this.GetType().FullName);
}
//
// parameter validation
//
if (remoteEP==null) {
throw new ArgumentNullException("remoteEP");
}