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