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