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