Fixed a few bugs that were found by Visual Studio's static code analysis.
[mono.git] / mono / metadata / socket-io.c
1 /*
2  * socket-io.c: Socket IO internal calls
3  *
4  * Authors:
5  *      Dick Porter (dick@ximian.com)
6  *      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7  *
8  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
10  */
11
12 #include <config.h>
13
14 #ifndef DISABLE_SOCKETS
15
16 #ifdef __APPLE__
17 #define __APPLE_USE_RFC_3542
18 #endif
19
20 #include <glib.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26 #include <errno.h>
27
28 #include <sys/types.h>
29 #ifdef HOST_WIN32
30 #include <ws2tcpip.h>
31 #else
32 #include <sys/socket.h>
33 #include <sys/ioctl.h>
34 #include <netinet/in.h>
35 #include <netinet/tcp.h>
36 #include <netdb.h>
37 #include <arpa/inet.h>
38 #endif
39
40 #include <mono/metadata/object.h>
41 #include <mono/io-layer/io-layer.h>
42 #include <mono/metadata/socket-io.h>
43 #include <mono/metadata/exception.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/appdomain.h>
46 #include <mono/metadata/file-io.h>
47 #include <mono/metadata/threads.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-poll.h>
50 /* FIXME change this code to not mess so much with the internals */
51 #include <mono/metadata/class-internals.h>
52 #include <mono/metadata/threadpool-internals.h>
53 #include <mono/metadata/domain-internals.h>
54 #include <mono/utils/mono-threads.h>
55 #include <mono/utils/mono-memory-model.h>
56
57 #include <time.h>
58 #ifdef HAVE_SYS_TIME_H
59 #include <sys/time.h>
60 #endif
61 #ifdef HAVE_SYS_IOCTL_H
62 #include <sys/ioctl.h>
63 #endif
64 #ifdef HAVE_NET_IF_H
65 #include <net/if.h>
66 #endif
67
68 #ifdef HAVE_NETDB_H
69 #include <netdb.h>
70 #endif
71 #ifdef HAVE_SYS_FILIO_H
72 #include <sys/filio.h>     /* defines FIONBIO and FIONREAD */
73 #endif
74 #ifdef HAVE_SYS_SOCKIO_H
75 #include <sys/sockio.h>    /* defines SIOCATMARK */
76 #endif
77 #ifdef HAVE_SYS_UN_H
78 #include <sys/un.h>
79 #endif
80
81 #ifdef HAVE_GETIFADDRS
82 // <net/if.h> must be included before <ifaddrs.h>
83 #include <ifaddrs.h>
84 #endif
85
86 #include "mono/io-layer/socket-wrappers.h"
87
88 #if defined(HOST_WIN32)
89 /* This is a kludge to make this file build under cygwin:
90  * w32api/ws2tcpip.h has definitions for some AF_INET6 values and
91  * prototypes for some but not all required functions (notably
92  * inet_ntop() is missing), but the libws2_32 library is missing the
93  * actual implementations of these functions.
94  */
95 #undef AF_INET6
96 #endif
97
98 #define LOGDEBUG(...)  
99 /* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
100
101 /* 
102  * Some older versions of libc provide IPV6 support without defining the AI_ADDRCONFIG
103  * flag for getaddrinfo.
104  */
105 #ifndef AI_ADDRCONFIG
106 #define AI_ADDRCONFIG 0
107 #endif
108
109 static gint32 convert_family(MonoAddressFamily mono_family)
110 {
111         gint32 family=-1;
112         
113         switch(mono_family) {
114         case AddressFamily_Unknown:
115         case AddressFamily_ImpLink:
116         case AddressFamily_Pup:
117         case AddressFamily_Chaos:
118         case AddressFamily_Iso:
119         case AddressFamily_Ecma:
120         case AddressFamily_DataKit:
121         case AddressFamily_Ccitt:
122         case AddressFamily_DataLink:
123         case AddressFamily_Lat:
124         case AddressFamily_HyperChannel:
125         case AddressFamily_NetBios:
126         case AddressFamily_VoiceView:
127         case AddressFamily_FireFox:
128         case AddressFamily_Banyan:
129         case AddressFamily_Atm:
130         case AddressFamily_Cluster:
131         case AddressFamily_Ieee12844:
132         case AddressFamily_NetworkDesigners:
133                 g_warning("System.Net.Sockets.AddressFamily has unsupported value 0x%x", mono_family);
134                 break;
135                 
136         case AddressFamily_Unspecified:
137                 family=AF_UNSPEC;
138                 break;
139                 
140         case AddressFamily_Unix:
141                 family=AF_UNIX;
142                 break;
143                 
144         case AddressFamily_InterNetwork:
145                 family=AF_INET;
146                 break;
147                 
148         case AddressFamily_Ipx:
149 #ifdef AF_IPX
150                 family=AF_IPX;
151 #endif
152                 break;
153                 
154         case AddressFamily_Sna:
155 #ifdef AF_SNA
156                 family=AF_SNA;
157 #endif
158                 break;
159                 
160         case AddressFamily_DecNet:
161 #ifdef AF_DECnet
162                 family=AF_DECnet;
163 #endif
164                 break;
165                 
166         case AddressFamily_AppleTalk:
167                 family=AF_APPLETALK;
168                 break;
169                 
170         case AddressFamily_InterNetworkV6:
171 #ifdef AF_INET6
172                 family=AF_INET6;
173 #endif
174                 break;
175         case AddressFamily_Irda:
176 #ifdef AF_IRDA  
177                 family=AF_IRDA;
178 #endif
179                 break;
180         default:
181                 g_warning("System.Net.Sockets.AddressFamily has unknown value 0x%x", mono_family);
182         }
183
184         return(family);
185 }
186
187 static MonoAddressFamily convert_to_mono_family(guint16 af_family)
188 {
189         MonoAddressFamily family=AddressFamily_Unknown;
190         
191         switch(af_family) {
192         case AF_UNSPEC:
193                 family=AddressFamily_Unspecified;
194                 break;
195                 
196         case AF_UNIX:
197                 family=AddressFamily_Unix;
198                 break;
199                 
200         case AF_INET:
201                 family=AddressFamily_InterNetwork;
202                 break;
203                 
204 #ifdef AF_IPX
205         case AF_IPX:
206                 family=AddressFamily_Ipx;
207                 break;
208 #endif
209                 
210 #ifdef AF_SNA
211         case AF_SNA:
212                 family=AddressFamily_Sna;
213                 break;
214 #endif
215                 
216 #ifdef AF_DECnet
217         case AF_DECnet:
218                 family=AddressFamily_DecNet;
219                 break;
220 #endif
221                 
222         case AF_APPLETALK:
223                 family=AddressFamily_AppleTalk;
224                 break;
225                 
226 #ifdef AF_INET6
227         case AF_INET6:
228                 family=AddressFamily_InterNetworkV6;
229                 break;
230 #endif
231                 
232 #ifdef AF_IRDA  
233         case AF_IRDA:
234                 family=AddressFamily_Irda;
235                 break;
236 #endif
237         default:
238                 g_warning("unknown address family 0x%x", af_family);
239         }
240
241         return(family);
242 }
243
244 static gint32 convert_type(MonoSocketType mono_type)
245 {
246         gint32 type=-1;
247         
248         switch(mono_type) {
249         case SocketType_Stream:
250                 type=SOCK_STREAM;
251                 break;
252
253         case SocketType_Dgram:
254                 type=SOCK_DGRAM;
255                 break;
256                 
257         case SocketType_Raw:
258                 type=SOCK_RAW;
259                 break;
260
261         case SocketType_Rdm:
262 #ifdef SOCK_RDM
263                 type=SOCK_RDM;
264 #endif
265                 break;
266
267         case SocketType_Seqpacket:
268                 type=SOCK_SEQPACKET;
269                 break;
270
271         case SocketType_Unknown:
272                 g_warning("System.Net.Sockets.SocketType has unsupported value 0x%x", mono_type);
273                 break;
274
275         default:
276                 g_warning("System.Net.Sockets.SocketType has unknown value 0x%x", mono_type);
277         }
278
279         return(type);
280 }
281
282 static gint32 convert_proto(MonoProtocolType mono_proto)
283 {
284         gint32 proto=-1;
285         
286         switch(mono_proto) {
287         case ProtocolType_IP:
288         case ProtocolType_IPv6:
289         case ProtocolType_Icmp:
290         case ProtocolType_Igmp:
291         case ProtocolType_Ggp:
292         case ProtocolType_Tcp:
293         case ProtocolType_Pup:
294         case ProtocolType_Udp:
295         case ProtocolType_Idp:
296                 /* These protocols are known (on my system at least) */
297                 proto=mono_proto;
298                 break;
299                 
300         case ProtocolType_ND:
301         case ProtocolType_Raw:
302         case ProtocolType_Ipx:
303         case ProtocolType_Spx:
304         case ProtocolType_SpxII:
305         case ProtocolType_Unknown:
306                 /* These protocols arent */
307                 g_warning("System.Net.Sockets.ProtocolType has unsupported value 0x%x", mono_proto);
308                 break;
309                 
310         default:
311                 break;
312         }
313
314         return(proto);
315 }
316
317 /* Convert MonoSocketFlags */
318 static gint32 convert_socketflags (gint32 sflags)
319 {
320         gint32 flags = 0;
321
322         if (!sflags)
323                 /* SocketFlags.None */
324                 return 0;
325
326         if (sflags & ~(SocketFlags_OutOfBand | SocketFlags_MaxIOVectorLength | SocketFlags_Peek | 
327                         SocketFlags_DontRoute | SocketFlags_Partial))
328                 /* Contains invalid flag values */
329                 return -1;
330
331         if (sflags & SocketFlags_OutOfBand)
332                 flags |= MSG_OOB;
333         if (sflags & SocketFlags_Peek)
334                 flags |= MSG_PEEK;
335         if (sflags & SocketFlags_DontRoute)
336                 flags |= MSG_DONTROUTE;
337
338         /* Ignore Partial - see bug 349688.  Don't return -1, because
339          * according to the comment in that bug ms runtime doesn't for
340          * UDP sockets (this means we will silently ignore it for TCP
341          * too)
342          */
343 #ifdef MSG_MORE
344         if (sflags & SocketFlags_Partial)
345                 flags |= MSG_MORE;
346 #endif
347 #if 0
348         /* Don't do anything for MaxIOVectorLength */
349         if (sflags & SocketFlags_MaxIOVectorLength)
350                 return -1;      
351 #endif
352         return flags;
353 }
354
355 /*
356  * Returns:
357  *    0 on success (mapped mono_level and mono_name to system_level and system_name
358  *   -1 on error
359  *   -2 on non-fatal error (ie, must ignore)
360  */
361 static gint32 convert_sockopt_level_and_name(MonoSocketOptionLevel mono_level,
362                                              MonoSocketOptionName mono_name,
363                                              int *system_level,
364                                              int *system_name)
365 {
366         switch (mono_level) {
367         case SocketOptionLevel_Socket:
368                 *system_level = SOL_SOCKET;
369                 
370                 switch(mono_name) {
371                 case SocketOptionName_DontLinger:
372                         /* This is SO_LINGER, because the setsockopt
373                          * internal call maps DontLinger to SO_LINGER
374                          * with l_onoff=0
375                          */
376                         *system_name = SO_LINGER;
377                         break;
378                 case SocketOptionName_Debug:
379                         *system_name = SO_DEBUG;
380                         break;
381 #ifdef SO_ACCEPTCONN
382                 case SocketOptionName_AcceptConnection:
383                         *system_name = SO_ACCEPTCONN;
384                         break;
385 #endif
386                 case SocketOptionName_ReuseAddress:
387                         *system_name = SO_REUSEADDR;
388                         break;
389                 case SocketOptionName_KeepAlive:
390                         *system_name = SO_KEEPALIVE;
391                         break;
392                 case SocketOptionName_DontRoute:
393                         *system_name = SO_DONTROUTE;
394                         break;
395                 case SocketOptionName_Broadcast:
396                         *system_name = SO_BROADCAST;
397                         break;
398                 case SocketOptionName_Linger:
399                         *system_name = SO_LINGER;
400                         break;
401                 case SocketOptionName_OutOfBandInline:
402                         *system_name = SO_OOBINLINE;
403                         break;
404                 case SocketOptionName_SendBuffer:
405                         *system_name = SO_SNDBUF;
406                         break;
407                 case SocketOptionName_ReceiveBuffer:
408                         *system_name = SO_RCVBUF;
409                         break;
410                 case SocketOptionName_SendLowWater:
411                         *system_name = SO_SNDLOWAT;
412                         break;
413                 case SocketOptionName_ReceiveLowWater:
414                         *system_name = SO_RCVLOWAT;
415                         break;
416                 case SocketOptionName_SendTimeout:
417                         *system_name = SO_SNDTIMEO;
418                         break;
419                 case SocketOptionName_ReceiveTimeout:
420                         *system_name = SO_RCVTIMEO;
421                         break;
422                 case SocketOptionName_Error:
423                         *system_name = SO_ERROR;
424                         break;
425                 case SocketOptionName_Type:
426                         *system_name = SO_TYPE;
427                         break;
428 #ifdef SO_PEERCRED
429                 case SocketOptionName_PeerCred:
430                         *system_name = SO_PEERCRED;
431                         break;
432 #endif
433                 case SocketOptionName_ExclusiveAddressUse:
434 #ifdef SO_EXCLUSIVEADDRUSE
435                         *system_name = SO_EXCLUSIVEADDRUSE;
436                         break;
437 #endif
438                 case SocketOptionName_UseLoopback:
439 #ifdef SO_USELOOPBACK
440                         *system_name = SO_USELOOPBACK;
441                         break;
442 #endif
443                 case SocketOptionName_MaxConnections:
444 #ifdef SO_MAXCONN
445                         *system_name = SO_MAXCONN;
446                         break;
447 #elif defined(SOMAXCONN)
448                         *system_name = SOMAXCONN;
449                         break;
450 #endif
451                 default:
452                         g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at Socket level", mono_name);
453                         return(-1);
454                 }
455                 break;
456                 
457         case SocketOptionLevel_IP:
458 #ifdef HAVE_SOL_IP
459                 *system_level = SOL_IP;
460 #else
461                 if (1) {
462                         static int cached = 0;
463                         static int proto;
464                         
465                         if (!cached) {
466                                 struct protoent *pent;
467                                 
468                                 pent = getprotobyname ("IP");
469                                 proto = pent ? pent->p_proto : 0 /* 0 a good default value?? */;
470                                 cached = 1;
471                         }
472                         
473                         *system_level = proto;
474                 }
475 #endif /* HAVE_SOL_IP */
476                 
477                 switch(mono_name) {
478                 case SocketOptionName_IPOptions:
479                         *system_name = IP_OPTIONS;
480                         break;
481 #ifdef IP_HDRINCL
482                 case SocketOptionName_HeaderIncluded:
483                         *system_name = IP_HDRINCL;
484                         break;
485 #endif
486 #ifdef IP_TOS
487                 case SocketOptionName_TypeOfService:
488                         *system_name = IP_TOS;
489                         break;
490 #endif
491 #ifdef IP_TTL
492                 case SocketOptionName_IpTimeToLive:
493                         *system_name = IP_TTL;
494                         break;
495 #endif
496                 case SocketOptionName_MulticastInterface:
497                         *system_name = IP_MULTICAST_IF;
498                         break;
499                 case SocketOptionName_MulticastTimeToLive:
500                         *system_name = IP_MULTICAST_TTL;
501                         break;
502                 case SocketOptionName_MulticastLoopback:
503                         *system_name = IP_MULTICAST_LOOP;
504                         break;
505                 case SocketOptionName_AddMembership:
506                         *system_name = IP_ADD_MEMBERSHIP;
507                         break;
508                 case SocketOptionName_DropMembership:
509                         *system_name = IP_DROP_MEMBERSHIP;
510                         break;
511 #ifdef HAVE_IP_PKTINFO
512                 case SocketOptionName_PacketInformation:
513                         *system_name = IP_PKTINFO;
514                         break;
515 #endif /* HAVE_IP_PKTINFO */
516
517                 case SocketOptionName_DontFragment:
518 #ifdef HAVE_IP_DONTFRAGMENT
519                         *system_name = IP_DONTFRAGMENT;
520                         break;
521 #elif defined HAVE_IP_MTU_DISCOVER
522                         /* Not quite the same */
523                         *system_name = IP_MTU_DISCOVER;
524                         break;
525 #else
526                         /* If the flag is not available on this system, we can ignore this error */
527                         return (-2);
528 #endif /* HAVE_IP_DONTFRAGMENT */
529                 case SocketOptionName_AddSourceMembership:
530                 case SocketOptionName_DropSourceMembership:
531                 case SocketOptionName_BlockSource:
532                 case SocketOptionName_UnblockSource:
533                         /* Can't figure out how to map these, so fall
534                          * through
535                          */
536                 default:
537                         g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at IP level", mono_name);
538                         return(-1);
539                 }
540                 break;
541
542 #ifdef AF_INET6
543         case SocketOptionLevel_IPv6:
544 #ifdef HAVE_SOL_IPV6
545                 *system_level = SOL_IPV6;
546 #else
547                 if (1) {
548                         static int cached = 0;
549                         static int proto;
550
551                         if (!cached) {
552                                 struct protoent *pent;
553
554                                 pent = getprotobyname ("IPV6");
555                                 proto = pent ? pent->p_proto : 41 /* 41 a good default value?? */;
556                                 cached = 1;
557                         }
558
559                         *system_level = proto;
560                 }
561 #endif /* HAVE_SOL_IPV6 */
562
563                 switch(mono_name) {
564                 case SocketOptionName_IpTimeToLive:
565                 case SocketOptionName_HopLimit:
566                         *system_name = IPV6_UNICAST_HOPS;
567                         break;
568                 case SocketOptionName_MulticastInterface:
569                         *system_name = IPV6_MULTICAST_IF;
570                         break;
571                 case SocketOptionName_MulticastTimeToLive:
572                         *system_name = IPV6_MULTICAST_HOPS;
573                         break;
574                 case SocketOptionName_MulticastLoopback:
575                         *system_name = IPV6_MULTICAST_LOOP;
576                         break;
577                 case SocketOptionName_AddMembership:
578                         *system_name = IPV6_JOIN_GROUP;
579                         break;
580                 case SocketOptionName_DropMembership:
581                         *system_name = IPV6_LEAVE_GROUP;
582                         break;
583                 case SocketOptionName_PacketInformation:
584 #ifdef HAVE_IPV6_PKTINFO
585                         *system_name = IPV6_PKTINFO;
586 #endif
587                         break;
588                 case SocketOptionName_HeaderIncluded:
589                 case SocketOptionName_IPOptions:
590                 case SocketOptionName_TypeOfService:
591                 case SocketOptionName_DontFragment:
592                 case SocketOptionName_AddSourceMembership:
593                 case SocketOptionName_DropSourceMembership:
594                 case SocketOptionName_BlockSource:
595                 case SocketOptionName_UnblockSource:
596                         /* Can't figure out how to map these, so fall
597                          * through
598                          */
599                 default:
600                         g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at IPv6 level", mono_name);
601                         return(-1);
602                 }
603
604                 break;  /* SocketOptionLevel_IPv6 */
605 #endif
606                 
607         case SocketOptionLevel_Tcp:
608 #ifdef HAVE_SOL_TCP
609                 *system_level = SOL_TCP;
610 #else
611                 if (1) {
612                         static int cached = 0;
613                         static int proto;
614                         
615                         if (!cached) {
616                                 struct protoent *pent;
617                                 
618                                 pent = getprotobyname ("TCP");
619                                 proto = pent ? pent->p_proto : 6 /* is 6 a good default value?? */;
620                                 cached = 1;
621                         }
622                         
623                         *system_level = proto;
624                 }
625 #endif /* HAVE_SOL_TCP */
626                 
627                 switch(mono_name) {
628                 case SocketOptionName_NoDelay:
629                         *system_name = TCP_NODELAY;
630                         break;
631 #if 0
632                         /* The documentation is talking complete
633                          * bollocks here: rfc-1222 is titled
634                          * 'Advancing the NSFNET Routing Architecture'
635                          * and doesn't mention either of the words
636                          * "expedite" or "urgent".
637                          */
638                 case SocketOptionName_BsdUrgent:
639                 case SocketOptionName_Expedited:
640 #endif
641                 default:
642                         g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at TCP level", mono_name);
643                         return(-1);
644                 }
645                 break;
646                 
647         case SocketOptionLevel_Udp:
648                 g_warning("System.Net.Sockets.SocketOptionLevel has unsupported value 0x%x", mono_level);
649
650                 switch(mono_name) {
651                 case SocketOptionName_NoChecksum:
652                 case SocketOptionName_ChecksumCoverage:
653                 default:
654                         g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at UDP level", mono_name);
655                         return(-1);
656                 }
657                 return(-1);
658                 break;
659
660         default:
661                 g_warning("System.Net.Sockets.SocketOptionLevel has unknown value 0x%x", mono_level);
662                 return(-1);
663         }
664
665         return(0);
666 }
667
668 static MonoImage *get_socket_assembly (void)
669 {
670         MonoDomain *domain = mono_domain_get ();
671         
672         if (domain->socket_assembly == NULL) {
673                 MonoImage *socket_assembly;
674
675                 socket_assembly = mono_image_loaded ("System");
676                 if (!socket_assembly) {
677                         MonoAssembly *sa = mono_assembly_open ("System.dll", NULL);
678                 
679                         if (!sa) {
680                                 g_assert_not_reached ();
681                         } else {
682                                 socket_assembly = mono_assembly_get_image (sa);
683                         }
684                 }
685                 mono_atomic_store_release (&domain->socket_assembly, socket_assembly);
686         }
687         
688         return domain->socket_assembly;
689 }
690
691 #ifdef AF_INET6
692 static gint32 get_family_hint(void)
693 {
694         MonoDomain *domain = mono_domain_get ();
695
696         if (!domain->inet_family_hint) {
697                 MonoClass *socket_class;
698                 MonoClassField *ipv6_field, *ipv4_field;
699                 gint32 ipv6_enabled = -1, ipv4_enabled = -1;
700                 MonoVTable *vtable;
701
702                 socket_class = mono_class_from_name (get_socket_assembly (), "System.Net.Sockets", "Socket");
703                 ipv4_field = mono_class_get_field_from_name (socket_class, "ipv4Supported");
704                 ipv6_field = mono_class_get_field_from_name (socket_class, "ipv6Supported");
705                 vtable = mono_class_vtable (mono_domain_get (), socket_class);
706                 g_assert (vtable);
707                 mono_runtime_class_init (vtable);
708
709                 mono_field_static_get_value (vtable, ipv4_field, &ipv4_enabled);
710                 mono_field_static_get_value (vtable, ipv6_field, &ipv6_enabled);
711
712                 mono_domain_lock (domain);
713                 if (ipv4_enabled == 1 && ipv6_enabled == 1) {
714                         domain->inet_family_hint = 1;
715                 } else if (ipv4_enabled == 1) {
716                         domain->inet_family_hint = 2;
717                 } else {
718                         domain->inet_family_hint = 3;
719                 }
720                 mono_domain_unlock (domain);
721         }
722         switch (domain->inet_family_hint) {
723         case 1: return PF_UNSPEC;
724         case 2: return PF_INET;
725         case 3: return PF_INET6;
726         default:
727                 return PF_UNSPEC;
728         }
729 }
730 #endif
731
732 gpointer ves_icall_System_Net_Sockets_Socket_Socket_internal(MonoObject *this, gint32 family, gint32 type, gint32 proto, gint32 *error)
733 {
734         SOCKET sock;
735         gint32 sock_family;
736         gint32 sock_proto;
737         gint32 sock_type;
738         
739         MONO_ARCH_SAVE_REGS;
740
741         *error = 0;
742         
743         sock_family=convert_family(family);
744         if(sock_family==-1) {
745                 *error = WSAEAFNOSUPPORT;
746                 return(NULL);
747         }
748
749         sock_proto=convert_proto(proto);
750         if(sock_proto==-1) {
751                 *error = WSAEPROTONOSUPPORT;
752                 return(NULL);
753         }
754         
755         sock_type=convert_type(type);
756         if(sock_type==-1) {
757                 *error = WSAESOCKTNOSUPPORT;
758                 return(NULL);
759         }
760         
761         sock = _wapi_socket (sock_family, sock_type, sock_proto,
762                              NULL, 0, WSA_FLAG_OVERLAPPED);
763
764         if(sock==INVALID_SOCKET) {
765                 *error = WSAGetLastError ();
766                 return(NULL);
767         }
768
769         if (sock_family == AF_INET && sock_type == SOCK_DGRAM) {
770                 return (GUINT_TO_POINTER (sock));
771         }
772
773 #ifdef AF_INET6
774         if (sock_family == AF_INET6 && sock_type == SOCK_DGRAM) {
775                 return (GUINT_TO_POINTER (sock));
776         }
777 #endif
778
779         return(GUINT_TO_POINTER (sock));
780 }
781
782 /* FIXME: the SOCKET parameter (here and in other functions in this
783  * file) is really an IntPtr which needs to be converted to a guint32.
784  */
785 void ves_icall_System_Net_Sockets_Socket_Close_internal(SOCKET sock,
786                                                         gint32 *error)
787 {
788         MONO_ARCH_SAVE_REGS;
789
790         LOGDEBUG (g_message ("%s: closing 0x%x", __func__, sock));
791
792         *error = 0;
793
794         /* Clear any pending work item from this socket if the underlying
795          * polling system does not notify when the socket is closed */
796         mono_thread_pool_remove_socket (GPOINTER_TO_INT (sock));
797         closesocket(sock);
798 }
799
800 gint32 ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal(void)
801 {
802         MONO_ARCH_SAVE_REGS;
803
804         LOGDEBUG (g_message("%s: returning %d", __func__, WSAGetLastError()));
805
806         return(WSAGetLastError());
807 }
808
809 gint32 ves_icall_System_Net_Sockets_Socket_Available_internal(SOCKET sock,
810                                                               gint32 *error)
811 {
812         int ret;
813         int amount;
814         
815         MONO_ARCH_SAVE_REGS;
816
817         *error = 0;
818
819         /* FIXME: this might require amount to be unsigned long. */
820         ret=ioctlsocket(sock, FIONREAD, &amount);
821         if(ret==SOCKET_ERROR) {
822                 *error = WSAGetLastError ();
823                 return(0);
824         }
825         
826         return(amount);
827 }
828
829 void ves_icall_System_Net_Sockets_Socket_Blocking_internal(SOCKET sock,
830                                                            gboolean block,
831                                                            gint32 *error)
832 {
833         int ret;
834         
835         MONO_ARCH_SAVE_REGS;
836
837         *error = 0;
838
839         /*
840          * block == TRUE/FALSE means we will block/not block.
841          * But the ioctlsocket call takes TRUE/FALSE for non-block/block
842          */
843         block = !block;
844         
845         ret = ioctlsocket (sock, FIONBIO, (gulong *) &block);
846         if(ret==SOCKET_ERROR) {
847                 *error = WSAGetLastError ();
848         }
849 }
850
851 gpointer ves_icall_System_Net_Sockets_Socket_Accept_internal(SOCKET sock,
852                                                              gint32 *error,
853                                                              gboolean blocking)
854 {
855         SOCKET newsock;
856         
857         MONO_ARCH_SAVE_REGS;
858
859         *error = 0;
860 #ifdef HOST_WIN32
861         {
862                 MonoInternalThread* curthread = mono_thread_internal_current ();
863                 curthread->interrupt_on_stop = (gpointer)TRUE;
864                 newsock = _wapi_accept (sock, NULL, 0);
865                 curthread->interrupt_on_stop = (gpointer)FALSE;
866         }
867 #else
868         newsock = _wapi_accept (sock, NULL, 0);
869 #endif
870         if(newsock==INVALID_SOCKET) {
871                 *error = WSAGetLastError ();
872                 return(NULL);
873         }
874         
875         return(GUINT_TO_POINTER (newsock));
876 }
877
878 void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock,
879                                                          guint32 backlog,
880                                                          gint32 *error)
881 {
882         int ret;
883         
884         MONO_ARCH_SAVE_REGS;
885
886         *error = 0;
887         
888         ret = _wapi_listen (sock, backlog);
889         if(ret==SOCKET_ERROR) {
890                 *error = WSAGetLastError ();
891         }
892 }
893
894 #ifdef AF_INET6
895 // Check whether it's ::ffff::0:0.
896 static gboolean
897 is_ipv4_mapped_any (const struct in6_addr *addr)
898 {
899         int i;
900         
901         for (i = 0; i < 10; i++) {
902                 if (addr->s6_addr [i])
903                         return FALSE;
904         }
905         if ((addr->s6_addr [10] != 0xff) || (addr->s6_addr [11] != 0xff))
906                 return FALSE;
907         for (i = 12; i < 16; i++) {
908                 if (addr->s6_addr [i])
909                         return FALSE;
910         }
911         return TRUE;
912 }
913 #endif
914
915 static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
916                                                int sa_size, gint32 *error)
917 {
918         MonoDomain *domain = mono_domain_get ();
919         MonoObject *sockaddr_obj;
920         MonoArray *data;
921         MonoAddressFamily family;
922
923         /* Build a System.Net.SocketAddress object instance */
924         if (!domain->sockaddr_class) {
925                 domain->sockaddr_class=mono_class_from_name (get_socket_assembly (), "System.Net", "SocketAddress");
926                 g_assert (domain->sockaddr_class);
927         }
928         sockaddr_obj=mono_object_new(domain, domain->sockaddr_class);
929         
930         /* Locate the SocketAddress data buffer in the object */
931         if (!domain->sockaddr_data_field) {
932                 domain->sockaddr_data_field=mono_class_get_field_from_name (domain->sockaddr_class, "data");
933                 g_assert (domain->sockaddr_data_field);
934         }
935
936         /* May be the +2 here is too conservative, as sa_len returns
937          * the length of the entire sockaddr_in/in6, including
938          * sizeof (unsigned short) of the family */
939         /* We can't really avoid the +2 as all code below depends on this size - INCLUDING unix domain sockets.*/
940         data=mono_array_new_cached(domain, mono_get_byte_class (), sa_size+2);
941
942         /* The data buffer is laid out as follows:
943          * bytes 0 and 1 are the address family
944          * bytes 2 and 3 are the port info
945          * the rest is the address info
946          */
947                 
948         family=convert_to_mono_family(saddr->sa_family);
949         if(family==AddressFamily_Unknown) {
950                 *error = WSAEAFNOSUPPORT;
951                 return(NULL);
952         }
953
954         mono_array_set(data, guint8, 0, family & 0x0FF);
955         mono_array_set(data, guint8, 1, (family >> 8) & 0x0FF);
956         
957         if(saddr->sa_family==AF_INET) {
958                 struct sockaddr_in *sa_in=(struct sockaddr_in *)saddr;
959                 guint16 port=ntohs(sa_in->sin_port);
960                 guint32 address=ntohl(sa_in->sin_addr.s_addr);
961                 
962                 if(sa_size<8) {
963                         mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
964                 }
965                 
966                 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
967                 mono_array_set(data, guint8, 3, (port) & 0xff);
968                 mono_array_set(data, guint8, 4, (address>>24) & 0xff);
969                 mono_array_set(data, guint8, 5, (address>>16) & 0xff);
970                 mono_array_set(data, guint8, 6, (address>>8) & 0xff);
971                 mono_array_set(data, guint8, 7, (address) & 0xff);
972         
973                 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
974
975                 return(sockaddr_obj);
976 #ifdef AF_INET6
977         } else if (saddr->sa_family == AF_INET6) {
978                 struct sockaddr_in6 *sa_in=(struct sockaddr_in6 *)saddr;
979                 int i;
980
981                 guint16 port=ntohs(sa_in->sin6_port);
982
983                 if(sa_size<28) {
984                         mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
985                 }
986
987                 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
988                 mono_array_set(data, guint8, 3, (port) & 0xff);
989                 
990                 if (is_ipv4_mapped_any (&sa_in->sin6_addr)) {
991                         // Map ::ffff:0:0 to :: (bug #5502)
992                         for(i=0; i<16; i++) {
993                                 mono_array_set(data, guint8, 8+i, 0);
994                         }
995                 } else {
996                         for(i=0; i<16; i++) {
997                                 mono_array_set(data, guint8, 8+i,
998                                                sa_in->sin6_addr.s6_addr[i]);
999                         }
1000                 }
1001
1002                 mono_array_set(data, guint8, 24, sa_in->sin6_scope_id & 0xff);
1003                 mono_array_set(data, guint8, 25,
1004                                (sa_in->sin6_scope_id >> 8) & 0xff);
1005                 mono_array_set(data, guint8, 26,
1006                                (sa_in->sin6_scope_id >> 16) & 0xff);
1007                 mono_array_set(data, guint8, 27,
1008                                (sa_in->sin6_scope_id >> 24) & 0xff);
1009
1010                 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
1011
1012                 return(sockaddr_obj);
1013 #endif
1014 #ifdef HAVE_SYS_UN_H
1015         } else if (saddr->sa_family == AF_UNIX) {
1016                 int i;
1017
1018                 for (i = 0; i < sa_size; i++) {
1019                         mono_array_set (data, guint8, i+2, saddr->sa_data[i]);
1020                 }
1021                 
1022                 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
1023
1024                 return sockaddr_obj;
1025 #endif
1026         } else {
1027                 *error = WSAEAFNOSUPPORT;
1028                 return(NULL);
1029         }
1030 }
1031
1032 static int
1033 get_sockaddr_size (int family)
1034 {
1035         int size;
1036
1037         size = 0;
1038         if (family == AF_INET) {
1039                 size = sizeof (struct sockaddr_in);
1040 #ifdef AF_INET6
1041         } else if (family == AF_INET6) {
1042                 size = sizeof (struct sockaddr_in6);
1043 #endif
1044 #ifdef HAVE_SYS_UN_H
1045         } else if (family == AF_UNIX) {
1046                 size = sizeof (struct sockaddr_un);
1047 #endif
1048         }
1049         return size;
1050 }
1051
1052 extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 af, gint32 *error)
1053 {
1054         gchar *sa;
1055         socklen_t salen;
1056         int ret;
1057         MonoObject *result;
1058         
1059         MONO_ARCH_SAVE_REGS;
1060
1061         *error = 0;
1062         
1063         salen = get_sockaddr_size (convert_family (af));
1064         if (salen == 0) {
1065                 *error = WSAEAFNOSUPPORT;
1066                 return NULL;
1067         }
1068         sa = (salen <= 128) ? alloca (salen) : g_malloc0 (salen);
1069         ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
1070         
1071         if(ret==SOCKET_ERROR) {
1072                 *error = WSAGetLastError ();
1073                 if (salen > 128)
1074                         g_free (sa);
1075                 return(NULL);
1076         }
1077         
1078         LOGDEBUG (g_message("%s: bound to %s port %d", __func__, inet_ntoa(((struct sockaddr_in *)&sa)->sin_addr), ntohs(((struct sockaddr_in *)&sa)->sin_port)));
1079
1080         result = create_object_from_sockaddr((struct sockaddr *)sa, salen, error);
1081         if (salen > 128)
1082                 g_free (sa);
1083         return result;
1084 }
1085
1086 extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 af, gint32 *error)
1087 {
1088         gchar *sa;
1089         socklen_t salen;
1090         int ret;
1091         MonoObject *result;
1092         
1093         MONO_ARCH_SAVE_REGS;
1094
1095         *error = 0;
1096         
1097         salen = get_sockaddr_size (convert_family (af));
1098         if (salen == 0) {
1099                 *error = WSAEAFNOSUPPORT;
1100                 return NULL;
1101         }
1102         sa = (salen <= 128) ? alloca (salen) : g_malloc0 (salen);
1103         /* Note: linux returns just 2 for AF_UNIX. Always. */
1104         ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
1105         if(ret==SOCKET_ERROR) {
1106                 *error = WSAGetLastError ();
1107                 if (salen > 128)
1108                         g_free (sa);
1109                 return(NULL);
1110         }
1111         
1112         LOGDEBUG (g_message("%s: connected to %s port %d", __func__, inet_ntoa(((struct sockaddr_in *)&sa)->sin_addr), ntohs(((struct sockaddr_in *)&sa)->sin_port)));
1113
1114         result = create_object_from_sockaddr((struct sockaddr *)sa, salen, error);
1115         if (salen > 128)
1116                 g_free (sa);
1117         return result;
1118 }
1119
1120 static struct sockaddr *create_sockaddr_from_object(MonoObject *saddr_obj,
1121                                                     socklen_t *sa_size,
1122                                                     gint32 *error)
1123 {
1124         MonoClassField *field;
1125         MonoArray *data;
1126         gint32 family;
1127         int len;
1128
1129         /* Dig the SocketAddress data buffer out of the object */
1130         field=mono_class_get_field_from_name(saddr_obj->vtable->klass, "data");
1131         data=*(MonoArray **)(((char *)saddr_obj) + field->offset);
1132
1133         /* The data buffer is laid out as follows:
1134          * byte 0 is the address family low byte
1135          * byte 1 is the address family high byte
1136          * INET:
1137          *      bytes 2 and 3 are the port info
1138          *      the rest is the address info
1139          * UNIX:
1140          *      the rest is the file name
1141          */
1142         len = mono_array_length (data);
1143         if (len < 2) {
1144                 mono_raise_exception (mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
1145         }
1146         
1147         family = convert_family (mono_array_get (data, guint8, 0) + (mono_array_get (data, guint8, 1) << 8));
1148         if (family == AF_INET) {
1149                 struct sockaddr_in *sa;
1150                 guint16 port;
1151                 guint32 address;
1152                 
1153                 if (len < 8) {
1154                         mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1155                 }
1156
1157                 sa = g_new0 (struct sockaddr_in, 1);
1158                 port = (mono_array_get (data, guint8, 2) << 8) +
1159                         mono_array_get (data, guint8, 3);
1160                 address = (mono_array_get (data, guint8, 4) << 24) +
1161                         (mono_array_get (data, guint8, 5) << 16 ) +
1162                         (mono_array_get (data, guint8, 6) << 8) +
1163                         mono_array_get (data, guint8, 7);
1164
1165                 sa->sin_family = family;
1166                 sa->sin_addr.s_addr = htonl (address);
1167                 sa->sin_port = htons (port);
1168
1169                 *sa_size = sizeof(struct sockaddr_in);
1170                 return((struct sockaddr *)sa);
1171
1172 #ifdef AF_INET6
1173         } else if (family == AF_INET6) {
1174                 struct sockaddr_in6 *sa;
1175                 int i;
1176                 guint16 port;
1177                 guint32 scopeid;
1178                 
1179                 if (len < 28) {
1180                         mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1181                 }
1182
1183                 sa = g_new0 (struct sockaddr_in6, 1);
1184                 port = mono_array_get (data, guint8, 3) +
1185                         (mono_array_get (data, guint8, 2) << 8);
1186                 scopeid = mono_array_get (data, guint8, 24) + 
1187                         (mono_array_get (data, guint8, 25) << 8) + 
1188                         (mono_array_get (data, guint8, 26) << 16) + 
1189                         (mono_array_get (data, guint8, 27) << 24);
1190
1191                 sa->sin6_family = family;
1192                 sa->sin6_port = htons (port);
1193                 sa->sin6_scope_id = scopeid;
1194
1195                 for(i=0; i<16; i++) {
1196                         sa->sin6_addr.s6_addr[i] = mono_array_get (data, guint8, 8+i);
1197                 }
1198
1199                 *sa_size = sizeof(struct sockaddr_in6);
1200                 return((struct sockaddr *)sa);
1201 #endif
1202 #ifdef HAVE_SYS_UN_H
1203         } else if (family == AF_UNIX) {
1204                 struct sockaddr_un *sock_un;
1205                 int i;
1206
1207                 /* Need a byte for the '\0' terminator/prefix, and the first
1208                  * two bytes hold the SocketAddress family
1209                  */
1210                 if (len - 2 >= MONO_SIZEOF_SUNPATH) {
1211                         mono_raise_exception (mono_get_exception_index_out_of_range ());
1212                 }
1213                 
1214                 sock_un = g_new0 (struct sockaddr_un, 1);
1215
1216                 sock_un->sun_family = family;
1217                 for (i = 0; i < len - 2; i++) {
1218                         sock_un->sun_path [i] = mono_array_get (data, guint8,
1219                                                                 i + 2);
1220                 }
1221                 
1222                 *sa_size = len;
1223
1224                 return (struct sockaddr *)sock_un;
1225 #endif
1226         } else {
1227                 *error = WSAEAFNOSUPPORT;
1228                 return(0);
1229         }
1230 }
1231
1232 extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1233 {
1234         struct sockaddr *sa;
1235         socklen_t sa_size;
1236         int ret;
1237         
1238         MONO_ARCH_SAVE_REGS;
1239
1240         *error = 0;
1241         
1242         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1243         if (*error != 0) {
1244                 return;
1245         }
1246
1247         LOGDEBUG (g_message("%s: binding to %s port %d", __func__, inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), ntohs (((struct sockaddr_in *)sa)->sin_port)));
1248
1249         ret = _wapi_bind (sock, sa, sa_size);
1250         if(ret==SOCKET_ERROR) {
1251                 *error = WSAGetLastError ();
1252         }
1253
1254         g_free(sa);
1255 }
1256
1257 enum {
1258         SelectModeRead,
1259         SelectModeWrite,
1260         SelectModeError
1261 };
1262
1263 MonoBoolean
1264 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
1265                                                    gint timeout, gint32 *error)
1266 {
1267         MonoInternalThread *thread = NULL;
1268         mono_pollfd *pfds;
1269         int ret;
1270         time_t start;
1271         
1272
1273         MONO_ARCH_SAVE_REGS;
1274         
1275         pfds = g_new0 (mono_pollfd, 1);
1276         pfds[0].fd = GPOINTER_TO_INT (sock);
1277         pfds[0].events = (mode == SelectModeRead) ? MONO_POLLIN :
1278                 (mode == SelectModeWrite) ? MONO_POLLOUT :
1279                 (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL);
1280
1281         timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1282         start = time (NULL);
1283         do {
1284                 *error = 0;
1285                 
1286                 ret = mono_poll (pfds, 1, timeout);
1287                 if (timeout > 0 && ret < 0) {
1288                         int err = errno;
1289                         int sec = time (NULL) - start;
1290                         
1291                         timeout -= sec * 1000;
1292                         if (timeout < 0) {
1293                                 timeout = 0;
1294                         }
1295                         
1296                         errno = err;
1297                 }
1298                 
1299                 if (ret == -1 && errno == EINTR) {
1300                         int leave = 0;
1301
1302                         if (thread == NULL) {
1303                                 thread = mono_thread_internal_current ();
1304                         }
1305                         
1306                         leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1307                         
1308                         if (leave != 0) {
1309                                 g_free (pfds);
1310                                 return(FALSE);
1311                         } else {
1312                                 /* Suspend requested? */
1313                                 mono_thread_interruption_checkpoint ();
1314                         }
1315                         errno = EINTR;
1316                 }
1317         } while (ret == -1 && errno == EINTR);
1318
1319         if (ret == -1) {
1320 #ifdef HOST_WIN32
1321                 *error = WSAGetLastError ();
1322 #else
1323                 *error = errno_to_WSA (errno, __func__);
1324 #endif
1325                 g_free (pfds);
1326                 return(FALSE);
1327         }
1328         
1329         g_free (pfds);
1330
1331         if (ret == 0) {
1332                 return(FALSE);
1333         } else {
1334                 return (TRUE);
1335         }
1336 }
1337
1338 extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1339 {
1340         struct sockaddr *sa;
1341         socklen_t sa_size;
1342         int ret;
1343         
1344         MONO_ARCH_SAVE_REGS;
1345
1346         *error = 0;
1347         
1348         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1349         if (*error != 0) {
1350                 return;
1351         }
1352         
1353         LOGDEBUG (g_message("%s: connecting to %s port %d", __func__, inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), ntohs (((struct sockaddr_in *)sa)->sin_port)));
1354
1355         ret = _wapi_connect (sock, sa, sa_size);
1356         if(ret==SOCKET_ERROR) {
1357                 *error = WSAGetLastError ();
1358         }
1359
1360         g_free(sa);
1361 }
1362
1363 /* These #defines from mswsock.h from wine.  Defining them here allows
1364  * us to build this file on a mingw box that doesn't know the magic
1365  * numbers, but still run on a newer windows box that does.
1366  */
1367 #ifndef WSAID_DISCONNECTEX
1368 #define WSAID_DISCONNECTEX {0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
1369 typedef BOOL (WINAPI *LPFN_DISCONNECTEX)(SOCKET, LPOVERLAPPED, DWORD, DWORD);
1370 #endif
1371
1372 #ifndef WSAID_TRANSMITFILE
1373 #define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
1374 typedef BOOL (WINAPI *LPFN_TRANSMITFILE)(SOCKET, HANDLE, DWORD, DWORD, LPOVERLAPPED, LPTRANSMIT_FILE_BUFFERS, DWORD);
1375 #endif
1376
1377 extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error)
1378 {
1379         int ret;
1380         glong output_bytes = 0;
1381         GUID disco_guid = WSAID_DISCONNECTEX;
1382         GUID trans_guid = WSAID_TRANSMITFILE;
1383         LPFN_DISCONNECTEX _wapi_disconnectex = NULL;
1384         LPFN_TRANSMITFILE _wapi_transmitfile = NULL;
1385         gboolean bret;
1386         
1387         MONO_ARCH_SAVE_REGS;
1388
1389         *error = 0;
1390         
1391         LOGDEBUG (g_message("%s: disconnecting from socket %p (reuse %d)", __func__, sock, reuse));
1392
1393         /* I _think_ the extension function pointers need to be looked
1394          * up for each socket.  FIXME: check the best way to store
1395          * pointers to functions in managed objects that still works
1396          * on 64bit platforms.
1397          */
1398         ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1399                         (void *)&disco_guid, sizeof(GUID),
1400                         (void *)&_wapi_disconnectex, sizeof(void *),
1401                         &output_bytes, NULL, NULL);
1402         if (ret != 0) {
1403                 /* make sure that WSAIoctl didn't put crap in the
1404                  * output pointer
1405                  */
1406                 _wapi_disconnectex = NULL;
1407
1408                 /* Look up the TransmitFile extension function pointer
1409                  * instead of calling TransmitFile() directly, because
1410                  * apparently "Several of the extension functions have
1411                  * been available since WinSock 1.1 and are exported
1412                  * from MSWsock.dll, however it's not advisable to
1413                  * link directly to this dll as this ties you to the
1414                  * Microsoft WinSock provider. A provider neutral way
1415                  * of accessing these extension functions is to load
1416                  * them dynamically via WSAIoctl using the
1417                  * SIO_GET_EXTENSION_FUNCTION_POINTER op code. This
1418                  * should, theoretically, allow you to access these
1419                  * functions from any provider that supports them..." 
1420                  * (http://www.codeproject.com/internet/jbsocketserver3.asp)
1421                  */
1422                 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1423                                 (void *)&trans_guid, sizeof(GUID),
1424                                 (void *)&_wapi_transmitfile, sizeof(void *),
1425                                 &output_bytes, NULL, NULL);
1426                 if (ret != 0) {
1427                         _wapi_transmitfile = NULL;
1428                 }
1429         }
1430
1431         if (_wapi_disconnectex != NULL) {
1432                 bret = _wapi_disconnectex (sock, NULL, TF_REUSE_SOCKET, 0);
1433         } else if (_wapi_transmitfile != NULL) {
1434                 bret = _wapi_transmitfile (sock, NULL, 0, 0, NULL, NULL,
1435                                            TF_DISCONNECT | TF_REUSE_SOCKET);
1436         } else {
1437                 *error = ERROR_NOT_SUPPORTED;
1438                 return;
1439         }
1440
1441         if (bret == FALSE) {
1442                 *error = WSAGetLastError ();
1443         }
1444 }
1445
1446 gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1447 {
1448         int ret;
1449         guchar *buf;
1450         gint32 alen;
1451         int recvflags=0;
1452         
1453         MONO_ARCH_SAVE_REGS;
1454
1455         *error = 0;
1456         
1457         alen = mono_array_length (buffer);
1458         if (offset > alen - count) {
1459                 return(0);
1460         }
1461         
1462         buf=mono_array_addr(buffer, guchar, offset);
1463         
1464         recvflags = convert_socketflags (flags);
1465         if (recvflags == -1) {
1466                 *error = WSAEOPNOTSUPP;
1467                 return (0);
1468         }
1469
1470 #ifdef HOST_WIN32
1471         {
1472                 MonoInternalThread* curthread = mono_thread_internal_current ();
1473                 curthread->interrupt_on_stop = (gpointer)TRUE;
1474                 ret = _wapi_recv (sock, buf, count, recvflags);
1475                 curthread->interrupt_on_stop = (gpointer)FALSE;
1476         }
1477 #else
1478         ret = _wapi_recv (sock, buf, count, recvflags);
1479 #endif
1480
1481         if(ret==SOCKET_ERROR) {
1482                 *error = WSAGetLastError ();
1483                 return(0);
1484         }
1485
1486         return(ret);
1487 }
1488
1489 gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error)
1490 {
1491         int ret, count;
1492         DWORD recv;
1493         WSABUF *wsabufs;
1494         DWORD recvflags = 0;
1495         
1496         MONO_ARCH_SAVE_REGS;
1497
1498         *error = 0;
1499         
1500         wsabufs = mono_array_addr (buffers, WSABUF, 0);
1501         count = mono_array_length (buffers);
1502         
1503         recvflags = convert_socketflags (flags);
1504         if (recvflags == -1) {
1505                 *error = WSAEOPNOTSUPP;
1506                 return(0);
1507         }
1508         
1509         ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
1510         if (ret == SOCKET_ERROR) {
1511                 *error = WSAGetLastError ();
1512                 return(0);
1513         }
1514         
1515         return(recv);
1516 }
1517
1518 gint32 ves_icall_System_Net_Sockets_Socket_RecvFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error)
1519 {
1520         int ret;
1521         guchar *buf;
1522         gint32 alen;
1523         int recvflags=0;
1524         struct sockaddr *sa;
1525         socklen_t sa_size;
1526         
1527         MONO_ARCH_SAVE_REGS;
1528
1529         *error = 0;
1530         
1531         alen = mono_array_length (buffer);
1532         if (offset > alen - count) {
1533                 return(0);
1534         }
1535
1536         sa=create_sockaddr_from_object(*sockaddr, &sa_size, error);
1537         if (*error != 0) {
1538                 return(0);
1539         }
1540         
1541         buf=mono_array_addr(buffer, guchar, offset);
1542         
1543         recvflags = convert_socketflags (flags);
1544         if (recvflags == -1) {
1545                 *error = WSAEOPNOTSUPP;
1546                 return (0);
1547         }
1548
1549         ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
1550         if(ret==SOCKET_ERROR) {
1551                 g_free(sa);
1552                 *error = WSAGetLastError ();
1553                 return(0);
1554         }
1555
1556         /* If we didn't get a socket size, then we're probably a
1557          * connected connection-oriented socket and the stack hasn't
1558          * returned the remote address. All we can do is return null.
1559          */
1560         if ( sa_size != 0 )
1561                 *sockaddr=create_object_from_sockaddr(sa, sa_size, error);
1562         else
1563                 *sockaddr=NULL;
1564
1565         g_free(sa);
1566         
1567         return(ret);
1568 }
1569
1570 gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1571 {
1572         int ret;
1573         guchar *buf;
1574         gint32 alen;
1575         int sendflags=0;
1576         
1577         MONO_ARCH_SAVE_REGS;
1578
1579         *error = 0;
1580         
1581         alen = mono_array_length (buffer);
1582         if (offset > alen - count) {
1583                 return(0);
1584         }
1585
1586         LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
1587         
1588         buf=mono_array_addr(buffer, guchar, offset);
1589
1590         LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1591
1592         sendflags = convert_socketflags (flags);
1593         if (sendflags == -1) {
1594                 *error = WSAEOPNOTSUPP;
1595                 return (0);
1596         }
1597
1598         ret = _wapi_send (sock, buf, count, sendflags);
1599         if(ret==SOCKET_ERROR) {
1600                 *error = WSAGetLastError ();
1601                 return(0);
1602         }
1603
1604         return(ret);
1605 }
1606
1607 gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error)
1608 {
1609         int ret, count;
1610         DWORD sent;
1611         WSABUF *wsabufs;
1612         DWORD sendflags = 0;
1613         
1614         MONO_ARCH_SAVE_REGS;
1615
1616         *error = 0;
1617         
1618         wsabufs = mono_array_addr (buffers, WSABUF, 0);
1619         count = mono_array_length (buffers);
1620         
1621         sendflags = convert_socketflags (flags);
1622         if (sendflags == -1) {
1623                 *error = WSAEOPNOTSUPP;
1624                 return(0);
1625         }
1626         
1627         ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
1628         if (ret == SOCKET_ERROR) {
1629                 *error = WSAGetLastError ();
1630                 return(0);
1631         }
1632         
1633         return(sent);
1634 }
1635
1636 gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error)
1637 {
1638         int ret;
1639         guchar *buf;
1640         gint32 alen;
1641         int sendflags=0;
1642         struct sockaddr *sa;
1643         socklen_t sa_size;
1644         
1645         MONO_ARCH_SAVE_REGS;
1646
1647         *error = 0;
1648         
1649         alen = mono_array_length (buffer);
1650         if (offset > alen - count) {
1651                 return(0);
1652         }
1653
1654         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1655         if(*error != 0) {
1656                 return(0);
1657         }
1658         
1659         LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
1660         
1661         buf=mono_array_addr(buffer, guchar, offset);
1662
1663         LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1664
1665         sendflags = convert_socketflags (flags);
1666         if (sendflags == -1) {
1667                 *error = WSAEOPNOTSUPP;
1668                 return (0);
1669         }
1670
1671         ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
1672         if(ret==SOCKET_ERROR) {
1673                 *error = WSAGetLastError ();
1674         }
1675
1676         g_free(sa);
1677         
1678         return(ret);
1679 }
1680
1681 static SOCKET Socket_to_SOCKET(MonoObject *sockobj)
1682 {
1683         SOCKET sock;
1684         MonoClassField *field;
1685         
1686         field=mono_class_get_field_from_name(sockobj->vtable->klass, "socket");
1687         sock=GPOINTER_TO_INT (*(gpointer *)(((char *)sockobj)+field->offset));
1688
1689         return(sock);
1690 }
1691
1692 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
1693 void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error)
1694 {
1695         MonoInternalThread *thread = NULL;
1696         MonoObject *obj;
1697         mono_pollfd *pfds;
1698         int nfds, idx;
1699         int ret;
1700         int i, count;
1701         int mode;
1702         MonoClass *sock_arr_class;
1703         MonoArray *socks;
1704         time_t start;
1705         uintptr_t socks_size;
1706         
1707         MONO_ARCH_SAVE_REGS;
1708
1709         /* *sockets -> READ, null, WRITE, null, ERROR, null */
1710         count = mono_array_length (*sockets);
1711         nfds = count - 3; /* NULL separators */
1712         pfds = g_new0 (mono_pollfd, nfds);
1713         mode = idx = 0;
1714         for (i = 0; i < count; i++) {
1715                 obj = mono_array_get (*sockets, MonoObject *, i);
1716                 if (obj == NULL) {
1717                         mode++;
1718                         continue;
1719                 }
1720
1721                 if (idx >= nfds) {
1722                         /* The socket array was bogus */
1723                         g_free (pfds);
1724                         *error = WSAEFAULT;
1725                         return;
1726                 }
1727
1728                 pfds [idx].fd = Socket_to_SOCKET (obj);
1729                 pfds [idx].events = (mode == 0) ? MONO_POLLIN : (mode == 1) ? MONO_POLLOUT : POLL_ERRORS;
1730                 idx++;
1731         }
1732
1733         timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1734         start = time (NULL);
1735         do {
1736                 *error = 0;
1737                 ret = mono_poll (pfds, nfds, timeout);
1738                 if (timeout > 0 && ret < 0) {
1739                         int err = errno;
1740                         int sec = time (NULL) - start;
1741
1742                         timeout -= sec * 1000;
1743                         if (timeout < 0)
1744                                 timeout = 0;
1745                         errno = err;
1746                 }
1747
1748                 if (ret == -1 && errno == EINTR) {
1749                         int leave = 0;
1750                         if (thread == NULL)
1751                                 thread = mono_thread_internal_current ();
1752
1753                         leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1754                         
1755                         if (leave != 0) {
1756                                 g_free (pfds);
1757                                 *sockets = NULL;
1758                                 return;
1759                         } else {
1760                                 /* Suspend requested? */
1761                                 mono_thread_interruption_checkpoint ();
1762                         }
1763                         errno = EINTR;
1764                 }
1765         } while (ret == -1 && errno == EINTR);
1766         
1767         if (ret == -1) {
1768 #ifdef HOST_WIN32
1769                 *error = WSAGetLastError ();
1770 #else
1771                 *error = errno_to_WSA (errno, __func__);
1772 #endif
1773                 g_free (pfds);
1774                 return;
1775         }
1776
1777         if (ret == 0) {
1778                 g_free (pfds);
1779                 *sockets = NULL;
1780                 return;
1781         }
1782
1783         sock_arr_class= ((MonoObject *)*sockets)->vtable->klass;
1784         socks_size = ((uintptr_t)ret) + 3; /* space for the NULL delimiters */
1785         socks = mono_array_new_full (mono_domain_get (), sock_arr_class, &socks_size, NULL);
1786
1787         mode = idx = 0;
1788         for (i = 0; i < count && ret > 0; i++) {
1789                 mono_pollfd *pfd;
1790
1791                 obj = mono_array_get (*sockets, MonoObject *, i);
1792                 if (obj == NULL) {
1793                         mode++;
1794                         idx++;
1795                         continue;
1796                 }
1797
1798                 pfd = &pfds [i - mode];
1799                 if (pfd->revents == 0)
1800                         continue;
1801
1802                 ret--;
1803                 if (mode == 0 && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
1804                         mono_array_setref (socks, idx++, obj);
1805                 } else if (mode == 1 && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
1806                         mono_array_setref (socks, idx++, obj);
1807                 } else if ((pfd->revents & POLL_ERRORS) != 0) {
1808                         mono_array_setref (socks, idx++, obj);
1809                 }
1810         }
1811
1812         *sockets = socks;
1813         g_free (pfds);
1814 }
1815
1816 static MonoObject* int_to_object (MonoDomain *domain, int val)
1817 {
1818         return mono_value_box (domain, mono_get_int32_class (), &val);
1819 }
1820
1821
1822 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error)
1823 {
1824         int system_level;
1825         int system_name;
1826         int ret;
1827         int val;
1828         socklen_t valsize=sizeof(val);
1829         struct linger linger;
1830         socklen_t lingersize=sizeof(linger);
1831         int time_ms = 0;
1832         socklen_t time_ms_size = sizeof (time_ms);
1833 #ifdef SO_PEERCRED
1834 #  if defined(__OpenBSD__)
1835         struct sockpeercred cred;
1836 #  else
1837         struct ucred cred;
1838 #  endif
1839         socklen_t credsize = sizeof(cred);
1840 #endif
1841         MonoDomain *domain=mono_domain_get();
1842         MonoObject *obj;
1843         MonoClass *obj_class;
1844         MonoClassField *field;
1845         
1846         MONO_ARCH_SAVE_REGS;
1847
1848         *error = 0;
1849         
1850 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
1851         if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
1852                 system_level = SOL_SOCKET;
1853                 system_name = SO_REUSEADDR;
1854                 ret = 0;
1855         } else
1856 #endif
1857         {
1858
1859                 ret = convert_sockopt_level_and_name (level, name, &system_level, &system_name);
1860         }
1861
1862         if(ret==-1) {
1863                 *error = WSAENOPROTOOPT;
1864                 return;
1865         }
1866         if (ret == -2) {
1867                 *obj_val = int_to_object (domain, 0);
1868                 return;
1869         }
1870         
1871         /* No need to deal with MulticastOption names here, because
1872          * you cant getsockopt AddMembership or DropMembership (the
1873          * int getsockopt will error, causing an exception)
1874          */
1875         switch(name) {
1876         case SocketOptionName_Linger:
1877         case SocketOptionName_DontLinger:
1878                 ret = _wapi_getsockopt(sock, system_level, system_name, &linger,
1879                                &lingersize);
1880                 break;
1881                 
1882         case SocketOptionName_SendTimeout:
1883         case SocketOptionName_ReceiveTimeout:
1884                 ret = _wapi_getsockopt (sock, system_level, system_name, (char *) &time_ms, &time_ms_size);
1885                 break;
1886
1887 #ifdef SO_PEERCRED
1888         case SocketOptionName_PeerCred: 
1889                 ret = _wapi_getsockopt (sock, system_level, system_name, &cred,
1890                                         &credsize);
1891                 break;
1892 #endif
1893
1894         default:
1895                 ret = _wapi_getsockopt (sock, system_level, system_name, &val,
1896                                &valsize);
1897         }
1898         
1899         if(ret==SOCKET_ERROR) {
1900                 *error = WSAGetLastError ();
1901                 return;
1902         }
1903         
1904         switch(name) {
1905         case SocketOptionName_Linger:
1906                 /* build a System.Net.Sockets.LingerOption */
1907                 obj_class=mono_class_from_name(get_socket_assembly (),
1908                                                "System.Net.Sockets",
1909                                                "LingerOption");
1910                 obj=mono_object_new(domain, obj_class);
1911                 
1912                 /* Locate and set the fields "bool enabled" and "int
1913                  * seconds"
1914                  */
1915                 field=mono_class_get_field_from_name(obj_class, "enabled");
1916                 *(guint8 *)(((char *)obj)+field->offset)=linger.l_onoff;
1917
1918                 field=mono_class_get_field_from_name(obj_class, "seconds");
1919                 *(guint32 *)(((char *)obj)+field->offset)=linger.l_linger;
1920                 
1921                 break;
1922                 
1923         case SocketOptionName_DontLinger:
1924                 /* construct a bool int in val - true if linger is off */
1925                 obj = int_to_object (domain, !linger.l_onoff);
1926                 break;
1927                 
1928         case SocketOptionName_SendTimeout:
1929         case SocketOptionName_ReceiveTimeout:
1930                 obj = int_to_object (domain, time_ms);
1931                 break;
1932
1933 #ifdef SO_PEERCRED
1934         case SocketOptionName_PeerCred: 
1935         {
1936                 /* build a Mono.Posix.PeerCred+PeerCredData if
1937                  * possible
1938                  */
1939                 static MonoImage *mono_posix_image = NULL;
1940                 MonoPeerCredData *cred_data;
1941                 
1942                 if (mono_posix_image == NULL) {
1943                         mono_posix_image=mono_image_loaded ("Mono.Posix");
1944                         if (!mono_posix_image) {
1945                                 MonoAssembly *sa = mono_assembly_open ("Mono.Posix.dll", NULL);
1946                                 if (!sa) {
1947                                         *error = WSAENOPROTOOPT;
1948                                         return;
1949                                 } else {
1950                                         mono_posix_image = mono_assembly_get_image (sa);
1951                                 }
1952                         }
1953                 }
1954                 
1955                 obj_class = mono_class_from_name(mono_posix_image,
1956                                                  "Mono.Posix",
1957                                                  "PeerCredData");
1958                 obj = mono_object_new(domain, obj_class);
1959                 cred_data = (MonoPeerCredData *)obj;
1960                 cred_data->pid = cred.pid;
1961                 cred_data->uid = cred.uid;
1962                 cred_data->gid = cred.gid;
1963                 break;
1964         }
1965 #endif
1966
1967         default:
1968 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
1969                 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse)
1970                         val = val ? 0 : 1;
1971 #endif
1972                 obj = int_to_object (domain, val);
1973         }
1974         *obj_val=obj;
1975 }
1976
1977 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal(SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *error)
1978 {
1979         int system_level;
1980         int system_name;
1981         int ret;
1982         guchar *buf;
1983         socklen_t valsize;
1984         
1985         MONO_ARCH_SAVE_REGS;
1986
1987         *error = 0;
1988         
1989         ret=convert_sockopt_level_and_name(level, name, &system_level,
1990                                            &system_name);
1991         if(ret==-1) {
1992                 *error = WSAENOPROTOOPT;
1993                 return;
1994         }
1995         if(ret==-2)
1996                 return;
1997
1998         valsize=mono_array_length(*byte_val);
1999         buf=mono_array_addr(*byte_val, guchar, 0);
2000         
2001         ret = _wapi_getsockopt (sock, system_level, system_name, buf, &valsize);
2002         if(ret==SOCKET_ERROR) {
2003                 *error = WSAGetLastError ();
2004         }
2005 }
2006
2007 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2008 static struct in_addr ipaddress_to_struct_in_addr(MonoObject *ipaddr)
2009 {
2010         struct in_addr inaddr;
2011         MonoClassField *field;
2012         
2013         field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Address");
2014
2015         /* No idea why .net uses a 64bit type to hold a 32bit value...
2016          *
2017          * Internal value of IPAddess is in little-endian order
2018          */
2019         inaddr.s_addr=GUINT_FROM_LE ((guint32)*(guint64 *)(((char *)ipaddr)+field->offset));
2020         
2021         return(inaddr);
2022 }
2023
2024 #ifdef AF_INET6
2025 static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
2026 {
2027         struct in6_addr in6addr;
2028         MonoClassField *field;
2029         MonoArray *data;
2030         int i;
2031
2032         field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Numbers");
2033         data=*(MonoArray **)(((char *)ipaddr) + field->offset);
2034
2035 /* Solaris has only the 8 bit version. */
2036 #ifndef s6_addr16
2037         for(i=0; i<8; i++) {
2038                 guint16 s = mono_array_get (data, guint16, i);
2039                 in6addr.s6_addr[2 * i + 1] = (s >> 8) & 0xff;
2040                 in6addr.s6_addr[2 * i] = s & 0xff;
2041         }
2042 #else
2043         for(i=0; i<8; i++)
2044                 in6addr.s6_addr16[i] = mono_array_get (data, guint16, i);
2045 #endif
2046         return(in6addr);
2047 }
2048 #endif /* AF_INET6 */
2049 #endif
2050
2051 #if defined(__APPLE__)
2052
2053 #if defined(HAVE_GETIFADDRS) && defined(HAVE_IF_NAMETOINDEX)
2054 static int
2055 get_local_interface_id (int family)
2056 {
2057         struct ifaddrs *ifap = NULL, *ptr;
2058         int idx = 0;
2059         
2060         if (getifaddrs (&ifap)) {
2061                 return 0;
2062         }
2063         
2064         for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
2065                 if (!ptr->ifa_addr || !ptr->ifa_name)
2066                         continue;
2067                 if (ptr->ifa_addr->sa_family != family)
2068                         continue;
2069                 if ((ptr->ifa_flags & IFF_LOOPBACK) != 0)
2070                         continue;
2071                 if ((ptr->ifa_flags & IFF_MULTICAST) == 0)
2072                         continue;
2073                         
2074                 idx = if_nametoindex (ptr->ifa_name);
2075                 break;
2076         }
2077         
2078         freeifaddrs (ifap);
2079         return idx;
2080 }
2081 #else
2082 static int
2083 get_local_interface_id (int family)
2084 {
2085         return 0;
2086 }
2087 #endif
2088
2089 #endif /* __APPLE__ */
2090
2091 void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, gint32 level, gint32 name, MonoObject *obj_val, MonoArray *byte_val, gint32 int_val, gint32 *error)
2092 {
2093         struct linger linger;
2094         int system_level;
2095         int system_name;
2096         int ret;
2097 #ifdef AF_INET6
2098         int sol_ip;
2099         int sol_ipv6;
2100
2101         *error = 0;
2102         
2103 #ifdef HAVE_SOL_IPV6
2104         sol_ipv6 = SOL_IPV6;
2105 #else
2106         {
2107                 struct protoent *pent;
2108                 pent = getprotobyname ("ipv6");
2109                 sol_ipv6 = (pent != NULL) ? pent->p_proto : 41;
2110         }
2111 #endif
2112
2113 #ifdef HAVE_SOL_IP
2114         sol_ip = SOL_IP;
2115 #else
2116         {
2117                 struct protoent *pent;
2118                 pent = getprotobyname ("ip");
2119                 sol_ip = (pent != NULL) ? pent->p_proto : 0;
2120         }
2121 #endif
2122 #endif /* AF_INET6 */
2123
2124         MONO_ARCH_SAVE_REGS;
2125
2126         ret=convert_sockopt_level_and_name(level, name, &system_level,
2127                                            &system_name);
2128
2129 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
2130         if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
2131                 system_name = SO_REUSEADDR;
2132                 int_val = int_val ? 0 : 1;
2133                 ret = 0;
2134         }
2135 #endif
2136
2137         if(ret==-1) {
2138                 *error = WSAENOPROTOOPT;
2139                 return;
2140         }
2141         if(ret==-2){
2142                 return;
2143         }
2144
2145         /* Only one of obj_val, byte_val or int_val has data */
2146         if(obj_val!=NULL) {
2147                 MonoClassField *field;
2148                 int valsize;
2149                 
2150                 switch(name) {
2151                 case SocketOptionName_Linger:
2152                         /* Dig out "bool enabled" and "int seconds"
2153                          * fields
2154                          */
2155                         field=mono_class_get_field_from_name(obj_val->vtable->klass, "enabled");
2156                         linger.l_onoff=*(guint8 *)(((char *)obj_val)+field->offset);
2157                         field=mono_class_get_field_from_name(obj_val->vtable->klass, "seconds");
2158                         linger.l_linger=*(guint32 *)(((char *)obj_val)+field->offset);
2159                         
2160                         valsize=sizeof(linger);
2161                         ret = _wapi_setsockopt (sock, system_level,
2162                                                 system_name, &linger, valsize);
2163                         break;
2164                 case SocketOptionName_AddMembership:
2165                 case SocketOptionName_DropMembership:
2166 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2167                 {
2168                         MonoObject *address = NULL;
2169
2170 #ifdef AF_INET6
2171                         if(system_level == sol_ipv6) {
2172                                 struct ipv6_mreq mreq6;
2173
2174                                 /*
2175                                  *      Get group address
2176                                  */
2177                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2178                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2179                                 
2180                                 if(address) {
2181                                         mreq6.ipv6mr_multiaddr = ipaddress_to_struct_in6_addr (address);
2182                                 }
2183
2184                                 field=mono_class_get_field_from_name(obj_val->vtable->klass, "ifIndex");
2185                                 mreq6.ipv6mr_interface =*(guint64 *)(((char *)obj_val)+field->offset);
2186                                 
2187 #if defined(__APPLE__)
2188                                 /*
2189                                 * Bug #5504:
2190                                 *
2191                                 * Mac OS Lion doesn't allow ipv6mr_interface = 0.
2192                                 *
2193                                 * Tests on Windows and Linux show that the multicast group is only
2194                                 * joined on one NIC when interface = 0, so we simply use the interface
2195                                 * id from the first non-loopback interface (this is also what
2196                                 * Dns.GetHostName (string.Empty) would return).
2197                                 */
2198                                 if (!mreq6.ipv6mr_interface)
2199                                         mreq6.ipv6mr_interface = get_local_interface_id (AF_INET6);
2200 #endif
2201                                         
2202                                 ret = _wapi_setsockopt (sock, system_level,
2203                                                         system_name, &mreq6,
2204                                                         sizeof (mreq6));
2205                         } else if(system_level == sol_ip)
2206 #endif /* AF_INET6 */
2207                         {
2208 #ifdef HAVE_STRUCT_IP_MREQN
2209                                 struct ip_mreqn mreq = {{0}};
2210 #else
2211                                 struct ip_mreq mreq = {{0}};
2212 #endif /* HAVE_STRUCT_IP_MREQN */
2213                         
2214                                 /* pain! MulticastOption holds two IPAddress
2215                                  * members, so I have to dig the value out of
2216                                  * those :-(
2217                                  */
2218                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2219                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2220
2221                                 /* address might not be defined and if so, set the address to ADDR_ANY.
2222                                  */
2223                                 if(address) {
2224                                         mreq.imr_multiaddr = ipaddress_to_struct_in_addr (address);
2225                                 }
2226
2227                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "local");
2228                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2229
2230 #ifdef HAVE_STRUCT_IP_MREQN
2231                                 if(address) {
2232                                         mreq.imr_address = ipaddress_to_struct_in_addr (address);
2233                                 }
2234 #else
2235                                 if(address) {
2236                                         mreq.imr_interface = ipaddress_to_struct_in_addr (address);
2237                                 }
2238 #endif /* HAVE_STRUCT_IP_MREQN */
2239                         
2240                                 ret = _wapi_setsockopt (sock, system_level,
2241                                                         system_name, &mreq,
2242                                                         sizeof (mreq));
2243                         }
2244                         break;
2245                 }
2246 #endif /* HAVE_STRUCT_IP_MREQN || HAVE_STRUCT_IP_MREQ */
2247                 default:
2248                         /* Cause an exception to be thrown */
2249                         *error = WSAEINVAL;
2250                         return;
2251                 }
2252         } else if (byte_val!=NULL) {
2253                 int valsize = mono_array_length (byte_val);
2254                 guchar *buf = mono_array_addr (byte_val, guchar, 0);
2255                 
2256                 switch(name) {
2257                 case SocketOptionName_DontLinger:
2258                         if (valsize == 1) {
2259                                 linger.l_onoff = (*buf) ? 0 : 1;
2260                                 linger.l_linger = 0;
2261                                 ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2262                         } else {
2263                                 *error = WSAEINVAL;
2264                         }
2265                         break;
2266                 default:
2267                         ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
2268                         break;
2269                 }
2270         } else {
2271                 /* ReceiveTimeout/SendTimeout get here */
2272                 switch(name) {
2273                 case SocketOptionName_DontLinger:
2274                         linger.l_onoff = !int_val;
2275                         linger.l_linger = 0;
2276                         ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2277                         break;
2278                 case SocketOptionName_DontFragment:
2279 #ifdef HAVE_IP_MTU_DISCOVER
2280                         /* Fiddle with the value slightly if we're
2281                          * turning DF on
2282                          */
2283                         if (int_val == 1) {
2284                                 int_val = IP_PMTUDISC_DO;
2285                         }
2286                         /* Fall through */
2287 #endif
2288                         
2289                 default:
2290                         ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2291                 }
2292         }
2293
2294         if(ret==SOCKET_ERROR) {
2295                 *error = WSAGetLastError ();
2296         }
2297 }
2298
2299 void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock,
2300                                                            gint32 how,
2301                                                            gint32 *error)
2302 {
2303         int ret;
2304         
2305         MONO_ARCH_SAVE_REGS;
2306
2307         *error = 0;
2308         
2309         /* Currently, the values for how (recv=0, send=1, both=2) match
2310          * the BSD API
2311          */
2312         ret = _wapi_shutdown (sock, how);
2313         if(ret==SOCKET_ERROR) {
2314                 *error = WSAGetLastError ();
2315         }
2316 }
2317
2318 gint
2319 ves_icall_System_Net_Sockets_Socket_WSAIoctl (SOCKET sock, gint32 code,
2320                                               MonoArray *input,
2321                                               MonoArray *output, gint32 *error)
2322 {
2323         glong output_bytes = 0;
2324         gchar *i_buffer, *o_buffer;
2325         gint i_len, o_len;
2326         gint ret;
2327
2328         MONO_ARCH_SAVE_REGS;
2329
2330         *error = 0;
2331         
2332         if ((guint32)code == FIONBIO) {
2333                 /* Invalid command. Must use Socket.Blocking */
2334                 return -1;
2335         }
2336
2337         if (input == NULL) {
2338                 i_buffer = NULL;
2339                 i_len = 0;
2340         } else {
2341                 i_buffer = mono_array_addr (input, gchar, 0);
2342                 i_len = mono_array_length (input);
2343         }
2344
2345         if (output == NULL) {
2346                 o_buffer = NULL;
2347                 o_len = 0;
2348         } else {
2349                 o_buffer = mono_array_addr (output, gchar, 0);
2350                 o_len = mono_array_length (output);
2351         }
2352
2353         ret = WSAIoctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes, NULL, NULL);
2354         if (ret == SOCKET_ERROR) {
2355                 *error = WSAGetLastError ();
2356                 return(-1);
2357         }
2358
2359         return (gint) output_bytes;
2360 }
2361
2362 #ifdef HAVE_SIOCGIFCONF
2363 static gboolean
2364 is_loopback (int family, void *ad)
2365 {
2366         char *ptr = (char *) ad;
2367
2368         if (family == AF_INET) {
2369                 return (ptr [0] == 127);
2370         }
2371 #ifdef AF_INET6
2372         else {
2373                 return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
2374         }
2375 #endif
2376         return FALSE;
2377 }
2378
2379 static void *
2380 get_local_ips (int family, int *nips)
2381 {
2382         int addr_size, offset, fd, i, count;
2383         int max_ifaces = 50; /* 50 interfaces should be enough... */
2384         struct ifconf ifc;
2385         struct ifreq *ifr;
2386         struct ifreq iflags;
2387         char *result, *tmp_ptr;
2388         gboolean ignore_loopback = FALSE;
2389
2390         *nips = 0;
2391         if (family == AF_INET) {
2392                 addr_size = sizeof (struct in_addr);
2393                 offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
2394 #ifdef AF_INET6
2395         } else if (family == AF_INET6) {
2396                 addr_size = sizeof (struct in6_addr);
2397                 offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
2398 #endif
2399         } else {
2400                 return NULL;
2401         }
2402
2403         fd = socket (family, SOCK_STREAM, 0);
2404
2405         ifc.ifc_len = max_ifaces * sizeof (struct ifreq);
2406         ifc.ifc_buf = g_malloc (ifc.ifc_len);
2407         if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) {
2408                 close (fd);
2409                 g_free (ifc.ifc_buf);
2410                 return NULL;
2411         }
2412
2413         count = ifc.ifc_len / sizeof (struct ifreq);
2414         *nips = count;
2415         if (count == 0) {
2416                 g_free (ifc.ifc_buf);
2417                 close (fd);
2418                 return NULL;
2419         }
2420
2421         for (i = 0, ifr = ifc.ifc_req; i < *nips; i++, ifr++) {
2422                 strcpy (iflags.ifr_name, ifr->ifr_name);
2423                 if (ioctl (fd, SIOCGIFFLAGS, &iflags) < 0) {
2424                         continue;
2425                 }
2426
2427                 if ((iflags.ifr_flags & IFF_UP) == 0) {
2428                         ifr->ifr_name [0] = '\0';
2429                         continue;
2430                 }
2431
2432                 if ((iflags.ifr_flags & IFF_LOOPBACK) == 0) {
2433                         ignore_loopback = TRUE;
2434                 }
2435         }
2436
2437         close (fd);
2438         result = g_malloc (addr_size * count);
2439         tmp_ptr = result;
2440         for (i = 0, ifr = ifc.ifc_req; i < count; i++, ifr++) {
2441                 if (ifr->ifr_name [0] == '\0') {
2442                         (*nips)--;
2443                         continue;
2444                 }
2445
2446                 if (ignore_loopback && is_loopback (family, ((char *) &ifr->ifr_addr) + offset)) {
2447                         (*nips)--;
2448                         continue;
2449                 }
2450
2451                 memcpy (tmp_ptr, ((char *) &ifr->ifr_addr) + offset, addr_size);
2452                 tmp_ptr += addr_size;
2453         }
2454
2455         g_free (ifc.ifc_buf);
2456         return result;
2457 }
2458 #elif defined(HAVE_GETIFADDRS)
2459 static gboolean
2460 is_loopback (int family, void *ad)
2461 {
2462         char *ptr = (char *) ad;
2463
2464         if (family == AF_INET) {
2465                 return (ptr [0] == 127);
2466         }
2467 #ifdef AF_INET6
2468         else {
2469                 return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
2470         }
2471 #endif
2472         return FALSE;
2473 }
2474
2475 static void *
2476 get_local_ips (int family, int *nips)
2477 {
2478         struct ifaddrs *ifap = NULL, *ptr;
2479         int addr_size, offset, count, i;
2480         char *result, *tmp_ptr;
2481
2482         *nips = 0;
2483         if (family == AF_INET) {
2484                 addr_size = sizeof (struct in_addr);
2485                 offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
2486 #ifdef AF_INET6
2487         } else if (family == AF_INET6) {
2488                 addr_size = sizeof (struct in6_addr);
2489                 offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
2490 #endif
2491         } else {
2492                 return NULL;
2493         }
2494         
2495         if (getifaddrs (&ifap)) {
2496                 return NULL;
2497         }
2498         
2499         count = 0;
2500         for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
2501                 if (!ptr->ifa_addr)
2502                         continue;
2503                 if (ptr->ifa_addr->sa_family != family)
2504                         continue;
2505                 if (is_loopback (family, ((char *) ptr->ifa_addr) + offset))
2506                         continue;
2507                 count++;
2508         }
2509                 
2510         result = g_malloc (addr_size * count);
2511         tmp_ptr = result;
2512         for (i = 0, ptr = ifap; ptr; ptr = ptr->ifa_next) {
2513                 if (!ptr->ifa_addr)
2514                         continue;
2515                 if (ptr->ifa_addr->sa_family != family)
2516                         continue;
2517                 if (is_loopback (family, ((char *) ptr->ifa_addr) + offset))
2518                         continue;
2519                         
2520                 memcpy (tmp_ptr, ((char *) ptr->ifa_addr) + offset, addr_size);
2521                 tmp_ptr += addr_size;
2522         }
2523         
2524         freeifaddrs (ifap);
2525         *nips = count;
2526         return result;
2527 }
2528 #else
2529 static void *
2530 get_local_ips (int family, int *nips)
2531 {
2532         *nips = 0;
2533         return NULL;
2534 }
2535
2536 #endif /* HAVE_SIOCGIFCONF */
2537
2538 #ifndef AF_INET6
2539 static gboolean hostent_to_IPHostEntry(struct hostent *he, MonoString **h_name,
2540                                        MonoArray **h_aliases,
2541                                        MonoArray **h_addr_list,
2542                                        gboolean add_local_ips)
2543 {
2544         MonoDomain *domain = mono_domain_get ();
2545         int i = 0;
2546         struct in_addr *local_in = NULL;
2547         int nlocal_in = 0;
2548
2549         if (he != NULL) {
2550                 if(he->h_length!=4 || he->h_addrtype!=AF_INET) {
2551                         return(FALSE);
2552                 }
2553
2554                 *h_name=mono_string_new(domain, he->h_name);
2555
2556                 while(he->h_aliases[i]!=NULL) {
2557                         i++;
2558                 }
2559                 
2560                 *h_aliases=mono_array_new(domain, mono_get_string_class (), i);
2561                 i=0;
2562                 while(he->h_aliases[i]!=NULL) {
2563                         MonoString *alias;
2564                         
2565                         alias=mono_string_new(domain, he->h_aliases[i]);
2566                         mono_array_setref (*h_aliases, i, alias);
2567                         i++;
2568                 }
2569         } else if (!add_local_ips) {
2570                 return FALSE;
2571         }
2572
2573         if (add_local_ips) {
2574                 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2575                 if (nlocal_in) {
2576                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), nlocal_in);
2577                         for (i = 0; i < nlocal_in; i++) {
2578                                 MonoString *addr_string;
2579                                 char addr [16], *ptr;
2580                                 
2581                                 ptr = (char *) &local_in [i];
2582                                 g_snprintf(addr, 16, "%u.%u.%u.%u",
2583                                          (unsigned char) ptr [0],
2584                                          (unsigned char) ptr [1],
2585                                          (unsigned char) ptr [2],
2586                                          (unsigned char) ptr [3]);
2587                                 
2588                                 addr_string = mono_string_new (domain, addr);
2589                                 mono_array_setref (*h_addr_list, i, addr_string);
2590                                 i++;
2591                         }
2592
2593                         g_free (local_in);
2594                 } else if (he == NULL) {
2595                         /* If requesting "" and there are no other interfaces up, MS returns 127.0.0.1 */
2596                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), 1);
2597                         mono_array_setref (*h_addr_list, 0, mono_string_new (domain, "127.0.0.1"));
2598                         return TRUE;
2599                 }
2600         }
2601         
2602         if (nlocal_in == 0 && he != NULL) {
2603                 i = 0;
2604                 while (he->h_addr_list[i]!=NULL) {
2605                         i++;
2606                 }
2607
2608                 *h_addr_list=mono_array_new(domain, mono_get_string_class (), i);
2609                 i=0;
2610                 while(he->h_addr_list[i]!=NULL) {
2611                         MonoString *addr_string;
2612                         char addr[16];
2613                         
2614                         g_snprintf(addr, 16, "%u.%u.%u.%u",
2615                                  (unsigned char)he->h_addr_list[i][0],
2616                                  (unsigned char)he->h_addr_list[i][1],
2617                                  (unsigned char)he->h_addr_list[i][2],
2618                                  (unsigned char)he->h_addr_list[i][3]);
2619                         
2620                         addr_string=mono_string_new(domain, addr);
2621                         mono_array_setref (*h_addr_list, i, addr_string);
2622                         i++;
2623                 }
2624         }
2625
2626         return(TRUE);
2627 }
2628
2629 static gboolean ipaddr_to_IPHostEntry(const char *addr, MonoString **h_name,
2630                                       MonoArray **h_aliases,
2631                                       MonoArray **h_addr_list)
2632 {
2633         MonoDomain *domain = mono_domain_get ();
2634
2635         *h_name=mono_string_new(domain, addr);
2636         *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2637         *h_addr_list=mono_array_new(domain, mono_get_string_class (), 1);
2638         mono_array_setref (*h_addr_list, 0, *h_name);
2639
2640         return(TRUE);
2641 }
2642 #endif
2643
2644 #if defined(AF_INET6) && defined(HAVE_GETHOSTBYNAME2_R)
2645 static gboolean hostent_to_IPHostEntry2(struct hostent *he1,struct hostent *he2, MonoString **h_name,
2646                                 MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
2647 {
2648         MonoDomain *domain = mono_domain_get ();
2649         int i, host_count, host_index, family_hint;
2650         struct in_addr *local_in = NULL;
2651         int nlocal_in = 0;
2652         struct in6_addr *local_in6 = NULL;
2653         int nlocal_in6 = 0;
2654         gboolean from_local = FALSE;
2655
2656         family_hint = get_family_hint ();
2657
2658         /*
2659          * Check if address length and family are correct
2660          */
2661         if (he1 != NULL && (he1->h_length!=4 || he1->h_addrtype!=AF_INET)) {
2662                 return(FALSE);
2663         }
2664
2665         if (he2 != NULL && (he2->h_length!=16 || he2->h_addrtype!=AF_INET6)) {
2666                 return(FALSE);
2667         }
2668
2669         /*
2670          * Get the aliases and host name from he1 or he2 whichever is
2671          * not null, if he1 is not null then take aliases from he1
2672          */
2673         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2674                             family_hint == PF_INET)) {
2675                 *h_name=mono_string_new (domain, he1->h_name);
2676
2677                 i=0;
2678                 while(he1->h_aliases[i]!=NULL) {
2679                         i++;
2680                 }
2681
2682                 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2683                                            i);
2684                 i=0;
2685                 while(he1->h_aliases[i]!=NULL) {
2686                         MonoString *alias;
2687
2688                         alias=mono_string_new (domain, he1->h_aliases[i]);
2689                         mono_array_setref (*h_aliases, i, alias);
2690                         i++;
2691                 }
2692         } else if (he2 != NULL && (family_hint == PF_UNSPEC ||
2693                                    family_hint == PF_INET6)) {
2694                 *h_name=mono_string_new (domain, he2->h_name);
2695
2696                 i=0;
2697                 while(he2->h_aliases [i] != NULL) {
2698                         i++;
2699                 }
2700
2701                 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2702                                            i);
2703                 i=0;
2704                 while(he2->h_aliases[i]!=NULL) {
2705                         MonoString *alias;
2706
2707                         alias=mono_string_new (domain, he2->h_aliases[i]);
2708                         mono_array_setref (*h_aliases, i, alias);
2709                         i++;
2710                 }
2711         } else if (!add_local_ips) {
2712                 return(FALSE);
2713         }
2714
2715         /*
2716          * Count the number of addresses in he1 + he2
2717          */
2718         host_count = 0;
2719         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2720                             family_hint == PF_INET)) {
2721                 i=0;
2722                 while(he1->h_addr_list[i]!=NULL) {
2723                         i++;
2724                         host_count++;
2725                 }
2726         }
2727
2728         if (he2 != NULL && (family_hint == PF_UNSPEC ||
2729                             family_hint == PF_INET6)) {
2730                 i=0;
2731                 while(he2->h_addr_list[i]!=NULL) {
2732                         i++;
2733                         host_count++;
2734                 }
2735         }
2736
2737         /*
2738          * Fills the array
2739          */
2740         host_index = 0;
2741         if (add_local_ips) {
2742                 if (family_hint == PF_UNSPEC || family_hint == PF_INET)
2743                         local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2744
2745                 if (family_hint == PF_UNSPEC || family_hint == PF_INET6)
2746                         local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2747
2748                 if (nlocal_in || nlocal_in6) {
2749                         from_local = TRUE;
2750                         *h_addr_list = mono_array_new (domain, mono_get_string_class (),
2751                                                              nlocal_in + nlocal_in6);
2752
2753                         if (nlocal_in6) {
2754                                 int n;
2755                                 for (n = 0; n < nlocal_in6; n++) {
2756                                         MonoString *addr_string;
2757                                         const char *ret;
2758                                         char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes with the trailing NULL */
2759
2760                                         ret = inet_ntop (AF_INET6, &local_in6 [n], addr, sizeof(addr));
2761
2762                                         if (ret != NULL) {
2763                                                 addr_string = mono_string_new (domain, addr);
2764                                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2765                                                 host_index++;
2766                                         }
2767                                 }
2768                         }
2769
2770                         if (nlocal_in) {
2771                                 int n;
2772                                 for (n = 0; n < nlocal_in; n++) {
2773                                         MonoString *addr_string;
2774                                         const char *ret;
2775                                         char addr[16]; /* INET_ADDRSTRLEN == 16 */
2776
2777                                         ret = inet_ntop (AF_INET, &local_in [n], addr, sizeof(addr));
2778
2779                                         if (ret != NULL) {
2780                                                 addr_string = mono_string_new (domain, addr);
2781                                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2782                                                 host_index++;
2783                                         }
2784                                 }
2785                         }
2786                         g_free (local_in);
2787                         g_free (local_in6);
2788                         return TRUE;
2789                 } else if (he1 == NULL && he2 == NULL) {
2790                         /* If requesting "" and there are no other interfaces up, MS returns 127.0.0.1 */
2791                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), 1);
2792                         mono_array_setref (*h_addr_list, 0, mono_string_new (domain, "127.0.0.1"));
2793                         g_free (local_in);
2794                         g_free (local_in6);
2795                         return TRUE;
2796                 }
2797
2798                 g_free (local_in);
2799                 g_free (local_in6);
2800         }
2801
2802         *h_addr_list=mono_array_new (domain, mono_get_string_class (), host_count);
2803
2804         if (he2 != NULL && (family_hint == PF_UNSPEC ||
2805                             family_hint == PF_INET6)) {
2806                 i = 0;
2807                 while(he2->h_addr_list[i] != NULL) {
2808                         MonoString *addr_string;
2809                         const char *ret;
2810                         char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes long with the trailing NULL */
2811
2812                         ret = inet_ntop (AF_INET6, he2->h_addr_list[i], addr,
2813                                          sizeof(addr));
2814
2815                         if (ret != NULL) {
2816                                 addr_string = mono_string_new (domain, addr);
2817                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2818                                 i++;
2819                                 host_index++;
2820                         }
2821                 }
2822         }
2823
2824         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2825                             family_hint == PF_INET)) {
2826                 i=0;
2827                 while(he1->h_addr_list[i] != NULL) {
2828                         MonoString *addr_string;
2829                         const char *ret;
2830                         char addr[16]; /* INET_ADDRSTRLEN == 16 */
2831
2832                         ret = inet_ntop (AF_INET, he1->h_addr_list[i], addr,
2833                                          sizeof(addr));
2834
2835                         if (ret != NULL) {
2836                                 addr_string=mono_string_new (domain, addr);
2837                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2838                                 i++;
2839                                 host_index++;
2840                         }
2841                 }
2842         }
2843
2844         return(TRUE);
2845 }
2846 #endif
2847
2848 #if defined(AF_INET6)
2849 static gboolean 
2850 addrinfo_to_IPHostEntry(struct addrinfo *info, MonoString **h_name,
2851                                                 MonoArray **h_aliases,
2852                                                 MonoArray **h_addr_list,
2853                                                 gboolean add_local_ips)
2854 {
2855         gint32 count, i;
2856         struct addrinfo *ai = NULL;
2857         struct in_addr *local_in = NULL;
2858         int nlocal_in = 0;
2859         struct in6_addr *local_in6 = NULL;
2860         int nlocal_in6 = 0;
2861         int addr_index;
2862
2863         MonoDomain *domain = mono_domain_get ();
2864
2865         addr_index = 0;
2866         *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2867         if (add_local_ips) {
2868                 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2869                 local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2870                 if (nlocal_in || nlocal_in6) {
2871                         *h_addr_list=mono_array_new(domain, mono_get_string_class (), nlocal_in + nlocal_in6);
2872                         if (nlocal_in) {
2873                                 MonoString *addr_string;
2874                                 char addr [16];
2875                                 int i;
2876
2877                                 for (i = 0; i < nlocal_in; i++) {
2878                                         inet_ntop (AF_INET, &local_in [i], addr, sizeof (addr));
2879                                         addr_string = mono_string_new (domain, addr);
2880                                         mono_array_setref (*h_addr_list, addr_index, addr_string);
2881                                         addr_index++;
2882                                 }
2883                         }
2884
2885                         if (nlocal_in6) {
2886                                 MonoString *addr_string;
2887                                 const char *ret;
2888                                 char addr [48];
2889                                 int i;
2890
2891                                 for (i = 0; i < nlocal_in6; i++) {
2892                                         ret = inet_ntop (AF_INET6, &local_in6 [i], addr, sizeof (addr));
2893                                         if (ret != NULL) {
2894                                                 addr_string = mono_string_new (domain, addr);
2895                                                 mono_array_setref (*h_addr_list, addr_index, addr_string);
2896                                                 addr_index++;
2897                                         }
2898                                 }
2899                         }
2900
2901                         g_free (local_in);
2902                         g_free (local_in6);
2903                         if (info) {
2904                                 freeaddrinfo (info);
2905                         }
2906                         return TRUE;
2907                 }
2908
2909                 g_free (local_in);
2910                 g_free (local_in6);
2911         }
2912
2913         for (count=0, ai=info; ai!=NULL; ai=ai->ai_next) {
2914                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2915                         continue;
2916
2917                 count++;
2918         }
2919
2920         *h_addr_list=mono_array_new(domain, mono_get_string_class (), count);
2921
2922         for (ai=info, i=0; ai!=NULL; ai=ai->ai_next) {
2923                 MonoString *addr_string;
2924                 const char *ret;
2925                 char buffer [48]; /* Max. size for IPv6 */
2926
2927                 if((ai->ai_family != PF_INET) && (ai->ai_family != PF_INET6)) {
2928                         continue;
2929                 }
2930
2931                 if(ai->ai_family == PF_INET) {
2932                         ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr), buffer, 16);
2933                 } else {
2934                         ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in6*)ai->ai_addr)->sin6_addr), buffer, 48);
2935                 }
2936
2937                 if(ret) {
2938                         addr_string=mono_string_new(domain, buffer);
2939                 } else {
2940                         addr_string=mono_string_new(domain, "");
2941                 }
2942
2943                 mono_array_setref (*h_addr_list, addr_index, addr_string);
2944
2945                 if(!i) {
2946                         i++;
2947                         if (ai->ai_canonname != NULL) {
2948                                 *h_name=mono_string_new(domain, ai->ai_canonname);
2949                         } else {
2950                                 *h_name=mono_string_new(domain, buffer);
2951                         }
2952                 }
2953
2954                 addr_index++;
2955         }
2956
2957         if(info) {
2958                 freeaddrinfo(info);
2959         }
2960
2961         return(TRUE);
2962 }
2963 #endif
2964
2965 #ifdef AF_INET6
2966 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2967 {
2968         gboolean add_local_ips = FALSE;
2969 #ifdef HAVE_SIOCGIFCONF
2970         gchar this_hostname [256];
2971 #endif
2972 #if !defined(HAVE_GETHOSTBYNAME2_R)
2973         struct addrinfo *info = NULL, hints;
2974         char *hostname;
2975         
2976         MONO_ARCH_SAVE_REGS;
2977         
2978         hostname=mono_string_to_utf8 (host);
2979         if (*hostname == '\0') {
2980                 add_local_ips = TRUE;
2981                 *h_name = host;
2982         }
2983 #ifdef HAVE_SIOCGIFCONF
2984         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2985                 if (!strcmp (hostname, this_hostname)) {
2986                         add_local_ips = TRUE;
2987                         *h_name = host;
2988                 }
2989         }
2990 #endif
2991
2992         memset(&hints, 0, sizeof(hints));
2993         hints.ai_family = get_family_hint ();
2994         hints.ai_socktype = SOCK_STREAM;
2995         hints.ai_flags = AI_CANONNAME;
2996
2997         if (*hostname && getaddrinfo(hostname, NULL, &hints, &info) == -1) {
2998                 return(FALSE);
2999         }
3000         
3001         g_free(hostname);
3002
3003         return(addrinfo_to_IPHostEntry(info, h_name, h_aliases, h_addr_list, add_local_ips));
3004 #else
3005         struct hostent he1,*hp1, he2, *hp2;
3006         int buffer_size1, buffer_size2;
3007         char *buffer1, *buffer2;
3008         int herr;
3009         gboolean return_value;
3010         char *hostname;
3011         
3012         MONO_ARCH_SAVE_REGS;
3013         
3014         hostname=mono_string_to_utf8 (host);
3015         if (*hostname == '\0')
3016                 add_local_ips = TRUE;
3017
3018 #ifdef HAVE_SIOCGIFCONF
3019         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
3020                 if (!strcmp (hostname, this_hostname))
3021                         add_local_ips = TRUE;
3022         }
3023 #endif
3024
3025         buffer_size1 = 512;
3026         buffer_size2 = 512;
3027         buffer1 = g_malloc0(buffer_size1);
3028         buffer2 = g_malloc0(buffer_size2);
3029
3030         hp1 = NULL;
3031         hp2 = NULL;
3032         while (*hostname && gethostbyname2_r(hostname, AF_INET, &he1, buffer1, buffer_size1,
3033                                 &hp1, &herr) == ERANGE) {
3034                 buffer_size1 *= 2;
3035                 buffer1 = g_realloc(buffer1, buffer_size1);
3036         }
3037
3038         if (*hostname && hp1 == NULL)
3039         {
3040                 while (gethostbyname2_r(hostname, AF_INET6, &he2, buffer2,
3041                                         buffer_size2, &hp2, &herr) == ERANGE) {
3042                         buffer_size2 *= 2;
3043                         buffer2 = g_realloc(buffer2, buffer_size2);
3044                 }
3045         }
3046
3047         return_value = hostent_to_IPHostEntry2(hp1, hp2, h_name, h_aliases,
3048                                                h_addr_list, add_local_ips);
3049
3050         g_free(buffer1);
3051         g_free(buffer2);
3052         g_free(hostname);
3053
3054         return(return_value);
3055 #endif /* HAVE_GETHOSTBYNAME2_R */
3056 }
3057 #else /* AF_INET6 */
3058 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
3059 {
3060         struct hostent *he;
3061         char *hostname;
3062         gboolean add_local_ips = FALSE;
3063 #ifdef HAVE_SIOCGIFCONF
3064         gchar this_hostname [256];
3065 #endif
3066         
3067         MONO_ARCH_SAVE_REGS;
3068
3069         hostname=mono_string_to_utf8(host);
3070         if (*hostname == '\0')
3071                 add_local_ips = TRUE;
3072 #ifdef HAVE_SIOCGIFCONF
3073         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
3074                 if (!strcmp (hostname, this_hostname))
3075                         add_local_ips = TRUE;
3076         }
3077 #endif
3078
3079 #ifndef HOST_WIN32
3080         he = NULL;
3081         if (*hostname)
3082                 he = _wapi_gethostbyname (hostname);
3083 #else
3084         he = _wapi_gethostbyname (hostname);
3085 #endif
3086         g_free(hostname);
3087
3088         if (*hostname && he==NULL)
3089                 return(FALSE);
3090
3091         return(hostent_to_IPHostEntry(he, h_name, h_aliases, h_addr_list, add_local_ips));
3092 }
3093 #endif /* AF_INET6 */
3094
3095 #ifndef HAVE_INET_PTON
3096 static int
3097 inet_pton (int family, const char *address, void *inaddrp)
3098 {
3099         if (family == AF_INET) {
3100 #ifdef HAVE_INET_ATON
3101                 struct in_addr inaddr;
3102                 
3103                 if (!inet_aton (address, &inaddr))
3104                         return 0;
3105                 
3106                 memcpy (inaddrp, &inaddr, sizeof (struct in_addr));
3107                 return 1;
3108 #else
3109                 /* assume the system has inet_addr(), if it doesn't
3110                    have that we're pretty much screwed... */
3111                 guint32 inaddr;
3112                 
3113                 if (!strcmp (address, "255.255.255.255")) {
3114                         /* special-case hack */
3115                         inaddr = 0xffffffff;
3116                 } else {
3117                         inaddr = inet_addr (address);
3118 #ifndef INADDR_NONE
3119 #define INADDR_NONE ((in_addr_t) -1)
3120 #endif
3121                         if (inaddr == INADDR_NONE)
3122                                 return 0;
3123                 }
3124                 
3125                 memcpy (inaddrp, &inaddr, sizeof (guint32));
3126                 return 1;
3127 #endif /* HAVE_INET_ATON */
3128         }
3129         
3130         return -1;
3131 }
3132 #endif /* !HAVE_INET_PTON */
3133
3134 extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
3135 {
3136         char *address;
3137         
3138 #ifdef AF_INET6
3139         struct sockaddr_in saddr;
3140         struct sockaddr_in6 saddr6;
3141         struct addrinfo *info = NULL, hints;
3142         gint32 family;
3143         char hostname[NI_MAXHOST] = {0};
3144         int flags = 0;
3145 #else
3146         struct in_addr inaddr;
3147         struct hostent *he;
3148         gboolean ret;
3149 #endif
3150
3151         address = mono_string_to_utf8 (addr);
3152
3153 #ifdef AF_INET6
3154         if (inet_pton (AF_INET, address, &saddr.sin_addr ) <= 0) {
3155                 /* Maybe an ipv6 address */
3156                 if (inet_pton (AF_INET6, address, &saddr6.sin6_addr) <= 0) {
3157                         g_free (address);
3158                         return FALSE;
3159                 }
3160                 else {
3161                         family = AF_INET6;
3162                         saddr6.sin6_family = AF_INET6;
3163                 }
3164         }
3165         else {
3166                 family = AF_INET;
3167                 saddr.sin_family = AF_INET;
3168         }
3169         g_free(address);
3170
3171         if(family == AF_INET) {
3172 #if HAVE_SOCKADDR_IN_SIN_LEN
3173                 saddr.sin_len = sizeof (saddr);
3174 #endif
3175                 if(getnameinfo ((struct sockaddr*)&saddr, sizeof(saddr),
3176                                 hostname, sizeof(hostname), NULL, 0,
3177                                 flags) != 0) {
3178                         return(FALSE);
3179                 }
3180         } else if(family == AF_INET6) {
3181 #if HAVE_SOCKADDR_IN6_SIN_LEN
3182                 saddr6.sin6_len = sizeof (saddr6);
3183 #endif
3184                 if(getnameinfo ((struct sockaddr*)&saddr6, sizeof(saddr6),
3185                                 hostname, sizeof(hostname), NULL, 0,
3186                                 flags) != 0) {
3187                         return(FALSE);
3188                 }
3189         }
3190
3191         memset (&hints, 0, sizeof(hints));
3192         hints.ai_family = get_family_hint ();
3193         hints.ai_socktype = SOCK_STREAM;
3194         hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
3195
3196         if( getaddrinfo (hostname, NULL, &hints, &info) == -1 ) {
3197                 return(FALSE);
3198         }
3199
3200         return(addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE));
3201 #else
3202         if (inet_pton (AF_INET, address, &inaddr) <= 0) {
3203                 g_free (address);
3204                 return(FALSE);
3205         }
3206
3207         if ((he = gethostbyaddr ((char *) &inaddr, sizeof (inaddr), AF_INET)) == NULL) {
3208                 ret = ipaddr_to_IPHostEntry (address, h_name, h_aliases, h_addr_list);
3209         } else {
3210                 ret = hostent_to_IPHostEntry (he, h_name, h_aliases,
3211                                               h_addr_list, FALSE);
3212         }
3213
3214         g_free (address);
3215         return(ret);
3216 #endif
3217 }
3218
3219 extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name)
3220 {
3221         gchar hostname[256];
3222         int ret;
3223         
3224         MONO_ARCH_SAVE_REGS;
3225
3226         ret = gethostname (hostname, sizeof (hostname));
3227         if(ret==-1) {
3228                 return(FALSE);
3229         }
3230         
3231         *h_name=mono_string_new(mono_domain_get (), hostname);
3232
3233         return(TRUE);
3234 }
3235
3236 gboolean
3237 ves_icall_System_Net_Sockets_Socket_SendFile (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
3238 {
3239         HANDLE file;
3240         gint32 error;
3241         TRANSMIT_FILE_BUFFERS buffers;
3242
3243         MONO_ARCH_SAVE_REGS;
3244
3245         if (filename == NULL)
3246                 return FALSE;
3247
3248         file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &error);
3249         if (file == INVALID_HANDLE_VALUE) {
3250                 SetLastError (error);
3251                 return FALSE;
3252         }
3253
3254         memset (&buffers, 0, sizeof (buffers));
3255         if (pre_buffer != NULL) {
3256                 buffers.Head = mono_array_addr (pre_buffer, guchar, 0);
3257                 buffers.HeadLength = mono_array_length (pre_buffer);
3258         }
3259         if (post_buffer != NULL) {
3260                 buffers.Tail = mono_array_addr (post_buffer, guchar, 0);
3261                 buffers.TailLength = mono_array_length (post_buffer);
3262         }
3263
3264         if (!TransmitFile (sock, file, 0, 0, NULL, &buffers, flags)) {
3265                 CloseHandle (file);
3266                 return FALSE;
3267         }
3268
3269         CloseHandle (file);
3270         return TRUE;
3271 }
3272
3273 void mono_network_init(void)
3274 {
3275         WSADATA wsadata;
3276         int err;
3277         
3278         err=WSAStartup(MAKEWORD(2,0), &wsadata);
3279         if(err!=0) {
3280                 g_error("%s: Couldn't initialise networking", __func__);
3281                 exit(-1);
3282         }
3283
3284         LOGDEBUG (g_message("%s: Using socket library: %s", __func__, wsadata.szDescription));
3285         LOGDEBUG (g_message("%s: Socket system status: %s", __func__, wsadata.szSystemStatus));
3286 }
3287
3288 void mono_network_cleanup(void)
3289 {
3290         WSACleanup();
3291 }
3292
3293 void
3294 icall_cancel_blocking_socket_operation (MonoThread *thread)
3295 {
3296         MonoInternalThread *internal = thread->internal_thread;
3297         
3298         if (mono_thread_info_new_interrupt_enabled ()) {
3299                 mono_thread_info_abort_socket_syscall_for_close ((MonoNativeThreadId)(gsize)internal->tid);
3300         } else {
3301 #ifndef HOST_WIN32
3302                 internal->ignore_next_signal = TRUE;
3303                 mono_thread_kill (internal, mono_thread_get_abort_signal ());           
3304 #endif
3305         }
3306 }
3307
3308 #endif /* #ifndef DISABLE_SOCKETS */