Fix copy-paste error in git 17085447
[mono.git] / mcs / class / System / System.Net.Sockets / Socket_2_1.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 //
10 // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
11 //    http://www.myelin.co.nz
12 // (c) 2004-2011 Novell, Inc. (http://www.novell.com)
13 //
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.IO;
44 using System.Security;
45 using System.Text;
46
47 #if !NET_2_1
48 using System.Net.Configuration;
49 using System.Net.NetworkInformation;
50 #endif
51 #if MOONLIGHT && !INSIDE_SYSTEM
52 using System.Net.Policy;
53 #endif
54
55 namespace System.Net.Sockets {
56
57         public partial class Socket : IDisposable {
58                 [StructLayout (LayoutKind.Sequential)]
59                 struct WSABUF {
60                         public int len;
61                         public IntPtr buf;
62                 }
63
64                 // Used by the runtime
65                 internal enum SocketOperation {
66                         Accept,
67                         Connect,
68                         Receive,
69                         ReceiveFrom,
70                         Send,
71                         SendTo,
72                         RecvJustCallback,
73                         SendJustCallback,
74                         UsedInProcess,
75                         UsedInConsole2,
76                         Disconnect,
77                         AcceptReceive,
78                         ReceiveGeneric,
79                         SendGeneric
80                 }
81
82                 [StructLayout (LayoutKind.Sequential)]
83                 internal sealed class SocketAsyncResult: IAsyncResult
84                 {
85                         /* Same structure in the runtime */
86                         /*
87                           Keep this in sync with MonoSocketAsyncResult in
88                           metadata/socket-io.h and ProcessAsyncReader
89                           in System.Diagnostics/Process.cs.
90                         */
91
92                         public Socket Sock;
93                         public IntPtr handle;
94                         object state;
95                         AsyncCallback callback; // used from the runtime
96                         WaitHandle waithandle;
97
98                         Exception delayedException;
99
100                         public EndPoint EndPoint;       // Connect,ReceiveFrom,SendTo
101                         public byte [] Buffer;          // Receive,ReceiveFrom,Send,SendTo
102                         public int Offset;              // Receive,ReceiveFrom,Send,SendTo
103                         public int Size;                // Receive,ReceiveFrom,Send,SendTo
104                         public SocketFlags SockFlags;   // Receive,ReceiveFrom,Send,SendTo
105                         public Socket AcceptSocket;     // AcceptReceive
106                         public IPAddress[] Addresses;   // Connect
107                         public int Port;                // Connect
108                         public IList<ArraySegment<byte>> Buffers;       // Receive, Send
109                         public bool ReuseSocket;        // Disconnect
110
111                         // Return values
112                         Socket acc_socket;
113                         int total;
114
115                         bool completed_sync;
116                         bool completed;
117                         public bool blocking;
118                         internal int error;
119                         public SocketOperation operation;
120                         public object ares;
121                         public int EndCalled;
122
123                         // These fields are not in MonoSocketAsyncResult
124                         public Worker Worker;
125                         public int CurrentAddress; // Connect
126
127                         public SocketAsyncResult ()
128                         {
129                         }
130
131                         public void Init (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
132                         {
133                                 this.Sock = sock;
134                                 if (sock != null) {
135                                         this.blocking = sock.blocking;
136                                         this.handle = sock.socket;
137                                 } else {
138                                         this.blocking = true;
139                                         this.handle = IntPtr.Zero;
140                                 }
141                                 this.state = state;
142                                 this.callback = callback;
143                                 GC.KeepAlive (this.callback);
144                                 this.operation = operation;
145                                 SockFlags = SocketFlags.None;
146                                 if (waithandle != null)
147                                         ((ManualResetEvent) waithandle).Reset ();
148
149                                 delayedException = null;
150
151                                 EndPoint = null;
152                                 Buffer = null;
153                                 Offset = 0;
154                                 Size = 0;
155                                 SockFlags = 0;
156                                 AcceptSocket = null;
157                                 Addresses = null;
158                                 Port = 0;
159                                 Buffers = null;
160                                 ReuseSocket = false;
161                                 acc_socket = null;
162                                 total = 0;
163
164                                 completed_sync = false;
165                                 completed = false;
166                                 blocking = false;
167                                 error = 0;
168                                 ares = null;
169                                 EndCalled = 0;
170                                 Worker = null;
171                         }
172
173                         public void DoMConnectCallback ()
174                         {
175                                 if (callback == null)
176                                         return;
177 #if MOONLIGHT
178                                 ThreadPool.QueueUserWorkItem (_ => { callback (this); }, null);
179 #else
180                                 ThreadPool.UnsafeQueueUserWorkItem (_ => { callback (this); }, null);
181 #endif
182                         }
183
184                         public void Dispose ()
185                         {
186                                 Init (null, null, null, 0);
187                                 if (waithandle != null) {
188                                         waithandle.Close ();
189                                         waithandle = null;
190                                 }
191                         }
192
193                         public SocketAsyncResult (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
194                         {
195                                 this.Sock = sock;
196                                 this.blocking = sock.blocking;
197                                 this.handle = sock.socket;
198                                 this.state = state;
199                                 this.callback = callback;
200                                 GC.KeepAlive (this.callback);
201                                 this.operation = operation;
202                                 SockFlags = SocketFlags.None;
203                                 Worker = new Worker (this);
204                         }
205
206                         public void CheckIfThrowDelayedException ()
207                         {
208                                 if (delayedException != null) {
209                                         Sock.connected = false;
210                                         throw delayedException;
211                                 }
212
213                                 if (error != 0) {
214                                         Sock.connected = false;
215                                         throw new SocketException (error);
216                                 }
217                         }
218
219                         void CompleteAllOnDispose (Queue queue)
220                         {
221                                 object [] pending = queue.ToArray ();
222                                 queue.Clear ();
223
224                                 WaitCallback cb;
225                                 for (int i = 0; i < pending.Length; i++) {
226                                         Worker worker = (Worker) pending [i];
227                                         SocketAsyncResult ares = worker.result;
228                                         cb = new WaitCallback (ares.CompleteDisposed);
229 #if MOONLIGHT
230                                         ThreadPool.QueueUserWorkItem (cb, null);
231 #else
232                                         ThreadPool.UnsafeQueueUserWorkItem (cb, null);
233 #endif
234                                 }
235                         }
236
237                         void CompleteDisposed (object unused)
238                         {
239                                 Complete ();
240                         }
241
242                         public void Complete ()
243                         {
244                                 if (operation != SocketOperation.Receive && Sock.disposed)
245                                         delayedException = new ObjectDisposedException (Sock.GetType ().ToString ());
246
247                                 IsCompleted = true;
248
249                                 Queue queue = null;
250                                 if (operation == SocketOperation.Receive ||
251                                     operation == SocketOperation.ReceiveFrom ||
252                                     operation == SocketOperation.ReceiveGeneric) {
253                                         queue = Sock.readQ;
254                                 } else if (operation == SocketOperation.Send ||
255                                            operation == SocketOperation.SendTo ||
256                                            operation == SocketOperation.SendGeneric) {
257
258                                         queue = Sock.writeQ;
259                                 }
260
261                                 if (queue != null) {
262                                         Worker worker = null;
263                                         SocketAsyncCall sac = null;
264                                         lock (queue) {
265                                                 // queue.Count will only be 0 if the socket is closed while receive/send
266                                                 // operation(s) are pending and at least one call to this method is
267                                                 // waiting on the lock while another one calls CompleteAllOnDispose()
268                                                 if (queue.Count > 0)
269                                                         queue.Dequeue (); // remove ourselves
270                                                 if (queue.Count > 0) {
271                                                         worker = (Worker) queue.Peek ();
272                                                         if (!Sock.disposed) {
273                                                                 sac = Worker.Dispatcher;
274                                                         } else {
275                                                                 CompleteAllOnDispose (queue);
276                                                         }
277                                                 }
278                                         }
279
280                                         if (sac != null)
281                                                 Socket.socket_pool_queue (sac, worker.result);
282                                 }
283                                 // IMPORTANT: 'callback', if any is scheduled from unmanaged code
284                         }
285
286                         public void Complete (bool synch)
287                         {
288                                 completed_sync = synch;
289                                 Complete ();
290                         }
291
292                         public void Complete (int total)
293                         {
294                                 this.total = total;
295                                 Complete ();
296                         }
297
298                         public void Complete (Exception e, bool synch)
299                         {
300                                 completed_sync = synch;
301                                 delayedException = e;
302                                 Complete ();
303                         }
304
305                         public void Complete (Exception e)
306                         {
307                                 delayedException = e;
308                                 Complete ();
309                         }
310
311                         public void Complete (Socket s)
312                         {
313                                 acc_socket = s;
314                                 Complete ();
315                         }
316
317                         public void Complete (Socket s, int total)
318                         {
319                                 acc_socket = s;
320                                 this.total = total;
321                                 Complete ();
322                         }
323
324                         public object AsyncState {
325                                 get {
326                                         return state;
327                                 }
328                         }
329
330                         public WaitHandle AsyncWaitHandle {
331                                 get {
332                                         lock (this) {
333                                                 if (waithandle == null)
334                                                         waithandle = new ManualResetEvent (completed);
335                                         }
336
337                                         return waithandle;
338                                 }
339                                 set {
340                                         waithandle=value;
341                                 }
342                         }
343
344                         public bool CompletedSynchronously {
345                                 get {
346                                         return(completed_sync);
347                                 }
348                         }
349
350                         public bool IsCompleted {
351                                 get {
352                                         return(completed);
353                                 }
354                                 set {
355                                         completed=value;
356                                         lock (this) {
357                                                 if (waithandle != null && value) {
358                                                         ((ManualResetEvent) waithandle).Set ();
359                                                 }
360                                         }
361                                 }
362                         }
363
364                         public Socket Socket {
365                                 get {
366                                         return acc_socket;
367                                 }
368                         }
369
370                         public int Total {
371                                 get { return total; }
372                                 set { total = value; }
373                         }
374
375                         public SocketError ErrorCode {
376                                 get {
377                                         SocketException ex = delayedException as SocketException;
378                                         if (ex != null)
379                                                 return(ex.SocketErrorCode);
380
381                                         if (error != 0)
382                                                 return((SocketError)error);
383
384                                         return(SocketError.Success);
385                                 }
386                         }
387                 }
388
389                 internal sealed class Worker
390                 {
391                         public SocketAsyncResult result;
392                         SocketAsyncEventArgs args;
393
394                         public Worker (SocketAsyncEventArgs args)
395                         {
396                                 this.args = args;
397                                 result = new SocketAsyncResult ();
398                                 result.Worker = this;
399                         }
400
401                         public Worker (SocketAsyncResult ares)
402                         {
403                                 this.result = ares;
404                         }
405
406                         public void Dispose ()
407                         {
408                                 if (result != null) {
409                                         result.Dispose ();
410                                         result = null;
411                                         args = null;
412                                 }
413                         }
414
415                         public static SocketAsyncCall Dispatcher = new SocketAsyncCall (DispatcherCB);
416
417                         static void DispatcherCB (SocketAsyncResult sar)
418                         {
419                                 SocketOperation op = sar.operation;
420                                 if (op == Socket.SocketOperation.Receive || op == Socket.SocketOperation.ReceiveGeneric ||
421                                         op == Socket.SocketOperation.RecvJustCallback)
422                                         sar.Worker.Receive ();
423                                 else if (op == Socket.SocketOperation.Send || op == Socket.SocketOperation.SendGeneric ||
424                                         op == Socket.SocketOperation.SendJustCallback)
425                                         sar.Worker.Send ();
426 #if !MOONLIGHT
427                                 else if (op == Socket.SocketOperation.ReceiveFrom)
428                                         sar.Worker.ReceiveFrom ();
429                                 else if (op == Socket.SocketOperation.SendTo)
430                                         sar.Worker.SendTo ();
431 #endif
432                                 else if (op == Socket.SocketOperation.Connect)
433                                         sar.Worker.Connect ();
434 #if !MOONLIGHT
435                                 else if (op == Socket.SocketOperation.Accept)
436                                         sar.Worker.Accept ();
437                                 else if (op == Socket.SocketOperation.AcceptReceive)
438                                         sar.Worker.AcceptReceive ();
439                                 else if (op == Socket.SocketOperation.Disconnect)
440                                         sar.Worker.Disconnect ();
441
442                                 // SendPackets and ReceiveMessageFrom are not implemented yet
443                                 /*
444                                 else if (op == Socket.SocketOperation.ReceiveMessageFrom)
445                                         async_op = SocketAsyncOperation.ReceiveMessageFrom;
446                                 else if (op == Socket.SocketOperation.SendPackets)
447                                         async_op = SocketAsyncOperation.SendPackets;
448                                 */
449 #endif
450                                 else
451                                         throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
452                         }
453
454                         /* This is called when reusing a SocketAsyncEventArgs */
455                         public void Init (Socket sock, SocketAsyncEventArgs args, SocketOperation op)
456                         {
457                                 result.Init (sock, args, SocketAsyncEventArgs.Dispatcher, op);
458                                 result.Worker = this;
459                                 SocketAsyncOperation async_op;
460
461                                 // Notes;
462                                 //      -SocketOperation.AcceptReceive not used in SocketAsyncEventArgs
463                                 //      -SendPackets and ReceiveMessageFrom are not implemented yet
464                                 if (op == Socket.SocketOperation.Connect)
465                                         async_op = SocketAsyncOperation.Connect;
466 #if !MOONLIGHT
467                                 else if (op == Socket.SocketOperation.Accept)
468                                         async_op = SocketAsyncOperation.Accept;
469                                 else if (op == Socket.SocketOperation.Disconnect)
470                                         async_op = SocketAsyncOperation.Disconnect;
471 #endif
472                                 else if (op == Socket.SocketOperation.Receive || op == Socket.SocketOperation.ReceiveGeneric)
473                                         async_op = SocketAsyncOperation.Receive;
474 #if !MOONLIGHT
475                                 else if (op == Socket.SocketOperation.ReceiveFrom)
476                                         async_op = SocketAsyncOperation.ReceiveFrom;
477 #endif
478                                 /*
479                                 else if (op == Socket.SocketOperation.ReceiveMessageFrom)
480                                         async_op = SocketAsyncOperation.ReceiveMessageFrom;
481                                 */
482                                 else if (op == Socket.SocketOperation.Send || op == Socket.SocketOperation.SendGeneric)
483                                         async_op = SocketAsyncOperation.Send;
484 #if !MOONLIGHT
485                                 /*
486                                 else if (op == Socket.SocketOperation.SendPackets)
487                                         async_op = SocketAsyncOperation.SendPackets;
488                                 */
489                                 else if (op == Socket.SocketOperation.SendTo)
490                                         async_op = SocketAsyncOperation.SendTo;
491 #endif
492                                 else
493                                         throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
494
495                                 args.SetLastOperation (async_op);
496                                 args.SocketError = SocketError.Success;
497                                 args.BytesTransferred = 0;
498                         }
499
500                         public void Accept ()
501                         {
502 #if !MOONLIGHT
503                                 Socket acc_socket = null;
504                                 try {
505                                         if (args != null && args.AcceptSocket != null) {
506                                                 result.Sock.Accept (args.AcceptSocket);
507                                                 acc_socket = args.AcceptSocket;
508                                         } else {
509                                                 acc_socket = result.Sock.Accept ();
510                                                 if (args != null)
511                                                         args.AcceptSocket = acc_socket;
512                                         }
513                                 } catch (Exception e) {
514                                         result.Complete (e);
515                                         return;
516                                 }
517
518                                 result.Complete (acc_socket);
519 #endif
520                         }
521
522                         /* only used in 2.0 profile and newer, but
523                          * leave in older profiles to keep interface
524                          * to runtime consistent
525                          */
526                         public void AcceptReceive ()
527                         {
528 #if !MOONLIGHT
529                                 Socket acc_socket = null;
530                                 try {
531                                         if (result.AcceptSocket == null) {
532                                                 acc_socket = result.Sock.Accept ();
533                                         } else {
534                                                 acc_socket = result.AcceptSocket;
535                                                 result.Sock.Accept (acc_socket);
536                                         }
537                                 } catch (Exception e) {
538                                         result.Complete (e);
539                                         return;
540                                 }
541
542                                 /* It seems the MS runtime
543                                  * special-cases 0-length requested
544                                  * receive data.  See bug 464201.
545                                  */
546                                 int total = 0;
547                                 if (result.Size > 0) {
548                                         try {
549                                                 SocketError error;
550                                                 total = acc_socket.Receive_nochecks (result.Buffer,
551                                                                                      result.Offset,
552                                                                                      result.Size,
553                                                                                      result.SockFlags,
554                                                                                      out error);
555                                                 if (error != 0) {
556                                                         result.Complete (new SocketException ((int) error));
557                                                         return;
558                                                 }
559                                         } catch (Exception e) {
560                                                 result.Complete (e);
561                                                 return;
562                                         }
563                                 }
564
565                                 result.Complete (acc_socket, total);
566 #endif
567                         }
568
569                         public void Connect ()
570                         {
571                                 if (result.EndPoint == null) {
572                                         result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
573                                         return;
574                                 }
575
576                                 SocketAsyncResult mconnect = result.AsyncState as SocketAsyncResult;
577 #if !MOONLIGHT
578                                 bool is_mconnect = (mconnect != null && mconnect.Addresses != null);
579 #else
580                                 bool is_mconnect = false;
581 #endif
582                                 try {
583                                         int error_code;
584                                         EndPoint ep = result.EndPoint;
585                                         error_code = (int) result.Sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
586                                         if (error_code == 0) {
587                                                 if (is_mconnect)
588                                                         result = mconnect;
589                                                 result.Sock.seed_endpoint = ep;
590                                                 result.Sock.connected = true;
591                                                 result.Sock.isbound = true;
592                                                 result.Sock.connect_in_progress = false;
593                                                 result.error = 0;
594                                                 result.Complete ();
595                                                 if (is_mconnect)
596                                                         result.DoMConnectCallback ();
597                                                 return;
598                                         }
599
600                                         if (!is_mconnect) {
601                                                 result.Sock.connect_in_progress = false;
602                                                 result.Complete (new SocketException (error_code));
603                                                 return;
604                                         }
605
606                                         if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
607                                                 mconnect.Complete (new SocketException (error_code));
608                                                 if (is_mconnect)
609                                                         mconnect.DoMConnectCallback ();
610                                                 return;
611                                         }
612                                         mconnect.Sock.BeginMConnect (mconnect);
613                                 } catch (Exception e) {
614                                         result.Sock.connect_in_progress = false;
615                                         if (is_mconnect)
616                                                 result = mconnect;
617                                         result.Complete (e);
618                                         if (is_mconnect)
619                                                 result.DoMConnectCallback ();
620                                         return;
621                                 }
622                         }
623
624                         /* Also only used in 2.0 profile and newer */
625                         public void Disconnect ()
626                         {
627 #if !MOONLIGHT
628                                 try {
629                                         if (args != null)
630                                                 result.ReuseSocket = args.DisconnectReuseSocket;
631                                         result.Sock.Disconnect (result.ReuseSocket);
632                                 } catch (Exception e) {
633                                         result.Complete (e);
634                                         return;
635                                 }
636                                 result.Complete ();
637 #endif
638                         }
639
640                         public void Receive ()
641                         {
642                                 if (result.operation == SocketOperation.ReceiveGeneric) {
643                                         ReceiveGeneric ();
644                                         return;
645                                 }
646                                 // Actual recv() done in the runtime
647                                 result.Complete ();
648                         }
649
650                         public void ReceiveFrom ()
651                         {
652 #if !MOONLIGHT
653                                 int total = 0;
654                                 try {
655                                         total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
656                                                                          result.Offset,
657                                                                          result.Size,
658                                                                          result.SockFlags,
659                                                                          ref result.EndPoint);
660                                 } catch (Exception e) {
661                                         result.Complete (e);
662                                         return;
663                                 }
664
665                                 result.Complete (total);
666 #endif
667                         }
668
669                         public void ReceiveGeneric ()
670                         {
671                                 int total = 0;
672                                 try {
673                                         total = result.Sock.Receive (result.Buffers, result.SockFlags);
674                                 } catch (Exception e) {
675                                         result.Complete (e);
676                                         return;
677                                 }
678                                 result.Complete (total);
679                         }
680
681                         int send_so_far;
682
683                         void UpdateSendValues (int last_sent)
684                         {
685                                 if (result.error == 0) {
686                                         send_so_far += last_sent;
687                                         result.Offset += last_sent;
688                                         result.Size -= last_sent;
689                                 }
690                         }
691
692                         public void Send ()
693                         {
694                                 if (result.operation == SocketOperation.SendGeneric) {
695                                         SendGeneric ();
696                                         return;
697                                 }
698                                 // Actual send() done in the runtime
699                                 if (result.error == 0) {
700                                         UpdateSendValues (result.Total);
701                                         if (result.Sock.disposed) {
702                                                 result.Complete ();
703                                                 return;
704                                         }
705
706                                         if (result.Size > 0) {
707                                                 Socket.socket_pool_queue (Worker.Dispatcher, result);
708                                                 return; // Have to finish writing everything. See bug #74475.
709                                         }
710                                         result.Total = send_so_far;
711                                 }
712                                 result.Complete ();
713                         }
714
715                         public void SendTo ()
716                         {
717 #if !MOONLIGHT
718                                 int total = 0;
719                                 try {
720                                         total = result.Sock.SendTo_nochecks (result.Buffer,
721                                                                     result.Offset,
722                                                                     result.Size,
723                                                                     result.SockFlags,
724                                                                     result.EndPoint);
725
726                                         UpdateSendValues (total);
727                                         if (result.Size > 0) {
728                                                 Socket.socket_pool_queue (Worker.Dispatcher, result);
729                                                 return; // Have to finish writing everything. See bug #74475.
730                                         }
731                                         result.Total = send_so_far;
732                                 } catch (Exception e) {
733                                         result.Complete (e);
734                                         return;
735                                 }
736
737                                 result.Complete ();
738 #endif
739                         }
740
741                         public void SendGeneric ()
742                         {
743                                 int total = 0;
744                                 try {
745                                         total = result.Sock.Send (result.Buffers, result.SockFlags);
746                                 } catch (Exception e) {
747                                         result.Complete (e);
748                                         return;
749                                 }
750                                 result.Complete (total);
751                         }
752                 }
753
754                 private Queue readQ = new Queue (2);
755                 private Queue writeQ = new Queue (2);
756
757                 internal delegate void SocketAsyncCall (SocketAsyncResult sar);
758
759                 /*
760                  *      These two fields are looked up by name by the runtime, don't change
761                  *  their name without also updating the runtime code.
762                  */
763                 private static int ipv4Supported = -1, ipv6Supported = -1;
764                 int linger_timeout;
765
766                 static Socket ()
767                 {
768                         // initialize ipv4Supported and ipv6Supported
769                         CheckProtocolSupport ();
770                 }
771
772                 internal static void CheckProtocolSupport ()
773                 {
774                         if(ipv4Supported == -1) {
775                                 try {
776                                         Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
777                                         tmp.Close();
778
779                                         ipv4Supported = 1;
780                                 } catch {
781                                         ipv4Supported = 0;
782                                 }
783                         }
784
785                         if (ipv6Supported == -1) {
786 #if !NET_2_1
787 #if CONFIGURATION_DEP
788                                 SettingsSection config;
789                                 config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
790                                 if (config != null)
791                                         ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
792 #else
793                                 NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
794                                 if (config != null)
795                                         ipv6Supported = config.ipv6Enabled ? -1 : 0;
796 #endif
797 #endif
798                                 if (ipv6Supported != 0) {
799                                         try {
800                                                 Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
801                                                 tmp.Close();
802
803                                                 ipv6Supported = 1;
804                                         } catch {
805                                                 ipv6Supported = 0;
806                                         }
807                                 }
808                         }
809                 }
810
811                 public static bool SupportsIPv4 {
812                         get {
813                                 CheckProtocolSupport();
814                                 return ipv4Supported == 1;
815                         }
816                 }
817
818                 [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
819                 public static bool SupportsIPv6 {
820                         get {
821                                 CheckProtocolSupport();
822                                 return ipv6Supported == 1;
823                         }
824                 }
825 #if NET_2_1
826                 public static bool OSSupportsIPv4 {
827                         get {
828                                 CheckProtocolSupport();
829                                 return ipv4Supported == 1;
830                         }
831                 }
832 #endif
833 #if NET_2_1
834                 public static bool OSSupportsIPv6 {
835                         get {
836                                 CheckProtocolSupport();
837                                 return ipv6Supported == 1;
838                         }
839                 }
840 #else
841                 public static bool OSSupportsIPv6 {
842                         get {
843                                 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
844                                 
845                                 foreach (NetworkInterface adapter in nics) {
846                                         if (adapter.Supports (NetworkInterfaceComponent.IPv6))
847                                                 return true;
848                                 }
849                                 return false;
850                         }
851                 }
852 #endif
853
854                 /* the field "socket" is looked up by name by the runtime */
855                 private IntPtr socket;
856                 private AddressFamily address_family;
857                 private SocketType socket_type;
858                 private ProtocolType protocol_type;
859                 internal bool blocking=true;
860                 Thread blocking_thread;
861                 private bool isbound;
862                 /* When true, the socket was connected at the time of
863                  * the last IO operation
864                  */
865                 private bool connected;
866                 /* true if we called Close_internal */
867                 private bool closed;
868                 internal bool disposed;
869                 bool connect_in_progress;
870
871                 /*
872                  * This EndPoint is used when creating new endpoints. Because
873                  * there are many types of EndPoints possible,
874                  * seed_endpoint.Create(addr) is used for creating new ones.
875                  * As such, this value is set on Bind, SentTo, ReceiveFrom,
876                  * Connect, etc.
877                  */
878                 internal EndPoint seed_endpoint = null;
879
880 #if !TARGET_JVM
881                 // Creates a new system socket, returning the handle
882                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
883                 private extern IntPtr Socket_internal(AddressFamily family,
884                                                       SocketType type,
885                                                       ProtocolType proto,
886                                                       out int error);
887 #endif          
888                 
889                 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
890                 {
891 #if NET_2_1 && !MOBILE
892                         switch (addressFamily) {
893                         case AddressFamily.InterNetwork:        // ok
894                         case AddressFamily.InterNetworkV6:      // ok
895                         case AddressFamily.Unknown:             // SocketException will be thrown later (with right error #)
896                                 break;
897                         // case AddressFamily.Unspecified:
898                         default:
899                                 throw new ArgumentException ("addressFamily");
900                         }
901
902                         switch (socketType) {
903                         case SocketType.Stream:                 // ok
904                         case SocketType.Unknown:                // SocketException will be thrown later (with right error #)
905                                 break;
906                         default:
907                                 throw new ArgumentException ("socketType");
908                         }
909
910                         switch (protocolType) {
911                         case ProtocolType.Tcp:                  // ok
912                         case ProtocolType.Unspecified:          // ok
913                         case ProtocolType.Unknown:              // SocketException will be thrown later (with right error #)
914                                 break;
915                         default:
916                                 throw new ArgumentException ("protocolType");
917                         }
918 #endif
919                         address_family = addressFamily;
920                         socket_type = socketType;
921                         protocol_type = protocolType;
922                         
923                         int error;
924                         
925                         socket = Socket_internal (addressFamily, socketType, protocolType, out error);
926                         if (error != 0)
927                                 throw new SocketException (error);
928 #if !NET_2_1 || MOBILE
929                         SocketDefaults ();
930 #endif
931                 }
932
933                 ~Socket ()
934                 {
935                         Dispose (false);
936                 }
937
938
939                 public AddressFamily AddressFamily {
940                         get { return address_family; }
941                 }
942
943 #if !TARGET_JVM
944                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
945                 private extern static void Blocking_internal(IntPtr socket,
946                                                              bool block,
947                                                              out int error);
948 #endif
949
950                 public bool Blocking {
951                         get {
952                                 return(blocking);
953                         }
954                         set {
955                                 if (disposed && closed)
956                                         throw new ObjectDisposedException (GetType ().ToString ());
957
958                                 int error;
959                                 
960                                 Blocking_internal (socket, value, out error);
961
962                                 if (error != 0)
963                                         throw new SocketException (error);
964                                 
965                                 blocking=value;
966                         }
967                 }
968
969                 public bool Connected {
970                         get { return connected; }
971                         internal set { connected = value; }
972                 }
973
974                 public ProtocolType ProtocolType {
975                         get { return protocol_type; }
976                 }
977
978                 public bool NoDelay {
979                         get {
980                                 if (disposed && closed)
981                                         throw new ObjectDisposedException (GetType ().ToString ());
982
983                                 ThrowIfUpd ();
984
985                                 return (int)(GetSocketOption (
986                                         SocketOptionLevel.Tcp,
987                                         SocketOptionName.NoDelay)) != 0;
988                         }
989
990                         set {
991                                 if (disposed && closed)
992                                         throw new ObjectDisposedException (GetType ().ToString ());
993
994                                 ThrowIfUpd ();
995
996                                 SetSocketOption (
997                                         SocketOptionLevel.Tcp,
998                                         SocketOptionName.NoDelay, value ? 1 : 0);
999                         }
1000                 }
1001
1002                 public int ReceiveBufferSize {
1003                         get {
1004                                 if (disposed && closed) {
1005                                         throw new ObjectDisposedException (GetType ().ToString ());
1006                                 }
1007                                 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer));
1008                         }
1009                         set {
1010                                 if (disposed && closed) {
1011                                         throw new ObjectDisposedException (GetType ().ToString ());
1012                                 }
1013                                 if (value < 0) {
1014                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1015                                 }
1016                                 
1017                                 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
1018                         }
1019                 }
1020
1021                 public int SendBufferSize {
1022                         get {
1023                                 if (disposed && closed) {
1024                                         throw new ObjectDisposedException (GetType ().ToString ());
1025                                 }
1026                                 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer));
1027                         }
1028                         set {
1029                                 if (disposed && closed) {
1030                                         throw new ObjectDisposedException (GetType ().ToString ());
1031                                 }
1032                                 if (value < 0) {
1033                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1034                                 }
1035                                 
1036                                 SetSocketOption (SocketOptionLevel.Socket,
1037                                                  SocketOptionName.SendBuffer,
1038                                                  value);
1039                         }
1040                 }
1041
1042                 public short Ttl {
1043                         get {
1044                                 if (disposed && closed) {
1045                                         throw new ObjectDisposedException (GetType ().ToString ());
1046                                 }
1047                                 
1048                                 short ttl_val;
1049                                 
1050                                 if (address_family == AddressFamily.InterNetwork) {
1051                                         ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive));
1052                                 } else if (address_family == AddressFamily.InterNetworkV6) {
1053                                         ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit));
1054                                 } else {
1055                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1056                                 }
1057                                 
1058                                 return(ttl_val);
1059                         }
1060                         set {
1061                                 if (disposed && closed) {
1062                                         throw new ObjectDisposedException (GetType ().ToString ());
1063                                 }
1064                                 if (value < 0) {
1065                                         throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1066                                 }
1067                                 
1068                                 if (address_family == AddressFamily.InterNetwork) {
1069                                         SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
1070                                 } else if (address_family == AddressFamily.InterNetworkV6) {
1071                                         SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
1072                                 } else {
1073                                         throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1074                                 }
1075                         }
1076                 }
1077
1078                 // Returns the remote endpoint details in addr and port
1079                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1080                 private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, int family, out int error);
1081
1082                 public EndPoint RemoteEndPoint {
1083                         get {
1084                                 if (disposed && closed)
1085                                         throw new ObjectDisposedException (GetType ().ToString ());
1086                                 
1087 #if MOONLIGHT
1088                                 if (!connected)
1089                                         return seed_endpoint;
1090 #else
1091                                 /*
1092                                  * If the seed EndPoint is null, Connect, Bind,
1093                                  * etc has not yet been called. MS returns null
1094                                  * in this case.
1095                                  */
1096                                 if (!connected || seed_endpoint == null)
1097                                         return null;
1098 #endif                  
1099                                 SocketAddress sa;
1100                                 int error;
1101                                 
1102                                 sa=RemoteEndPoint_internal(socket, (int) address_family, out error);
1103
1104                                 if (error != 0)
1105                                         throw new SocketException (error);
1106
1107                                 return seed_endpoint.Create (sa);
1108                         }
1109                 }
1110
1111                 void Linger (IntPtr handle)
1112                 {
1113                         if (!connected || linger_timeout <= 0)
1114                                 return;
1115
1116                         // We don't want to receive any more data
1117                         int error;
1118                         Shutdown_internal (handle, SocketShutdown.Receive, out error);
1119                         if (error != 0)
1120                                 return;
1121
1122                         int seconds = linger_timeout / 1000;
1123                         int ms = linger_timeout % 1000;
1124                         if (ms > 0) {
1125                                 // If the other end closes, this will return 'true' with 'Available' == 0
1126                                 Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
1127                                 if (error != 0)
1128                                         return;
1129
1130                         }
1131                         if (seconds > 0) {
1132                                 LingerOption linger = new LingerOption (true, seconds);
1133                                 SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
1134                                 /* Not needed, we're closing upon return */
1135                                 /*if (error != 0)
1136                                         return; */
1137                         }
1138                 }
1139
1140                 protected virtual void Dispose (bool disposing)
1141                 {
1142                         if (disposed)
1143                                 return;
1144
1145                         disposed = true;
1146                         bool was_connected = connected;
1147                         connected = false;
1148                         if ((int) socket != -1) {
1149                                 int error;
1150                                 closed = true;
1151                                 IntPtr x = socket;
1152                                 socket = (IntPtr) (-1);
1153                                 Thread th = blocking_thread;
1154                                 if (th != null) {
1155                                         th.Abort ();
1156                                         blocking_thread = null;
1157                                 }
1158
1159                                 if (was_connected)
1160                                         Linger (x);
1161                                 //DateTime start = DateTime.UtcNow;
1162                                 Close_internal (x, out error);
1163                                 //Console.WriteLine ("Time spent in Close_internal: {0}ms", (DateTime.UtcNow - start).TotalMilliseconds);
1164                                 if (error != 0)
1165                                         throw new SocketException (error);
1166                         }
1167                 }
1168
1169 #if NET_2_1 || NET_4_0
1170                 public void Dispose ()
1171 #else
1172                 void IDisposable.Dispose ()
1173 #endif
1174                 {
1175                         Dispose (true);
1176                         GC.SuppressFinalize (this);
1177                 }
1178
1179                 // Closes the socket
1180                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1181                 private extern static void Close_internal(IntPtr socket, out int error);
1182
1183                 public void Close ()
1184                 {
1185                         linger_timeout = 0;
1186                         ((IDisposable) this).Dispose ();
1187                 }
1188
1189                 public void Close (int timeout) 
1190                 {
1191                         linger_timeout = timeout;
1192                         ((IDisposable) this).Dispose ();
1193                 }
1194
1195                 // Connects to the remote address
1196                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1197                 private extern static void Connect_internal(IntPtr sock,
1198                                                             SocketAddress sa,
1199                                                             out int error);
1200
1201                 public void Connect (EndPoint remoteEP)
1202                 {
1203                         SocketAddress serial = null;
1204
1205                         if (disposed && closed)
1206                                 throw new ObjectDisposedException (GetType ().ToString ());
1207
1208                         if (remoteEP == null)
1209                                 throw new ArgumentNullException ("remoteEP");
1210
1211                         IPEndPoint ep = remoteEP as IPEndPoint;
1212 #if !MOONLIGHT
1213                         if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
1214 #else
1215                         if (ep != null)
1216 #endif
1217                                 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
1218                                         throw new SocketException ((int) SocketError.AddressNotAvailable);
1219
1220 #if MOONLIGHT
1221                         if (protocol_type != ProtocolType.Tcp)
1222                                 throw new SocketException ((int) SocketError.AccessDenied);
1223 #else
1224                         if (islistening)
1225                                 throw new InvalidOperationException ();
1226 #endif
1227                         serial = remoteEP.Serialize ();
1228
1229                         int error = 0;
1230
1231                         blocking_thread = Thread.CurrentThread;
1232                         try {
1233                                 Connect_internal (socket, serial, out error);
1234                         } catch (ThreadAbortException) {
1235                                 if (disposed) {
1236                                         Thread.ResetAbort ();
1237                                         error = (int) SocketError.Interrupted;
1238                                 }
1239                         } finally {
1240                                 blocking_thread = null;
1241                         }
1242
1243                         if (error == 0 || error == 10035)
1244                                 seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
1245
1246                         if (error != 0)
1247                                 throw new SocketException (error);
1248
1249 #if !MOONLIGHT
1250                         if (socket_type == SocketType.Dgram && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)))
1251                                 connected = false;
1252                         else
1253                                 connected = true;
1254 #else
1255                         connected = true;
1256 #endif
1257                         isbound = true;
1258                 }
1259
1260                 public bool ReceiveAsync (SocketAsyncEventArgs e)
1261                 {
1262                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1263                         if (disposed && closed)
1264                                 throw new ObjectDisposedException (GetType ().ToString ());
1265
1266                         // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
1267                         // thrown when e.Buffer and e.BufferList are null (works fine when one is
1268                         // set to a valid object)
1269                         if (e.Buffer == null && e.BufferList == null)
1270                                 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1271
1272                         e.curSocket = this;
1273                         SocketOperation op = (e.Buffer != null) ? SocketOperation.Receive : SocketOperation.ReceiveGeneric;
1274                         e.Worker.Init (this, e, op);
1275                         SocketAsyncResult res = e.Worker.result;
1276                         if (e.Buffer != null) {
1277                                 res.Buffer = e.Buffer;
1278                                 res.Offset = e.Offset;
1279                                 res.Size = e.Count;
1280                         } else {
1281                                 res.Buffers = e.BufferList;
1282                         }
1283                         res.SockFlags = e.SocketFlags;
1284                         int count;
1285                         lock (readQ) {
1286                                 readQ.Enqueue (e.Worker);
1287                                 count = readQ.Count;
1288                         }
1289                         if (count == 1) {
1290                                 // Receive takes care of ReceiveGeneric
1291                                 socket_pool_queue (Worker.Dispatcher, res);
1292                         }
1293
1294                         return true;
1295                 }
1296
1297                 public bool SendAsync (SocketAsyncEventArgs e)
1298                 {
1299                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1300                         if (disposed && closed)
1301                                 throw new ObjectDisposedException (GetType ().ToString ());
1302                         if (e.Buffer == null && e.BufferList == null)
1303                                 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1304
1305                         e.curSocket = this;
1306                         SocketOperation op = (e.Buffer != null) ? SocketOperation.Send : SocketOperation.SendGeneric;
1307                         e.Worker.Init (this, e, op);
1308                         SocketAsyncResult res = e.Worker.result;
1309                         if (e.Buffer != null) {
1310                                 res.Buffer = e.Buffer;
1311                                 res.Offset = e.Offset;
1312                                 res.Size = e.Count;
1313                         } else {
1314                                 res.Buffers = e.BufferList;
1315                         }
1316                         res.SockFlags = e.SocketFlags;
1317                         int count;
1318                         lock (writeQ) {
1319                                 writeQ.Enqueue (e.Worker);
1320                                 count = writeQ.Count;
1321                         }
1322                         if (count == 1) {
1323                                 // Send takes care of SendGeneric
1324                                 socket_pool_queue (Worker.Dispatcher, res);
1325                         }
1326                         return true;
1327                 }
1328
1329                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1330                 extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
1331
1332                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1333                 private extern static int Receive_internal(IntPtr sock,
1334                                                            byte[] buffer,
1335                                                            int offset,
1336                                                            int count,
1337                                                            SocketFlags flags,
1338                                                            out int error);
1339
1340                 internal int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1341                 {
1342                         int nativeError;
1343                         int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
1344                         error = (SocketError) nativeError;
1345                         if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1346                                 connected = false;
1347                                 isbound = false;
1348                         } else {
1349                                 connected = true;
1350                         }
1351                         
1352                         return ret;
1353                 }
1354
1355                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1356                 private extern static void GetSocketOption_obj_internal(IntPtr socket,
1357                         SocketOptionLevel level, SocketOptionName name, out object obj_val,
1358                         out int error);
1359
1360                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1361                 private extern static int Send_internal(IntPtr sock,
1362                                                         byte[] buf, int offset,
1363                                                         int count,
1364                                                         SocketFlags flags,
1365                                                         out int error);
1366
1367                 internal int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1368                 {
1369                         if (size == 0) {
1370                                 error = SocketError.Success;
1371                                 return 0;
1372                         }
1373
1374                         int nativeError;
1375
1376                         int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
1377
1378                         error = (SocketError)nativeError;
1379
1380                         if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1381                                 connected = false;
1382                                 isbound = false;
1383                         } else {
1384                                 connected = true;
1385                         }
1386
1387                         return ret;
1388                 }
1389
1390                 public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
1391                 {
1392                         if (disposed && closed)
1393                                 throw new ObjectDisposedException (GetType ().ToString ());
1394
1395                         object obj_val;
1396                         int error;
1397
1398                         GetSocketOption_obj_internal (socket, optionLevel, optionName, out obj_val,
1399                                 out error);
1400                         if (error != 0)
1401                                 throw new SocketException (error);
1402
1403                         if (optionName == SocketOptionName.Linger) {
1404                                 return((LingerOption)obj_val);
1405                         } else if (optionName == SocketOptionName.AddMembership ||
1406                                    optionName == SocketOptionName.DropMembership) {
1407                                 return((MulticastOption)obj_val);
1408                         } else if (obj_val is int) {
1409                                 return((int)obj_val);
1410                         } else {
1411                                 return(obj_val);
1412                         }
1413                 }
1414
1415                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1416                 private extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
1417                 
1418                 public void Shutdown (SocketShutdown how)
1419                 {
1420                         if (disposed && closed)
1421                                 throw new ObjectDisposedException (GetType ().ToString ());
1422
1423                         if (!connected)
1424                                 throw new SocketException (10057); // Not connected
1425
1426                         int error;
1427                         
1428                         Shutdown_internal (socket, how, out error);
1429                         if (error != 0)
1430                                 throw new SocketException (error);
1431                 }
1432
1433                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1434                 private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
1435                                                                      SocketOptionName name, object obj_val,
1436                                                                      byte [] byte_val, int int_val,
1437                                                                      out int error);
1438
1439                 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
1440                 {
1441                         if (disposed && closed)
1442                                 throw new ObjectDisposedException (GetType ().ToString ());
1443
1444                         int error;
1445
1446                         SetSocketOption_internal (socket, optionLevel, optionName, null,
1447                                                  null, optionValue, out error);
1448
1449                         if (error != 0)
1450                                 throw new SocketException (error);
1451                 }
1452
1453                 private void ThrowIfUpd ()
1454                 {
1455 #if !NET_2_1 || MOBILE
1456                         if (protocol_type == ProtocolType.Udp)
1457                                 throw new SocketException ((int)SocketError.ProtocolOption);
1458 #endif
1459                 }
1460
1461 #if !MOONLIGHT
1462                 public
1463 #endif
1464                 IAsyncResult BeginConnect(EndPoint end_point, AsyncCallback callback, object state)
1465                 {
1466                         if (disposed && closed)
1467                                 throw new ObjectDisposedException (GetType ().ToString ());
1468
1469                         if (end_point == null)
1470                                 throw new ArgumentNullException ("end_point");
1471
1472                         SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1473                         req.EndPoint = end_point;
1474
1475                         // Bug #75154: Connect() should not succeed for .Any addresses.
1476                         if (end_point is IPEndPoint) {
1477                                 IPEndPoint ep = (IPEndPoint) end_point;
1478                                 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
1479                                         req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
1480                                         return req;
1481                                 }
1482                         }
1483
1484                         int error = 0;
1485                         if (connect_in_progress) {
1486                                 // This could happen when multiple IPs are used
1487                                 // Calling connect() again will reset the connection attempt and cause
1488                                 // an error. Better to just close the socket and move on.
1489                                 connect_in_progress = false;
1490                                 Close_internal (socket, out error);
1491                                 socket = Socket_internal (address_family, socket_type, protocol_type, out error);
1492                                 if (error != 0)
1493                                         throw new SocketException (error);
1494                         }
1495                         bool blk = blocking;
1496                         if (blk)
1497                                 Blocking = false;
1498                         SocketAddress serial = end_point.Serialize ();
1499                         Connect_internal (socket, serial, out error);
1500                         if (blk)
1501                                 Blocking = true;
1502                         if (error == 0) {
1503                                 // succeeded synch
1504                                 connected = true;
1505                                 isbound = true;
1506                                 req.Complete (true);
1507                                 return req;
1508                         }
1509
1510                         if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
1511                                 // error synch
1512                                 connected = false;
1513                                 isbound = false;
1514                                 req.Complete (new SocketException (error), true);
1515                                 return req;
1516                         }
1517
1518                         // continue asynch
1519                         connected = false;
1520                         isbound = false;
1521                         connect_in_progress = true;
1522                         socket_pool_queue (Worker.Dispatcher, req);
1523                         return req;
1524                 }
1525
1526 #if !MOONLIGHT
1527                 public
1528 #else
1529                 internal
1530 #endif
1531                 IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
1532
1533                 {
1534                         if (disposed && closed)
1535                                 throw new ObjectDisposedException (GetType ().ToString ());
1536
1537                         if (addresses == null)
1538                                 throw new ArgumentNullException ("addresses");
1539
1540                         if (addresses.Length == 0)
1541                                 throw new ArgumentException ("Empty addresses list");
1542
1543                         if (this.AddressFamily != AddressFamily.InterNetwork &&
1544                                 this.AddressFamily != AddressFamily.InterNetworkV6)
1545                                 throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
1546
1547                         if (port <= 0 || port > 65535)
1548                                 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1549 #if !MOONLIGHT
1550                         if (islistening)
1551                                 throw new InvalidOperationException ();
1552 #endif
1553
1554                         SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1555                         req.Addresses = addresses;
1556                         req.Port = port;
1557                         connected = false;
1558                         return BeginMConnect (req);
1559                 }
1560
1561                 IAsyncResult BeginMConnect (SocketAsyncResult req)
1562                 {
1563                         IAsyncResult ares = null;
1564                         Exception exc = null;
1565                         for (int i = req.CurrentAddress; i < req.Addresses.Length; i++) {
1566                                 IPAddress addr = req.Addresses [i];
1567                                 IPEndPoint ep = new IPEndPoint (addr, req.Port);
1568                                 try {
1569                                         req.CurrentAddress++;
1570                                         ares = BeginConnect (ep, null, req);
1571                                         if (ares.IsCompleted && ares.CompletedSynchronously) {
1572                                                 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1573                                                 req.DoMConnectCallback ();
1574                                         }
1575                                         break;
1576                                 } catch (Exception e) {
1577                                         exc = e;
1578                                         ares = null;
1579                                 }
1580                         }
1581
1582                         if (ares == null)
1583                                 throw exc;
1584
1585                         return req;
1586                 }
1587
1588                 // Returns false when it is ok to use RemoteEndPoint
1589                 //         true when addresses must be used (and addresses could be null/empty)
1590                 bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
1591                 {
1592                         addresses = null;
1593 #if MOONLIGHT || NET_4_0
1594                         // Connect to the first address that match the host name, like:
1595                         // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
1596                         // while skipping entries that do not match the address family
1597                         DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1598                         if (dep != null) {
1599                                 addresses = Dns.GetHostAddresses (dep.Host);
1600                                 IPEndPoint endpoint;
1601 #if MOONLIGHT && !INSIDE_SYSTEM
1602                                 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1603                                         List<IPAddress> valid = new List<IPAddress> ();
1604                                         foreach (IPAddress a in addresses) {
1605                                                 // if we're not downloading a socket policy then check the policy
1606                                                 // and if we're not running with elevated permissions (SL4 OoB option)
1607                                                 endpoint = new IPEndPoint (a, dep.Port);
1608                                                 if (!CrossDomainPolicyManager.CheckEndPoint (endpoint, e.SocketClientAccessPolicyProtocol))
1609                                                         continue;
1610                                                 valid.Add (a);
1611                                         }
1612                                         addresses = valid.ToArray ();
1613                                 }
1614 #endif
1615                                 return true;
1616                         } else {
1617                                 e.ConnectByNameError = null;
1618 #if MOONLIGHT && !INSIDE_SYSTEM
1619                                 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1620                                         if (CrossDomainPolicyManager.CheckEndPoint (e.RemoteEndPoint, e.SocketClientAccessPolicyProtocol))
1621                                                 return false;
1622                                 } else
1623 #endif
1624                                         return false;
1625                         }
1626                         return true; // do not use remote endpoint
1627 #else
1628                         return false; // < NET_4_0 -> use remote endpoint
1629 #endif
1630                 }
1631
1632                 bool ConnectAsyncReal (SocketAsyncEventArgs e)
1633                 {
1634                         IPAddress [] addresses = null;
1635                         bool use_remoteep = true;
1636 #if MOONLIGHT || NET_4_0
1637                         use_remoteep = !GetCheckedIPs (e, out addresses);
1638 #endif
1639                         e.curSocket = this;
1640                         Worker w = e.Worker;
1641                         w.Init (this, e, SocketOperation.Connect);
1642                         SocketAsyncResult result = w.result;
1643                         IAsyncResult ares = null;
1644                         try {
1645                                 if (use_remoteep) {
1646                                         result.EndPoint = e.RemoteEndPoint;
1647                                         ares = BeginConnect (e.RemoteEndPoint, SocketAsyncEventArgs.Dispatcher, e);
1648                                 }
1649 #if MOONLIGHT || NET_4_0
1650                                 else {
1651
1652                                         DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1653                                         result.Addresses = addresses;
1654                                         result.Port = dep.Port;
1655
1656                                         ares = BeginConnect (addresses, dep.Port, SocketAsyncEventArgs.Dispatcher, e);
1657                                 }
1658 #endif
1659                                 if (ares.IsCompleted && ares.CompletedSynchronously) {
1660                                         ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1661                                         return false;
1662                                 }
1663                         } catch (Exception exc) {
1664                                 result.Complete (exc, true);
1665                                 return false;
1666                         }
1667                         return true;
1668                 }
1669
1670 #if !MOONLIGHT
1671                 public bool ConnectAsync (SocketAsyncEventArgs e)
1672                 {
1673                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1674                         if (disposed && closed)
1675                                 throw new ObjectDisposedException (GetType ().ToString ());
1676                         if (islistening)
1677                                 throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
1678                         if (e.RemoteEndPoint == null)
1679                                 throw new ArgumentNullException ("remoteEP");
1680
1681                         return ConnectAsyncReal (e);
1682                 }
1683 #endif
1684 #if MOONLIGHT
1685                 static void CheckConnect (SocketAsyncEventArgs e)
1686                 {
1687                         // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1688
1689                         if (e.RemoteEndPoint == null)
1690                                 throw new ArgumentNullException ("remoteEP");
1691                         if (e.BufferList != null)
1692                                 throw new ArgumentException ("Multiple buffers cannot be used with this method.");
1693                 }
1694
1695                 public bool ConnectAsync (SocketAsyncEventArgs e)
1696                 {
1697                         if (disposed && closed)
1698                                 throw new ObjectDisposedException (GetType ().ToString ());
1699
1700                         CheckConnect (e);
1701                         // if an address family is specified then they must match
1702                         AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1703                         if ((raf != AddressFamily.Unspecified) && (raf != AddressFamily))
1704                                 throw new NotSupportedException ("AddressFamily mismatch between socket and endpoint");
1705
1706                         return ConnectAsyncReal (e);
1707                 }
1708
1709                 public static bool ConnectAsync (SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
1710                 {
1711                         // exception ordering requires to check before creating the socket (good thing resource wise too)
1712                         CheckConnect (e);
1713
1714                         // create socket based on the endpoint address family (if specified), otherwise default fo IPv4
1715                         AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1716                         if (raf == AddressFamily.Unspecified)
1717                                 raf = AddressFamily.InterNetwork;
1718                         Socket s = new Socket (raf, socketType, protocolType);
1719                         return s.ConnectAsyncReal (e);
1720                 }
1721
1722                 public static void CancelConnectAsync (SocketAsyncEventArgs e)
1723                 {
1724                         if (e == null)
1725                                 throw new ArgumentNullException ("e");
1726
1727                         // FIXME: this is canceling a synchronous connect, not an async one
1728                         Socket s = e.ConnectSocket;
1729                         if ((s != null) && (s.blocking_thread != null))
1730                                 s.blocking_thread.Abort ();
1731                 }
1732 #endif
1733                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1734                 private extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1735 #if !MOONLIGHT
1736                 public
1737 #else
1738                 internal
1739 #endif
1740                 int Receive (IList<ArraySegment<byte>> buffers)
1741                 {
1742                         int ret;
1743                         SocketError error;
1744                         ret = Receive (buffers, SocketFlags.None, out error);
1745                         if (error != SocketError.Success) {
1746                                 throw new SocketException ((int)error);
1747                         }
1748                         return(ret);
1749                 }
1750
1751                 [CLSCompliant (false)]
1752 #if !MOONLIGHT
1753                 public
1754 #else
1755                 internal
1756 #endif
1757                 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1758                 {
1759                         int ret;
1760                         SocketError error;
1761                         ret = Receive (buffers, socketFlags, out error);
1762                         if (error != SocketError.Success) {
1763                                 throw new SocketException ((int)error);
1764                         }
1765                         return(ret);
1766                 }
1767
1768                 [CLSCompliant (false)]
1769 #if !MOONLIGHT
1770                 public
1771 #else
1772                 internal
1773 #endif
1774                 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1775                 {
1776                         if (disposed && closed)
1777                                 throw new ObjectDisposedException (GetType ().ToString ());
1778
1779                         if (buffers == null ||
1780                             buffers.Count == 0) {
1781                                 throw new ArgumentNullException ("buffers");
1782                         }
1783
1784                         int numsegments = buffers.Count;
1785                         int nativeError;
1786                         int ret;
1787
1788                         /* Only example I can find of sending a byte
1789                          * array reference directly into an internal
1790                          * call is in
1791                          * System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
1792                          * so taking a lead from that...
1793                          */
1794                         WSABUF[] bufarray = new WSABUF[numsegments];
1795                         GCHandle[] gch = new GCHandle[numsegments];
1796
1797                         for(int i = 0; i < numsegments; i++) {
1798                                 ArraySegment<byte> segment = buffers[i];
1799                                 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1800                                 bufarray[i].len = segment.Count;
1801                                 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1802                         }
1803
1804                         try {
1805                                 ret = Receive_internal (socket, bufarray,
1806                                                         socketFlags,
1807                                                         out nativeError);
1808                         } finally {
1809                                 for(int i = 0; i < numsegments; i++) {
1810                                         if (gch[i].IsAllocated) {
1811                                                 gch[i].Free ();
1812                                         }
1813                                 }
1814                         }
1815
1816                         errorCode = (SocketError)nativeError;
1817                         return(ret);
1818                 }
1819
1820                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1821                 private extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1822 #if !MOONLIGHT
1823                 public
1824 #else
1825                 internal
1826 #endif
1827                 int Send (IList<ArraySegment<byte>> buffers)
1828                 {
1829                         int ret;
1830                         SocketError error;
1831                         ret = Send (buffers, SocketFlags.None, out error);
1832                         if (error != SocketError.Success) {
1833                                 throw new SocketException ((int)error);
1834                         }
1835                         return(ret);
1836                 }
1837
1838 #if !MOONLIGHT
1839                 public
1840 #else
1841                 internal
1842 #endif
1843                 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1844                 {
1845                         int ret;
1846                         SocketError error;
1847                         ret = Send (buffers, socketFlags, out error);
1848                         if (error != SocketError.Success) {
1849                                 throw new SocketException ((int)error);
1850                         }
1851                         return(ret);
1852                 }
1853
1854                 [CLSCompliant (false)]
1855 #if !MOONLIGHT
1856                 public
1857 #else
1858                 internal
1859 #endif
1860                 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1861                 {
1862                         if (disposed && closed)
1863                                 throw new ObjectDisposedException (GetType ().ToString ());
1864                         if (buffers == null)
1865                                 throw new ArgumentNullException ("buffers");
1866                         if (buffers.Count == 0)
1867                                 throw new ArgumentException ("Buffer is empty", "buffers");
1868                         int numsegments = buffers.Count;
1869                         int nativeError;
1870                         int ret;
1871
1872                         WSABUF[] bufarray = new WSABUF[numsegments];
1873                         GCHandle[] gch = new GCHandle[numsegments];
1874                         for(int i = 0; i < numsegments; i++) {
1875                                 ArraySegment<byte> segment = buffers[i];
1876                                 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1877                                 bufarray[i].len = segment.Count;
1878                                 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1879                         }
1880
1881                         try {
1882                                 ret = Send_internal (socket, bufarray, socketFlags, out nativeError);
1883                         } finally {
1884                                 for(int i = 0; i < numsegments; i++) {
1885                                         if (gch[i].IsAllocated) {
1886                                                 gch[i].Free ();
1887                                         }
1888                                 }
1889                         }
1890                         errorCode = (SocketError)nativeError;
1891                         return(ret);
1892                 }
1893
1894                 Exception InvalidAsyncOp (string method)
1895                 {
1896                         return new InvalidOperationException (method + " can only be called once per asynchronous operation");
1897                 }
1898
1899 #if !MOONLIGHT
1900                 public
1901 #else
1902                 internal
1903 #endif
1904                 int EndReceive (IAsyncResult result)
1905                 {
1906                         SocketError error;
1907                         int bytesReceived = EndReceive (result, out error);
1908                         if (error != SocketError.Success) {
1909                                 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1910                                         connected = false;
1911                                 throw new SocketException ((int)error);
1912                         }
1913                         return bytesReceived;
1914                 }
1915
1916 #if !MOONLIGHT
1917                 public
1918 #else
1919                 internal
1920 #endif
1921                 int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
1922                 {
1923                         if (disposed && closed)
1924                                 throw new ObjectDisposedException (GetType ().ToString ());
1925
1926                         if (asyncResult == null)
1927                                 throw new ArgumentNullException ("asyncResult");
1928
1929                         SocketAsyncResult req = asyncResult as SocketAsyncResult;
1930                         if (req == null)
1931                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
1932
1933                         if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
1934                                 throw InvalidAsyncOp ("EndReceive");
1935                         if (!asyncResult.IsCompleted)
1936                                 asyncResult.AsyncWaitHandle.WaitOne ();
1937
1938                         errorCode = req.ErrorCode;
1939                         // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
1940                         // kinds of exceptions that should be thrown.
1941                         if (errorCode == SocketError.Success)
1942                                 req.CheckIfThrowDelayedException();
1943
1944                         return(req.Total);
1945                 }
1946
1947 #if !MOONLIGHT
1948                 public
1949 #else
1950                 internal
1951 #endif
1952                 int EndSend (IAsyncResult result)
1953                 {
1954                         SocketError error;
1955                         int bytesSent = EndSend (result, out error);
1956                         if (error != SocketError.Success) {
1957                                 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1958                                         connected = false;
1959                                 throw new SocketException ((int)error);
1960                         }
1961                         return bytesSent;
1962                 }
1963
1964 #if !MOONLIGHT
1965                 public
1966 #else
1967                 internal
1968 #endif
1969                 int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
1970                 {
1971                         if (disposed && closed)
1972                                 throw new ObjectDisposedException (GetType ().ToString ());
1973                         if (asyncResult == null)
1974                                 throw new ArgumentNullException ("asyncResult");
1975
1976                         SocketAsyncResult req = asyncResult as SocketAsyncResult;
1977                         if (req == null)
1978                                 throw new ArgumentException ("Invalid IAsyncResult", "result");
1979
1980                         if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
1981                                 throw InvalidAsyncOp ("EndSend");
1982                         if (!asyncResult.IsCompleted)
1983                                 asyncResult.AsyncWaitHandle.WaitOne ();
1984
1985                         errorCode = req.ErrorCode;
1986                         // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
1987                         // kinds of exceptions that should be thrown.
1988                         if (errorCode == SocketError.Success)
1989                                 req.CheckIfThrowDelayedException ();
1990
1991                         return(req.Total);
1992                 }
1993
1994                 // Used by Udpclient
1995 #if !MOONLIGHT
1996                 public
1997 #else
1998                 internal
1999 #endif
2000                 int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
2001                 {
2002                         if (disposed && closed)
2003                                 throw new ObjectDisposedException (GetType ().ToString ());
2004
2005                         if (result == null)
2006                                 throw new ArgumentNullException ("result");
2007
2008                         if (end_point == null)
2009                                 throw new ArgumentNullException ("remote_end");
2010
2011                         SocketAsyncResult req = result as SocketAsyncResult;
2012                         if (req == null)
2013                                 throw new ArgumentException ("Invalid IAsyncResult", "result");
2014
2015                         if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2016                                 throw InvalidAsyncOp ("EndReceiveFrom");
2017                         if (!result.IsCompleted)
2018                                 result.AsyncWaitHandle.WaitOne();
2019
2020                         req.CheckIfThrowDelayedException();
2021                         end_point = req.EndPoint;
2022                         return req.Total;
2023                 }
2024
2025                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2026                 static extern void socket_pool_queue (SocketAsyncCall d, SocketAsyncResult r);
2027         }
2028 }
2029