Merge pull request #2227 from esdrubal/tzparse
[mono.git] / mcs / class / System / System.Net.Sockets / Socket.cs
1 // System.Net.Sockets.Socket.cs
2 //
3 // Authors:
4 //      Phillip Pearson (pp@myelin.co.nz)
5 //      Dick Porter <dick@ximian.com>
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //      Sridhar Kulkarni (sridharkulkarni@gmail.com)
8 //      Brian Nickel (brian.nickel@gmail.com)
9 //      Ludovic Henry (ludovic@xamarin.com)
10 //
11 // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
12 //    http://www.myelin.co.nz
13 // (c) 2004-2011 Novell, Inc. (http://www.novell.com)
14 //
15 //
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
23 // 
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 // 
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 //
35
36 using System;
37 using System.Net;
38 using System.Collections;
39 using System.Collections.Generic;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Threading;
43 using System.Reflection;
44 using System.IO;
45 using System.Net.Configuration;
46 using System.Text;
47 using System.Timers;
48 using System.Net.NetworkInformation;
49
50 namespace System.Net.Sockets 
51 {
52         public partial class Socket : IDisposable
53         {
54                 const int SOCKET_CLOSED_CODE = 10004;
55                 const string TIMEOUT_EXCEPTION_MSG = "A connection attempt failed because the connected party did not properly respond" +
56                         "after a period of time, or established connection failed because connected host has failed to respond";
57
58                 /*
59                  *      These two fields are looked up by name by the runtime, don't change
60                  *  their name without also updating the runtime code.
61                  */
62                 static int ipv4_supported = -1;
63                 static int ipv6_supported = -1;
64
65                 /* true if we called Close_internal */
66                 bool is_closed;
67
68                 bool is_listening;
69                 bool use_overlapped_io;
70
71                 int linger_timeout;
72
73                 AddressFamily address_family;
74                 SocketType socket_type;
75                 ProtocolType protocol_type;
76
77                 /* the field "safe_handle" is looked up by name by the runtime */
78                 internal SafeSocketHandle safe_handle;
79
80                 /*
81                  * This EndPoint is used when creating new endpoints. Because
82                  * there are many types of EndPoints possible,
83                  * seed_endpoint.Create(addr) is used for creating new ones.
84                  * As such, this value is set on Bind, SentTo, ReceiveFrom,
85                  * Connect, etc.
86                  */
87                 internal EndPoint seed_endpoint = null;
88
89                 internal Queue<KeyValuePair<IntPtr, IOSelectorJob>> readQ = new Queue<KeyValuePair<IntPtr, IOSelectorJob>> (2);
90                 internal Queue<KeyValuePair<IntPtr, IOSelectorJob>> writeQ = new Queue<KeyValuePair<IntPtr, IOSelectorJob>> (2);
91
92                 internal bool is_blocking = true;
93                 internal bool is_bound;
94
95                 /* When true, the socket was connected at the time of the last IO operation */
96                 internal bool is_connected;
97
98                 internal bool is_disposed;
99                 internal bool connect_in_progress;
100
101 #region Constructors
102
103                 static Socket ()
104                 {
105                         if (ipv4_supported == -1) {
106                                 try {
107                                         Socket tmp = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
108                                         tmp.Close();
109
110                                         ipv4_supported = 1;
111                                 } catch {
112                                         ipv4_supported = 0;
113                                 }
114                         }
115
116                         if (ipv6_supported == -1) {
117                                 // We need to put a try/catch around ConfigurationManager methods as will always throw an exception 
118                                 // when run in a mono embedded application.  This occurs as embedded applications do not have a setup
119                                 // for application config.  The exception is not thrown when called from a normal .NET application. 
120                                 //
121                                 // We, then, need to guard calls to the ConfigurationManager.  If the config is not found or throws an
122                                 // exception, will fall through to the existing Socket / API directly below in the code.
123                                 //
124                                 // Also note that catching ConfigurationErrorsException specifically would require library dependency
125                                 // System.Configuration, and wanted to avoid that.
126 #if !NET_2_1
127 #if CONFIGURATION_DEP
128                                 try {
129                                         SettingsSection config;
130                                         config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
131                                         if (config != null)
132                                                 ipv6_supported = config.Ipv6.Enabled ? -1 : 0;
133                                 } catch {
134                                         ipv6_supported = -1;
135                                 }
136 #else
137                                 try {
138                                         NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
139                                         if (config != null)
140                                                 ipv6_supported = config.ipv6Enabled ? -1 : 0;
141                                 } catch {
142                                         ipv6_supported = -1;
143                                 }
144 #endif
145 #endif
146                                 if (ipv6_supported != 0) {
147                                         try {
148                                                 Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
149                                                 tmp.Close();
150
151                                                 ipv6_supported = 1;
152                                         } catch {
153                                                 ipv6_supported = 0;
154                                         }
155                                 }
156                         }
157                 }
158
159                 //
160                 // This constructor is used by servers that want to listen for instance on both
161                 // ipv4 and ipv6.   Mono has historically done that if you use InterNetworkV6 (at
162                 // least on Unix), because that is the default behavior unless the IPV6_V6ONLY
163                 // option is explicitly set by using setsockopt (sock, IPPROTO_IPV6, IPV6_ONLY)
164                 //
165                 public Socket (SocketType socketType, ProtocolType protocolType)
166                         : this (AddressFamily.InterNetworkV6, socketType, protocolType)
167                 {
168                         DualMode = true;
169                 }
170                 
171                 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
172                 {
173 #if NET_2_1 && !MOBILE
174                         switch (addressFamily) {
175                         case AddressFamily.InterNetwork:    // ok
176                         case AddressFamily.InterNetworkV6:  // ok
177                         case AddressFamily.Unknown:         // SocketException will be thrown later (with right error #)
178                                 break;
179                         // case AddressFamily.Unspecified:
180                         default:
181                                 throw new ArgumentException ("addressFamily");
182                         }
183
184                         switch (socketType) {
185                         case SocketType.Stream:             // ok
186                         case SocketType.Unknown:            // SocketException will be thrown later (with right error #)
187                                 break;
188                         default:
189                                 throw new ArgumentException ("socketType");
190                         }
191
192                         switch (protocolType) {
193                         case ProtocolType.Tcp:              // ok
194                         case ProtocolType.Unspecified:      // ok
195                         case ProtocolType.Unknown:          // SocketException will be thrown later (with right error #)
196                                 break;
197                         default:
198                                 throw new ArgumentException ("protocolType");
199                         }
200 #endif
201                         this.address_family = addressFamily;
202                         this.socket_type = socketType;
203                         this.protocol_type = protocolType;
204
205                         int error;
206                         this.safe_handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);
207
208                         if (error != 0)
209                                 throw new SocketException (error);
210
211 #if !NET_2_1 || MOBILE
212                         SocketDefaults ();
213 #endif
214                 }
215
216 #if !MOBILE
217                 public Socket (SocketInformation socketInformation)
218                 {
219                         this.is_listening      = (socketInformation.Options & SocketInformationOptions.Listening) != 0;
220                         this.is_connected      = (socketInformation.Options & SocketInformationOptions.Connected) != 0;
221                         this.is_blocking       = (socketInformation.Options & SocketInformationOptions.NonBlocking) == 0;
222                         this.use_overlapped_io = (socketInformation.Options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;
223
224                         var result = Mono.DataConverter.Unpack ("iiiil", socketInformation.ProtocolInformation, 0);
225
226                         this.address_family = (AddressFamily) (int) result [0];
227                         this.socket_type = (SocketType) (int) result [1];
228                         this.protocol_type = (ProtocolType) (int) result [2];
229                         this.is_bound = (ProtocolType) (int) result [3] != 0;
230                         this.safe_handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);
231
232                         SocketDefaults ();
233                 }
234 #endif
235
236                 /* private constructor used by Accept, which already has a socket handle to use */
237                 internal Socket(AddressFamily family, SocketType type, ProtocolType proto, SafeSocketHandle safe_handle)
238                 {
239                         this.address_family = family;
240                         this.socket_type = type;
241                         this.protocol_type = proto;
242                         
243                         this.safe_handle = safe_handle;
244                         this.is_connected = true;
245                 }
246
247                 ~Socket ()
248                 {
249                         Dispose (false);
250                 }
251
252                 void SocketDefaults ()
253                 {
254                         try {
255                                 /* Need to test IPv6 further */
256                                 if (address_family == AddressFamily.InterNetwork
257                                         // || address_family == AddressFamily.InterNetworkV6
258                                 ) {
259                                         /* This is the default, but it probably has nasty side
260                                          * effects on Linux, as the socket option is kludged by
261                                          * turning on or off PMTU discovery... */
262                                         this.DontFragment = false;
263                                 }
264
265                                 /* Microsoft sets these to 8192, but we are going to keep them
266                                  * both to the OS defaults as these have a big performance impact.
267                                  * on WebClient performance. */
268                                 // this.ReceiveBufferSize = 8192;
269                                 // this.SendBufferSize = 8192;
270                         } catch (SocketException) {
271                         }
272                 }
273
274                 /* Creates a new system socket, returning the handle */
275                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
276                 extern IntPtr Socket_internal (AddressFamily family, SocketType type, ProtocolType proto, out int error);
277
278 #endregion
279
280 #region Properties
281
282                 [ObsoleteAttribute ("Use OSSupportsIPv4 instead")]
283                 public static bool SupportsIPv4 {
284                         get { return ipv4_supported == 1; }
285                 }
286
287                 [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
288                 public static bool SupportsIPv6 {
289                         get { return ipv6_supported == 1; }
290                 }
291
292 #if NET_2_1
293                 public static bool OSSupportsIPv4 {
294                         get { return ipv4_supported == 1; }
295                 }
296 #else
297                 public static bool OSSupportsIPv4 {
298                         get {
299                                 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
300
301                                 foreach (NetworkInterface adapter in nics) {
302                                         if (adapter.Supports (NetworkInterfaceComponent.IPv4))
303                                                 return true;
304                                 }
305
306                                 return false;
307                         }
308                 }
309 #endif
310
311 #if NET_2_1
312                 public static bool OSSupportsIPv6 {
313                         get { return ipv6_supported == 1; }
314                 }
315 #else
316                 public static bool OSSupportsIPv6 {
317                         get {
318                                 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
319
320                                 foreach (NetworkInterface adapter in nics) {
321                                         if (adapter.Supports (NetworkInterfaceComponent.IPv6))
322                                                 return true;
323                                 }
324
325                                 return false;
326                         }
327                 }
328 #endif
329
330                 public int Available {
331                         get {
332                                 ThrowIfDisposedAndClosed ();
333
334                                 int ret, error;
335                                 ret = Available_internal (safe_handle, out error);
336
337                                 if (error != 0)
338                                         throw new SocketException (error);
339
340                                 return ret;
341                         }
342                 }
343
344                 static int Available_internal (SafeSocketHandle safeHandle, out int error)
345                 {
346                         bool release = false;
347                         try {
348                                 safeHandle.DangerousAddRef (ref release);
349                                 return Available_internal (safeHandle.DangerousGetHandle (), out error);
350                         } finally {
351                                 if (release)
352                                         safeHandle.DangerousRelease ();
353                         }
354                 }
355
356                 /* Returns the amount of data waiting to be read on socket */
357                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
358                 extern static int Available_internal (IntPtr socket, out int error);
359
360                 public bool DontFragment {
361                         get {
362                                 ThrowIfDisposedAndClosed ();
363
364                                 switch (address_family) {
365                                 case AddressFamily.InterNetwork:
366                                         return ((int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment)) != 0;
367                                 case AddressFamily.InterNetworkV6:
368                                         return ((int) GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment)) != 0;
369                                 default:
370                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
371                                 }
372                         }
373                         set {
374                                 ThrowIfDisposedAndClosed ();
375
376                                 switch (address_family) {
377                                 case AddressFamily.InterNetwork:
378                                         SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment, value ? 1 : 0);
379                                         break;
380                                 case AddressFamily.InterNetworkV6:
381                                         SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment, value ? 1 : 0);
382                                         break;
383                                 default:
384                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
385                                 }
386                         }
387                 }
388
389                 public bool EnableBroadcast {
390                         get {
391                                 ThrowIfDisposedAndClosed ();
392
393                                 if (protocol_type != ProtocolType.Udp)
394                                         throw new SocketException ((int) SocketError.ProtocolOption);
395
396                                 return ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast)) != 0;
397                         }
398                         set {
399                                 ThrowIfDisposedAndClosed ();
400
401                                 if (protocol_type != ProtocolType.Udp)
402                                         throw new SocketException ((int) SocketError.ProtocolOption);
403
404                                 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
405                         }
406                 }
407
408                 public bool ExclusiveAddressUse {
409                         get {
410                                 ThrowIfDisposedAndClosed ();
411
412                                 return ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse)) != 0;
413                         }
414                         set {
415                                 ThrowIfDisposedAndClosed ();
416
417                                 if (is_bound)
418                                         throw new InvalidOperationException ("Bind has already been called for this socket");
419
420                                 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value ? 1 : 0);
421                         }
422                 }
423
424                 public bool IsBound {
425                         get {
426                                 return is_bound;
427                         }
428                 }
429
430                 public LingerOption LingerState {
431                         get {
432                                 ThrowIfDisposedAndClosed ();
433
434                                 return (LingerOption) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger);
435                         }
436                         set {
437                                 ThrowIfDisposedAndClosed ();
438                                 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, value);
439                         }
440                 }
441
442                 public bool MulticastLoopback {
443                         get {
444                                 ThrowIfDisposedAndClosed ();
445
446                                 /* Even though this option can be set for TCP sockets on Linux, throw
447                                  * this exception anyway to be compatible (the MSDN docs say
448                                  * "Setting this property on a Transmission Control Protocol (TCP)
449                                  * socket will have no effect." but the MS runtime throws the
450                                  * exception...) */
451                                 if (protocol_type == ProtocolType.Tcp)
452                                         throw new SocketException ((int)SocketError.ProtocolOption);
453
454                                 switch (address_family) {
455                                 case AddressFamily.InterNetwork:
456                                         return ((int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)) != 0;
457                                 case AddressFamily.InterNetworkV6:
458                                         return ((int) GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)) != 0;
459                                 default:
460                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
461                                 }
462                         }
463                         set {
464                                 ThrowIfDisposedAndClosed ();
465
466                                 /* Even though this option can be set for TCP sockets on Linux, throw
467                                  * this exception anyway to be compatible (the MSDN docs say
468                                  * "Setting this property on a Transmission Control Protocol (TCP)
469                                  * socket will have no effect." but the MS runtime throws the
470                                  * exception...) */
471                                 if (protocol_type == ProtocolType.Tcp)
472                                         throw new SocketException ((int)SocketError.ProtocolOption);
473
474                                 switch (address_family) {
475                                 case AddressFamily.InterNetwork:
476                                         SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value ? 1 : 0);
477                                         break;
478                                 case AddressFamily.InterNetworkV6:
479                                         SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value ? 1 : 0);
480                                         break;
481                                 default:
482                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
483                                 }
484                         }
485                 }
486
487                 public bool DualMode {
488                         get {
489                                 if (AddressFamily != AddressFamily.InterNetworkV6) 
490                                         throw new NotSupportedException("This protocol version is not supported");
491
492                                 return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only) == 0);
493                         }
494                         set {
495                                 if (AddressFamily != AddressFamily.InterNetworkV6) 
496                                         throw new NotSupportedException("This protocol version is not supported");
497
498                                 SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, value ? 0 : 1);
499                         }
500                 }
501
502                 private bool IsDualMode {
503                         get {
504                                 return AddressFamily == AddressFamily.InterNetworkV6 && DualMode;
505                         }
506                 }
507
508                 [MonoTODO ("This doesn't do anything on Mono yet")]
509                 public bool UseOnlyOverlappedIO {
510                         get { return use_overlapped_io; }
511                         set { use_overlapped_io = value; }
512                 }
513
514                 public IntPtr Handle {
515                         get { return safe_handle.DangerousGetHandle (); }
516                 }
517
518                 // Wish:  support non-IP endpoints.
519                 public EndPoint LocalEndPoint {
520                         get {
521                                 ThrowIfDisposedAndClosed ();
522
523                                 /* If the seed EndPoint is null, Connect, Bind, etc has not yet
524                                  * been called. MS returns null in this case. */
525                                 if (seed_endpoint == null)
526                                         return null;
527
528                                 int error;
529                                 SocketAddress sa = LocalEndPoint_internal (safe_handle, (int) address_family, out error);
530
531                                 if (error != 0)
532                                         throw new SocketException (error);
533
534                                 return seed_endpoint.Create (sa);
535                         }
536                 }
537
538                 static SocketAddress LocalEndPoint_internal (SafeSocketHandle safeHandle, int family, out int error)
539                 {
540                         bool release = false;
541                         try {
542                                 safeHandle.DangerousAddRef (ref release);
543                                 return LocalEndPoint_internal (safeHandle.DangerousGetHandle (), family, out error);
544                         } finally {
545                                 if (release)
546                                         safeHandle.DangerousRelease ();
547                         }
548                 }
549
550                 /* Returns the local endpoint details in addr and port */
551                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
552                 extern static SocketAddress LocalEndPoint_internal (IntPtr socket, int family, out int error);
553
554                 public SocketType SocketType {
555                         get { return socket_type; }
556                 }
557
558                 public int SendTimeout {
559                         get {
560                                 ThrowIfDisposedAndClosed ();
561
562                                 return (int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
563                         }
564                         set {
565                                 ThrowIfDisposedAndClosed ();
566
567                                 if (value < -1)
568                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
569
570                                 /* According to the MSDN docs we should adjust values between 1 and
571                                  * 499 to 500, but the MS runtime doesn't do this. */
572                                 if (value == -1)
573                                         value = 0;
574
575                                 SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
576                         }
577                 }
578
579                 public int ReceiveTimeout {
580                         get {
581                                 ThrowIfDisposedAndClosed ();
582
583                                 return (int) GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
584                         }
585                         set {
586                                 ThrowIfDisposedAndClosed ();
587
588                                 if (value < -1)
589                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
590
591                                 if (value == -1)
592                                         value = 0;
593
594                                 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value);
595                         }
596                 }
597
598                 public AddressFamily AddressFamily {
599                         get { return address_family; }
600                 }
601
602                 public bool Blocking {
603                         get { return is_blocking; }
604                         set {
605                                 ThrowIfDisposedAndClosed ();
606
607                                 int error;
608                                 Blocking_internal (safe_handle, value, out error);
609
610                                 if (error != 0)
611                                         throw new SocketException (error);
612
613                                 is_blocking = value;
614                         }
615                 }
616
617                 static void Blocking_internal (SafeSocketHandle safeHandle, bool block, out int error)
618                 {
619                         bool release = false;
620                         try {
621                                 safeHandle.DangerousAddRef (ref release);
622                                 Blocking_internal (safeHandle.DangerousGetHandle (), block, out error);
623                         } finally {
624                                 if (release)
625                                         safeHandle.DangerousRelease ();
626                         }
627                 }
628
629                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
630                 internal extern static void Blocking_internal(IntPtr socket, bool block, out int error);
631
632                 public bool Connected {
633                         get { return is_connected; }
634                         internal set { is_connected = value; }
635                 }
636
637                 public ProtocolType ProtocolType {
638                         get { return protocol_type; }
639                 }
640
641                 public bool NoDelay {
642                         get {
643                                 ThrowIfDisposedAndClosed ();
644                                 ThrowIfUdp ();
645
646                                 return ((int) GetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay)) != 0;
647                         }
648
649                         set {
650                                 ThrowIfDisposedAndClosed ();
651                                 ThrowIfUdp ();
652
653                                 SetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
654                         }
655                 }
656
657                 public int ReceiveBufferSize {
658                         get {
659                                 ThrowIfDisposedAndClosed ();
660
661                                 return (int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
662                         }
663                         set {
664                                 ThrowIfDisposedAndClosed ();
665
666                                 if (value < 0)
667                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
668
669                                 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
670                         }
671                 }
672
673                 public int SendBufferSize {
674                         get {
675                                 ThrowIfDisposedAndClosed ();
676
677                                 return (int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
678                         }
679                         set {
680                                 ThrowIfDisposedAndClosed ();
681
682                                 if (value < 0)
683                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
684
685                                 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value);
686                         }
687                 }
688
689                 public short Ttl {
690                         get {
691                                 ThrowIfDisposedAndClosed ();
692
693                                 switch (address_family) {
694                                 case AddressFamily.InterNetwork:
695                                         return (short) (int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive);
696                                 case AddressFamily.InterNetworkV6:
697                                         return (short) (int) GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit);
698                                 default:
699                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
700                                 }
701                         }
702                         set {
703                                 ThrowIfDisposedAndClosed ();
704
705                                 if (value < 0)
706                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
707
708                                 switch (address_family) {
709                                 case AddressFamily.InterNetwork:
710                                         SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
711                                         break;
712                                 case AddressFamily.InterNetworkV6:
713                                         SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
714                                         break;
715                                 default:
716                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
717                                 }
718                         }
719                 }
720
721                 public EndPoint RemoteEndPoint {
722                         get {
723                                 ThrowIfDisposedAndClosed ();
724
725                                 /* If the seed EndPoint is null, Connect, Bind, etc has
726                                  * not yet been called. MS returns null in this case. */
727                                 if (!is_connected || seed_endpoint == null)
728                                         return null;
729
730                                 int error;
731                                 SocketAddress sa = RemoteEndPoint_internal (safe_handle, (int) address_family, out error);
732
733                                 if (error != 0)
734                                         throw new SocketException (error);
735
736                                 return seed_endpoint.Create (sa);
737                         }
738                 }
739
740                 static SocketAddress RemoteEndPoint_internal (SafeSocketHandle safeHandle, int family, out int error)
741                 {
742                         bool release = false;
743                         try {
744                                 safeHandle.DangerousAddRef (ref release);
745                                 return RemoteEndPoint_internal (safeHandle.DangerousGetHandle (), family, out error);
746                         } finally {
747                                 if (release)
748                                         safeHandle.DangerousRelease ();
749                         }
750                 }
751
752                 /* Returns the remote endpoint details in addr and port */
753                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
754                 extern static SocketAddress RemoteEndPoint_internal (IntPtr socket, int family, out int error);
755
756 #endregion
757
758 #region Select
759
760                 public static void Select (IList checkRead, IList checkWrite, IList checkError, int microSeconds)
761                 {
762                         var list = new List<Socket> ();
763                         AddSockets (list, checkRead, "checkRead");
764                         AddSockets (list, checkWrite, "checkWrite");
765                         AddSockets (list, checkError, "checkError");
766
767                         if (list.Count == 3)
768                                 throw new ArgumentNullException ("checkRead, checkWrite, checkError", "All the lists are null or empty.");
769
770                         /* The 'sockets' array contains:
771                          *  - READ socket 0-n, null,
772                          *  - WRITE socket 0-n, null,
773                          *  - ERROR socket 0-n, null */
774                         Socket [] sockets = list.ToArray ();
775
776                         int error;
777                         Select_internal (ref sockets, microSeconds, out error);
778
779                         if (error != 0)
780                                 throw new SocketException (error);
781
782                         if (sockets == null) {
783                                 if (checkRead != null)
784                                         checkRead.Clear ();
785                                 if (checkWrite != null)
786                                         checkWrite.Clear ();
787                                 if (checkError != null)
788                                         checkError.Clear ();
789                                 return;
790                         }
791
792                         int mode = 0;
793                         int count = sockets.Length;
794                         IList currentList = checkRead;
795                         int currentIdx = 0;
796                         for (int i = 0; i < count; i++) {
797                                 Socket sock = sockets [i];
798                                 if (sock == null) { // separator
799                                         if (currentList != null) {
800                                                 // Remove non-signaled sockets after the current one
801                                                 int to_remove = currentList.Count - currentIdx;
802                                                 for (int k = 0; k < to_remove; k++)
803                                                         currentList.RemoveAt (currentIdx);
804                                         }
805                                         currentList = (mode == 0) ? checkWrite : checkError;
806                                         currentIdx = 0;
807                                         mode++;
808                                         continue;
809                                 }
810
811                                 if (mode == 1 && currentList == checkWrite && !sock.is_connected) {
812                                         if ((int) sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0)
813                                                 sock.is_connected = true;
814                                 }
815
816                                 /* Remove non-signaled sockets before the current one */
817                                 while (((Socket) currentList [currentIdx]) != sock)
818                                         currentList.RemoveAt (currentIdx);
819
820                                 currentIdx++;
821                         }
822                 }
823
824                 static void AddSockets (List<Socket> sockets, IList list, string name)
825                 {
826                         if (list != null) {
827                                 foreach (Socket sock in list) {
828                                         if (sock == null) // MS throws a NullRef
829                                                 throw new ArgumentNullException ("name", "Contains a null element");
830                                         sockets.Add (sock);
831                                 }
832                         }
833
834                         sockets.Add (null);
835                 }
836
837                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
838                 extern static void Select_internal (ref Socket [] sockets, int microSeconds, out int error);
839
840 #endregion
841
842 #region Poll
843
844                 public bool Poll (int time_us, SelectMode mode)
845                 {
846                         ThrowIfDisposedAndClosed ();
847
848                         if (mode != SelectMode.SelectRead && mode != SelectMode.SelectWrite && mode != SelectMode.SelectError)
849                                 throw new NotSupportedException ("'mode' parameter is not valid.");
850
851                         int error;
852                         bool result = Poll_internal (safe_handle, mode, time_us, out error);
853
854                         if (error != 0)
855                                 throw new SocketException (error);
856
857                         if (mode == SelectMode.SelectWrite && result && !is_connected) {
858                                 /* Update the is_connected state; for non-blocking Connect()
859                                  * this is when we can find out that the connect succeeded. */
860                                 if ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0)
861                                         is_connected = true;
862                         }
863
864                         return result;
865                 }
866
867                 static bool Poll_internal (SafeSocketHandle safeHandle, SelectMode mode, int timeout, out int error)
868                 {
869                         bool release = false;
870                         try {
871                                 safeHandle.DangerousAddRef (ref release);
872                                 return Poll_internal (safeHandle.DangerousGetHandle (), mode, timeout, out error);
873                         } finally {
874                                 if (release)
875                                         safeHandle.DangerousRelease ();
876                         }
877                 }
878
879                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
880                 extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
881
882 #endregion
883
884 #region Accept
885
886                 public Socket Accept()
887                 {
888                         ThrowIfDisposedAndClosed ();
889
890                         int error = 0;
891                         SafeSocketHandle safe_handle = Accept_internal (this.safe_handle, out error, is_blocking);
892
893                         if (error != 0) {
894                                 if (is_closed)
895                                         error = SOCKET_CLOSED_CODE;
896                                 throw new SocketException(error);
897                         }
898
899                         Socket accepted = new Socket (this.AddressFamily, this.SocketType, this.ProtocolType, safe_handle) {
900                                 seed_endpoint = this.seed_endpoint,
901                                 Blocking = this.Blocking,
902                         };
903
904                         return accepted;
905                 }
906
907                 internal void Accept (Socket acceptSocket)
908                 {
909                         ThrowIfDisposedAndClosed ();
910
911                         int error = 0;
912                         SafeSocketHandle safe_handle = Accept_internal (this.safe_handle, out error, is_blocking);
913
914                         if (error != 0) {
915                                 if (is_closed)
916                                         error = SOCKET_CLOSED_CODE;
917                                 throw new SocketException (error);
918                         }
919
920                         acceptSocket.address_family = this.AddressFamily;
921                         acceptSocket.socket_type = this.SocketType;
922                         acceptSocket.protocol_type = this.ProtocolType;
923                         acceptSocket.safe_handle = safe_handle;
924                         acceptSocket.is_connected = true;
925                         acceptSocket.seed_endpoint = this.seed_endpoint;
926                         acceptSocket.Blocking = this.Blocking;
927
928                         // FIXME: figure out what if anything else needs to be reset
929                 }
930
931                 public bool AcceptAsync (SocketAsyncEventArgs e)
932                 {
933                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
934
935                         ThrowIfDisposedAndClosed ();
936
937                         if (!is_bound)
938                                 throw new InvalidOperationException ("You must call the Bind method before performing this operation.");
939                         if (!is_listening)
940                                 throw new InvalidOperationException ("You must call the Listen method before performing this operation.");
941                         if (e.BufferList != null)
942                                 throw new ArgumentException ("Multiple buffers cannot be used with this method.");
943                         if (e.Count < 0)
944                                 throw new ArgumentOutOfRangeException ("e.Count");
945
946                         Socket acceptSocket = e.AcceptSocket;
947                         if (acceptSocket != null) {
948                                 if (acceptSocket.is_bound || acceptSocket.is_connected)
949                                         throw new InvalidOperationException ("AcceptSocket: The socket must not be bound or connected.");
950                         }
951
952                         InitSocketAsyncEventArgs (e, AcceptAsyncCallback, e, SocketOperation.Accept);
953
954                         QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, e.socket_async_result));
955
956                         return true;
957                 }
958
959                 static AsyncCallback AcceptAsyncCallback = new AsyncCallback (ares => {
960                         SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
961
962                         if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
963                                 throw new InvalidOperationException ("No operation in progress");
964
965                         try {
966                                 e.AcceptSocket = e.current_socket.EndAccept (ares);
967                         } catch (SocketException ex) {
968                                 e.SocketError = ex.SocketErrorCode;
969                         } catch (ObjectDisposedException) {
970                                 e.SocketError = SocketError.OperationAborted;
971                         } finally {
972                                 if (e.AcceptSocket == null)
973                                         e.AcceptSocket = new Socket (e.current_socket.AddressFamily, e.current_socket.SocketType, e.current_socket.ProtocolType, null);
974                                 e.Complete ();
975                         }
976                 });
977
978                 public IAsyncResult BeginAccept(AsyncCallback callback, object state)
979                 {
980                         ThrowIfDisposedAndClosed ();
981
982                         if (!is_bound || !is_listening)
983                                 throw new InvalidOperationException ();
984
985                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Accept);
986
987                         QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, sockares));
988
989                         return sockares;
990                 }
991
992                 static IOAsyncCallback BeginAcceptCallback = new IOAsyncCallback (ares => {
993                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
994                         Socket socket = null;
995
996                         try {
997                                 socket = sockares.socket.Accept ();
998                         } catch (Exception e) {
999                                 sockares.Complete (e);
1000                                 return;
1001                         }
1002
1003                         sockares.Complete (socket);
1004                 });
1005
1006                 public IAsyncResult BeginAccept (int receiveSize, AsyncCallback callback, object state)
1007                 {
1008                         ThrowIfDisposedAndClosed ();
1009
1010                         if (receiveSize < 0)
1011                                 throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
1012
1013                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.AcceptReceive) {
1014                                 Buffer = new byte [receiveSize],
1015                                 Offset = 0,
1016                                 Size = receiveSize,
1017                                 SockFlags = SocketFlags.None,
1018                         };
1019
1020                         QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptReceiveCallback, sockares));
1021
1022                         return sockares;
1023                 }
1024
1025                 public IAsyncResult BeginAccept (Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
1026                 {
1027                         ThrowIfDisposedAndClosed ();
1028
1029                         if (receiveSize < 0)
1030                                 throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
1031
1032                         if (acceptSocket != null) {
1033                                 ThrowIfDisposedAndClosed (acceptSocket);
1034
1035                                 if (acceptSocket.IsBound)
1036                                         throw new InvalidOperationException ();
1037
1038                                 /* For some reason the MS runtime
1039                                  * barfs if the new socket is not TCP,
1040                                  * even though it's just about to blow
1041                                  * away all those parameters
1042                                  */
1043                                 if (acceptSocket.ProtocolType != ProtocolType.Tcp)
1044                                         throw new SocketException ((int)SocketError.InvalidArgument);
1045                         }
1046
1047                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.AcceptReceive) {
1048                                 Buffer = new byte [receiveSize],
1049                                 Offset = 0,
1050                                 Size = receiveSize,
1051                                 SockFlags = SocketFlags.None,
1052                                 AcceptSocket = acceptSocket,
1053                         };
1054
1055                         QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptReceiveCallback, sockares));
1056
1057                         return sockares;
1058                 }
1059
1060                 static IOAsyncCallback BeginAcceptReceiveCallback = new IOAsyncCallback (ares => {
1061                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
1062                         Socket acc_socket = null;
1063
1064                         try {
1065                                 if (sockares.AcceptSocket == null) {
1066                                         acc_socket = sockares.socket.Accept ();
1067                                 } else {
1068                                         acc_socket = sockares.AcceptSocket;
1069                                         sockares.socket.Accept (acc_socket);
1070                                 }
1071                         } catch (Exception e) {
1072                                 sockares.Complete (e);
1073                                 return;
1074                         }
1075
1076                         /* It seems the MS runtime special-cases 0-length requested receive data.  See bug 464201. */
1077                         int total = 0;
1078                         if (sockares.Size > 0) {
1079                                 try {
1080                                         SocketError error;
1081                                         total = acc_socket.Receive_nochecks (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out error);
1082                                         if (error != 0) {
1083                                                 sockares.Complete (new SocketException ((int) error));
1084                                                 return;
1085                                         }
1086                                 } catch (Exception e) {
1087                                         sockares.Complete (e);
1088                                         return;
1089                                 }
1090                         }
1091
1092                         sockares.Complete (acc_socket, total);
1093                 });
1094
1095                 public Socket EndAccept (IAsyncResult result)
1096                 {
1097                         int bytes;
1098                         byte[] buffer;
1099                         return EndAccept (out buffer, out bytes, result);
1100                 }
1101
1102                 public Socket EndAccept (out byte[] buffer, IAsyncResult asyncResult)
1103                 {
1104                         int bytes;
1105                         return EndAccept (out buffer, out bytes, asyncResult);
1106                 }
1107
1108                 public Socket EndAccept (out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
1109                 {
1110                         ThrowIfDisposedAndClosed ();
1111
1112                         SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndAccept", "asyncResult");
1113
1114                         if (!sockares.IsCompleted)
1115                                 sockares.AsyncWaitHandle.WaitOne ();
1116
1117                         sockares.CheckIfThrowDelayedException ();
1118
1119                         buffer = sockares.Buffer;
1120                         bytesTransferred = sockares.Total;
1121
1122                         return sockares.AcceptedSocket;
1123                 }
1124
1125                 static SafeSocketHandle Accept_internal (SafeSocketHandle safeHandle, out int error, bool blocking)
1126                 {
1127                         try {
1128                                 safeHandle.RegisterForBlockingSyscall ();
1129                                 var ret = Accept_internal (safeHandle.DangerousGetHandle (), out error, blocking);
1130                                 return new SafeSocketHandle (ret, true);
1131                         } finally {
1132                                 safeHandle.UnRegisterForBlockingSyscall ();
1133                         }
1134                 }
1135
1136                 /* Creates a new system socket, returning the handle */
1137                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1138                 extern static IntPtr Accept_internal (IntPtr sock, out int error, bool blocking);
1139
1140 #endregion
1141
1142 #region Bind
1143
1144                 public void Bind (EndPoint local_end)
1145                 {
1146                         ThrowIfDisposedAndClosed ();
1147
1148                         if (local_end == null)
1149                                 throw new ArgumentNullException("local_end");
1150
1151                         int error;
1152                         Bind_internal (safe_handle, local_end.Serialize(), out error);
1153
1154                         if (error != 0)
1155                                 throw new SocketException (error);
1156                         if (error == 0)
1157                                 is_bound = true;
1158
1159                         seed_endpoint = local_end;
1160                 }
1161
1162                 private static void Bind_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
1163                 {
1164                         bool release = false;
1165                         try {
1166                                 safeHandle.DangerousAddRef (ref release);
1167                                 Bind_internal (safeHandle.DangerousGetHandle (), sa, out error);
1168                         } finally {
1169                                 if (release)
1170                                         safeHandle.DangerousRelease ();
1171                         }
1172                 }
1173
1174                 // Creates a new system socket, returning the handle
1175                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1176                 private extern static void Bind_internal(IntPtr sock, SocketAddress sa, out int error);
1177
1178 #endregion
1179
1180 #region Listen
1181
1182                 public void Listen (int backlog)
1183                 {
1184                         ThrowIfDisposedAndClosed ();
1185
1186                         if (!is_bound)
1187                                 throw new SocketException ((int) SocketError.InvalidArgument);
1188
1189                         int error;
1190                         Listen_internal(safe_handle, backlog, out error);
1191
1192                         if (error != 0)
1193                                 throw new SocketException (error);
1194
1195                         is_listening = true;
1196                 }
1197
1198                 static void Listen_internal (SafeSocketHandle safeHandle, int backlog, out int error)
1199                 {
1200                         bool release = false;
1201                         try {
1202                                 safeHandle.DangerousAddRef (ref release);
1203                                 Listen_internal (safeHandle.DangerousGetHandle (), backlog, out error);
1204                         } finally {
1205                                 if (release)
1206                                         safeHandle.DangerousRelease ();
1207                         }
1208                 }
1209
1210                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1211                 extern static void Listen_internal (IntPtr sock, int backlog, out int error);
1212
1213 #endregion
1214
1215 #region Connect
1216
1217                 public void Connect (IPAddress address, int port)
1218                 {
1219                         Connect (new IPEndPoint (address, port));
1220                 }
1221
1222                 public void Connect (string host, int port)
1223                 {
1224                         Connect (Dns.GetHostAddresses (host), port);
1225                 }
1226
1227                 public void Connect (IPAddress[] addresses, int port)
1228                 {
1229                         ThrowIfDisposedAndClosed ();
1230
1231                         if (addresses == null)
1232                                 throw new ArgumentNullException ("addresses");
1233                         if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
1234                                 throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
1235                         if (is_listening)
1236                                 throw new InvalidOperationException ();
1237
1238                         // FIXME: do non-blocking sockets Poll here?
1239                         int error = 0;
1240                         foreach (IPAddress address in addresses) {
1241                                 IPEndPoint iep = new IPEndPoint (address, port);
1242
1243                                 Connect_internal (safe_handle, iep.Serialize (), out error);
1244                                 if (error == 0) {
1245                                         is_connected = true;
1246                                         is_bound = true;
1247                                         seed_endpoint = iep;
1248                                         return;
1249                                 }
1250                                 if (error != (int)SocketError.InProgress && error != (int)SocketError.WouldBlock)
1251                                         continue;
1252
1253                                 if (!is_blocking) {
1254                                         Poll (-1, SelectMode.SelectWrite);
1255                                         error = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
1256                                         if (error == 0) {
1257                                                 is_connected = true;
1258                                                 is_bound = true;
1259                                                 seed_endpoint = iep;
1260                                                 return;
1261                                         }
1262                                 }
1263                         }
1264
1265                         if (error != 0)
1266                                 throw new SocketException (error);
1267                 }
1268
1269
1270                 public void Connect (EndPoint remoteEP)
1271                 {
1272                         ThrowIfDisposedAndClosed ();
1273
1274                         if (remoteEP == null)
1275                                 throw new ArgumentNullException ("remoteEP");
1276
1277                         IPEndPoint ep = remoteEP as IPEndPoint;
1278                         /* Dgram uses Any to 'disconnect' */
1279                         if (ep != null && socket_type != SocketType.Dgram) {
1280                                 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
1281                                         throw new SocketException ((int) SocketError.AddressNotAvailable);
1282                         }
1283
1284                         if (is_listening)
1285                                 throw new InvalidOperationException ();
1286
1287                         SocketAddress serial = remoteEP.Serialize ();
1288
1289                         int error = 0;
1290                         Connect_internal (safe_handle, serial, out error);
1291
1292                         if (error == 0 || error == 10035)
1293                                 seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
1294
1295                         if (error != 0) {
1296                                 if (is_closed)
1297                                         error = SOCKET_CLOSED_CODE;
1298                                 throw new SocketException (error);
1299                         }
1300
1301                         is_connected = !(socket_type == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)));
1302                         is_bound = true;
1303                 }
1304
1305                 public bool ConnectAsync (SocketAsyncEventArgs e)
1306                 {
1307                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1308
1309                         ThrowIfDisposedAndClosed ();
1310
1311                         if (is_listening)
1312                                 throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
1313                         if (e.RemoteEndPoint == null)
1314                                 throw new ArgumentNullException ("remoteEP");
1315
1316                         InitSocketAsyncEventArgs (e, ConnectAsyncCallback, e, SocketOperation.Connect);
1317
1318                         try {
1319                                 IPAddress [] addresses;
1320                                 SocketAsyncResult ares;
1321
1322                                 if (!GetCheckedIPs (e, out addresses)) {
1323                                         e.socket_async_result.EndPoint = e.RemoteEndPoint;
1324                                         ares = (SocketAsyncResult) BeginConnect (e.RemoteEndPoint, ConnectAsyncCallback, e);
1325                                 } else {
1326                                         DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1327                                         e.socket_async_result.Addresses = addresses;
1328                                         e.socket_async_result.Port = dep.Port;
1329                                         ares = (SocketAsyncResult) BeginConnect (addresses, dep.Port, ConnectAsyncCallback, e);
1330                                 }
1331
1332                                 if (ares.IsCompleted && ares.CompletedSynchronously) {
1333                                         ares.CheckIfThrowDelayedException ();
1334                                         return false;
1335                                 }
1336                         } catch (Exception exc) {
1337                                 e.socket_async_result.Complete (exc, true);
1338                                 return false;
1339                         }
1340
1341                         return true;
1342                 }
1343
1344                 static AsyncCallback ConnectAsyncCallback = new AsyncCallback (ares => {
1345                         SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
1346
1347                         if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
1348                                 throw new InvalidOperationException ("No operation in progress");
1349
1350                         try {
1351                                 e.current_socket.EndConnect (ares);
1352                         } catch (SocketException se) {
1353                                 e.SocketError = se.SocketErrorCode;
1354                         } catch (ObjectDisposedException) {
1355                                 e.SocketError = SocketError.OperationAborted;
1356                         } finally {
1357                                 e.Complete ();
1358                         }
1359                 });
1360
1361                 public IAsyncResult BeginConnect (IPAddress address, int port, AsyncCallback callback, object state)
1362                 {
1363                         ThrowIfDisposedAndClosed ();
1364
1365                         if (address == null)
1366                                 throw new ArgumentNullException ("address");
1367                         if (address.ToString ().Length == 0)
1368                                 throw new ArgumentException ("The length of the IP address is zero");
1369                         if (port <= 0 || port > 65535)
1370                                 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1371                         if (is_listening)
1372                                 throw new InvalidOperationException ();
1373
1374                         return BeginConnect (new IPEndPoint (address, port), callback, state);
1375                 }
1376
1377                 public IAsyncResult BeginConnect (string host, int port, AsyncCallback callback, object state)
1378                 {
1379                         ThrowIfDisposedAndClosed ();
1380
1381                         if (host == null)
1382                                 throw new ArgumentNullException ("host");
1383                         if (address_family != AddressFamily.InterNetwork && address_family != AddressFamily.InterNetworkV6)
1384                                 throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
1385                         if (port <= 0 || port > 65535)
1386                                 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1387                         if (is_listening)
1388                                 throw new InvalidOperationException ();
1389
1390                         return BeginConnect (Dns.GetHostAddresses (host), port, callback, state);
1391                 }
1392
1393                 public IAsyncResult BeginConnect (EndPoint end_point, AsyncCallback callback, object state)
1394                 {
1395                         ThrowIfDisposedAndClosed ();
1396
1397                         if (end_point == null)
1398                                 throw new ArgumentNullException ("end_point");
1399
1400                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
1401                                 EndPoint = end_point,
1402                         };
1403
1404                         // Bug #75154: Connect() should not succeed for .Any addresses.
1405                         if (end_point is IPEndPoint) {
1406                                 IPEndPoint ep = (IPEndPoint) end_point;
1407                                 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
1408                                         sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
1409                                         return sockares;
1410                                 }
1411                         }
1412
1413                         int error = 0;
1414
1415                         if (connect_in_progress) {
1416                                 // This could happen when multiple IPs are used
1417                                 // Calling connect() again will reset the connection attempt and cause
1418                                 // an error. Better to just close the socket and move on.
1419                                 connect_in_progress = false;
1420                                 safe_handle.Dispose ();
1421                                 safe_handle = new SafeSocketHandle (Socket_internal (address_family, socket_type, protocol_type, out error), true);
1422                                 if (error != 0)
1423                                         throw new SocketException (error);
1424                         }
1425
1426                         bool blk = is_blocking;
1427                         if (blk)
1428                                 Blocking = false;
1429                         Connect_internal (safe_handle, end_point.Serialize (), out error);
1430                         if (blk)
1431                                 Blocking = true;
1432
1433                         if (error == 0) {
1434                                 // succeeded synch
1435                                 is_connected = true;
1436                                 is_bound = true;
1437                                 sockares.Complete (true);
1438                                 return sockares;
1439                         }
1440
1441                         if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
1442                                 // error synch
1443                                 is_connected = false;
1444                                 is_bound = false;
1445                                 sockares.Complete (new SocketException (error), true);
1446                                 return sockares;
1447                         }
1448
1449                         // continue asynch
1450                         is_connected = false;
1451                         is_bound = false;
1452                         connect_in_progress = true;
1453
1454                         IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginConnectCallback, sockares));
1455
1456                         return sockares;
1457                 }
1458
1459                 public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
1460                 {
1461                         ThrowIfDisposedAndClosed ();
1462
1463                         if (addresses == null)
1464                                 throw new ArgumentNullException ("addresses");
1465                         if (addresses.Length == 0)
1466                                 throw new ArgumentException ("Empty addresses list");
1467                         if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
1468                                 throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
1469                         if (port <= 0 || port > 65535)
1470                                 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1471                         if (is_listening)
1472                                 throw new InvalidOperationException ();
1473
1474                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
1475                                 Addresses = addresses,
1476                                 Port = port,
1477                         };
1478
1479                         is_connected = false;
1480
1481                         return BeginMConnect (sockares);
1482                 }
1483
1484                 internal IAsyncResult BeginMConnect (SocketAsyncResult sockares)
1485                 {
1486                         SocketAsyncResult ares = null;
1487                         Exception exc = null;
1488                         AsyncCallback callback;
1489
1490                         for (int i = sockares.CurrentAddress; i < sockares.Addresses.Length; i++) {
1491                                 try {
1492                                         sockares.CurrentAddress++;
1493
1494                                         ares = (SocketAsyncResult) BeginConnect (new IPEndPoint (sockares.Addresses [i], sockares.Port), null, sockares);
1495                                         if (ares.IsCompleted && ares.CompletedSynchronously) {
1496                                                 ares.CheckIfThrowDelayedException ();
1497
1498                                                 callback = ares.AsyncCallback;
1499                                                 if (callback != null)
1500                                                         ThreadPool.UnsafeQueueUserWorkItem (_ => callback (ares), null);
1501                                         }
1502
1503                                         break;
1504                                 } catch (Exception e) {
1505                                         exc = e;
1506                                         ares = null;
1507                                 }
1508                         }
1509
1510                         if (ares == null)
1511                                 throw exc;
1512
1513                         return sockares;
1514                 }
1515
1516                 static IOAsyncCallback BeginConnectCallback = new IOAsyncCallback (ares => {
1517                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
1518
1519                         if (sockares.EndPoint == null) {
1520                                 sockares.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
1521                                 return;
1522                         }
1523
1524                         SocketAsyncResult mconnect = sockares.AsyncState as SocketAsyncResult;
1525                         bool is_mconnect = mconnect != null && mconnect.Addresses != null;
1526
1527                         try {
1528                                 EndPoint ep = sockares.EndPoint;
1529                                 int error_code = (int) sockares.socket.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
1530
1531                                 if (error_code == 0) {
1532                                         if (is_mconnect)
1533                                                 sockares = mconnect;
1534
1535                                         sockares.socket.seed_endpoint = ep;
1536                                         sockares.socket.is_connected = true;
1537                                         sockares.socket.is_bound = true;
1538                                         sockares.socket.connect_in_progress = false;
1539                                         sockares.error = 0;
1540                                         sockares.Complete ();
1541                                         return;
1542                                 }
1543
1544                                 if (!is_mconnect) {
1545                                         sockares.socket.connect_in_progress = false;
1546                                         sockares.Complete (new SocketException (error_code));
1547                                         return;
1548                                 }
1549
1550                                 if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
1551                                         mconnect.Complete (new SocketException (error_code));
1552                                         return;
1553                                 }
1554
1555                                 mconnect.socket.BeginMConnect (mconnect);
1556                         } catch (Exception e) {
1557                                 sockares.socket.connect_in_progress = false;
1558
1559                                 if (is_mconnect)
1560                                         sockares = mconnect;
1561
1562                                 sockares.Complete (e);
1563                                 return;
1564                         }
1565                 });
1566
1567                 public void EndConnect (IAsyncResult result)
1568                 {
1569                         ThrowIfDisposedAndClosed ();
1570
1571                         SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndConnect", "result");
1572
1573                         if (!sockares.IsCompleted)
1574                                 sockares.AsyncWaitHandle.WaitOne();
1575
1576                         sockares.CheckIfThrowDelayedException();
1577                 }
1578
1579                 static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
1580                 {
1581                         try {
1582                                 safeHandle.RegisterForBlockingSyscall ();
1583                                 Connect_internal (safeHandle.DangerousGetHandle (), sa, out error);
1584                         } finally {
1585                                 safeHandle.UnRegisterForBlockingSyscall ();
1586                         }
1587                 }
1588
1589                 /* Connects to the remote address */
1590                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1591                 extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error);
1592
1593                 /* Returns :
1594                  *  - false when it is ok to use RemoteEndPoint
1595                  *  - true when addresses must be used (and addresses could be null/empty) */
1596                 bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
1597                 {
1598                         addresses = null;
1599
1600                         // Connect to the first address that match the host name, like:
1601                         // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
1602                         // while skipping entries that do not match the address family
1603                         DnsEndPoint dep = e.RemoteEndPoint as DnsEndPoint;
1604                         if (dep != null) {
1605                                 addresses = Dns.GetHostAddresses (dep.Host);
1606                                 return true;
1607                         } else {
1608                                 e.ConnectByNameError = null;
1609                                 return false;
1610                         }
1611                 }
1612
1613 #endregion
1614
1615 #region Disconnect
1616
1617                 /* According to the docs, the MS runtime will throw PlatformNotSupportedException
1618                  * if the platform is newer than w2k.  We should be able to cope... */
1619                 public void Disconnect (bool reuseSocket)
1620                 {
1621                         ThrowIfDisposedAndClosed ();
1622
1623                         int error = 0;
1624                         Disconnect_internal (safe_handle, reuseSocket, out error);
1625
1626                         if (error != 0) {
1627                                 if (error == 50) {
1628                                         /* ERROR_NOT_SUPPORTED */
1629                                         throw new PlatformNotSupportedException ();
1630                                 } else {
1631                                         throw new SocketException (error);
1632                                 }
1633                         }
1634
1635                         is_connected = false;
1636                         if (reuseSocket) {
1637                                 /* Do managed housekeeping here... */
1638                         }
1639                 }
1640
1641                 public bool DisconnectAsync (SocketAsyncEventArgs e)
1642                 {
1643                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1644
1645                         ThrowIfDisposedAndClosed ();
1646
1647                         InitSocketAsyncEventArgs (e, DisconnectAsyncCallback, e, SocketOperation.Disconnect);
1648
1649                         IOSelector.Add (e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, e.socket_async_result));
1650
1651                         return true;
1652                 }
1653
1654                 static AsyncCallback DisconnectAsyncCallback = new AsyncCallback (ares => {
1655                         SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
1656
1657                         if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
1658                                 throw new InvalidOperationException ("No operation in progress");
1659
1660                         try {
1661                                 e.current_socket.EndDisconnect (ares);
1662                         } catch (SocketException ex) {
1663                                 e.SocketError = ex.SocketErrorCode;
1664                         } catch (ObjectDisposedException) {
1665                                 e.SocketError = SocketError.OperationAborted;
1666                         } finally {
1667                                 e.Complete ();
1668                         }
1669                 });
1670
1671                 public IAsyncResult BeginDisconnect (bool reuseSocket, AsyncCallback callback, object state)
1672                 {
1673                         ThrowIfDisposedAndClosed ();
1674
1675                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Disconnect) {
1676                                 ReuseSocket = reuseSocket,
1677                         };
1678
1679                         IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, sockares));
1680
1681                         return sockares;
1682                 }
1683
1684                 static IOAsyncCallback BeginDisconnectCallback = new IOAsyncCallback (ares => {
1685                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
1686
1687                         try {
1688                                 sockares.socket.Disconnect (sockares.ReuseSocket);
1689                         } catch (Exception e) {
1690                                 sockares.Complete (e);
1691                                 return;
1692                         }
1693
1694                         sockares.Complete ();
1695                 });
1696
1697                 public void EndDisconnect (IAsyncResult asyncResult)
1698                 {
1699                         ThrowIfDisposedAndClosed ();
1700
1701                         SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndDisconnect", "asyncResult");
1702
1703                         if (!sockares.IsCompleted)
1704                                 sockares.AsyncWaitHandle.WaitOne ();
1705
1706                         sockares.CheckIfThrowDelayedException ();
1707                 }
1708
1709                 static void Disconnect_internal (SafeSocketHandle safeHandle, bool reuse, out int error)
1710                 {
1711                         bool release = false;
1712                         try {
1713                                 safeHandle.DangerousAddRef (ref release);
1714                                 Disconnect_internal (safeHandle.DangerousGetHandle (), reuse, out error);
1715                         } finally {
1716                                 if (release)
1717                                         safeHandle.DangerousRelease ();
1718                         }
1719                 }
1720
1721                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1722                 extern static void Disconnect_internal (IntPtr sock, bool reuse, out int error);
1723
1724 #endregion
1725
1726 #region Receive
1727
1728                 public int Receive (byte [] buffer)
1729                 {
1730                         return Receive (buffer, SocketFlags.None);
1731                 }
1732
1733                 public int Receive (byte [] buffer, SocketFlags flags)
1734                 {
1735                         ThrowIfDisposedAndClosed ();
1736                         ThrowIfBufferNull (buffer);
1737                         ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
1738
1739                         SocketError error;
1740                         int ret = Receive_nochecks (buffer, 0, buffer.Length, flags, out error);
1741
1742                         if (error != SocketError.Success) {
1743                                 if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
1744                                         throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
1745                                 throw new SocketException ((int) error);
1746                         }
1747
1748                         return ret;
1749                 }
1750
1751                 public int Receive (byte [] buffer, int size, SocketFlags flags)
1752                 {
1753                         ThrowIfDisposedAndClosed ();
1754                         ThrowIfBufferNull (buffer);
1755                         ThrowIfBufferOutOfRange (buffer, 0, size);
1756
1757                         SocketError error;
1758                         int ret = Receive_nochecks (buffer, 0, size, flags, out error);
1759
1760                         if (error != SocketError.Success) {
1761                                 if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
1762                                         throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
1763                                 throw new SocketException ((int) error);
1764                         }
1765
1766                         return ret;
1767                 }
1768
1769                 public int Receive (byte [] buffer, int offset, int size, SocketFlags flags)
1770                 {
1771                         ThrowIfDisposedAndClosed ();
1772                         ThrowIfBufferNull (buffer);
1773                         ThrowIfBufferOutOfRange (buffer, offset, size);
1774
1775                         SocketError error;
1776                         int ret = Receive_nochecks (buffer, offset, size, flags, out error);
1777
1778                         if (error != SocketError.Success) {
1779                                 if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
1780                                         throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
1781                                 throw new SocketException ((int) error);
1782                         }
1783
1784                         return ret;
1785                 }
1786
1787                 public int Receive (byte [] buffer, int offset, int size, SocketFlags flags, out SocketError error)
1788                 {
1789                         ThrowIfDisposedAndClosed ();
1790                         ThrowIfBufferNull (buffer);
1791                         ThrowIfBufferOutOfRange (buffer, offset, size);
1792
1793                         return Receive_nochecks (buffer, offset, size, flags, out error);
1794                 }
1795
1796                 public int Receive (IList<ArraySegment<byte>> buffers)
1797                 {
1798                         SocketError error;
1799                         int ret = Receive (buffers, SocketFlags.None, out error);
1800
1801                         if (error != SocketError.Success)
1802                                 throw new SocketException ((int) error);
1803
1804                         return ret;
1805                 }
1806
1807                 [CLSCompliant (false)]
1808                 public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1809                 {
1810                         SocketError error;
1811                         int ret = Receive (buffers, socketFlags, out error);
1812
1813                         if (error != SocketError.Success)
1814                                 throw new SocketException ((int) error);
1815
1816                         return(ret);
1817                 }
1818
1819                 [CLSCompliant (false)]
1820                 public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1821                 {
1822                         ThrowIfDisposedAndClosed ();
1823
1824                         if (buffers == null || buffers.Count == 0)
1825                                 throw new ArgumentNullException ("buffers");
1826
1827                         int numsegments = buffers.Count;
1828                         int nativeError;
1829                         int ret;
1830
1831                         /* Only example I can find of sending a byte array reference directly into an internal
1832                          * call is in System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
1833                          * so taking a lead from that... */
1834                         WSABUF[] bufarray = new WSABUF[numsegments];
1835                         GCHandle[] gch = new GCHandle[numsegments];
1836
1837                         for (int i = 0; i < numsegments; i++) {
1838                                 ArraySegment<byte> segment = buffers[i];
1839
1840                                 if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
1841                                         throw new ArgumentOutOfRangeException ("segment");
1842
1843                                 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1844                                 bufarray[i].len = segment.Count;
1845                                 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1846                         }
1847
1848                         try {
1849                                 ret = Receive_internal (safe_handle, bufarray, socketFlags, out nativeError);
1850                         } finally {
1851                                 for (int i = 0; i < numsegments; i++) {
1852                                         if (gch[i].IsAllocated)
1853                                                 gch[i].Free ();
1854                                 }
1855                         }
1856
1857                         errorCode = (SocketError) nativeError;
1858
1859                         return ret;
1860                 }
1861
1862                 public bool ReceiveAsync (SocketAsyncEventArgs e)
1863                 {
1864                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1865
1866                         ThrowIfDisposedAndClosed ();
1867
1868                         // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
1869                         // thrown when e.Buffer and e.BufferList are null (works fine when one is
1870                         // set to a valid object)
1871                         if (e.Buffer == null && e.BufferList == null)
1872                                 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1873
1874                         if (e.Buffer == null) {
1875                                 InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.ReceiveGeneric);
1876
1877                                 e.socket_async_result.Buffers = e.BufferList;
1878
1879                                 QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, e.socket_async_result));
1880                         } else {
1881                                 InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.Receive);
1882
1883                                 e.socket_async_result.Buffer = e.Buffer;
1884                                 e.socket_async_result.Offset = e.Offset;
1885                                 e.socket_async_result.Size = e.Count;
1886
1887                                 QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, e.socket_async_result));
1888                         }
1889
1890                         return true;
1891                 }
1892
1893                 static AsyncCallback ReceiveAsyncCallback = new AsyncCallback (ares => {
1894                         SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
1895
1896                         if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
1897                                 throw new InvalidOperationException ("No operation in progress");
1898
1899                         try {
1900                                 e.BytesTransferred = e.current_socket.EndReceive (ares);
1901                         } catch (SocketException se){
1902                                 e.SocketError = se.SocketErrorCode;
1903                         } catch (ObjectDisposedException) {
1904                                 e.SocketError = SocketError.OperationAborted;
1905                         } finally {
1906                                 e.Complete ();
1907                         }
1908                 });
1909
1910                 public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags socket_flags, AsyncCallback callback, object state)
1911                 {
1912                         ThrowIfDisposedAndClosed ();
1913                         ThrowIfBufferNull (buffer);
1914                         ThrowIfBufferOutOfRange (buffer, offset, size);
1915
1916                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Receive) {
1917                                 Buffer = buffer,
1918                                 Offset = offset,
1919                                 Size = size,
1920                                 SockFlags = socket_flags,
1921                         };
1922
1923                         QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, sockares));
1924
1925                         return sockares;
1926                 }
1927
1928                 public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags flags, out SocketError error, AsyncCallback callback, object state)
1929                 {
1930                         /* As far as I can tell from the docs and from experimentation, a pointer to the
1931                          * SocketError parameter is not supposed to be saved for the async parts.  And as we don't
1932                          * set any socket errors in the setup code, we just have to set it to Success. */
1933                         error = SocketError.Success;
1934                         return BeginReceive (buffer, offset, size, flags, callback, state);
1935                 }
1936
1937                 static IOAsyncCallback BeginReceiveCallback = new IOAsyncCallback (ares => {
1938                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
1939                         int total = 0;
1940
1941                         try {
1942                                 total = Receive_internal (sockares.socket.safe_handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
1943                         } catch (Exception e) {
1944                                 sockares.Complete (e);
1945                                 return;
1946                         }
1947
1948                         sockares.Complete (total);
1949                 });
1950
1951                 [CLSCompliant (false)]
1952                 public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
1953                 {
1954                         ThrowIfDisposedAndClosed ();
1955
1956                         if (buffers == null)
1957                                 throw new ArgumentNullException ("buffers");
1958
1959                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveGeneric) {
1960                                 Buffers = buffers,
1961                                 SockFlags = socketFlags,
1962                         };
1963
1964                         QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, sockares));
1965
1966                         return sockares;
1967                 }
1968
1969                 [CLSCompliant (false)]
1970                 public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
1971                 {
1972                         /* I assume the same SocketError semantics as above */
1973                         errorCode = SocketError.Success;
1974                         return BeginReceive (buffers, socketFlags, callback, state);
1975                 }
1976
1977                 static IOAsyncCallback BeginReceiveGenericCallback = new IOAsyncCallback (ares => {
1978                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
1979                         int total = 0;
1980
1981                         try {
1982                                 total = sockares.socket.Receive (sockares.Buffers, sockares.SockFlags);
1983                         } catch (Exception e) {
1984                                 sockares.Complete (e);
1985                                 return;
1986                         }
1987
1988                         sockares.Complete (total);
1989                 });
1990
1991                 public int EndReceive (IAsyncResult result)
1992                 {
1993                         SocketError error;
1994                         int bytesReceived = EndReceive (result, out error);
1995
1996                         if (error != SocketError.Success) {
1997                                 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1998                                         is_connected = false;
1999                                 throw new SocketException ((int)error);
2000                         }
2001
2002                         return bytesReceived;
2003                 }
2004
2005                 public int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
2006                 {
2007                         ThrowIfDisposedAndClosed ();
2008
2009                         SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceive", "asyncResult");
2010
2011                         if (!sockares.IsCompleted)
2012                                 sockares.AsyncWaitHandle.WaitOne ();
2013
2014                         // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
2015                         // kinds of exceptions that should be thrown.
2016                         if ((errorCode = sockares.ErrorCode) == SocketError.Success)
2017                                 sockares.CheckIfThrowDelayedException();
2018
2019                         return sockares.Total;
2020                 }
2021
2022                 int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
2023                 {
2024                         int nativeError;
2025                         int ret = Receive_internal (safe_handle, buf, offset, size, flags, out nativeError);
2026
2027                         error = (SocketError) nativeError;
2028                         if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
2029                                 is_connected = false;
2030                                 is_bound = false;
2031                         } else {
2032                                 is_connected = true;
2033                         }
2034
2035                         return ret;
2036                 }
2037
2038                 static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
2039                 {
2040                         try {
2041                                 safeHandle.RegisterForBlockingSyscall ();
2042                                 return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
2043                         } finally {
2044                                 safeHandle.UnRegisterForBlockingSyscall ();
2045                         }
2046                 }
2047
2048                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
2049                 extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
2050
2051                 static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error)
2052                 {
2053                         try {
2054                                 safeHandle.RegisterForBlockingSyscall ();
2055                                 return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error);
2056                         } finally {
2057                                 safeHandle.UnRegisterForBlockingSyscall ();
2058                         }
2059                 }
2060
2061                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2062                 extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error);
2063
2064 #endregion
2065
2066 #region ReceiveFrom
2067
2068                 public int ReceiveFrom (byte [] buffer, ref EndPoint remoteEP)
2069                 {
2070                         ThrowIfDisposedAndClosed ();
2071                         ThrowIfBufferNull (buffer);
2072
2073                         return ReceiveFrom (buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP);
2074                 }
2075
2076                 public int ReceiveFrom (byte [] buffer, SocketFlags flags, ref EndPoint remoteEP)
2077                 {
2078                         ThrowIfDisposedAndClosed ();
2079                         ThrowIfBufferNull (buffer);
2080
2081                         return ReceiveFrom (buffer, 0, buffer.Length, flags, ref remoteEP);
2082                 }
2083
2084                 public int ReceiveFrom (byte [] buffer, int size, SocketFlags flags, ref EndPoint remoteEP)
2085                 {
2086                         ThrowIfDisposedAndClosed ();
2087                         ThrowIfBufferNull (buffer);
2088                         ThrowIfBufferOutOfRange (buffer, 0, size);
2089
2090                         return ReceiveFrom (buffer, 0, size, flags, ref remoteEP);
2091                 }
2092
2093                 public int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags flags, ref EndPoint remoteEP)
2094                 {
2095                         ThrowIfDisposedAndClosed ();
2096                         ThrowIfBufferNull (buffer);
2097                         ThrowIfBufferOutOfRange (buffer, offset, size);
2098
2099                         if (remoteEP == null)
2100                                 throw new ArgumentNullException ("remoteEP");
2101
2102                         int error;
2103                         return ReceiveFrom_nochecks_exc (buffer, offset, size, flags, ref remoteEP, true, out error);
2104                 }
2105
2106                 public bool ReceiveFromAsync (SocketAsyncEventArgs e)
2107                 {
2108                         ThrowIfDisposedAndClosed ();
2109
2110                         // We do not support recv into multiple buffers yet
2111                         if (e.BufferList != null)
2112                                 throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
2113                         if (e.RemoteEndPoint == null)
2114                                 throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
2115
2116                         InitSocketAsyncEventArgs (e, ReceiveFromAsyncCallback, e, SocketOperation.ReceiveFrom);
2117
2118                         e.socket_async_result.Buffer = e.Buffer;
2119                         e.socket_async_result.Offset = e.Offset;
2120                         e.socket_async_result.Size = e.Count;
2121                         e.socket_async_result.EndPoint = e.RemoteEndPoint;
2122                         e.socket_async_result.SockFlags = e.SocketFlags;
2123
2124                         QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, e.socket_async_result));
2125
2126                         return true;
2127                 }
2128
2129                 static AsyncCallback ReceiveFromAsyncCallback = new AsyncCallback (ares => {
2130                         SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
2131
2132                         if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
2133                                 throw new InvalidOperationException ("No operation in progress");
2134
2135                         try {
2136                                 e.BytesTransferred = e.current_socket.EndReceiveFrom (ares, ref e.remote_ep);
2137                         } catch (SocketException ex) {
2138                                 e.SocketError = ex.SocketErrorCode;
2139                         } catch (ObjectDisposedException) {
2140                                 e.SocketError = SocketError.OperationAborted;
2141                         } finally {
2142                                 e.Complete ();
2143                         }
2144                 });
2145
2146                 public IAsyncResult BeginReceiveFrom (byte[] buffer, int offset, int size, SocketFlags socket_flags, ref EndPoint remote_end, AsyncCallback callback, object state)
2147                 {
2148                         ThrowIfDisposedAndClosed ();
2149                         ThrowIfBufferNull (buffer);
2150                         ThrowIfBufferOutOfRange (buffer, offset, size);
2151
2152                         if (remote_end == null)
2153                                 throw new ArgumentNullException ("remote_end");
2154
2155                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveFrom) {
2156                                 Buffer = buffer,
2157                                 Offset = offset,
2158                                 Size = size,
2159                                 SockFlags = socket_flags,
2160                                 EndPoint = remote_end,
2161                         };
2162
2163                         QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, sockares));
2164
2165                         return sockares;
2166                 }
2167
2168                 static IOAsyncCallback BeginReceiveFromCallback = new IOAsyncCallback (ares => {
2169                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
2170                         int total = 0;
2171
2172                         try {
2173                                 int error;
2174                                 total = sockares.socket.ReceiveFrom_nochecks_exc (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, ref sockares.EndPoint, true, out error);
2175                         } catch (Exception e) {
2176                                 sockares.Complete (e);
2177                                 return;
2178                         }
2179
2180                         sockares.Complete (total);
2181                 });
2182
2183                 public int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
2184                 {
2185                         ThrowIfDisposedAndClosed ();
2186
2187                         if (end_point == null)
2188                                 throw new ArgumentNullException ("remote_end");
2189
2190                         SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndReceiveFrom", "result");
2191
2192                         if (!sockares.IsCompleted)
2193                                 sockares.AsyncWaitHandle.WaitOne();
2194
2195                         sockares.CheckIfThrowDelayedException();
2196
2197                         end_point = sockares.EndPoint;
2198
2199                         return sockares.Total;
2200                 }
2201
2202                 internal int ReceiveFrom_nochecks_exc (byte [] buf, int offset, int size, SocketFlags flags, ref EndPoint remote_end, bool throwOnError, out int error)
2203                 {
2204                         SocketAddress sockaddr = remote_end.Serialize();
2205
2206                         int cnt = ReceiveFrom_internal (safe_handle, buf, offset, size, flags, ref sockaddr, out error);
2207
2208                         SocketError err = (SocketError) error;
2209                         if (err != 0) {
2210                                 if (err != SocketError.WouldBlock && err != SocketError.InProgress) {
2211                                         is_connected = false;
2212                                 } else if (err == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
2213                                         if (throwOnError)       
2214                                                 throw new SocketException ((int) SocketError.TimedOut, TIMEOUT_EXCEPTION_MSG);
2215                                         error = (int) SocketError.TimedOut;
2216                                         return 0;
2217                                 }
2218
2219                                 if (throwOnError)
2220                                         throw new SocketException (error);
2221
2222                                 return 0;
2223                         }
2224
2225                         is_connected = true;
2226                         is_bound = true;
2227
2228                         /* If sockaddr is null then we're a connection oriented protocol and should ignore the
2229                          * remote_end parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
2230                         if (sockaddr != null) {
2231                                 /* Stupidly, EndPoint.Create() is an instance method */
2232                                 remote_end = remote_end.Create (sockaddr);
2233                         }
2234
2235                         seed_endpoint = remote_end;
2236
2237                         return cnt;
2238                 }
2239
2240                 static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error)
2241                 {
2242                         try {
2243                                 safeHandle.RegisterForBlockingSyscall ();
2244                                 return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error);
2245                         } finally {
2246                                 safeHandle.UnRegisterForBlockingSyscall ();
2247                         }
2248                 }
2249
2250                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2251                 extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error);
2252
2253 #endregion
2254
2255 #region ReceiveMessageFrom
2256
2257                 [MonoTODO ("Not implemented")]
2258                 public int ReceiveMessageFrom (byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
2259                 {
2260                         ThrowIfDisposedAndClosed ();
2261                         ThrowIfBufferNull (buffer);
2262                         ThrowIfBufferOutOfRange (buffer, offset, size);
2263
2264                         if (remoteEP == null)
2265                                 throw new ArgumentNullException ("remoteEP");
2266
2267                         // FIXME: figure out how we get hold of the IPPacketInformation
2268                         throw new NotImplementedException ();
2269                 }
2270
2271                 [MonoTODO ("Not implemented")]
2272                 public bool ReceiveMessageFromAsync (SocketAsyncEventArgs e)
2273                 {
2274                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
2275
2276                         ThrowIfDisposedAndClosed ();
2277
2278                         throw new NotImplementedException ();
2279                 }
2280
2281                 [MonoTODO]
2282                 public IAsyncResult BeginReceiveMessageFrom (byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
2283                 {
2284                         ThrowIfDisposedAndClosed ();
2285                         ThrowIfBufferNull (buffer);
2286                         ThrowIfBufferOutOfRange (buffer, offset, size);
2287
2288                         if (remoteEP == null)
2289                                 throw new ArgumentNullException ("remoteEP");
2290
2291                         throw new NotImplementedException ();
2292                 }
2293
2294                 [MonoTODO]
2295                 public int EndReceiveMessageFrom (IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
2296                 {
2297                         ThrowIfDisposedAndClosed ();
2298
2299                         if (endPoint == null)
2300                                 throw new ArgumentNullException ("endPoint");
2301
2302                         SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceiveMessageFrom", "asyncResult");
2303
2304                         throw new NotImplementedException ();
2305                 }
2306
2307 #endregion
2308
2309 #region Send
2310
2311                 public int Send (byte [] buffer)
2312                 {
2313                         ThrowIfDisposedAndClosed ();
2314                         ThrowIfBufferNull (buffer);
2315                         ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
2316
2317                         SocketError error;
2318                         int ret = Send_nochecks (buffer, 0, buffer.Length, SocketFlags.None, out error);
2319
2320                         if (error != SocketError.Success)
2321                                 throw new SocketException ((int) error);
2322
2323                         return ret;
2324                 }
2325
2326                 public int Send (byte [] buffer, SocketFlags flags)
2327                 {
2328                         ThrowIfDisposedAndClosed ();
2329                         ThrowIfBufferNull (buffer);
2330                         ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
2331
2332                         SocketError error;
2333                         int ret = Send_nochecks (buffer, 0, buffer.Length, flags, out error);
2334
2335                         if (error != SocketError.Success)
2336                                 throw new SocketException ((int) error);
2337
2338                         return ret;
2339                 }
2340
2341                 public int Send (byte [] buffer, int size, SocketFlags flags)
2342                 {
2343                         ThrowIfDisposedAndClosed ();
2344                         ThrowIfBufferNull (buffer);
2345                         ThrowIfBufferOutOfRange (buffer, 0, size);
2346
2347                         SocketError error;
2348                         int ret = Send_nochecks (buffer, 0, size, flags, out error);
2349
2350                         if (error != SocketError.Success)
2351                                 throw new SocketException ((int) error);
2352
2353                         return ret;
2354                 }
2355
2356                 public int Send (byte [] buffer, int offset, int size, SocketFlags flags)
2357                 {
2358                         ThrowIfDisposedAndClosed ();
2359                         ThrowIfBufferNull (buffer);
2360                         ThrowIfBufferOutOfRange (buffer, offset, size);
2361
2362                         SocketError error;
2363                         int ret = Send_nochecks (buffer, offset, size, flags, out error);
2364
2365                         if (error != SocketError.Success)
2366                                 throw new SocketException ((int) error);
2367
2368                         return ret;
2369                 }
2370
2371                 public int Send (byte [] buffer, int offset, int size, SocketFlags flags, out SocketError error)
2372                 {
2373                         ThrowIfDisposedAndClosed ();
2374                         ThrowIfBufferNull (buffer);
2375                         ThrowIfBufferOutOfRange (buffer, offset, size);
2376
2377                         return Send_nochecks (buffer, offset, size, flags, out error);
2378                 }
2379
2380                 public
2381                 int Send (IList<ArraySegment<byte>> buffers)
2382                 {
2383                         SocketError error;
2384                         int ret = Send (buffers, SocketFlags.None, out error);
2385
2386                         if (error != SocketError.Success)
2387                                 throw new SocketException ((int) error);
2388
2389                         return ret;
2390                 }
2391
2392                 public
2393                 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
2394                 {
2395                         SocketError error;
2396                         int ret = Send (buffers, socketFlags, out error);
2397
2398                         if (error != SocketError.Success)
2399                                 throw new SocketException ((int) error);
2400
2401                         return ret;
2402                 }
2403
2404                 [CLSCompliant (false)]
2405                 public int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
2406                 {
2407                         ThrowIfDisposedAndClosed ();
2408
2409                         if (buffers == null)
2410                                 throw new ArgumentNullException ("buffers");
2411                         if (buffers.Count == 0)
2412                                 throw new ArgumentException ("Buffer is empty", "buffers");
2413
2414                         int numsegments = buffers.Count;
2415                         int nativeError;
2416                         int ret;
2417
2418                         WSABUF[] bufarray = new WSABUF[numsegments];
2419                         GCHandle[] gch = new GCHandle[numsegments];
2420
2421                         for(int i = 0; i < numsegments; i++) {
2422                                 ArraySegment<byte> segment = buffers[i];
2423
2424                                 if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
2425                                         throw new ArgumentOutOfRangeException ("segment");
2426
2427                                 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
2428                                 bufarray[i].len = segment.Count;
2429                                 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
2430                         }
2431
2432                         try {
2433                                 ret = Send_internal (safe_handle, bufarray, socketFlags, out nativeError);
2434                         } finally {
2435                                 for(int i = 0; i < numsegments; i++) {
2436                                         if (gch[i].IsAllocated) {
2437                                                 gch[i].Free ();
2438                                         }
2439                                 }
2440                         }
2441
2442                         errorCode = (SocketError)nativeError;
2443
2444                         return ret;
2445                 }
2446
2447                 int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
2448                 {
2449                         if (size == 0) {
2450                                 error = SocketError.Success;
2451                                 return 0;
2452                         }
2453
2454                         int nativeError;
2455                         int ret = Send_internal (safe_handle, buf, offset, size, flags, out nativeError);
2456
2457                         error = (SocketError)nativeError;
2458
2459                         if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
2460                                 is_connected = false;
2461                                 is_bound = false;
2462                         } else {
2463                                 is_connected = true;
2464                         }
2465
2466                         return ret;
2467                 }
2468
2469                 public bool SendAsync (SocketAsyncEventArgs e)
2470                 {
2471                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
2472
2473                         ThrowIfDisposedAndClosed ();
2474
2475                         if (e.Buffer == null && e.BufferList == null)
2476                                 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
2477
2478                         if (e.Buffer == null) {
2479                                 InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.SendGeneric);
2480
2481                                 e.socket_async_result.Buffers = e.BufferList;
2482
2483                                 QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, e.socket_async_result));
2484                         } else {
2485                                 InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.Send);
2486
2487                                 e.socket_async_result.Buffer = e.Buffer;
2488                                 e.socket_async_result.Offset = e.Offset;
2489                                 e.socket_async_result.Size = e.Count;
2490
2491                                 QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
2492                         }
2493
2494                         return true;
2495                 }
2496
2497                 static AsyncCallback SendAsyncCallback = new AsyncCallback (ares => {
2498                         SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
2499
2500                         if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
2501                                 throw new InvalidOperationException ("No operation in progress");
2502
2503                         try {
2504                                 e.BytesTransferred = e.current_socket.EndSend (ares);
2505                         } catch (SocketException se){
2506                                 e.SocketError = se.SocketErrorCode;
2507                         } catch (ObjectDisposedException) {
2508                                 e.SocketError = SocketError.OperationAborted;
2509                         } finally {
2510                                 e.Complete ();
2511                         }
2512                 });
2513
2514                 public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
2515                 {
2516                         if (!is_connected) {
2517                                 errorCode = SocketError.NotConnected;
2518                                 throw new SocketException ((int) errorCode);
2519                         }
2520
2521                         errorCode = SocketError.Success;
2522                         return BeginSend (buffer, offset, size, socketFlags, callback, state);
2523                 }
2524
2525                 public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags, AsyncCallback callback, object state)
2526                 {
2527                         ThrowIfDisposedAndClosed ();
2528                         ThrowIfBufferNull (buffer);
2529                         ThrowIfBufferOutOfRange (buffer, offset, size);
2530
2531                         if (!is_connected)
2532                                 throw new SocketException ((int)SocketError.NotConnected);
2533
2534                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Send) {
2535                                 Buffer = buffer,
2536                                 Offset = offset,
2537                                 Size = size,
2538                                 SockFlags = socket_flags,
2539                         };
2540
2541                         QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), sockares));
2542
2543                         return sockares;
2544                 }
2545
2546                 static void BeginSendCallback (SocketAsyncResult sockares, int sent_so_far)
2547                 {
2548                         int total = 0;
2549
2550                         try {
2551                                 total = Socket.Send_internal (sockares.socket.safe_handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
2552                         } catch (Exception e) {
2553                                 sockares.Complete (e);
2554                                 return;
2555                         }
2556
2557                         if (sockares.error == 0) {
2558                                 sent_so_far += total;
2559                                 sockares.Offset += total;
2560                                 sockares.Size -= total;
2561
2562                                 if (sockares.socket.is_disposed) {
2563                                         sockares.Complete (total);
2564                                         return;
2565                                 }
2566
2567                                 if (sockares.Size > 0) {
2568                                         IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, sent_so_far), sockares));
2569                                         return; // Have to finish writing everything. See bug #74475.
2570                                 }
2571
2572                                 sockares.Total = sent_so_far;
2573                         }
2574
2575                         sockares.Complete (total);
2576                 }
2577
2578                 public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
2579                 {
2580                         ThrowIfDisposedAndClosed ();
2581
2582                         if (buffers == null)
2583                                 throw new ArgumentNullException ("buffers");
2584                         if (!is_connected)
2585                                 throw new SocketException ((int)SocketError.NotConnected);
2586
2587                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendGeneric) {
2588                                 Buffers = buffers,
2589                                 SockFlags = socketFlags,
2590                         };
2591
2592                         QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, sockares));
2593
2594                         return sockares;
2595                 }
2596
2597                 [CLSCompliant (false)]
2598                 public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
2599                 {
2600                         if (!is_connected) {
2601                                 errorCode = SocketError.NotConnected;
2602                                 throw new SocketException ((int)errorCode);
2603                         }
2604
2605                         errorCode = SocketError.Success;
2606                         return BeginSend (buffers, socketFlags, callback, state);
2607                 }
2608
2609                 static IOAsyncCallback BeginSendGenericCallback = new IOAsyncCallback (ares => {
2610                         SocketAsyncResult sockares = (SocketAsyncResult) ares;
2611                         int total = 0;
2612
2613                         try {
2614                                 total = sockares.socket.Send (sockares.Buffers, sockares.SockFlags);
2615                         } catch (Exception e) {
2616                                 sockares.Complete (e);
2617                                 return;
2618                         }
2619
2620                         sockares.Complete (total);
2621                 });
2622
2623                 public int EndSend (IAsyncResult result)
2624                 {
2625                         SocketError error;
2626                         int bytesSent = EndSend (result, out error);
2627
2628                         if (error != SocketError.Success) {
2629                                 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
2630                                         is_connected = false;
2631                                 throw new SocketException ((int)error);
2632                         }
2633
2634                         return bytesSent;
2635                 }
2636
2637                 public int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
2638                 {
2639                         ThrowIfDisposedAndClosed ();
2640
2641                         SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndSend", "asyncResult");
2642
2643                         if (!sockares.IsCompleted)
2644                                 sockares.AsyncWaitHandle.WaitOne ();
2645
2646                         /* If no socket error occurred, call CheckIfThrowDelayedException in
2647                          * case there are other kinds of exceptions that should be thrown.*/
2648                         if ((errorCode = sockares.ErrorCode) == SocketError.Success)
2649                                 sockares.CheckIfThrowDelayedException ();
2650
2651                         return sockares.Total;
2652                 }
2653
2654                 static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
2655                 {
2656                         bool release = false;
2657                         try {
2658                                 safeHandle.DangerousAddRef (ref release);
2659                                 return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
2660                         } finally {
2661                                 if (release)
2662                                         safeHandle.DangerousRelease ();
2663                         }
2664                 }
2665
2666                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
2667                 extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
2668
2669                 static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error)
2670                 {
2671                         try {
2672                                 safeHandle.RegisterForBlockingSyscall ();
2673                                 return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error);
2674                         } finally {
2675                                 safeHandle.UnRegisterForBlockingSyscall ();
2676                         }
2677                 }
2678
2679                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2680                 extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error);
2681
2682 #endregion
2683
2684 #region SendTo
2685
2686                 public int SendTo (byte [] buffer, EndPoint remote_end)
2687                 {
2688                         ThrowIfDisposedAndClosed ();
2689                         ThrowIfBufferNull (buffer);
2690
2691                         return SendTo (buffer, 0, buffer.Length, SocketFlags.None, remote_end);
2692                 }
2693
2694                 public int SendTo (byte [] buffer, SocketFlags flags, EndPoint remote_end)
2695                 {
2696                         ThrowIfDisposedAndClosed ();
2697                         ThrowIfBufferNull (buffer);
2698
2699                         return SendTo (buffer, 0, buffer.Length, flags, remote_end);
2700                 }
2701
2702                 public int SendTo (byte [] buffer, int size, SocketFlags flags, EndPoint remote_end)
2703                 {
2704                         return SendTo (buffer, 0, size, flags, remote_end);
2705                 }
2706
2707                 public int SendTo (byte [] buffer, int offset, int size, SocketFlags flags, EndPoint remote_end)
2708                 {
2709                         ThrowIfDisposedAndClosed ();
2710                         ThrowIfBufferNull (buffer);
2711                         ThrowIfBufferOutOfRange (buffer, offset, size);
2712
2713                         if (remote_end == null)
2714                                 throw new ArgumentNullException("remote_end");
2715
2716                         return SendTo_nochecks (buffer, offset, size, flags, remote_end);
2717                 }
2718
2719                 public bool SendToAsync (SocketAsyncEventArgs e)
2720                 {
2721                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
2722
2723                         ThrowIfDisposedAndClosed ();
2724
2725                         if (e.BufferList != null)
2726                                 throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
2727                         if (e.RemoteEndPoint == null)
2728                                 throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
2729
2730                         InitSocketAsyncEventArgs (e, SendToAsyncCallback, e, SocketOperation.SendTo);
2731
2732                         e.socket_async_result.Buffer = e.Buffer;
2733                         e.socket_async_result.Offset = e.Offset;
2734                         e.socket_async_result.Size = e.Count;
2735                         e.socket_async_result.SockFlags = e.SocketFlags;
2736                         e.socket_async_result.EndPoint = e.RemoteEndPoint;
2737
2738                         QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
2739
2740                         return true;
2741                 }
2742
2743                 static AsyncCallback SendToAsyncCallback = new AsyncCallback (ares => {
2744                         SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
2745
2746                         if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
2747                                 throw new InvalidOperationException ("No operation in progress");
2748
2749                         try {
2750                                 e.BytesTransferred = e.current_socket.EndSendTo (ares);
2751                         } catch (SocketException ex) {
2752                                 e.SocketError = ex.SocketErrorCode;
2753                         } catch (ObjectDisposedException) {
2754                                 e.SocketError = SocketError.OperationAborted;
2755                         } finally {
2756                                 e.Complete ();
2757                         }
2758                 });
2759
2760                 public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socket_flags, EndPoint remote_end, AsyncCallback callback, object state)
2761                 {
2762                         ThrowIfDisposedAndClosed ();
2763                         ThrowIfBufferNull (buffer);
2764                         ThrowIfBufferOutOfRange (buffer, offset, size);
2765
2766                         SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendTo) {
2767                                 Buffer = buffer,
2768                                 Offset = offset,
2769                                 Size = size,
2770                                 SockFlags = socket_flags,
2771                                 EndPoint = remote_end,
2772                         };
2773
2774                         QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), sockares));
2775
2776                         return sockares;
2777                 }
2778
2779                 static void BeginSendToCallback (SocketAsyncResult sockares, int sent_so_far)
2780                 {
2781                         int total = 0;
2782                         try {
2783                                 total = sockares.socket.SendTo_nochecks (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, sockares.EndPoint);
2784
2785                                 if (sockares.error == 0) {
2786                                         sent_so_far += total;
2787                                         sockares.Offset += total;
2788                                         sockares.Size -= total;
2789                                 }
2790
2791                                 if (sockares.Size > 0) {
2792                                         IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, sent_so_far), sockares));
2793                                         return; // Have to finish writing everything. See bug #74475.
2794                                 }
2795
2796                                 sockares.Total = sent_so_far;
2797                         } catch (Exception e) {
2798                                 sockares.Complete (e);
2799                                 return;
2800                         }
2801
2802                         sockares.Complete ();
2803                 }
2804
2805                 public int EndSendTo (IAsyncResult result)
2806                 {
2807                         ThrowIfDisposedAndClosed ();
2808
2809                         SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndSendTo", "result");
2810
2811                         if (!sockares.IsCompleted)
2812                                 sockares.AsyncWaitHandle.WaitOne();
2813
2814                         sockares.CheckIfThrowDelayedException();
2815
2816                         return sockares.Total;
2817                 }
2818
2819                 int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags, EndPoint remote_end)
2820                 {
2821                         int error;
2822                         int ret = SendTo_internal (safe_handle, buffer, offset, size, flags, remote_end.Serialize (), out error);
2823
2824                         SocketError err = (SocketError) error;
2825                         if (err != 0) {
2826                                 if (err != SocketError.WouldBlock && err != SocketError.InProgress)
2827                                         is_connected = false;
2828                                 throw new SocketException (error);
2829                         }
2830
2831                         is_connected = true;
2832                         is_bound = true;
2833                         seed_endpoint = remote_end;
2834
2835                         return ret;
2836                 }
2837
2838                 static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error)
2839                 {
2840                         try {
2841                                 safeHandle.RegisterForBlockingSyscall ();
2842                                 return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error);
2843                         } finally {
2844                                 safeHandle.UnRegisterForBlockingSyscall ();
2845                         }
2846                 }
2847
2848                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2849                 extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error);
2850
2851 #endregion
2852
2853 #region SendFile
2854
2855                 public void SendFile (string fileName)
2856                 {
2857                         ThrowIfDisposedAndClosed ();
2858
2859                         if (!is_connected)
2860                                 throw new NotSupportedException ();
2861                         if (!is_blocking)
2862                                 throw new InvalidOperationException ();
2863
2864                         SendFile (fileName, null, null, 0);
2865                 }
2866
2867                 public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
2868                 {
2869                         ThrowIfDisposedAndClosed ();
2870
2871                         if (!is_connected)
2872                                 throw new NotSupportedException ();
2873                         if (!is_blocking)
2874                                 throw new InvalidOperationException ();
2875
2876                         if (!SendFile_internal (safe_handle, fileName, preBuffer, postBuffer, flags)) {
2877                                 SocketException exc = new SocketException ();
2878                                 if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
2879                                         throw new FileNotFoundException ();
2880                                 throw exc;
2881                         }
2882                 }
2883
2884                 public IAsyncResult BeginSendFile (string fileName, AsyncCallback callback, object state)
2885                 {
2886                         ThrowIfDisposedAndClosed ();
2887
2888                         if (!is_connected)
2889                                 throw new NotSupportedException ();
2890                         if (!File.Exists (fileName))
2891                                 throw new FileNotFoundException ();
2892
2893                         return BeginSendFile (fileName, null, null, 0, callback, state);
2894                 }
2895
2896                 public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
2897                 {
2898                         ThrowIfDisposedAndClosed ();
2899
2900                         if (!is_connected)
2901                                 throw new NotSupportedException ();
2902                         if (!File.Exists (fileName))
2903                                 throw new FileNotFoundException ();
2904
2905                         SendFileHandler handler = new SendFileHandler (SendFile);
2906
2907                         return new SendFileAsyncResult (handler, handler.BeginInvoke (fileName, preBuffer, postBuffer, flags, ar => callback (new SendFileAsyncResult (handler, ar)), state));
2908                 }
2909
2910                 public void EndSendFile (IAsyncResult asyncResult)
2911                 {
2912                         ThrowIfDisposedAndClosed ();
2913
2914                         if (asyncResult == null)
2915                                 throw new ArgumentNullException ("asyncResult");
2916
2917                         SendFileAsyncResult ares = asyncResult as SendFileAsyncResult;
2918                         if (ares == null)
2919                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
2920
2921                         ares.Delegate.EndInvoke (ares.Original);
2922                 }
2923
2924                 static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags)
2925                 {
2926                         try {
2927                                 safeHandle.RegisterForBlockingSyscall ();
2928                                 return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags);
2929                         } finally {
2930                                 safeHandle.UnRegisterForBlockingSyscall ();
2931                         }
2932                 }
2933
2934                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2935                 extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags);
2936
2937                 delegate void SendFileHandler (string fileName, byte [] preBuffer, byte [] postBuffer, TransmitFileOptions flags);
2938
2939                 sealed class SendFileAsyncResult : IAsyncResult {
2940                         IAsyncResult ares;
2941                         SendFileHandler d;
2942
2943                         public SendFileAsyncResult (SendFileHandler d, IAsyncResult ares)
2944                         {
2945                                 this.d = d;
2946                                 this.ares = ares;
2947                         }
2948
2949                         public object AsyncState {
2950                                 get { return ares.AsyncState; }
2951                         }
2952
2953                         public WaitHandle AsyncWaitHandle {
2954                                 get { return ares.AsyncWaitHandle; }
2955                         }
2956
2957                         public bool CompletedSynchronously {
2958                                 get { return ares.CompletedSynchronously; }
2959                         }
2960
2961                         public bool IsCompleted {
2962                                 get { return ares.IsCompleted; }
2963                         }
2964
2965                         public SendFileHandler Delegate {
2966                                 get { return d; }
2967                         }
2968
2969                         public IAsyncResult Original {
2970                                 get { return ares; }
2971                         }
2972                 }
2973
2974 #endregion
2975
2976 #region SendPackets
2977
2978                 [MonoTODO ("Not implemented")]
2979                 public bool SendPacketsAsync (SocketAsyncEventArgs e)
2980                 {
2981                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
2982
2983                         ThrowIfDisposedAndClosed ();
2984
2985                         throw new NotImplementedException ();
2986                 }
2987
2988 #endregion
2989
2990 #region DuplicateAndClose
2991
2992 #if !MOBILE
2993                 [MonoLimitation ("We do not support passing sockets across processes, we merely allow this API to pass the socket across AppDomains")]
2994                 public SocketInformation DuplicateAndClose (int targetProcessId)
2995                 {
2996                         var si = new SocketInformation ();
2997                         si.Options =
2998                                 (is_listening      ? SocketInformationOptions.Listening : 0) |
2999                                 (is_connected      ? SocketInformationOptions.Connected : 0) |
3000                                 (is_blocking       ? 0 : SocketInformationOptions.NonBlocking) |
3001                                 (use_overlapped_io ? SocketInformationOptions.UseOnlyOverlappedIO : 0);
3002
3003                         si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)address_family, (int)socket_type, (int)protocol_type, is_bound ? 1 : 0, (long)Handle);
3004                         safe_handle = null;
3005
3006                         return si;
3007                 }
3008 #endif
3009
3010 #endregion
3011
3012 #region GetSocketOption
3013
3014                 public void GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
3015                 {
3016                         ThrowIfDisposedAndClosed ();
3017
3018                         if (optionValue == null)
3019                                 throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
3020
3021                         int error;
3022                         GetSocketOption_arr_internal (safe_handle, optionLevel, optionName, ref optionValue, out error);
3023
3024                         if (error != 0)
3025                                 throw new SocketException (error);
3026                 }
3027
3028                 public byte [] GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int length)
3029                 {
3030                         ThrowIfDisposedAndClosed ();
3031
3032                         int error;
3033                         byte[] byte_val = new byte [length];
3034                         GetSocketOption_arr_internal (safe_handle, optionLevel, optionName, ref byte_val, out error);
3035
3036                         if (error != 0)
3037                                 throw new SocketException (error);
3038
3039                         return byte_val;
3040                 }
3041
3042                 public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
3043                 {
3044                         ThrowIfDisposedAndClosed ();
3045
3046                         int error;
3047                         object obj_val;
3048                         GetSocketOption_obj_internal (safe_handle, optionLevel, optionName, out obj_val, out error);
3049
3050                         if (error != 0)
3051                                 throw new SocketException (error);
3052
3053                         if (optionName == SocketOptionName.Linger)
3054                                 return (LingerOption) obj_val;
3055                         else if (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)
3056                                 return (MulticastOption) obj_val;
3057                         else if (obj_val is int)
3058                                 return (int) obj_val;
3059                         else
3060                                 return obj_val;
3061                 }
3062
3063                 static void GetSocketOption_arr_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error)
3064                 {
3065                         bool release = false;
3066                         try {
3067                                 safeHandle.DangerousAddRef (ref release);
3068                                 GetSocketOption_arr_internal (safeHandle.DangerousGetHandle (), level, name, ref byte_val, out error);
3069                         } finally {
3070                                 if (release)
3071                                         safeHandle.DangerousRelease ();
3072                         }
3073                 }
3074
3075                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3076                 extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);
3077
3078                 static void GetSocketOption_obj_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error)
3079                 {
3080                         bool release = false;
3081                         try {
3082                                 safeHandle.DangerousAddRef (ref release);
3083                                 GetSocketOption_obj_internal (safeHandle.DangerousGetHandle (), level, name, out obj_val, out error);
3084                         } finally {
3085                                 if (release)
3086                                         safeHandle.DangerousRelease ();
3087                         }
3088                 }
3089
3090                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3091                 extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);
3092
3093 #endregion
3094
3095 #region SetSocketOption
3096
3097                 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
3098                 {
3099                         ThrowIfDisposedAndClosed ();
3100
3101                         // I'd throw an ArgumentNullException, but this is what MS does.
3102                         if (optionValue == null)
3103                                 throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
3104
3105                         int error;
3106                         SetSocketOption_internal (safe_handle, optionLevel, optionName, null, optionValue, 0, out error);
3107
3108                         if (error != 0) {
3109                                 if (error == (int) SocketError.InvalidArgument)
3110                                         throw new ArgumentException ();
3111                                 throw new SocketException (error);
3112                         }
3113                 }
3114
3115                 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
3116                 {
3117                         ThrowIfDisposedAndClosed ();
3118
3119                         // NOTE: if a null is passed, the byte[] overload is used instead...
3120                         if (optionValue == null)
3121                                 throw new ArgumentNullException("optionValue");
3122
3123                         int error;
3124
3125                         if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger) {
3126                                 LingerOption linger = optionValue as LingerOption;
3127                                 if (linger == null)
3128                                         throw new ArgumentException ("A 'LingerOption' value must be specified.", "optionValue");
3129                                 SetSocketOption_internal (safe_handle, optionLevel, optionName, linger, null, 0, out error);
3130                         } else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
3131                                 MulticastOption multicast = optionValue as MulticastOption;
3132                                 if (multicast == null)
3133                                         throw new ArgumentException ("A 'MulticastOption' value must be specified.", "optionValue");
3134                                 SetSocketOption_internal (safe_handle, optionLevel, optionName, multicast, null, 0, out error);
3135                         } else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
3136                                 IPv6MulticastOption multicast = optionValue as IPv6MulticastOption;
3137                                 if (multicast == null)
3138                                         throw new ArgumentException ("A 'IPv6MulticastOption' value must be specified.", "optionValue");
3139                                 SetSocketOption_internal (safe_handle, optionLevel, optionName, multicast, null, 0, out error);
3140                         } else {
3141                                 throw new ArgumentException ("Invalid value specified.", "optionValue");
3142                         }
3143
3144                         if (error != 0) {
3145                                 if (error == (int) SocketError.InvalidArgument)
3146                                         throw new ArgumentException ();
3147                                 throw new SocketException (error);
3148                         }
3149                 }
3150
3151                 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
3152                 {
3153                         ThrowIfDisposedAndClosed ();
3154
3155                         int error;
3156                         int int_val = optionValue ? 1 : 0;
3157                         SetSocketOption_internal (safe_handle, optionLevel, optionName, null, null, int_val, out error);
3158
3159                         if (error != 0) {
3160                                 if (error == (int) SocketError.InvalidArgument)
3161                                         throw new ArgumentException ();
3162                                 throw new SocketException (error);
3163                         }
3164                 }
3165
3166                 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
3167                 {
3168                         ThrowIfDisposedAndClosed ();
3169
3170                         int error;
3171                         SetSocketOption_internal (safe_handle, optionLevel, optionName, null, null, optionValue, out error);
3172
3173                         if (error != 0) {
3174                                 throw new SocketException (error);
3175                         }
3176                 }
3177
3178                 static void SetSocketOption_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error)
3179                 {
3180                         bool release = false;
3181                         try {
3182                                 safeHandle.DangerousAddRef (ref release);
3183                                 SetSocketOption_internal (safeHandle.DangerousGetHandle (), level, name, obj_val, byte_val, int_val, out error);
3184                         } finally {
3185                                 if (release)
3186                                         safeHandle.DangerousRelease ();
3187                         }
3188                 }
3189
3190                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3191                 extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error);
3192
3193 #endregion
3194
3195 #region IOControl
3196
3197                 public int IOControl (int ioctl_code, byte [] in_value, byte [] out_value)
3198                 {
3199                         if (is_disposed)
3200                                 throw new ObjectDisposedException (GetType ().ToString ());
3201
3202                         int error;
3203                         int result = IOControl_internal (safe_handle, ioctl_code, in_value, out_value, out error);
3204
3205                         if (error != 0)
3206                                 throw new SocketException (error);
3207                         if (result == -1)
3208                                 throw new InvalidOperationException ("Must use Blocking property instead.");
3209
3210                         return result;
3211                 }
3212
3213                 public int IOControl (IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
3214                 {
3215                         return IOControl ((int) ioControlCode, optionInValue, optionOutValue);
3216                 }
3217
3218                 static int IOControl_internal (SafeSocketHandle safeHandle, int ioctl_code, byte [] input, byte [] output, out int error)
3219                 {
3220                         bool release = false;
3221                         try {
3222                                 safeHandle.DangerousAddRef (ref release);
3223                                 return IOControl_internal (safeHandle.DangerousGetHandle (), ioctl_code, input, output, out error);
3224                         } finally {
3225                                 if (release)
3226                                         safeHandle.DangerousRelease ();
3227                         }
3228                 }
3229
3230                 /* See Socket.IOControl, WSAIoctl documentation in MSDN. The common options between UNIX
3231                  * and Winsock are FIONREAD, FIONBIO and SIOCATMARK. Anything else will depend on the system
3232                  * except SIO_KEEPALIVE_VALS which is properly handled on both windows and linux. */
3233                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3234                 extern static int IOControl_internal (IntPtr sock, int ioctl_code, byte [] input, byte [] output, out int error);
3235
3236 #endregion
3237
3238 #region Close
3239
3240                 public void Close ()
3241                 {
3242                         linger_timeout = 0;
3243                         Dispose ();
3244                 }
3245
3246                 public void Close (int timeout)
3247                 {
3248                         linger_timeout = timeout;
3249                         Dispose ();
3250                 }
3251
3252                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3253                 internal extern static void Close_internal (IntPtr socket, out int error);
3254
3255 #endregion
3256
3257 #region Shutdown
3258
3259                 public void Shutdown (SocketShutdown how)
3260                 {
3261                         ThrowIfDisposedAndClosed ();
3262
3263                         if (!is_connected)
3264                                 throw new SocketException (10057); // Not connected
3265
3266                         int error;
3267                         Shutdown_internal (safe_handle, how, out error);
3268
3269                         if (error != 0)
3270                                 throw new SocketException (error);
3271                 }
3272
3273                 static void Shutdown_internal (SafeSocketHandle safeHandle, SocketShutdown how, out int error)
3274                 {
3275                         bool release = false;
3276                         try {
3277                                 safeHandle.DangerousAddRef (ref release);
3278                                 Shutdown_internal (safeHandle.DangerousGetHandle (), how, out error);
3279                         } finally {
3280                                 if (release)
3281                                         safeHandle.DangerousRelease ();
3282                         }
3283                 }
3284
3285                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
3286                 internal extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
3287
3288 #endregion
3289
3290 #region Dispose
3291
3292                 protected virtual void Dispose (bool disposing)
3293                 {
3294                         if (is_disposed)
3295                                 return;
3296
3297                         is_disposed = true;
3298                         bool was_connected = is_connected;
3299                         is_connected = false;
3300
3301                         if (safe_handle != null) {
3302                                 is_closed = true;
3303                                 IntPtr x = Handle;
3304
3305                                 if (was_connected)
3306                                         Linger (x);
3307
3308                                 safe_handle.Dispose ();
3309                         }
3310                 }
3311
3312                 public void Dispose ()
3313                 {
3314                         Dispose (true);
3315                         GC.SuppressFinalize (this);
3316                 }
3317
3318                 void Linger (IntPtr handle)
3319                 {
3320                         if (!is_connected || linger_timeout <= 0)
3321                                 return;
3322
3323                         /* We don't want to receive any more data */
3324                         int error;
3325                         Shutdown_internal (handle, SocketShutdown.Receive, out error);
3326
3327                         if (error != 0)
3328                                 return;
3329
3330                         int seconds = linger_timeout / 1000;
3331                         int ms = linger_timeout % 1000;
3332                         if (ms > 0) {
3333                                 /* If the other end closes, this will return 'true' with 'Available' == 0 */
3334                                 Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
3335                                 if (error != 0)
3336                                         return;
3337                         }
3338
3339                         if (seconds > 0) {
3340                                 LingerOption linger = new LingerOption (true, seconds);
3341                                 SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
3342                                 /* Not needed, we're closing upon return */
3343                                 //if (error != 0)
3344                                 //      return;
3345                         }
3346                 }
3347
3348 #endregion
3349
3350                 void ThrowIfDisposedAndClosed (Socket socket)
3351                 {
3352                         if (socket.is_disposed && socket.is_closed)
3353                                 throw new ObjectDisposedException (socket.GetType ().ToString ());
3354                 }
3355
3356                 void ThrowIfDisposedAndClosed ()
3357                 {
3358                         if (is_disposed && is_closed)
3359                                 throw new ObjectDisposedException (GetType ().ToString ());
3360                 }
3361
3362                 void ThrowIfBufferNull (byte[] buffer)
3363                 {
3364                         if (buffer == null)
3365                                 throw new ArgumentNullException ("buffer");
3366                 }
3367
3368                 void ThrowIfBufferOutOfRange (byte[] buffer, int offset, int size)
3369                 {
3370                         if (offset < 0)
3371                                 throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
3372                         if (offset > buffer.Length)
3373                                 throw new ArgumentOutOfRangeException ("offset", "offset must be <= buffer.Length");
3374                         if (size < 0)
3375                                 throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
3376                         if (size > buffer.Length - offset)
3377                                 throw new ArgumentOutOfRangeException ("size", "size must be <= buffer.Length - offset");
3378                 }
3379
3380                 void ThrowIfUdp ()
3381                 {
3382 #if !NET_2_1 || MOBILE
3383                         if (protocol_type == ProtocolType.Udp)
3384                                 throw new SocketException ((int)SocketError.ProtocolOption);
3385 #endif
3386                 }
3387
3388                 SocketAsyncResult ValidateEndIAsyncResult (IAsyncResult ares, string methodName, string argName)
3389                 {
3390                         if (ares == null)
3391                                 throw new ArgumentNullException (argName);
3392
3393                         SocketAsyncResult sockares = ares as SocketAsyncResult;
3394                         if (sockares == null)
3395                                 throw new ArgumentException ("Invalid IAsyncResult", argName);
3396                         if (Interlocked.CompareExchange (ref sockares.EndCalled, 1, 0) == 1)
3397                                 throw new InvalidOperationException (methodName + " can only be called once per asynchronous operation");
3398
3399                         return sockares;
3400                 }
3401
3402                 void QueueIOSelectorJob (Queue<KeyValuePair<IntPtr, IOSelectorJob>> queue, IntPtr handle, IOSelectorJob job)
3403                 {
3404                         int count;
3405                         lock (queue) {
3406                                 queue.Enqueue (new KeyValuePair<IntPtr, IOSelectorJob> (handle, job));
3407                                 count = queue.Count;
3408                         }
3409
3410                         if (count == 1)
3411                                 IOSelector.Add (handle, job);
3412                 }
3413
3414                 void InitSocketAsyncEventArgs (SocketAsyncEventArgs e, AsyncCallback callback, object state, SocketOperation operation)
3415                 {
3416                         e.socket_async_result.Init (this, callback, state, operation);
3417
3418                         e.current_socket = this;
3419                         e.SetLastOperation (SocketOperationToSocketAsyncOperation (operation));
3420                         e.SocketError = SocketError.Success;
3421                         e.BytesTransferred = 0;
3422                 }
3423
3424                 SocketAsyncOperation SocketOperationToSocketAsyncOperation (SocketOperation op)
3425                 {
3426                         switch (op) {
3427                         case SocketOperation.Connect:
3428                                 return SocketAsyncOperation.Connect;
3429                         case SocketOperation.Accept:
3430                                 return SocketAsyncOperation.Accept;
3431                         case SocketOperation.Disconnect:
3432                                 return SocketAsyncOperation.Disconnect;
3433                         case SocketOperation.Receive:
3434                         case SocketOperation.ReceiveGeneric:
3435                                 return SocketAsyncOperation.Receive;
3436                         case SocketOperation.ReceiveFrom:
3437                                 return SocketAsyncOperation.ReceiveFrom;
3438                         case SocketOperation.Send:
3439                         case SocketOperation.SendGeneric:
3440                                 return SocketAsyncOperation.Send;
3441                         case SocketOperation.SendTo:
3442                                 return SocketAsyncOperation.SendTo;
3443                         default:
3444                                 throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
3445                         }
3446                 }
3447
3448                 [StructLayout (LayoutKind.Sequential)]
3449                 struct WSABUF {
3450                         public int len;
3451                         public IntPtr buf;
3452                 }
3453
3454                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3455                 internal static extern void cancel_blocking_socket_operation (Thread thread);
3456
3457                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3458                 internal static extern bool SupportsPortReuse ();
3459         }
3460 }
3461