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