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