Fixed incorrect pointer arithmetic on SGen for MSVC.
[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         ret=ioctlsocket(sock, FIONREAD, &amount);
820         if(ret==SOCKET_ERROR) {
821                 *error = WSAGetLastError ();
822                 return(0);
823         }
824         
825         return(amount);
826 }
827
828 void ves_icall_System_Net_Sockets_Socket_Blocking_internal(SOCKET sock,
829                                                            gboolean block,
830                                                            gint32 *error)
831 {
832         int ret;
833         
834         MONO_ARCH_SAVE_REGS;
835
836         *error = 0;
837
838         /*
839          * block == TRUE/FALSE means we will block/not block.
840          * But the ioctlsocket call takes TRUE/FALSE for non-block/block
841          */
842         block = !block;
843         
844         ret = ioctlsocket (sock, FIONBIO, (gulong *) &block);
845         if(ret==SOCKET_ERROR) {
846                 *error = WSAGetLastError ();
847         }
848 }
849
850 gpointer ves_icall_System_Net_Sockets_Socket_Accept_internal(SOCKET sock,
851                                                              gint32 *error,
852                                                              gboolean blocking)
853 {
854         SOCKET newsock;
855         
856         MONO_ARCH_SAVE_REGS;
857
858         *error = 0;
859 #ifdef HOST_WIN32
860         {
861                 MonoInternalThread* curthread = mono_thread_internal_current ();
862                 curthread->interrupt_on_stop = (gpointer)TRUE;
863                 newsock = _wapi_accept (sock, NULL, 0);
864                 curthread->interrupt_on_stop = (gpointer)FALSE;
865         }
866 #else
867         newsock = _wapi_accept (sock, NULL, 0);
868 #endif
869         if(newsock==INVALID_SOCKET) {
870                 *error = WSAGetLastError ();
871                 return(NULL);
872         }
873         
874         return(GUINT_TO_POINTER (newsock));
875 }
876
877 void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock,
878                                                          guint32 backlog,
879                                                          gint32 *error)
880 {
881         int ret;
882         
883         MONO_ARCH_SAVE_REGS;
884
885         *error = 0;
886         
887         ret = _wapi_listen (sock, backlog);
888         if(ret==SOCKET_ERROR) {
889                 *error = WSAGetLastError ();
890         }
891 }
892
893 #ifdef AF_INET6
894 // Check whether it's ::ffff::0:0.
895 static gboolean
896 is_ipv4_mapped_any (const struct in6_addr *addr)
897 {
898         int i;
899         
900         for (i = 0; i < 10; i++) {
901                 if (addr->s6_addr [i])
902                         return FALSE;
903         }
904         if ((addr->s6_addr [10] != 0xff) || (addr->s6_addr [11] != 0xff))
905                 return FALSE;
906         for (i = 12; i < 16; i++) {
907                 if (addr->s6_addr [i])
908                         return FALSE;
909         }
910         return TRUE;
911 }
912 #endif
913
914 static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
915                                                int sa_size, gint32 *error)
916 {
917         MonoDomain *domain = mono_domain_get ();
918         MonoObject *sockaddr_obj;
919         MonoArray *data;
920         MonoAddressFamily family;
921
922         /* Build a System.Net.SocketAddress object instance */
923         if (!domain->sockaddr_class) {
924                 domain->sockaddr_class=mono_class_from_name (get_socket_assembly (), "System.Net", "SocketAddress");
925                 g_assert (domain->sockaddr_class);
926         }
927         sockaddr_obj=mono_object_new(domain, domain->sockaddr_class);
928         
929         /* Locate the SocketAddress data buffer in the object */
930         if (!domain->sockaddr_data_field) {
931                 domain->sockaddr_data_field=mono_class_get_field_from_name (domain->sockaddr_class, "data");
932                 g_assert (domain->sockaddr_data_field);
933         }
934
935         /* May be the +2 here is too conservative, as sa_len returns
936          * the length of the entire sockaddr_in/in6, including
937          * sizeof (unsigned short) of the family */
938         /* We can't really avoid the +2 as all code below depends on this size - INCLUDING unix domain sockets.*/
939         data=mono_array_new_cached(domain, mono_get_byte_class (), sa_size+2);
940
941         /* The data buffer is laid out as follows:
942          * bytes 0 and 1 are the address family
943          * bytes 2 and 3 are the port info
944          * the rest is the address info
945          */
946                 
947         family=convert_to_mono_family(saddr->sa_family);
948         if(family==AddressFamily_Unknown) {
949                 *error = WSAEAFNOSUPPORT;
950                 return(NULL);
951         }
952
953         mono_array_set(data, guint8, 0, family & 0x0FF);
954         mono_array_set(data, guint8, 1, (family >> 8) & 0x0FF);
955         
956         if(saddr->sa_family==AF_INET) {
957                 struct sockaddr_in *sa_in=(struct sockaddr_in *)saddr;
958                 guint16 port=ntohs(sa_in->sin_port);
959                 guint32 address=ntohl(sa_in->sin_addr.s_addr);
960                 
961                 if(sa_size<8) {
962                         mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
963                 }
964                 
965                 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
966                 mono_array_set(data, guint8, 3, (port) & 0xff);
967                 mono_array_set(data, guint8, 4, (address>>24) & 0xff);
968                 mono_array_set(data, guint8, 5, (address>>16) & 0xff);
969                 mono_array_set(data, guint8, 6, (address>>8) & 0xff);
970                 mono_array_set(data, guint8, 7, (address) & 0xff);
971         
972                 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
973
974                 return(sockaddr_obj);
975 #ifdef AF_INET6
976         } else if (saddr->sa_family == AF_INET6) {
977                 struct sockaddr_in6 *sa_in=(struct sockaddr_in6 *)saddr;
978                 int i;
979
980                 guint16 port=ntohs(sa_in->sin6_port);
981
982                 if(sa_size<28) {
983                         mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
984                 }
985
986                 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
987                 mono_array_set(data, guint8, 3, (port) & 0xff);
988                 
989                 if (is_ipv4_mapped_any (&sa_in->sin6_addr)) {
990                         // Map ::ffff:0:0 to :: (bug #5502)
991                         for(i=0; i<16; i++) {
992                                 mono_array_set(data, guint8, 8+i, 0);
993                         }
994                 } else {
995                         for(i=0; i<16; i++) {
996                                 mono_array_set(data, guint8, 8+i,
997                                                sa_in->sin6_addr.s6_addr[i]);
998                         }
999                 }
1000
1001                 mono_array_set(data, guint8, 24, sa_in->sin6_scope_id & 0xff);
1002                 mono_array_set(data, guint8, 25,
1003                                (sa_in->sin6_scope_id >> 8) & 0xff);
1004                 mono_array_set(data, guint8, 26,
1005                                (sa_in->sin6_scope_id >> 16) & 0xff);
1006                 mono_array_set(data, guint8, 27,
1007                                (sa_in->sin6_scope_id >> 24) & 0xff);
1008
1009                 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
1010
1011                 return(sockaddr_obj);
1012 #endif
1013 #ifdef HAVE_SYS_UN_H
1014         } else if (saddr->sa_family == AF_UNIX) {
1015                 int i;
1016
1017                 for (i = 0; i < sa_size; i++) {
1018                         mono_array_set (data, guint8, i+2, saddr->sa_data[i]);
1019                 }
1020                 
1021                 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
1022
1023                 return sockaddr_obj;
1024 #endif
1025         } else {
1026                 *error = WSAEAFNOSUPPORT;
1027                 return(NULL);
1028         }
1029 }
1030
1031 static int
1032 get_sockaddr_size (int family)
1033 {
1034         int size;
1035
1036         size = 0;
1037         if (family == AF_INET) {
1038                 size = sizeof (struct sockaddr_in);
1039 #ifdef AF_INET6
1040         } else if (family == AF_INET6) {
1041                 size = sizeof (struct sockaddr_in6);
1042 #endif
1043 #ifdef HAVE_SYS_UN_H
1044         } else if (family == AF_UNIX) {
1045                 size = sizeof (struct sockaddr_un);
1046 #endif
1047         }
1048         return size;
1049 }
1050
1051 extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 af, gint32 *error)
1052 {
1053         gchar *sa;
1054         socklen_t salen;
1055         int ret;
1056         MonoObject *result;
1057         
1058         MONO_ARCH_SAVE_REGS;
1059
1060         *error = 0;
1061         
1062         salen = get_sockaddr_size (convert_family (af));
1063         if (salen == 0) {
1064                 *error = WSAEAFNOSUPPORT;
1065                 return NULL;
1066         }
1067         sa = (salen <= 128) ? alloca (salen) : g_malloc0 (salen);
1068         ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
1069         
1070         if(ret==SOCKET_ERROR) {
1071                 *error = WSAGetLastError ();
1072                 if (salen > 128)
1073                         g_free (sa);
1074                 return(NULL);
1075         }
1076         
1077         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)));
1078
1079         result = create_object_from_sockaddr((struct sockaddr *)sa, salen, error);
1080         if (salen > 128)
1081                 g_free (sa);
1082         return result;
1083 }
1084
1085 extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 af, gint32 *error)
1086 {
1087         gchar *sa;
1088         socklen_t salen;
1089         int ret;
1090         MonoObject *result;
1091         
1092         MONO_ARCH_SAVE_REGS;
1093
1094         *error = 0;
1095         
1096         salen = get_sockaddr_size (convert_family (af));
1097         if (salen == 0) {
1098                 *error = WSAEAFNOSUPPORT;
1099                 return NULL;
1100         }
1101         sa = (salen <= 128) ? alloca (salen) : g_malloc0 (salen);
1102         /* Note: linux returns just 2 for AF_UNIX. Always. */
1103         ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
1104         if(ret==SOCKET_ERROR) {
1105                 *error = WSAGetLastError ();
1106                 if (salen > 128)
1107                         g_free (sa);
1108                 return(NULL);
1109         }
1110         
1111         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)));
1112
1113         result = create_object_from_sockaddr((struct sockaddr *)sa, salen, error);
1114         if (salen > 128)
1115                 g_free (sa);
1116         return result;
1117 }
1118
1119 static struct sockaddr *create_sockaddr_from_object(MonoObject *saddr_obj,
1120                                                     socklen_t *sa_size,
1121                                                     gint32 *error)
1122 {
1123         MonoClassField *field;
1124         MonoArray *data;
1125         gint32 family;
1126         int len;
1127
1128         /* Dig the SocketAddress data buffer out of the object */
1129         field=mono_class_get_field_from_name(saddr_obj->vtable->klass, "data");
1130         data=*(MonoArray **)(((char *)saddr_obj) + field->offset);
1131
1132         /* The data buffer is laid out as follows:
1133          * byte 0 is the address family low byte
1134          * byte 1 is the address family high byte
1135          * INET:
1136          *      bytes 2 and 3 are the port info
1137          *      the rest is the address info
1138          * UNIX:
1139          *      the rest is the file name
1140          */
1141         len = mono_array_length (data);
1142         if (len < 2) {
1143                 mono_raise_exception (mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
1144         }
1145         
1146         family = convert_family (mono_array_get (data, guint8, 0) + (mono_array_get (data, guint8, 1) << 8));
1147         if (family == AF_INET) {
1148                 struct sockaddr_in *sa;
1149                 guint16 port;
1150                 guint32 address;
1151                 
1152                 if (len < 8) {
1153                         mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1154                 }
1155
1156                 sa = g_new0 (struct sockaddr_in, 1);
1157                 port = (mono_array_get (data, guint8, 2) << 8) +
1158                         mono_array_get (data, guint8, 3);
1159                 address = (mono_array_get (data, guint8, 4) << 24) +
1160                         (mono_array_get (data, guint8, 5) << 16 ) +
1161                         (mono_array_get (data, guint8, 6) << 8) +
1162                         mono_array_get (data, guint8, 7);
1163
1164                 sa->sin_family = family;
1165                 sa->sin_addr.s_addr = htonl (address);
1166                 sa->sin_port = htons (port);
1167
1168                 *sa_size = sizeof(struct sockaddr_in);
1169                 return((struct sockaddr *)sa);
1170
1171 #ifdef AF_INET6
1172         } else if (family == AF_INET6) {
1173                 struct sockaddr_in6 *sa;
1174                 int i;
1175                 guint16 port;
1176                 guint32 scopeid;
1177                 
1178                 if (len < 28) {
1179                         mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1180                 }
1181
1182                 sa = g_new0 (struct sockaddr_in6, 1);
1183                 port = mono_array_get (data, guint8, 3) +
1184                         (mono_array_get (data, guint8, 2) << 8);
1185                 scopeid = mono_array_get (data, guint8, 24) + 
1186                         (mono_array_get (data, guint8, 25) << 8) + 
1187                         (mono_array_get (data, guint8, 26) << 16) + 
1188                         (mono_array_get (data, guint8, 27) << 24);
1189
1190                 sa->sin6_family = family;
1191                 sa->sin6_port = htons (port);
1192                 sa->sin6_scope_id = scopeid;
1193
1194                 for(i=0; i<16; i++) {
1195                         sa->sin6_addr.s6_addr[i] = mono_array_get (data, guint8, 8+i);
1196                 }
1197
1198                 *sa_size = sizeof(struct sockaddr_in6);
1199                 return((struct sockaddr *)sa);
1200 #endif
1201 #ifdef HAVE_SYS_UN_H
1202         } else if (family == AF_UNIX) {
1203                 struct sockaddr_un *sock_un;
1204                 int i;
1205
1206                 /* Need a byte for the '\0' terminator/prefix, and the first
1207                  * two bytes hold the SocketAddress family
1208                  */
1209                 if (len - 2 >= MONO_SIZEOF_SUNPATH) {
1210                         mono_raise_exception (mono_get_exception_index_out_of_range ());
1211                 }
1212                 
1213                 sock_un = g_new0 (struct sockaddr_un, 1);
1214
1215                 sock_un->sun_family = family;
1216                 for (i = 0; i < len - 2; i++) {
1217                         sock_un->sun_path [i] = mono_array_get (data, guint8,
1218                                                                 i + 2);
1219                 }
1220                 
1221                 *sa_size = len;
1222
1223                 return (struct sockaddr *)sock_un;
1224 #endif
1225         } else {
1226                 *error = WSAEAFNOSUPPORT;
1227                 return(0);
1228         }
1229 }
1230
1231 extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1232 {
1233         struct sockaddr *sa;
1234         socklen_t sa_size;
1235         int ret;
1236         
1237         MONO_ARCH_SAVE_REGS;
1238
1239         *error = 0;
1240         
1241         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1242         if (*error != 0) {
1243                 return;
1244         }
1245
1246         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)));
1247
1248         ret = _wapi_bind (sock, sa, sa_size);
1249         if(ret==SOCKET_ERROR) {
1250                 *error = WSAGetLastError ();
1251         }
1252
1253         g_free(sa);
1254 }
1255
1256 enum {
1257         SelectModeRead,
1258         SelectModeWrite,
1259         SelectModeError
1260 };
1261
1262 MonoBoolean
1263 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
1264                                                    gint timeout, gint32 *error)
1265 {
1266         MonoInternalThread *thread = NULL;
1267         mono_pollfd *pfds;
1268         int ret;
1269         time_t start;
1270         
1271
1272         MONO_ARCH_SAVE_REGS;
1273         
1274         pfds = g_new0 (mono_pollfd, 1);
1275         pfds[0].fd = GPOINTER_TO_INT (sock);
1276         pfds[0].events = (mode == SelectModeRead) ? MONO_POLLIN :
1277                 (mode == SelectModeWrite) ? MONO_POLLOUT :
1278                 (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL);
1279
1280         timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1281         start = time (NULL);
1282         do {
1283                 *error = 0;
1284                 
1285                 ret = mono_poll (pfds, 1, timeout);
1286                 if (timeout > 0 && ret < 0) {
1287                         int err = errno;
1288                         int sec = time (NULL) - start;
1289                         
1290                         timeout -= sec * 1000;
1291                         if (timeout < 0) {
1292                                 timeout = 0;
1293                         }
1294                         
1295                         errno = err;
1296                 }
1297                 
1298                 if (ret == -1 && errno == EINTR) {
1299                         int leave = 0;
1300
1301                         if (thread == NULL) {
1302                                 thread = mono_thread_internal_current ();
1303                         }
1304                         
1305                         leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1306                         
1307                         if (leave != 0) {
1308                                 g_free (pfds);
1309                                 return(FALSE);
1310                         } else {
1311                                 /* Suspend requested? */
1312                                 mono_thread_interruption_checkpoint ();
1313                         }
1314                         errno = EINTR;
1315                 }
1316         } while (ret == -1 && errno == EINTR);
1317
1318         if (ret == -1) {
1319 #ifdef HOST_WIN32
1320                 *error = WSAGetLastError ();
1321 #else
1322                 *error = errno_to_WSA (errno, __func__);
1323 #endif
1324                 g_free (pfds);
1325                 return(FALSE);
1326         }
1327         
1328         g_free (pfds);
1329
1330         if (ret == 0) {
1331                 return(FALSE);
1332         } else {
1333                 return (TRUE);
1334         }
1335 }
1336
1337 extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1338 {
1339         struct sockaddr *sa;
1340         socklen_t sa_size;
1341         int ret;
1342         
1343         MONO_ARCH_SAVE_REGS;
1344
1345         *error = 0;
1346         
1347         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1348         if (*error != 0) {
1349                 return;
1350         }
1351         
1352         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)));
1353
1354         ret = _wapi_connect (sock, sa, sa_size);
1355         if(ret==SOCKET_ERROR) {
1356                 *error = WSAGetLastError ();
1357         }
1358
1359         g_free(sa);
1360 }
1361
1362 /* These #defines from mswsock.h from wine.  Defining them here allows
1363  * us to build this file on a mingw box that doesn't know the magic
1364  * numbers, but still run on a newer windows box that does.
1365  */
1366 #ifndef WSAID_DISCONNECTEX
1367 #define WSAID_DISCONNECTEX {0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
1368 typedef BOOL (WINAPI *LPFN_DISCONNECTEX)(SOCKET, LPOVERLAPPED, DWORD, DWORD);
1369 #endif
1370
1371 #ifndef WSAID_TRANSMITFILE
1372 #define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
1373 typedef BOOL (WINAPI *LPFN_TRANSMITFILE)(SOCKET, HANDLE, DWORD, DWORD, LPOVERLAPPED, LPTRANSMIT_FILE_BUFFERS, DWORD);
1374 #endif
1375
1376 extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error)
1377 {
1378         int ret;
1379         glong output_bytes = 0;
1380         GUID disco_guid = WSAID_DISCONNECTEX;
1381         GUID trans_guid = WSAID_TRANSMITFILE;
1382         LPFN_DISCONNECTEX _wapi_disconnectex = NULL;
1383         LPFN_TRANSMITFILE _wapi_transmitfile = NULL;
1384         gboolean bret;
1385         
1386         MONO_ARCH_SAVE_REGS;
1387
1388         *error = 0;
1389         
1390         LOGDEBUG (g_message("%s: disconnecting from socket %p (reuse %d)", __func__, sock, reuse));
1391
1392         /* I _think_ the extension function pointers need to be looked
1393          * up for each socket.  FIXME: check the best way to store
1394          * pointers to functions in managed objects that still works
1395          * on 64bit platforms.
1396          */
1397         ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1398                         (void *)&disco_guid, sizeof(GUID),
1399                         (void *)&_wapi_disconnectex, sizeof(void *),
1400                         &output_bytes, NULL, NULL);
1401         if (ret != 0) {
1402                 /* make sure that WSAIoctl didn't put crap in the
1403                  * output pointer
1404                  */
1405                 _wapi_disconnectex = NULL;
1406
1407                 /* Look up the TransmitFile extension function pointer
1408                  * instead of calling TransmitFile() directly, because
1409                  * apparently "Several of the extension functions have
1410                  * been available since WinSock 1.1 and are exported
1411                  * from MSWsock.dll, however it's not advisable to
1412                  * link directly to this dll as this ties you to the
1413                  * Microsoft WinSock provider. A provider neutral way
1414                  * of accessing these extension functions is to load
1415                  * them dynamically via WSAIoctl using the
1416                  * SIO_GET_EXTENSION_FUNCTION_POINTER op code. This
1417                  * should, theoretically, allow you to access these
1418                  * functions from any provider that supports them..." 
1419                  * (http://www.codeproject.com/internet/jbsocketserver3.asp)
1420                  */
1421                 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1422                                 (void *)&trans_guid, sizeof(GUID),
1423                                 (void *)&_wapi_transmitfile, sizeof(void *),
1424                                 &output_bytes, NULL, NULL);
1425                 if (ret != 0) {
1426                         _wapi_transmitfile = NULL;
1427                 }
1428         }
1429
1430         if (_wapi_disconnectex != NULL) {
1431                 bret = _wapi_disconnectex (sock, NULL, TF_REUSE_SOCKET, 0);
1432         } else if (_wapi_transmitfile != NULL) {
1433                 bret = _wapi_transmitfile (sock, NULL, 0, 0, NULL, NULL,
1434                                            TF_DISCONNECT | TF_REUSE_SOCKET);
1435         } else {
1436                 *error = ERROR_NOT_SUPPORTED;
1437                 return;
1438         }
1439
1440         if (bret == FALSE) {
1441                 *error = WSAGetLastError ();
1442         }
1443 }
1444
1445 gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1446 {
1447         int ret;
1448         guchar *buf;
1449         gint32 alen;
1450         int recvflags=0;
1451         
1452         MONO_ARCH_SAVE_REGS;
1453
1454         *error = 0;
1455         
1456         alen = mono_array_length (buffer);
1457         if (offset > alen - count) {
1458                 return(0);
1459         }
1460         
1461         buf=mono_array_addr(buffer, guchar, offset);
1462         
1463         recvflags = convert_socketflags (flags);
1464         if (recvflags == -1) {
1465                 *error = WSAEOPNOTSUPP;
1466                 return (0);
1467         }
1468
1469 #ifdef HOST_WIN32
1470         {
1471                 MonoInternalThread* curthread = mono_thread_internal_current ();
1472                 curthread->interrupt_on_stop = (gpointer)TRUE;
1473                 ret = _wapi_recv (sock, buf, count, recvflags);
1474                 curthread->interrupt_on_stop = (gpointer)FALSE;
1475         }
1476 #else
1477         ret = _wapi_recv (sock, buf, count, recvflags);
1478 #endif
1479
1480         if(ret==SOCKET_ERROR) {
1481                 *error = WSAGetLastError ();
1482                 return(0);
1483         }
1484
1485         return(ret);
1486 }
1487
1488 gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error)
1489 {
1490         int ret, count;
1491         DWORD recv;
1492         WSABUF *wsabufs;
1493         DWORD recvflags = 0;
1494         
1495         MONO_ARCH_SAVE_REGS;
1496
1497         *error = 0;
1498         
1499         wsabufs = mono_array_addr (buffers, WSABUF, 0);
1500         count = mono_array_length (buffers);
1501         
1502         recvflags = convert_socketflags (flags);
1503         if (recvflags == -1) {
1504                 *error = WSAEOPNOTSUPP;
1505                 return(0);
1506         }
1507         
1508         ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
1509         if (ret == SOCKET_ERROR) {
1510                 *error = WSAGetLastError ();
1511                 return(0);
1512         }
1513         
1514         return(recv);
1515 }
1516
1517 gint32 ves_icall_System_Net_Sockets_Socket_RecvFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error)
1518 {
1519         int ret;
1520         guchar *buf;
1521         gint32 alen;
1522         int recvflags=0;
1523         struct sockaddr *sa;
1524         socklen_t sa_size;
1525         
1526         MONO_ARCH_SAVE_REGS;
1527
1528         *error = 0;
1529         
1530         alen = mono_array_length (buffer);
1531         if (offset > alen - count) {
1532                 return(0);
1533         }
1534
1535         sa=create_sockaddr_from_object(*sockaddr, &sa_size, error);
1536         if (*error != 0) {
1537                 return(0);
1538         }
1539         
1540         buf=mono_array_addr(buffer, guchar, offset);
1541         
1542         recvflags = convert_socketflags (flags);
1543         if (recvflags == -1) {
1544                 *error = WSAEOPNOTSUPP;
1545                 return (0);
1546         }
1547
1548         ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
1549         if(ret==SOCKET_ERROR) {
1550                 g_free(sa);
1551                 *error = WSAGetLastError ();
1552                 return(0);
1553         }
1554
1555         /* If we didn't get a socket size, then we're probably a
1556          * connected connection-oriented socket and the stack hasn't
1557          * returned the remote address. All we can do is return null.
1558          */
1559         if ( sa_size != 0 )
1560                 *sockaddr=create_object_from_sockaddr(sa, sa_size, error);
1561         else
1562                 *sockaddr=NULL;
1563
1564         g_free(sa);
1565         
1566         return(ret);
1567 }
1568
1569 gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1570 {
1571         int ret;
1572         guchar *buf;
1573         gint32 alen;
1574         int sendflags=0;
1575         
1576         MONO_ARCH_SAVE_REGS;
1577
1578         *error = 0;
1579         
1580         alen = mono_array_length (buffer);
1581         if (offset > alen - count) {
1582                 return(0);
1583         }
1584
1585         LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
1586         
1587         buf=mono_array_addr(buffer, guchar, offset);
1588
1589         LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1590
1591         sendflags = convert_socketflags (flags);
1592         if (sendflags == -1) {
1593                 *error = WSAEOPNOTSUPP;
1594                 return (0);
1595         }
1596
1597         ret = _wapi_send (sock, buf, count, sendflags);
1598         if(ret==SOCKET_ERROR) {
1599                 *error = WSAGetLastError ();
1600                 return(0);
1601         }
1602
1603         return(ret);
1604 }
1605
1606 gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error)
1607 {
1608         int ret, count;
1609         DWORD sent;
1610         WSABUF *wsabufs;
1611         DWORD sendflags = 0;
1612         
1613         MONO_ARCH_SAVE_REGS;
1614
1615         *error = 0;
1616         
1617         wsabufs = mono_array_addr (buffers, WSABUF, 0);
1618         count = mono_array_length (buffers);
1619         
1620         sendflags = convert_socketflags (flags);
1621         if (sendflags == -1) {
1622                 *error = WSAEOPNOTSUPP;
1623                 return(0);
1624         }
1625         
1626         ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
1627         if (ret == SOCKET_ERROR) {
1628                 *error = WSAGetLastError ();
1629                 return(0);
1630         }
1631         
1632         return(sent);
1633 }
1634
1635 gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error)
1636 {
1637         int ret;
1638         guchar *buf;
1639         gint32 alen;
1640         int sendflags=0;
1641         struct sockaddr *sa;
1642         socklen_t sa_size;
1643         
1644         MONO_ARCH_SAVE_REGS;
1645
1646         *error = 0;
1647         
1648         alen = mono_array_length (buffer);
1649         if (offset > alen - count) {
1650                 return(0);
1651         }
1652
1653         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1654         if(*error != 0) {
1655                 return(0);
1656         }
1657         
1658         LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
1659         
1660         buf=mono_array_addr(buffer, guchar, offset);
1661
1662         LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1663
1664         sendflags = convert_socketflags (flags);
1665         if (sendflags == -1) {
1666                 *error = WSAEOPNOTSUPP;
1667                 return (0);
1668         }
1669
1670         ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
1671         if(ret==SOCKET_ERROR) {
1672                 *error = WSAGetLastError ();
1673         }
1674
1675         g_free(sa);
1676         
1677         return(ret);
1678 }
1679
1680 static SOCKET Socket_to_SOCKET(MonoObject *sockobj)
1681 {
1682         SOCKET sock;
1683         MonoClassField *field;
1684         
1685         field=mono_class_get_field_from_name(sockobj->vtable->klass, "socket");
1686         sock=GPOINTER_TO_INT (*(gpointer *)(((char *)sockobj)+field->offset));
1687
1688         return(sock);
1689 }
1690
1691 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
1692 void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error)
1693 {
1694         MonoInternalThread *thread = NULL;
1695         MonoObject *obj;
1696         mono_pollfd *pfds;
1697         int nfds, idx;
1698         int ret;
1699         int i, count;
1700         int mode;
1701         MonoClass *sock_arr_class;
1702         MonoArray *socks;
1703         time_t start;
1704         uintptr_t socks_size;
1705         
1706         MONO_ARCH_SAVE_REGS;
1707
1708         /* *sockets -> READ, null, WRITE, null, ERROR, null */
1709         count = mono_array_length (*sockets);
1710         nfds = count - 3; /* NULL separators */
1711         pfds = g_new0 (mono_pollfd, nfds);
1712         mode = idx = 0;
1713         for (i = 0; i < count; i++) {
1714                 obj = mono_array_get (*sockets, MonoObject *, i);
1715                 if (obj == NULL) {
1716                         mode++;
1717                         continue;
1718                 }
1719
1720                 if (idx >= nfds) {
1721                         /* The socket array was bogus */
1722                         g_free (pfds);
1723                         *error = WSAEFAULT;
1724                         return;
1725                 }
1726
1727                 pfds [idx].fd = Socket_to_SOCKET (obj);
1728                 pfds [idx].events = (mode == 0) ? MONO_POLLIN : (mode == 1) ? MONO_POLLOUT : POLL_ERRORS;
1729                 idx++;
1730         }
1731
1732         timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1733         start = time (NULL);
1734         do {
1735                 *error = 0;
1736                 ret = mono_poll (pfds, nfds, timeout);
1737                 if (timeout > 0 && ret < 0) {
1738                         int err = errno;
1739                         int sec = time (NULL) - start;
1740
1741                         timeout -= sec * 1000;
1742                         if (timeout < 0)
1743                                 timeout = 0;
1744                         errno = err;
1745                 }
1746
1747                 if (ret == -1 && errno == EINTR) {
1748                         int leave = 0;
1749                         if (thread == NULL)
1750                                 thread = mono_thread_internal_current ();
1751
1752                         leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1753                         
1754                         if (leave != 0) {
1755                                 g_free (pfds);
1756                                 *sockets = NULL;
1757                                 return;
1758                         } else {
1759                                 /* Suspend requested? */
1760                                 mono_thread_interruption_checkpoint ();
1761                         }
1762                         errno = EINTR;
1763                 }
1764         } while (ret == -1 && errno == EINTR);
1765         
1766         if (ret == -1) {
1767 #ifdef HOST_WIN32
1768                 *error = WSAGetLastError ();
1769 #else
1770                 *error = errno_to_WSA (errno, __func__);
1771 #endif
1772                 g_free (pfds);
1773                 return;
1774         }
1775
1776         if (ret == 0) {
1777                 g_free (pfds);
1778                 *sockets = NULL;
1779                 return;
1780         }
1781
1782         sock_arr_class= ((MonoObject *)*sockets)->vtable->klass;
1783         socks_size = ((uintptr_t)ret) + 3; /* space for the NULL delimiters */
1784         socks = mono_array_new_full (mono_domain_get (), sock_arr_class, &socks_size, NULL);
1785
1786         mode = idx = 0;
1787         for (i = 0; i < count && ret > 0; i++) {
1788                 mono_pollfd *pfd;
1789
1790                 obj = mono_array_get (*sockets, MonoObject *, i);
1791                 if (obj == NULL) {
1792                         mode++;
1793                         idx++;
1794                         continue;
1795                 }
1796
1797                 pfd = &pfds [i - mode];
1798                 if (pfd->revents == 0)
1799                         continue;
1800
1801                 ret--;
1802                 if (mode == 0 && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
1803                         mono_array_setref (socks, idx++, obj);
1804                 } else if (mode == 1 && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
1805                         mono_array_setref (socks, idx++, obj);
1806                 } else if ((pfd->revents & POLL_ERRORS) != 0) {
1807                         mono_array_setref (socks, idx++, obj);
1808                 }
1809         }
1810
1811         *sockets = socks;
1812         g_free (pfds);
1813 }
1814
1815 static MonoObject* int_to_object (MonoDomain *domain, int val)
1816 {
1817         return mono_value_box (domain, mono_get_int32_class (), &val);
1818 }
1819
1820
1821 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error)
1822 {
1823         int system_level;
1824         int system_name;
1825         int ret;
1826         int val;
1827         socklen_t valsize=sizeof(val);
1828         struct linger linger;
1829         socklen_t lingersize=sizeof(linger);
1830         int time_ms = 0;
1831         socklen_t time_ms_size = sizeof (time_ms);
1832 #ifdef SO_PEERCRED
1833 #  if defined(__OpenBSD__)
1834         struct sockpeercred cred;
1835 #  else
1836         struct ucred cred;
1837 #  endif
1838         socklen_t credsize = sizeof(cred);
1839 #endif
1840         MonoDomain *domain=mono_domain_get();
1841         MonoObject *obj;
1842         MonoClass *obj_class;
1843         MonoClassField *field;
1844         
1845         MONO_ARCH_SAVE_REGS;
1846
1847         *error = 0;
1848         
1849 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
1850         if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
1851                 system_level = SOL_SOCKET;
1852                 system_name = SO_REUSEADDR;
1853                 ret = 0;
1854         } else
1855 #endif
1856         {
1857
1858                 ret = convert_sockopt_level_and_name (level, name, &system_level, &system_name);
1859         }
1860
1861         if(ret==-1) {
1862                 *error = WSAENOPROTOOPT;
1863                 return;
1864         }
1865         if (ret == -2) {
1866                 *obj_val = int_to_object (domain, 0);
1867                 return;
1868         }
1869         
1870         /* No need to deal with MulticastOption names here, because
1871          * you cant getsockopt AddMembership or DropMembership (the
1872          * int getsockopt will error, causing an exception)
1873          */
1874         switch(name) {
1875         case SocketOptionName_Linger:
1876         case SocketOptionName_DontLinger:
1877                 ret = _wapi_getsockopt(sock, system_level, system_name, &linger,
1878                                &lingersize);
1879                 break;
1880                 
1881         case SocketOptionName_SendTimeout:
1882         case SocketOptionName_ReceiveTimeout:
1883                 ret = _wapi_getsockopt (sock, system_level, system_name, (char *) &time_ms, &time_ms_size);
1884                 break;
1885
1886 #ifdef SO_PEERCRED
1887         case SocketOptionName_PeerCred: 
1888                 ret = _wapi_getsockopt (sock, system_level, system_name, &cred,
1889                                         &credsize);
1890                 break;
1891 #endif
1892
1893         default:
1894                 ret = _wapi_getsockopt (sock, system_level, system_name, &val,
1895                                &valsize);
1896         }
1897         
1898         if(ret==SOCKET_ERROR) {
1899                 *error = WSAGetLastError ();
1900                 return;
1901         }
1902         
1903         switch(name) {
1904         case SocketOptionName_Linger:
1905                 /* build a System.Net.Sockets.LingerOption */
1906                 obj_class=mono_class_from_name(get_socket_assembly (),
1907                                                "System.Net.Sockets",
1908                                                "LingerOption");
1909                 obj=mono_object_new(domain, obj_class);
1910                 
1911                 /* Locate and set the fields "bool enabled" and "int
1912                  * seconds"
1913                  */
1914                 field=mono_class_get_field_from_name(obj_class, "enabled");
1915                 *(guint8 *)(((char *)obj)+field->offset)=linger.l_onoff;
1916
1917                 field=mono_class_get_field_from_name(obj_class, "seconds");
1918                 *(guint32 *)(((char *)obj)+field->offset)=linger.l_linger;
1919                 
1920                 break;
1921                 
1922         case SocketOptionName_DontLinger:
1923                 /* construct a bool int in val - true if linger is off */
1924                 obj = int_to_object (domain, !linger.l_onoff);
1925                 break;
1926                 
1927         case SocketOptionName_SendTimeout:
1928         case SocketOptionName_ReceiveTimeout:
1929                 obj = int_to_object (domain, time_ms);
1930                 break;
1931
1932 #ifdef SO_PEERCRED
1933         case SocketOptionName_PeerCred: 
1934         {
1935                 /* build a Mono.Posix.PeerCred+PeerCredData if
1936                  * possible
1937                  */
1938                 static MonoImage *mono_posix_image = NULL;
1939                 MonoPeerCredData *cred_data;
1940                 
1941                 if (mono_posix_image == NULL) {
1942                         mono_posix_image=mono_image_loaded ("Mono.Posix");
1943                         if (!mono_posix_image) {
1944                                 MonoAssembly *sa = mono_assembly_open ("Mono.Posix.dll", NULL);
1945                                 if (!sa) {
1946                                         *error = WSAENOPROTOOPT;
1947                                         return;
1948                                 } else {
1949                                         mono_posix_image = mono_assembly_get_image (sa);
1950                                 }
1951                         }
1952                 }
1953                 
1954                 obj_class = mono_class_from_name(mono_posix_image,
1955                                                  "Mono.Posix",
1956                                                  "PeerCredData");
1957                 obj = mono_object_new(domain, obj_class);
1958                 cred_data = (MonoPeerCredData *)obj;
1959                 cred_data->pid = cred.pid;
1960                 cred_data->uid = cred.uid;
1961                 cred_data->gid = cred.gid;
1962                 break;
1963         }
1964 #endif
1965
1966         default:
1967 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
1968                 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse)
1969                         val = val ? 0 : 1;
1970 #endif
1971                 obj = int_to_object (domain, val);
1972         }
1973         *obj_val=obj;
1974 }
1975
1976 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal(SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *error)
1977 {
1978         int system_level;
1979         int system_name;
1980         int ret;
1981         guchar *buf;
1982         socklen_t valsize;
1983         
1984         MONO_ARCH_SAVE_REGS;
1985
1986         *error = 0;
1987         
1988         ret=convert_sockopt_level_and_name(level, name, &system_level,
1989                                            &system_name);
1990         if(ret==-1) {
1991                 *error = WSAENOPROTOOPT;
1992                 return;
1993         }
1994         if(ret==-2)
1995                 return;
1996
1997         valsize=mono_array_length(*byte_val);
1998         buf=mono_array_addr(*byte_val, guchar, 0);
1999         
2000         ret = _wapi_getsockopt (sock, system_level, system_name, buf, &valsize);
2001         if(ret==SOCKET_ERROR) {
2002                 *error = WSAGetLastError ();
2003         }
2004 }
2005
2006 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2007 static struct in_addr ipaddress_to_struct_in_addr(MonoObject *ipaddr)
2008 {
2009         struct in_addr inaddr;
2010         MonoClassField *field;
2011         
2012         field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Address");
2013
2014         /* No idea why .net uses a 64bit type to hold a 32bit value...
2015          *
2016          * Internal value of IPAddess is in little-endian order
2017          */
2018         inaddr.s_addr=GUINT_FROM_LE ((guint32)*(guint64 *)(((char *)ipaddr)+field->offset));
2019         
2020         return(inaddr);
2021 }
2022
2023 #ifdef AF_INET6
2024 static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
2025 {
2026         struct in6_addr in6addr;
2027         MonoClassField *field;
2028         MonoArray *data;
2029         int i;
2030
2031         field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Numbers");
2032         data=*(MonoArray **)(((char *)ipaddr) + field->offset);
2033
2034 /* Solaris has only the 8 bit version. */
2035 #ifndef s6_addr16
2036         for(i=0; i<8; i++) {
2037                 guint16 s = mono_array_get (data, guint16, i);
2038                 in6addr.s6_addr[2 * i + 1] = (s >> 8) & 0xff;
2039                 in6addr.s6_addr[2 * i] = s & 0xff;
2040         }
2041 #else
2042         for(i=0; i<8; i++)
2043                 in6addr.s6_addr16[i] = mono_array_get (data, guint16, i);
2044 #endif
2045         return(in6addr);
2046 }
2047 #endif /* AF_INET6 */
2048 #endif
2049
2050 #if defined(__APPLE__)
2051
2052 #if defined(HAVE_GETIFADDRS) && defined(HAVE_IF_NAMETOINDEX)
2053 static int
2054 get_local_interface_id (int family)
2055 {
2056         struct ifaddrs *ifap = NULL, *ptr;
2057         int idx = 0;
2058         
2059         if (getifaddrs (&ifap)) {
2060                 return 0;
2061         }
2062         
2063         for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
2064                 if (!ptr->ifa_addr || !ptr->ifa_name)
2065                         continue;
2066                 if (ptr->ifa_addr->sa_family != family)
2067                         continue;
2068                 if ((ptr->ifa_flags & IFF_LOOPBACK) != 0)
2069                         continue;
2070                 if ((ptr->ifa_flags & IFF_MULTICAST) == 0)
2071                         continue;
2072                         
2073                 idx = if_nametoindex (ptr->ifa_name);
2074                 break;
2075         }
2076         
2077         freeifaddrs (ifap);
2078         return idx;
2079 }
2080 #else
2081 static int
2082 get_local_interface_id (int family)
2083 {
2084         return 0;
2085 }
2086 #endif
2087
2088 #endif /* __APPLE__ */
2089
2090 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)
2091 {
2092         struct linger linger;
2093         int system_level;
2094         int system_name;
2095         int ret;
2096 #ifdef AF_INET6
2097         int sol_ip;
2098         int sol_ipv6;
2099
2100         *error = 0;
2101         
2102 #ifdef HAVE_SOL_IPV6
2103         sol_ipv6 = SOL_IPV6;
2104 #else
2105         {
2106                 struct protoent *pent;
2107                 pent = getprotobyname ("ipv6");
2108                 sol_ipv6 = (pent != NULL) ? pent->p_proto : 41;
2109         }
2110 #endif
2111
2112 #ifdef HAVE_SOL_IP
2113         sol_ip = SOL_IP;
2114 #else
2115         {
2116                 struct protoent *pent;
2117                 pent = getprotobyname ("ip");
2118                 sol_ip = (pent != NULL) ? pent->p_proto : 0;
2119         }
2120 #endif
2121 #endif /* AF_INET6 */
2122
2123         MONO_ARCH_SAVE_REGS;
2124
2125         ret=convert_sockopt_level_and_name(level, name, &system_level,
2126                                            &system_name);
2127
2128 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
2129         if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
2130                 system_name = SO_REUSEADDR;
2131                 int_val = int_val ? 0 : 1;
2132                 ret = 0;
2133         }
2134 #endif
2135
2136         if(ret==-1) {
2137                 *error = WSAENOPROTOOPT;
2138                 return;
2139         }
2140         if(ret==-2){
2141                 return;
2142         }
2143
2144         /* Only one of obj_val, byte_val or int_val has data */
2145         if(obj_val!=NULL) {
2146                 MonoClassField *field;
2147                 int valsize;
2148                 
2149                 switch(name) {
2150                 case SocketOptionName_Linger:
2151                         /* Dig out "bool enabled" and "int seconds"
2152                          * fields
2153                          */
2154                         field=mono_class_get_field_from_name(obj_val->vtable->klass, "enabled");
2155                         linger.l_onoff=*(guint8 *)(((char *)obj_val)+field->offset);
2156                         field=mono_class_get_field_from_name(obj_val->vtable->klass, "seconds");
2157                         linger.l_linger=*(guint32 *)(((char *)obj_val)+field->offset);
2158                         
2159                         valsize=sizeof(linger);
2160                         ret = _wapi_setsockopt (sock, system_level,
2161                                                 system_name, &linger, valsize);
2162                         break;
2163                 case SocketOptionName_AddMembership:
2164                 case SocketOptionName_DropMembership:
2165 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2166                 {
2167                         MonoObject *address = NULL;
2168
2169 #ifdef AF_INET6
2170                         if(system_level == sol_ipv6) {
2171                                 struct ipv6_mreq mreq6;
2172
2173                                 /*
2174                                  *      Get group address
2175                                  */
2176                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2177                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2178                                 
2179                                 if(address) {
2180                                         mreq6.ipv6mr_multiaddr = ipaddress_to_struct_in6_addr (address);
2181                                 }
2182
2183                                 field=mono_class_get_field_from_name(obj_val->vtable->klass, "ifIndex");
2184                                 mreq6.ipv6mr_interface =*(guint64 *)(((char *)obj_val)+field->offset);
2185                                 
2186 #if defined(__APPLE__)
2187                                 /*
2188                                 * Bug #5504:
2189                                 *
2190                                 * Mac OS Lion doesn't allow ipv6mr_interface = 0.
2191                                 *
2192                                 * Tests on Windows and Linux show that the multicast group is only
2193                                 * joined on one NIC when interface = 0, so we simply use the interface
2194                                 * id from the first non-loopback interface (this is also what
2195                                 * Dns.GetHostName (string.Empty) would return).
2196                                 */
2197                                 if (!mreq6.ipv6mr_interface)
2198                                         mreq6.ipv6mr_interface = get_local_interface_id (AF_INET6);
2199 #endif
2200                                         
2201                                 ret = _wapi_setsockopt (sock, system_level,
2202                                                         system_name, &mreq6,
2203                                                         sizeof (mreq6));
2204                         } else if(system_level == sol_ip)
2205 #endif /* AF_INET6 */
2206                         {
2207 #ifdef HAVE_STRUCT_IP_MREQN
2208                                 struct ip_mreqn mreq = {{0}};
2209 #else
2210                                 struct ip_mreq mreq = {{0}};
2211 #endif /* HAVE_STRUCT_IP_MREQN */
2212                         
2213                                 /* pain! MulticastOption holds two IPAddress
2214                                  * members, so I have to dig the value out of
2215                                  * those :-(
2216                                  */
2217                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2218                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2219
2220                                 /* address might not be defined and if so, set the address to ADDR_ANY.
2221                                  */
2222                                 if(address) {
2223                                         mreq.imr_multiaddr = ipaddress_to_struct_in_addr (address);
2224                                 }
2225
2226                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "local");
2227                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2228
2229 #ifdef HAVE_STRUCT_IP_MREQN
2230                                 if(address) {
2231                                         mreq.imr_address = ipaddress_to_struct_in_addr (address);
2232                                 }
2233 #else
2234                                 if(address) {
2235                                         mreq.imr_interface = ipaddress_to_struct_in_addr (address);
2236                                 }
2237 #endif /* HAVE_STRUCT_IP_MREQN */
2238                         
2239                                 ret = _wapi_setsockopt (sock, system_level,
2240                                                         system_name, &mreq,
2241                                                         sizeof (mreq));
2242                         }
2243                         break;
2244                 }
2245 #endif /* HAVE_STRUCT_IP_MREQN || HAVE_STRUCT_IP_MREQ */
2246                 default:
2247                         /* Cause an exception to be thrown */
2248                         *error = WSAEINVAL;
2249                         return;
2250                 }
2251         } else if (byte_val!=NULL) {
2252                 int valsize = mono_array_length (byte_val);
2253                 guchar *buf = mono_array_addr (byte_val, guchar, 0);
2254                 
2255                 switch(name) {
2256                 case SocketOptionName_DontLinger:
2257                         if (valsize == 1) {
2258                                 linger.l_onoff = (*buf) ? 0 : 1;
2259                                 linger.l_linger = 0;
2260                                 ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2261                         } else {
2262                                 *error = WSAEINVAL;
2263                         }
2264                         break;
2265                 default:
2266                         ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
2267                         break;
2268                 }
2269         } else {
2270                 /* ReceiveTimeout/SendTimeout get here */
2271                 switch(name) {
2272                 case SocketOptionName_DontLinger:
2273                         linger.l_onoff = !int_val;
2274                         linger.l_linger = 0;
2275                         ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2276                         break;
2277                 case SocketOptionName_DontFragment:
2278 #ifdef HAVE_IP_MTU_DISCOVER
2279                         /* Fiddle with the value slightly if we're
2280                          * turning DF on
2281                          */
2282                         if (int_val == 1) {
2283                                 int_val = IP_PMTUDISC_DO;
2284                         }
2285                         /* Fall through */
2286 #endif
2287                         
2288                 default:
2289                         ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2290                 }
2291         }
2292
2293         if(ret==SOCKET_ERROR) {
2294                 *error = WSAGetLastError ();
2295         }
2296 }
2297
2298 void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock,
2299                                                            gint32 how,
2300                                                            gint32 *error)
2301 {
2302         int ret;
2303         
2304         MONO_ARCH_SAVE_REGS;
2305
2306         *error = 0;
2307         
2308         /* Currently, the values for how (recv=0, send=1, both=2) match
2309          * the BSD API
2310          */
2311         ret = _wapi_shutdown (sock, how);
2312         if(ret==SOCKET_ERROR) {
2313                 *error = WSAGetLastError ();
2314         }
2315 }
2316
2317 gint
2318 ves_icall_System_Net_Sockets_Socket_WSAIoctl (SOCKET sock, gint32 code,
2319                                               MonoArray *input,
2320                                               MonoArray *output, gint32 *error)
2321 {
2322         glong output_bytes = 0;
2323         gchar *i_buffer, *o_buffer;
2324         gint i_len, o_len;
2325         gint ret;
2326
2327         MONO_ARCH_SAVE_REGS;
2328
2329         *error = 0;
2330         
2331         if ((guint32)code == FIONBIO) {
2332                 /* Invalid command. Must use Socket.Blocking */
2333                 return -1;
2334         }
2335
2336         if (input == NULL) {
2337                 i_buffer = NULL;
2338                 i_len = 0;
2339         } else {
2340                 i_buffer = mono_array_addr (input, gchar, 0);
2341                 i_len = mono_array_length (input);
2342         }
2343
2344         if (output == NULL) {
2345                 o_buffer = NULL;
2346                 o_len = 0;
2347         } else {
2348                 o_buffer = mono_array_addr (output, gchar, 0);
2349                 o_len = mono_array_length (output);
2350         }
2351
2352         ret = WSAIoctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes, NULL, NULL);
2353         if (ret == SOCKET_ERROR) {
2354                 *error = WSAGetLastError ();
2355                 return(-1);
2356         }
2357
2358         return (gint) output_bytes;
2359 }
2360
2361 #ifdef HAVE_SIOCGIFCONF
2362 static gboolean
2363 is_loopback (int family, void *ad)
2364 {
2365         char *ptr = (char *) ad;
2366
2367         if (family == AF_INET) {
2368                 return (ptr [0] == 127);
2369         }
2370 #ifdef AF_INET6
2371         else {
2372                 return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
2373         }
2374 #endif
2375         return FALSE;
2376 }
2377
2378 static void *
2379 get_local_ips (int family, int *nips)
2380 {
2381         int addr_size, offset, fd, i, count;
2382         int max_ifaces = 50; /* 50 interfaces should be enough... */
2383         struct ifconf ifc;
2384         struct ifreq *ifr;
2385         struct ifreq iflags;
2386         char *result, *tmp_ptr;
2387         gboolean ignore_loopback = FALSE;
2388
2389         *nips = 0;
2390         if (family == AF_INET) {
2391                 addr_size = sizeof (struct in_addr);
2392                 offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
2393 #ifdef AF_INET6
2394         } else if (family == AF_INET6) {
2395                 addr_size = sizeof (struct in6_addr);
2396                 offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
2397 #endif
2398         } else {
2399                 return NULL;
2400         }
2401
2402         fd = socket (family, SOCK_STREAM, 0);
2403
2404         ifc.ifc_len = max_ifaces * sizeof (struct ifreq);
2405         ifc.ifc_buf = g_malloc (ifc.ifc_len);
2406         if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) {
2407                 close (fd);
2408                 g_free (ifc.ifc_buf);
2409                 return NULL;
2410         }
2411
2412         count = ifc.ifc_len / sizeof (struct ifreq);
2413         *nips = count;
2414         if (count == 0) {
2415                 g_free (ifc.ifc_buf);
2416                 close (fd);
2417                 return NULL;
2418         }
2419
2420         for (i = 0, ifr = ifc.ifc_req; i < *nips; i++, ifr++) {
2421                 strcpy (iflags.ifr_name, ifr->ifr_name);
2422                 if (ioctl (fd, SIOCGIFFLAGS, &iflags) < 0) {
2423                         continue;
2424                 }
2425
2426                 if ((iflags.ifr_flags & IFF_UP) == 0) {
2427                         ifr->ifr_name [0] = '\0';
2428                         continue;
2429                 }
2430
2431                 if ((iflags.ifr_flags & IFF_LOOPBACK) == 0) {
2432                         ignore_loopback = TRUE;
2433                 }
2434         }
2435
2436         close (fd);
2437         result = g_malloc (addr_size * count);
2438         tmp_ptr = result;
2439         for (i = 0, ifr = ifc.ifc_req; i < count; i++, ifr++) {
2440                 if (ifr->ifr_name [0] == '\0') {
2441                         (*nips)--;
2442                         continue;
2443                 }
2444
2445                 if (ignore_loopback && is_loopback (family, ((char *) &ifr->ifr_addr) + offset)) {
2446                         (*nips)--;
2447                         continue;
2448                 }
2449
2450                 memcpy (tmp_ptr, ((char *) &ifr->ifr_addr) + offset, addr_size);
2451                 tmp_ptr += addr_size;
2452         }
2453
2454         g_free (ifc.ifc_buf);
2455         return result;
2456 }
2457 #elif defined(HAVE_GETIFADDRS)
2458 static gboolean
2459 is_loopback (int family, void *ad)
2460 {
2461         char *ptr = (char *) ad;
2462
2463         if (family == AF_INET) {
2464                 return (ptr [0] == 127);
2465         }
2466 #ifdef AF_INET6
2467         else {
2468                 return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
2469         }
2470 #endif
2471         return FALSE;
2472 }
2473
2474 static void *
2475 get_local_ips (int family, int *nips)
2476 {
2477         struct ifaddrs *ifap = NULL, *ptr;
2478         int addr_size, offset, count, i;
2479         char *result, *tmp_ptr;
2480
2481         *nips = 0;
2482         if (family == AF_INET) {
2483                 addr_size = sizeof (struct in_addr);
2484                 offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
2485 #ifdef AF_INET6
2486         } else if (family == AF_INET6) {
2487                 addr_size = sizeof (struct in6_addr);
2488                 offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
2489 #endif
2490         } else {
2491                 return NULL;
2492         }
2493         
2494         if (getifaddrs (&ifap)) {
2495                 return NULL;
2496         }
2497         
2498         count = 0;
2499         for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
2500                 if (!ptr->ifa_addr)
2501                         continue;
2502                 if (ptr->ifa_addr->sa_family != family)
2503                         continue;
2504                 if (is_loopback (family, ((char *) ptr->ifa_addr) + offset))
2505                         continue;
2506                 count++;
2507         }
2508                 
2509         result = g_malloc (addr_size * count);
2510         tmp_ptr = result;
2511         for (i = 0, ptr = ifap; ptr; ptr = ptr->ifa_next) {
2512                 if (!ptr->ifa_addr)
2513                         continue;
2514                 if (ptr->ifa_addr->sa_family != family)
2515                         continue;
2516                 if (is_loopback (family, ((char *) ptr->ifa_addr) + offset))
2517                         continue;
2518                         
2519                 memcpy (tmp_ptr, ((char *) ptr->ifa_addr) + offset, addr_size);
2520                 tmp_ptr += addr_size;
2521         }
2522         
2523         freeifaddrs (ifap);
2524         *nips = count;
2525         return result;
2526 }
2527 #else
2528 static void *
2529 get_local_ips (int family, int *nips)
2530 {
2531         *nips = 0;
2532         return NULL;
2533 }
2534
2535 #endif /* HAVE_SIOCGIFCONF */
2536
2537 #ifndef AF_INET6
2538 static gboolean hostent_to_IPHostEntry(struct hostent *he, MonoString **h_name,
2539                                        MonoArray **h_aliases,
2540                                        MonoArray **h_addr_list,
2541                                        gboolean add_local_ips)
2542 {
2543         MonoDomain *domain = mono_domain_get ();
2544         int i = 0;
2545         struct in_addr *local_in = NULL;
2546         int nlocal_in = 0;
2547
2548         if (he != NULL) {
2549                 if(he->h_length!=4 || he->h_addrtype!=AF_INET) {
2550                         return(FALSE);
2551                 }
2552
2553                 *h_name=mono_string_new(domain, he->h_name);
2554
2555                 while(he->h_aliases[i]!=NULL) {
2556                         i++;
2557                 }
2558                 
2559                 *h_aliases=mono_array_new(domain, mono_get_string_class (), i);
2560                 i=0;
2561                 while(he->h_aliases[i]!=NULL) {
2562                         MonoString *alias;
2563                         
2564                         alias=mono_string_new(domain, he->h_aliases[i]);
2565                         mono_array_setref (*h_aliases, i, alias);
2566                         i++;
2567                 }
2568         } else if (!add_local_ips) {
2569                 return FALSE;
2570         }
2571
2572         if (add_local_ips) {
2573                 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2574                 if (nlocal_in) {
2575                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), nlocal_in);
2576                         for (i = 0; i < nlocal_in; i++) {
2577                                 MonoString *addr_string;
2578                                 char addr [16], *ptr;
2579                                 
2580                                 ptr = (char *) &local_in [i];
2581                                 g_snprintf(addr, 16, "%u.%u.%u.%u",
2582                                          (unsigned char) ptr [0],
2583                                          (unsigned char) ptr [1],
2584                                          (unsigned char) ptr [2],
2585                                          (unsigned char) ptr [3]);
2586                                 
2587                                 addr_string = mono_string_new (domain, addr);
2588                                 mono_array_setref (*h_addr_list, i, addr_string);
2589                                 i++;
2590                         }
2591
2592                         g_free (local_in);
2593                 } else if (he == NULL) {
2594                         /* If requesting "" and there are no other interfaces up, MS returns 127.0.0.1 */
2595                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), 1);
2596                         mono_array_setref (*h_addr_list, 0, mono_string_new (domain, "127.0.0.1"));
2597                         return TRUE;
2598                 }
2599         }
2600         
2601         if (nlocal_in == 0 && he != NULL) {
2602                 i = 0;
2603                 while (he->h_addr_list[i]!=NULL) {
2604                         i++;
2605                 }
2606
2607                 *h_addr_list=mono_array_new(domain, mono_get_string_class (), i);
2608                 i=0;
2609                 while(he->h_addr_list[i]!=NULL) {
2610                         MonoString *addr_string;
2611                         char addr[16];
2612                         
2613                         g_snprintf(addr, 16, "%u.%u.%u.%u",
2614                                  (unsigned char)he->h_addr_list[i][0],
2615                                  (unsigned char)he->h_addr_list[i][1],
2616                                  (unsigned char)he->h_addr_list[i][2],
2617                                  (unsigned char)he->h_addr_list[i][3]);
2618                         
2619                         addr_string=mono_string_new(domain, addr);
2620                         mono_array_setref (*h_addr_list, i, addr_string);
2621                         i++;
2622                 }
2623         }
2624
2625         return(TRUE);
2626 }
2627
2628 static gboolean ipaddr_to_IPHostEntry(const char *addr, MonoString **h_name,
2629                                       MonoArray **h_aliases,
2630                                       MonoArray **h_addr_list)
2631 {
2632         MonoDomain *domain = mono_domain_get ();
2633
2634         *h_name=mono_string_new(domain, addr);
2635         *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2636         *h_addr_list=mono_array_new(domain, mono_get_string_class (), 1);
2637         mono_array_setref (*h_addr_list, 0, *h_name);
2638
2639         return(TRUE);
2640 }
2641 #endif
2642
2643 #if defined(AF_INET6) && defined(HAVE_GETHOSTBYNAME2_R)
2644 static gboolean hostent_to_IPHostEntry2(struct hostent *he1,struct hostent *he2, MonoString **h_name,
2645                                 MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
2646 {
2647         MonoDomain *domain = mono_domain_get ();
2648         int i, host_count, host_index, family_hint;
2649         struct in_addr *local_in = NULL;
2650         int nlocal_in = 0;
2651         struct in6_addr *local_in6 = NULL;
2652         int nlocal_in6 = 0;
2653         gboolean from_local = FALSE;
2654
2655         family_hint = get_family_hint ();
2656
2657         /*
2658          * Check if address length and family are correct
2659          */
2660         if (he1 != NULL && (he1->h_length!=4 || he1->h_addrtype!=AF_INET)) {
2661                 return(FALSE);
2662         }
2663
2664         if (he2 != NULL && (he2->h_length!=16 || he2->h_addrtype!=AF_INET6)) {
2665                 return(FALSE);
2666         }
2667
2668         /*
2669          * Get the aliases and host name from he1 or he2 whichever is
2670          * not null, if he1 is not null then take aliases from he1
2671          */
2672         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2673                             family_hint == PF_INET)) {
2674                 *h_name=mono_string_new (domain, he1->h_name);
2675
2676                 i=0;
2677                 while(he1->h_aliases[i]!=NULL) {
2678                         i++;
2679                 }
2680
2681                 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2682                                            i);
2683                 i=0;
2684                 while(he1->h_aliases[i]!=NULL) {
2685                         MonoString *alias;
2686
2687                         alias=mono_string_new (domain, he1->h_aliases[i]);
2688                         mono_array_setref (*h_aliases, i, alias);
2689                         i++;
2690                 }
2691         } else if (he2 != NULL && (family_hint == PF_UNSPEC ||
2692                                    family_hint == PF_INET6)) {
2693                 *h_name=mono_string_new (domain, he2->h_name);
2694
2695                 i=0;
2696                 while(he2->h_aliases [i] != NULL) {
2697                         i++;
2698                 }
2699
2700                 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2701                                            i);
2702                 i=0;
2703                 while(he2->h_aliases[i]!=NULL) {
2704                         MonoString *alias;
2705
2706                         alias=mono_string_new (domain, he2->h_aliases[i]);
2707                         mono_array_setref (*h_aliases, i, alias);
2708                         i++;
2709                 }
2710         } else if (!add_local_ips) {
2711                 return(FALSE);
2712         }
2713
2714         /*
2715          * Count the number of addresses in he1 + he2
2716          */
2717         host_count = 0;
2718         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2719                             family_hint == PF_INET)) {
2720                 i=0;
2721                 while(he1->h_addr_list[i]!=NULL) {
2722                         i++;
2723                         host_count++;
2724                 }
2725         }
2726
2727         if (he2 != NULL && (family_hint == PF_UNSPEC ||
2728                             family_hint == PF_INET6)) {
2729                 i=0;
2730                 while(he2->h_addr_list[i]!=NULL) {
2731                         i++;
2732                         host_count++;
2733                 }
2734         }
2735
2736         /*
2737          * Fills the array
2738          */
2739         host_index = 0;
2740         if (add_local_ips) {
2741                 if (family_hint == PF_UNSPEC || family_hint == PF_INET)
2742                         local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2743
2744                 if (family_hint == PF_UNSPEC || family_hint == PF_INET6)
2745                         local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2746
2747                 if (nlocal_in || nlocal_in6) {
2748                         from_local = TRUE;
2749                         *h_addr_list = mono_array_new (domain, mono_get_string_class (),
2750                                                              nlocal_in + nlocal_in6);
2751
2752                         if (nlocal_in6) {
2753                                 int n;
2754                                 for (n = 0; n < nlocal_in6; n++) {
2755                                         MonoString *addr_string;
2756                                         const char *ret;
2757                                         char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes with the trailing NULL */
2758
2759                                         ret = inet_ntop (AF_INET6, &local_in6 [n], addr, sizeof(addr));
2760
2761                                         if (ret != NULL) {
2762                                                 addr_string = mono_string_new (domain, addr);
2763                                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2764                                                 host_index++;
2765                                         }
2766                                 }
2767                         }
2768
2769                         if (nlocal_in) {
2770                                 int n;
2771                                 for (n = 0; n < nlocal_in; n++) {
2772                                         MonoString *addr_string;
2773                                         const char *ret;
2774                                         char addr[16]; /* INET_ADDRSTRLEN == 16 */
2775
2776                                         ret = inet_ntop (AF_INET, &local_in [n], addr, sizeof(addr));
2777
2778                                         if (ret != NULL) {
2779                                                 addr_string = mono_string_new (domain, addr);
2780                                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2781                                                 host_index++;
2782                                         }
2783                                 }
2784                         }
2785                         g_free (local_in);
2786                         g_free (local_in6);
2787                         return TRUE;
2788                 } else if (he1 == NULL && he2 == NULL) {
2789                         /* If requesting "" and there are no other interfaces up, MS returns 127.0.0.1 */
2790                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), 1);
2791                         mono_array_setref (*h_addr_list, 0, mono_string_new (domain, "127.0.0.1"));
2792                         g_free (local_in);
2793                         g_free (local_in6);
2794                         return TRUE;
2795                 }
2796
2797                 g_free (local_in);
2798                 g_free (local_in6);
2799         }
2800
2801         *h_addr_list=mono_array_new (domain, mono_get_string_class (), host_count);
2802
2803         if (he2 != NULL && (family_hint == PF_UNSPEC ||
2804                             family_hint == PF_INET6)) {
2805                 i = 0;
2806                 while(he2->h_addr_list[i] != NULL) {
2807                         MonoString *addr_string;
2808                         const char *ret;
2809                         char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes long with the trailing NULL */
2810
2811                         ret = inet_ntop (AF_INET6, he2->h_addr_list[i], addr,
2812                                          sizeof(addr));
2813
2814                         if (ret != NULL) {
2815                                 addr_string = mono_string_new (domain, addr);
2816                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2817                                 i++;
2818                                 host_index++;
2819                         }
2820                 }
2821         }
2822
2823         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2824                             family_hint == PF_INET)) {
2825                 i=0;
2826                 while(he1->h_addr_list[i] != NULL) {
2827                         MonoString *addr_string;
2828                         const char *ret;
2829                         char addr[16]; /* INET_ADDRSTRLEN == 16 */
2830
2831                         ret = inet_ntop (AF_INET, he1->h_addr_list[i], addr,
2832                                          sizeof(addr));
2833
2834                         if (ret != NULL) {
2835                                 addr_string=mono_string_new (domain, addr);
2836                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2837                                 i++;
2838                                 host_index++;
2839                         }
2840                 }
2841         }
2842
2843         return(TRUE);
2844 }
2845 #endif
2846
2847 #if defined(AF_INET6)
2848 static gboolean 
2849 addrinfo_to_IPHostEntry(struct addrinfo *info, MonoString **h_name,
2850                                                 MonoArray **h_aliases,
2851                                                 MonoArray **h_addr_list,
2852                                                 gboolean add_local_ips)
2853 {
2854         gint32 count, i;
2855         struct addrinfo *ai = NULL;
2856         struct in_addr *local_in = NULL;
2857         int nlocal_in = 0;
2858         struct in6_addr *local_in6 = NULL;
2859         int nlocal_in6 = 0;
2860         int addr_index;
2861
2862         MonoDomain *domain = mono_domain_get ();
2863
2864         addr_index = 0;
2865         *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2866         if (add_local_ips) {
2867                 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2868                 local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2869                 if (nlocal_in || nlocal_in6) {
2870                         *h_addr_list=mono_array_new(domain, mono_get_string_class (), nlocal_in + nlocal_in6);
2871                         if (nlocal_in) {
2872                                 MonoString *addr_string;
2873                                 char addr [16];
2874                                 int i;
2875
2876                                 for (i = 0; i < nlocal_in; i++) {
2877                                         inet_ntop (AF_INET, &local_in [i], addr, sizeof (addr));
2878                                         addr_string = mono_string_new (domain, addr);
2879                                         mono_array_setref (*h_addr_list, addr_index, addr_string);
2880                                         addr_index++;
2881                                 }
2882                         }
2883
2884                         if (nlocal_in6) {
2885                                 MonoString *addr_string;
2886                                 const char *ret;
2887                                 char addr [48];
2888                                 int i;
2889
2890                                 for (i = 0; i < nlocal_in6; i++) {
2891                                         ret = inet_ntop (AF_INET6, &local_in6 [i], addr, sizeof (addr));
2892                                         if (ret != NULL) {
2893                                                 addr_string = mono_string_new (domain, addr);
2894                                                 mono_array_setref (*h_addr_list, addr_index, addr_string);
2895                                                 addr_index++;
2896                                         }
2897                                 }
2898                         }
2899
2900                         g_free (local_in);
2901                         g_free (local_in6);
2902                         if (info) {
2903                                 freeaddrinfo (info);
2904                         }
2905                         return TRUE;
2906                 }
2907
2908                 g_free (local_in);
2909                 g_free (local_in6);
2910         }
2911
2912         for (count=0, ai=info; ai!=NULL; ai=ai->ai_next) {
2913                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2914                         continue;
2915
2916                 count++;
2917         }
2918
2919         *h_addr_list=mono_array_new(domain, mono_get_string_class (), count);
2920
2921         for (ai=info, i=0; ai!=NULL; ai=ai->ai_next) {
2922                 MonoString *addr_string;
2923                 const char *ret;
2924                 char buffer [48]; /* Max. size for IPv6 */
2925
2926                 if((ai->ai_family != PF_INET) && (ai->ai_family != PF_INET6)) {
2927                         continue;
2928                 }
2929
2930                 if(ai->ai_family == PF_INET) {
2931                         ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr), buffer, 16);
2932                 } else {
2933                         ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in6*)ai->ai_addr)->sin6_addr), buffer, 48);
2934                 }
2935
2936                 if(ret) {
2937                         addr_string=mono_string_new(domain, buffer);
2938                 } else {
2939                         addr_string=mono_string_new(domain, "");
2940                 }
2941
2942                 mono_array_setref (*h_addr_list, addr_index, addr_string);
2943
2944                 if(!i) {
2945                         i++;
2946                         if (ai->ai_canonname != NULL) {
2947                                 *h_name=mono_string_new(domain, ai->ai_canonname);
2948                         } else {
2949                                 *h_name=mono_string_new(domain, buffer);
2950                         }
2951                 }
2952
2953                 addr_index++;
2954         }
2955
2956         if(info) {
2957                 freeaddrinfo(info);
2958         }
2959
2960         return(TRUE);
2961 }
2962 #endif
2963
2964 #ifdef AF_INET6
2965 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2966 {
2967         gboolean add_local_ips = FALSE;
2968 #ifdef HAVE_SIOCGIFCONF
2969         gchar this_hostname [256];
2970 #endif
2971 #if !defined(HAVE_GETHOSTBYNAME2_R)
2972         struct addrinfo *info = NULL, hints;
2973         char *hostname;
2974         
2975         MONO_ARCH_SAVE_REGS;
2976         
2977         hostname=mono_string_to_utf8 (host);
2978         if (*hostname == '\0') {
2979                 add_local_ips = TRUE;
2980                 *h_name = host;
2981         }
2982 #ifdef HAVE_SIOCGIFCONF
2983         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2984                 if (!strcmp (hostname, this_hostname)) {
2985                         add_local_ips = TRUE;
2986                         *h_name = host;
2987                 }
2988         }
2989 #endif
2990
2991         memset(&hints, 0, sizeof(hints));
2992         hints.ai_family = get_family_hint ();
2993         hints.ai_socktype = SOCK_STREAM;
2994         hints.ai_flags = AI_CANONNAME;
2995
2996         if (*hostname && getaddrinfo(hostname, NULL, &hints, &info) == -1) {
2997                 return(FALSE);
2998         }
2999         
3000         g_free(hostname);
3001
3002         return(addrinfo_to_IPHostEntry(info, h_name, h_aliases, h_addr_list, add_local_ips));
3003 #else
3004         struct hostent he1,*hp1, he2, *hp2;
3005         int buffer_size1, buffer_size2;
3006         char *buffer1, *buffer2;
3007         int herr;
3008         gboolean return_value;
3009         char *hostname;
3010         
3011         MONO_ARCH_SAVE_REGS;
3012         
3013         hostname=mono_string_to_utf8 (host);
3014         if (*hostname == '\0')
3015                 add_local_ips = TRUE;
3016
3017 #ifdef HAVE_SIOCGIFCONF
3018         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
3019                 if (!strcmp (hostname, this_hostname))
3020                         add_local_ips = TRUE;
3021         }
3022 #endif
3023
3024         buffer_size1 = 512;
3025         buffer_size2 = 512;
3026         buffer1 = g_malloc0(buffer_size1);
3027         buffer2 = g_malloc0(buffer_size2);
3028
3029         hp1 = NULL;
3030         hp2 = NULL;
3031         while (*hostname && gethostbyname2_r(hostname, AF_INET, &he1, buffer1, buffer_size1,
3032                                 &hp1, &herr) == ERANGE) {
3033                 buffer_size1 *= 2;
3034                 buffer1 = g_realloc(buffer1, buffer_size1);
3035         }
3036
3037         if (*hostname && hp1 == NULL)
3038         {
3039                 while (gethostbyname2_r(hostname, AF_INET6, &he2, buffer2,
3040                                         buffer_size2, &hp2, &herr) == ERANGE) {
3041                         buffer_size2 *= 2;
3042                         buffer2 = g_realloc(buffer2, buffer_size2);
3043                 }
3044         }
3045
3046         return_value = hostent_to_IPHostEntry2(hp1, hp2, h_name, h_aliases,
3047                                                h_addr_list, add_local_ips);
3048
3049         g_free(buffer1);
3050         g_free(buffer2);
3051         g_free(hostname);
3052
3053         return(return_value);
3054 #endif /* HAVE_GETHOSTBYNAME2_R */
3055 }
3056 #else /* AF_INET6 */
3057 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
3058 {
3059         struct hostent *he;
3060         char *hostname;
3061         gboolean add_local_ips = FALSE;
3062 #ifdef HAVE_SIOCGIFCONF
3063         gchar this_hostname [256];
3064 #endif
3065         
3066         MONO_ARCH_SAVE_REGS;
3067
3068         hostname=mono_string_to_utf8(host);
3069         if (*hostname == '\0')
3070                 add_local_ips = TRUE;
3071 #ifdef HAVE_SIOCGIFCONF
3072         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
3073                 if (!strcmp (hostname, this_hostname))
3074                         add_local_ips = TRUE;
3075         }
3076 #endif
3077
3078 #ifndef HOST_WIN32
3079         he = NULL;
3080         if (*hostname)
3081                 he = _wapi_gethostbyname (hostname);
3082 #else
3083         he = _wapi_gethostbyname (hostname);
3084 #endif
3085         g_free(hostname);
3086
3087         if (*hostname && he==NULL)
3088                 return(FALSE);
3089
3090         return(hostent_to_IPHostEntry(he, h_name, h_aliases, h_addr_list, add_local_ips));
3091 }
3092 #endif /* AF_INET6 */
3093
3094 #ifndef HAVE_INET_PTON
3095 static int
3096 inet_pton (int family, const char *address, void *inaddrp)
3097 {
3098         if (family == AF_INET) {
3099 #ifdef HAVE_INET_ATON
3100                 struct in_addr inaddr;
3101                 
3102                 if (!inet_aton (address, &inaddr))
3103                         return 0;
3104                 
3105                 memcpy (inaddrp, &inaddr, sizeof (struct in_addr));
3106                 return 1;
3107 #else
3108                 /* assume the system has inet_addr(), if it doesn't
3109                    have that we're pretty much screwed... */
3110                 guint32 inaddr;
3111                 
3112                 if (!strcmp (address, "255.255.255.255")) {
3113                         /* special-case hack */
3114                         inaddr = 0xffffffff;
3115                 } else {
3116                         inaddr = inet_addr (address);
3117 #ifndef INADDR_NONE
3118 #define INADDR_NONE ((in_addr_t) -1)
3119 #endif
3120                         if (inaddr == INADDR_NONE)
3121                                 return 0;
3122                 }
3123                 
3124                 memcpy (inaddrp, &inaddr, sizeof (guint32));
3125                 return 1;
3126 #endif /* HAVE_INET_ATON */
3127         }
3128         
3129         return -1;
3130 }
3131 #endif /* !HAVE_INET_PTON */
3132
3133 extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
3134 {
3135         char *address;
3136         
3137 #ifdef AF_INET6
3138         struct sockaddr_in saddr;
3139         struct sockaddr_in6 saddr6;
3140         struct addrinfo *info = NULL, hints;
3141         gint32 family;
3142         char hostname[NI_MAXHOST] = {0};
3143         int flags = 0;
3144 #else
3145         struct in_addr inaddr;
3146         struct hostent *he;
3147         gboolean ret;
3148 #endif
3149
3150         address = mono_string_to_utf8 (addr);
3151
3152 #ifdef AF_INET6
3153         if (inet_pton (AF_INET, address, &saddr.sin_addr ) <= 0) {
3154                 /* Maybe an ipv6 address */
3155                 if (inet_pton (AF_INET6, address, &saddr6.sin6_addr) <= 0) {
3156                         g_free (address);
3157                         return FALSE;
3158                 }
3159                 else {
3160                         family = AF_INET6;
3161                         saddr6.sin6_family = AF_INET6;
3162                 }
3163         }
3164         else {
3165                 family = AF_INET;
3166                 saddr.sin_family = AF_INET;
3167         }
3168         g_free(address);
3169
3170         if(family == AF_INET) {
3171 #if HAVE_SOCKADDR_IN_SIN_LEN
3172                 saddr.sin_len = sizeof (saddr);
3173 #endif
3174                 if(getnameinfo ((struct sockaddr*)&saddr, sizeof(saddr),
3175                                 hostname, sizeof(hostname), NULL, 0,
3176                                 flags) != 0) {
3177                         return(FALSE);
3178                 }
3179         } else if(family == AF_INET6) {
3180 #if HAVE_SOCKADDR_IN6_SIN_LEN
3181                 saddr6.sin6_len = sizeof (saddr6);
3182 #endif
3183                 if(getnameinfo ((struct sockaddr*)&saddr6, sizeof(saddr6),
3184                                 hostname, sizeof(hostname), NULL, 0,
3185                                 flags) != 0) {
3186                         return(FALSE);
3187                 }
3188         }
3189
3190         memset (&hints, 0, sizeof(hints));
3191         hints.ai_family = get_family_hint ();
3192         hints.ai_socktype = SOCK_STREAM;
3193         hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
3194
3195         if( getaddrinfo (hostname, NULL, &hints, &info) == -1 ) {
3196                 return(FALSE);
3197         }
3198
3199         return(addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE));
3200 #else
3201         if (inet_pton (AF_INET, address, &inaddr) <= 0) {
3202                 g_free (address);
3203                 return(FALSE);
3204         }
3205
3206         if ((he = gethostbyaddr ((char *) &inaddr, sizeof (inaddr), AF_INET)) == NULL) {
3207                 ret = ipaddr_to_IPHostEntry (address, h_name, h_aliases, h_addr_list);
3208         } else {
3209                 ret = hostent_to_IPHostEntry (he, h_name, h_aliases,
3210                                               h_addr_list, FALSE);
3211         }
3212
3213         g_free (address);
3214         return(ret);
3215 #endif
3216 }
3217
3218 extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name)
3219 {
3220         gchar hostname[256];
3221         int ret;
3222         
3223         MONO_ARCH_SAVE_REGS;
3224
3225         ret = gethostname (hostname, sizeof (hostname));
3226         if(ret==-1) {
3227                 return(FALSE);
3228         }
3229         
3230         *h_name=mono_string_new(mono_domain_get (), hostname);
3231
3232         return(TRUE);
3233 }
3234
3235 gboolean
3236 ves_icall_System_Net_Sockets_Socket_SendFile (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
3237 {
3238         HANDLE file;
3239         gint32 error;
3240         TRANSMIT_FILE_BUFFERS buffers;
3241
3242         MONO_ARCH_SAVE_REGS;
3243
3244         if (filename == NULL)
3245                 return FALSE;
3246
3247         file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &error);
3248         if (file == INVALID_HANDLE_VALUE) {
3249                 SetLastError (error);
3250                 return FALSE;
3251         }
3252
3253         memset (&buffers, 0, sizeof (buffers));
3254         if (pre_buffer != NULL) {
3255                 buffers.Head = mono_array_addr (pre_buffer, guchar, 0);
3256                 buffers.HeadLength = mono_array_length (pre_buffer);
3257         }
3258         if (post_buffer != NULL) {
3259                 buffers.Tail = mono_array_addr (post_buffer, guchar, 0);
3260                 buffers.TailLength = mono_array_length (post_buffer);
3261         }
3262
3263         if (!TransmitFile (sock, file, 0, 0, NULL, &buffers, flags)) {
3264                 CloseHandle (file);
3265                 return FALSE;
3266         }
3267
3268         CloseHandle (file);
3269         return TRUE;
3270 }
3271
3272 void mono_network_init(void)
3273 {
3274         WSADATA wsadata;
3275         int err;
3276         
3277         err=WSAStartup(MAKEWORD(2,0), &wsadata);
3278         if(err!=0) {
3279                 g_error("%s: Couldn't initialise networking", __func__);
3280                 exit(-1);
3281         }
3282
3283         LOGDEBUG (g_message("%s: Using socket library: %s", __func__, wsadata.szDescription));
3284         LOGDEBUG (g_message("%s: Socket system status: %s", __func__, wsadata.szSystemStatus));
3285 }
3286
3287 void mono_network_cleanup(void)
3288 {
3289         WSACleanup();
3290 }
3291
3292 void
3293 icall_cancel_blocking_socket_operation (MonoThread *thread)
3294 {
3295         MonoInternalThread *internal = thread->internal_thread;
3296         
3297         if (mono_thread_info_new_interrupt_enabled ()) {
3298                 mono_thread_info_abort_socket_syscall_for_close ((MonoNativeThreadId)(gsize)internal->tid);
3299         } else {
3300 #ifndef HOST_WIN32
3301                 internal->ignore_next_signal = TRUE;
3302                 mono_thread_kill (internal, mono_thread_get_abort_signal ());           
3303 #endif
3304         }
3305 }
3306
3307 #endif /* #ifndef DISABLE_SOCKETS */