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