2009-06-12 Bill Holmes <billholmes54@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         ret=ioctlsocket(sock, FIONREAD, &amount);
808         if(ret==SOCKET_ERROR) {
809                 *error = WSAGetLastError ();
810                 return(0);
811         }
812         
813         return(amount);
814 }
815
816 void ves_icall_System_Net_Sockets_Socket_Blocking_internal(SOCKET sock,
817                                                            gboolean block,
818                                                            gint32 *error)
819 {
820         int ret;
821         
822         MONO_ARCH_SAVE_REGS;
823
824         *error = 0;
825
826         /*
827          * block == TRUE/FALSE means we will block/not block.
828          * But the ioctlsocket call takes TRUE/FALSE for non-block/block
829          */
830         block = !block;
831         
832         ret = ioctlsocket (sock, FIONBIO, (gulong *) &block);
833         if(ret==SOCKET_ERROR) {
834                 *error = WSAGetLastError ();
835         }
836 }
837
838 gpointer ves_icall_System_Net_Sockets_Socket_Accept_internal(SOCKET sock,
839                                                              gint32 *error,
840                                                              gboolean blocking)
841 {
842         SOCKET newsock;
843         
844         MONO_ARCH_SAVE_REGS;
845
846         *error = 0;
847
848 #ifdef PLATFORM_WIN32
849         /* Several applications are getting stuck during shutdown on Windows 
850          * when an accept call is on a background thread.
851          * 
852          */
853         if (blocking) {
854                 MonoThread* curthread = mono_thread_current ();
855
856                 if (curthread) {
857                         for (;;) {
858                                 int selectret;
859                                 int optlen = sizeof (gint);
860                                 TIMEVAL timeout; 
861                                 fd_set readfds;
862                                 FD_ZERO (&readfds);
863                                 FD_SET(sock, &readfds);
864                                 timeout.tv_sec = 0;
865                                 timeout.tv_usec = 1000;
866                                 selectret = select (0, &readfds, NULL, NULL, &timeout);
867                                 if (selectret > 0)
868                                         break;
869                                 if (curthread->state & ThreadState_StopRequested)
870                                         return NULL;
871                                 /* A negative return from select means that an error has occurred.
872                                  * Let _wapi_accept handle that.*/
873                                 if (selectret != 0)
874                                         break;
875                                 /* The socket's state may have changed.  If it is no longer listening, stop.*/
876                                 if (!getsockopt (sock, SOL_SOCKET, SO_ACCEPTCONN, (char*)&selectret, &optlen)) {
877                                         if (!selectret)
878                                                 break;
879                                 }
880                         }
881                 }
882         }
883 #endif
884         
885         newsock = _wapi_accept (sock, NULL, 0);
886         if(newsock==INVALID_SOCKET) {
887                 *error = WSAGetLastError ();
888                 return(NULL);
889         }
890         
891         return(GUINT_TO_POINTER (newsock));
892 }
893
894 void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock,
895                                                          guint32 backlog,
896                                                          gint32 *error)
897 {
898         int ret;
899         
900         MONO_ARCH_SAVE_REGS;
901
902         *error = 0;
903         
904         ret = _wapi_listen (sock, backlog);
905         if(ret==SOCKET_ERROR) {
906                 *error = WSAGetLastError ();
907         }
908 }
909
910 static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
911                                                int sa_size, gint32 *error)
912 {
913         MonoDomain *domain = mono_domain_get ();
914         MonoObject *sockaddr_obj;
915         MonoClass *sockaddr_class;
916         MonoClassField *field;
917         MonoArray *data;
918         MonoAddressFamily family;
919
920         /* Build a System.Net.SocketAddress object instance */
921         sockaddr_class=mono_class_from_name_cached (get_socket_assembly (), "System.Net", "SocketAddress");
922         sockaddr_obj=mono_object_new(domain, sockaddr_class);
923         
924         /* Locate the SocketAddress data buffer in the object */
925         field=mono_class_get_field_from_name_cached (sockaddr_class, "data");
926
927         /* Make sure there is space for the family and size bytes */
928 #ifdef HAVE_SYS_UN_H
929         if (saddr->sa_family == AF_UNIX) {
930                 /* sa_len includes the entire sockaddr size, so we don't need the
931                  * N bytes (sizeof (unsigned short)) of the family. */
932                 data=mono_array_new_cached(domain, mono_get_byte_class (), sa_size);
933         } else
934 #endif
935         {
936                 /* May be the +2 here is too conservative, as sa_len returns
937                  * the length of the entire sockaddr_in/in6, including
938                  * sizeof (unsigned short) of the family */
939                 data=mono_array_new_cached(domain, mono_get_byte_class (), sa_size+2);
940         }
941
942         /* The data buffer is laid out as follows:
943          * bytes 0 and 1 are the address family
944          * bytes 2 and 3 are the port info
945          * the rest is the address info
946          */
947                 
948         family=convert_to_mono_family(saddr->sa_family);
949         if(family==AddressFamily_Unknown) {
950                 *error = WSAEAFNOSUPPORT;
951                 return(NULL);
952         }
953
954         mono_array_set(data, guint8, 0, family & 0x0FF);
955         mono_array_set(data, guint8, 1, (family >> 8) & 0x0FF);
956         
957         if(saddr->sa_family==AF_INET) {
958                 struct sockaddr_in *sa_in=(struct sockaddr_in *)saddr;
959                 guint16 port=ntohs(sa_in->sin_port);
960                 guint32 address=ntohl(sa_in->sin_addr.s_addr);
961                 
962                 if(sa_size<8) {
963                         mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
964                 }
965                 
966                 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
967                 mono_array_set(data, guint8, 3, (port) & 0xff);
968                 mono_array_set(data, guint8, 4, (address>>24) & 0xff);
969                 mono_array_set(data, guint8, 5, (address>>16) & 0xff);
970                 mono_array_set(data, guint8, 6, (address>>8) & 0xff);
971                 mono_array_set(data, guint8, 7, (address) & 0xff);
972         
973                 mono_field_set_value (sockaddr_obj, field, data);
974
975                 return(sockaddr_obj);
976 #ifdef AF_INET6
977         } else if (saddr->sa_family == AF_INET6) {
978                 struct sockaddr_in6 *sa_in=(struct sockaddr_in6 *)saddr;
979                 int i;
980
981                 guint16 port=ntohs(sa_in->sin6_port);
982
983                 if(sa_size<28) {
984                         mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
985                 }
986
987                 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
988                 mono_array_set(data, guint8, 3, (port) & 0xff);
989
990                 for(i=0; i<16; i++) {
991                         mono_array_set(data, guint8, 8+i,
992                                        sa_in->sin6_addr.s6_addr[i]);
993                 }
994
995                 mono_array_set(data, guint8, 24, sa_in->sin6_scope_id & 0xff);
996                 mono_array_set(data, guint8, 25,
997                                (sa_in->sin6_scope_id >> 8) & 0xff);
998                 mono_array_set(data, guint8, 26,
999                                (sa_in->sin6_scope_id >> 16) & 0xff);
1000                 mono_array_set(data, guint8, 27,
1001                                (sa_in->sin6_scope_id >> 24) & 0xff);
1002
1003                 mono_field_set_value (sockaddr_obj, field, data);
1004
1005                 return(sockaddr_obj);
1006 #endif
1007 #ifdef HAVE_SYS_UN_H
1008         } else if (saddr->sa_family == AF_UNIX) {
1009                 int i;
1010
1011                 for (i = 0; i < sa_size; i++) {
1012                         mono_array_set (data, guint8, i+2, saddr->sa_data[i]);
1013                 }
1014                 
1015                 mono_field_set_value (sockaddr_obj, field, data);
1016
1017                 return sockaddr_obj;
1018 #endif
1019         } else {
1020                 *error = WSAEAFNOSUPPORT;
1021                 return(NULL);
1022         }
1023 }
1024
1025 extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 *error)
1026 {
1027         gchar sa[32];   /* sockaddr in not big enough for sockaddr_in6 */
1028         socklen_t salen;
1029         int ret;
1030         
1031         MONO_ARCH_SAVE_REGS;
1032
1033         *error = 0;
1034         
1035         salen=sizeof(sa);
1036         ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
1037         
1038         if(ret==SOCKET_ERROR) {
1039                 *error = WSAGetLastError ();
1040                 return(NULL);
1041         }
1042         
1043 #ifdef DEBUG
1044         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));
1045 #endif
1046
1047         return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
1048                                            error));
1049 }
1050
1051 extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 *error)
1052 {
1053         gchar sa[32];   /* sockaddr in not big enough for sockaddr_in6 */
1054         socklen_t salen;
1055         int ret;
1056         
1057         MONO_ARCH_SAVE_REGS;
1058
1059         *error = 0;
1060         
1061         salen=sizeof(sa);
1062         ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
1063         
1064         if(ret==SOCKET_ERROR) {
1065                 *error = WSAGetLastError ();
1066                 return(NULL);
1067         }
1068         
1069 #ifdef DEBUG
1070         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));
1071 #endif
1072
1073         return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
1074                                            error));
1075 }
1076
1077 static struct sockaddr *create_sockaddr_from_object(MonoObject *saddr_obj,
1078                                                     socklen_t *sa_size,
1079                                                     gint32 *error)
1080 {
1081         MonoClassField *field;
1082         MonoArray *data;
1083         gint32 family;
1084         int len;
1085
1086         /* Dig the SocketAddress data buffer out of the object */
1087         field=mono_class_get_field_from_name(saddr_obj->vtable->klass, "data");
1088         data=*(MonoArray **)(((char *)saddr_obj) + field->offset);
1089
1090         /* The data buffer is laid out as follows:
1091          * byte 0 is the address family low byte
1092          * byte 1 is the address family high byte
1093          * INET:
1094          *      bytes 2 and 3 are the port info
1095          *      the rest is the address info
1096          * UNIX:
1097          *      the rest is the file name
1098          */
1099         len = mono_array_length (data);
1100         if (len < 2) {
1101                 mono_raise_exception (mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
1102         }
1103         
1104         family = convert_family (mono_array_get (data, guint8, 0) + (mono_array_get (data, guint8, 1) << 8));
1105         if (family == AF_INET) {
1106                 struct sockaddr_in *sa;
1107                 guint16 port;
1108                 guint32 address;
1109                 
1110                 if (len < 8) {
1111                         mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1112                 }
1113
1114                 sa = g_new0 (struct sockaddr_in, 1);
1115                 port = (mono_array_get (data, guint8, 2) << 8) +
1116                         mono_array_get (data, guint8, 3);
1117                 address = (mono_array_get (data, guint8, 4) << 24) +
1118                         (mono_array_get (data, guint8, 5) << 16 ) +
1119                         (mono_array_get (data, guint8, 6) << 8) +
1120                         mono_array_get (data, guint8, 7);
1121
1122                 sa->sin_family = family;
1123                 sa->sin_addr.s_addr = htonl (address);
1124                 sa->sin_port = htons (port);
1125
1126                 *sa_size = sizeof(struct sockaddr_in);
1127                 return((struct sockaddr *)sa);
1128
1129 #ifdef AF_INET6
1130         } else if (family == AF_INET6) {
1131                 struct sockaddr_in6 *sa;
1132                 int i;
1133                 guint16 port;
1134                 guint32 scopeid;
1135                 
1136                 if (len < 28) {
1137                         mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1138                 }
1139
1140                 sa = g_new0 (struct sockaddr_in6, 1);
1141                 port = mono_array_get (data, guint8, 3) +
1142                         (mono_array_get (data, guint8, 2) << 8);
1143                 scopeid = mono_array_get (data, guint8, 24) + 
1144                         (mono_array_get (data, guint8, 25) << 8) + 
1145                         (mono_array_get (data, guint8, 26) << 16) + 
1146                         (mono_array_get (data, guint8, 27) << 24);
1147
1148                 sa->sin6_family = family;
1149                 sa->sin6_port = htons (port);
1150                 sa->sin6_scope_id = scopeid;
1151
1152                 for(i=0; i<16; i++) {
1153                         sa->sin6_addr.s6_addr[i] = mono_array_get (data, guint8, 8+i);
1154                 }
1155
1156                 *sa_size = sizeof(struct sockaddr_in6);
1157                 return((struct sockaddr *)sa);
1158 #endif
1159 #ifdef HAVE_SYS_UN_H
1160         } else if (family == AF_UNIX) {
1161                 struct sockaddr_un *sock_un;
1162                 int i;
1163
1164                 /* Need a byte for the '\0' terminator/prefix, and the first
1165                  * two bytes hold the SocketAddress family
1166                  */
1167                 if (len - 2 >= MONO_SIZEOF_SUNPATH) {
1168                         mono_raise_exception (mono_get_exception_index_out_of_range ());
1169                 }
1170                 
1171                 sock_un = g_new0 (struct sockaddr_un, 1);
1172
1173                 sock_un->sun_family = family;
1174                 for (i = 0; i < len - 2; i++) {
1175                         sock_un->sun_path [i] = mono_array_get (data, guint8,
1176                                                                 i + 2);
1177                 }
1178                 
1179                 *sa_size = len;
1180
1181                 return (struct sockaddr *)sock_un;
1182 #endif
1183         } else {
1184                 *error = WSAEAFNOSUPPORT;
1185                 return(0);
1186         }
1187 }
1188
1189 extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1190 {
1191         struct sockaddr *sa;
1192         socklen_t sa_size;
1193         int ret;
1194         
1195         MONO_ARCH_SAVE_REGS;
1196
1197         *error = 0;
1198         
1199         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1200         if (*error != 0) {
1201                 return;
1202         }
1203
1204 #ifdef DEBUG
1205         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));
1206 #endif
1207
1208         ret = _wapi_bind (sock, sa, sa_size);
1209         if(ret==SOCKET_ERROR) {
1210                 *error = WSAGetLastError ();
1211         }
1212
1213         g_free(sa);
1214 }
1215
1216 enum {
1217         SelectModeRead,
1218         SelectModeWrite,
1219         SelectModeError
1220 };
1221
1222 MonoBoolean
1223 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
1224                                                    gint timeout, gint32 *error)
1225 {
1226         MonoThread *thread = NULL;
1227         mono_pollfd *pfds;
1228         int ret;
1229         time_t start;
1230         
1231
1232         MONO_ARCH_SAVE_REGS;
1233         
1234         pfds = g_new0 (mono_pollfd, 1);
1235         pfds[0].fd = GPOINTER_TO_INT (sock);
1236         pfds[0].events = (mode == SelectModeRead) ? MONO_POLLIN :
1237                 (mode == SelectModeWrite) ? MONO_POLLOUT :
1238                 (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL);
1239
1240         timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1241         start = time (NULL);
1242         do {
1243                 *error = 0;
1244                 
1245                 ret = mono_poll (pfds, 1, timeout);
1246                 if (timeout > 0 && ret < 0) {
1247                         int err = errno;
1248                         int sec = time (NULL) - start;
1249                         
1250                         timeout -= sec * 1000;
1251                         if (timeout < 0) {
1252                                 timeout = 0;
1253                         }
1254                         
1255                         errno = err;
1256                 }
1257                 
1258                 if (ret == -1 && errno == EINTR) {
1259                         int leave = 0;
1260
1261                         if (thread == NULL) {
1262                                 thread = mono_thread_current ();
1263                         }
1264                         
1265                         leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1266                         
1267                         if (leave != 0) {
1268                                 g_free (pfds);
1269                                 return(FALSE);
1270                         } else {
1271                                 /* Suspend requested? */
1272                                 mono_thread_interruption_checkpoint ();
1273                         }
1274                         errno = EINTR;
1275                 }
1276         } while (ret == -1 && errno == EINTR);
1277
1278         if (ret == -1) {
1279 #ifdef PLATFORM_WIN32
1280                 *error = WSAGetLastError ();
1281 #else
1282                 *error = errno_to_WSA (errno, __func__);
1283 #endif
1284                 g_free (pfds);
1285                 return(FALSE);
1286         }
1287         
1288         g_free (pfds);
1289
1290         if (ret == 0) {
1291                 return(FALSE);
1292         } else {
1293                 return (TRUE);
1294         }
1295 }
1296
1297 extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1298 {
1299         struct sockaddr *sa;
1300         socklen_t sa_size;
1301         int ret;
1302         
1303         MONO_ARCH_SAVE_REGS;
1304
1305         *error = 0;
1306         
1307         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1308         if (*error != 0) {
1309                 return;
1310         }
1311         
1312 #ifdef DEBUG
1313         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));
1314 #endif
1315
1316         ret = _wapi_connect (sock, sa, sa_size);
1317         if(ret==SOCKET_ERROR) {
1318                 *error = WSAGetLastError ();
1319         }
1320
1321         g_free(sa);
1322 }
1323
1324 /* These #defines from mswsock.h from wine.  Defining them here allows
1325  * us to build this file on a mingw box that doesn't know the magic
1326  * numbers, but still run on a newer windows box that does.
1327  */
1328 #ifndef WSAID_DISCONNECTEX
1329 #define WSAID_DISCONNECTEX {0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
1330 typedef BOOL (WINAPI *LPFN_DISCONNECTEX)(SOCKET, LPOVERLAPPED, DWORD, DWORD);
1331 #endif
1332
1333 #ifndef WSAID_TRANSMITFILE
1334 #define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
1335 typedef BOOL (WINAPI *LPFN_TRANSMITFILE)(SOCKET, HANDLE, DWORD, DWORD, LPOVERLAPPED, LPTRANSMIT_FILE_BUFFERS, DWORD);
1336 #endif
1337
1338 extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error)
1339 {
1340         int ret;
1341         glong output_bytes = 0;
1342         GUID disco_guid = WSAID_DISCONNECTEX;
1343         GUID trans_guid = WSAID_TRANSMITFILE;
1344         LPFN_DISCONNECTEX _wapi_disconnectex = NULL;
1345         LPFN_TRANSMITFILE _wapi_transmitfile = NULL;
1346         gboolean bret;
1347         
1348         MONO_ARCH_SAVE_REGS;
1349
1350         *error = 0;
1351         
1352 #ifdef DEBUG
1353         g_message("%s: disconnecting from socket %p (reuse %d)", __func__,
1354                   sock, reuse);
1355 #endif
1356
1357         /* I _think_ the extension function pointers need to be looked
1358          * up for each socket.  FIXME: check the best way to store
1359          * pointers to functions in managed objects that still works
1360          * on 64bit platforms.
1361          */
1362         ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1363                         (void *)&disco_guid, sizeof(GUID),
1364                         (void *)&_wapi_disconnectex, sizeof(void *),
1365                         &output_bytes, NULL, NULL);
1366         if (ret != 0) {
1367                 /* make sure that WSAIoctl didn't put crap in the
1368                  * output pointer
1369                  */
1370                 _wapi_disconnectex = NULL;
1371
1372                 /* Look up the TransmitFile extension function pointer
1373                  * instead of calling TransmitFile() directly, because
1374                  * apparently "Several of the extension functions have
1375                  * been available since WinSock 1.1 and are exported
1376                  * from MSWsock.dll, however it's not advisable to
1377                  * link directly to this dll as this ties you to the
1378                  * Microsoft WinSock provider. A provider neutral way
1379                  * of accessing these extension functions is to load
1380                  * them dynamically via WSAIoctl using the
1381                  * SIO_GET_EXTENSION_FUNCTION_POINTER op code. This
1382                  * should, theoretically, allow you to access these
1383                  * functions from any provider that supports them..." 
1384                  * (http://www.codeproject.com/internet/jbsocketserver3.asp)
1385                  */
1386                 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1387                                 (void *)&trans_guid, sizeof(GUID),
1388                                 (void *)&_wapi_transmitfile, sizeof(void *),
1389                                 &output_bytes, NULL, NULL);
1390                 if (ret != 0) {
1391                         _wapi_transmitfile = NULL;
1392                 }
1393         }
1394
1395         if (_wapi_disconnectex != NULL) {
1396                 bret = _wapi_disconnectex (sock, NULL, TF_REUSE_SOCKET, 0);
1397         } else if (_wapi_transmitfile != NULL) {
1398                 bret = _wapi_transmitfile (sock, NULL, 0, 0, NULL, NULL,
1399                                            TF_DISCONNECT | TF_REUSE_SOCKET);
1400         } else {
1401                 *error = ERROR_NOT_SUPPORTED;
1402                 return;
1403         }
1404
1405         if (bret == FALSE) {
1406                 *error = WSAGetLastError ();
1407         }
1408 }
1409
1410 gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1411 {
1412         int ret;
1413         guchar *buf;
1414         gint32 alen;
1415         int recvflags=0;
1416         
1417         MONO_ARCH_SAVE_REGS;
1418
1419         *error = 0;
1420         
1421         alen = mono_array_length (buffer);
1422         if (offset > alen - count) {
1423                 return(0);
1424         }
1425         
1426         buf=mono_array_addr(buffer, guchar, offset);
1427         
1428         recvflags = convert_socketflags (flags);
1429         if (recvflags == -1) {
1430                 *error = WSAEOPNOTSUPP;
1431                 return (0);
1432         }
1433                 
1434         ret = _wapi_recv (sock, buf, count, recvflags);
1435         if(ret==SOCKET_ERROR) {
1436                 *error = WSAGetLastError ();
1437                 return(0);
1438         }
1439
1440         return(ret);
1441 }
1442
1443 gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error)
1444 {
1445         int ret, count;
1446         DWORD recv;
1447         WSABUF *wsabufs;
1448         DWORD recvflags = 0;
1449         
1450         MONO_ARCH_SAVE_REGS;
1451
1452         *error = 0;
1453         
1454         wsabufs = mono_array_addr (buffers, WSABUF, 0);
1455         count = mono_array_length (buffers);
1456         
1457         recvflags = convert_socketflags (flags);
1458         if (recvflags == -1) {
1459                 *error = WSAEOPNOTSUPP;
1460                 return(0);
1461         }
1462         
1463         ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
1464         if (ret == SOCKET_ERROR) {
1465                 *error = WSAGetLastError ();
1466                 return(0);
1467         }
1468         
1469         return(recv);
1470 }
1471
1472 gint32 ves_icall_System_Net_Sockets_Socket_RecvFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error)
1473 {
1474         int ret;
1475         guchar *buf;
1476         gint32 alen;
1477         int recvflags=0;
1478         struct sockaddr *sa;
1479         socklen_t sa_size;
1480         
1481         MONO_ARCH_SAVE_REGS;
1482
1483         *error = 0;
1484         
1485         alen = mono_array_length (buffer);
1486         if (offset > alen - count) {
1487                 return(0);
1488         }
1489
1490         sa=create_sockaddr_from_object(*sockaddr, &sa_size, error);
1491         if (*error != 0) {
1492                 return(0);
1493         }
1494         
1495         buf=mono_array_addr(buffer, guchar, offset);
1496         
1497         recvflags = convert_socketflags (flags);
1498         if (recvflags == -1) {
1499                 *error = WSAEOPNOTSUPP;
1500                 return (0);
1501         }
1502
1503         ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
1504         if(ret==SOCKET_ERROR) {
1505                 g_free(sa);
1506                 *error = WSAGetLastError ();
1507                 return(0);
1508         }
1509
1510         /* If we didn't get a socket size, then we're probably a
1511          * connected connection-oriented socket and the stack hasn't
1512          * returned the remote address. All we can do is return null.
1513          */
1514         if ( sa_size != 0 )
1515                 *sockaddr=create_object_from_sockaddr(sa, sa_size, error);
1516         else
1517                 *sockaddr=NULL;
1518
1519         g_free(sa);
1520         
1521         return(ret);
1522 }
1523
1524 gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1525 {
1526         int ret;
1527         guchar *buf;
1528         gint32 alen;
1529         int sendflags=0;
1530         
1531         MONO_ARCH_SAVE_REGS;
1532
1533         *error = 0;
1534         
1535         alen = mono_array_length (buffer);
1536         if (offset > alen - count) {
1537                 return(0);
1538         }
1539
1540 #ifdef DEBUG
1541         g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
1542 #endif
1543         
1544         buf=mono_array_addr(buffer, guchar, offset);
1545
1546 #ifdef DEBUG
1547         g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
1548 #endif
1549
1550         sendflags = convert_socketflags (flags);
1551         if (sendflags == -1) {
1552                 *error = WSAEOPNOTSUPP;
1553                 return (0);
1554         }
1555
1556         ret = _wapi_send (sock, buf, count, sendflags);
1557         if(ret==SOCKET_ERROR) {
1558                 *error = WSAGetLastError ();
1559                 return(0);
1560         }
1561
1562         return(ret);
1563 }
1564
1565 gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error)
1566 {
1567         int ret, count;
1568         DWORD sent;
1569         WSABUF *wsabufs;
1570         DWORD sendflags = 0;
1571         
1572         MONO_ARCH_SAVE_REGS;
1573
1574         *error = 0;
1575         
1576         wsabufs = mono_array_addr (buffers, WSABUF, 0);
1577         count = mono_array_length (buffers);
1578         
1579         sendflags = convert_socketflags (flags);
1580         if (sendflags == -1) {
1581                 *error = WSAEOPNOTSUPP;
1582                 return(0);
1583         }
1584         
1585         ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
1586         if (ret == SOCKET_ERROR) {
1587                 *error = WSAGetLastError ();
1588                 return(0);
1589         }
1590         
1591         return(sent);
1592 }
1593
1594 gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error)
1595 {
1596         int ret;
1597         guchar *buf;
1598         gint32 alen;
1599         int sendflags=0;
1600         struct sockaddr *sa;
1601         socklen_t sa_size;
1602         
1603         MONO_ARCH_SAVE_REGS;
1604
1605         *error = 0;
1606         
1607         alen = mono_array_length (buffer);
1608         if (offset > alen - count) {
1609                 return(0);
1610         }
1611
1612         sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1613         if(*error != 0) {
1614                 return(0);
1615         }
1616         
1617 #ifdef DEBUG
1618         g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
1619 #endif
1620         
1621         buf=mono_array_addr(buffer, guchar, offset);
1622
1623 #ifdef DEBUG
1624         g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
1625 #endif
1626
1627         sendflags = convert_socketflags (flags);
1628         if (sendflags == -1) {
1629                 *error = WSAEOPNOTSUPP;
1630                 return (0);
1631         }
1632
1633         ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
1634         if(ret==SOCKET_ERROR) {
1635                 *error = WSAGetLastError ();
1636         }
1637
1638         g_free(sa);
1639         
1640         return(ret);
1641 }
1642
1643 static SOCKET Socket_to_SOCKET(MonoObject *sockobj)
1644 {
1645         SOCKET sock;
1646         MonoClassField *field;
1647         
1648         field=mono_class_get_field_from_name(sockobj->vtable->klass, "socket");
1649         sock=GPOINTER_TO_INT (*(gpointer *)(((char *)sockobj)+field->offset));
1650
1651         return(sock);
1652 }
1653
1654 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
1655 void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error)
1656 {
1657         MonoThread *thread = NULL;
1658         MonoObject *obj;
1659         mono_pollfd *pfds;
1660         int nfds, idx;
1661         int ret;
1662         int i, count;
1663         int mode;
1664         MonoClass *sock_arr_class;
1665         MonoArray *socks;
1666         time_t start;
1667         mono_array_size_t socks_size;
1668         
1669         MONO_ARCH_SAVE_REGS;
1670
1671         /* *sockets -> READ, null, WRITE, null, ERROR, null */
1672         count = mono_array_length (*sockets);
1673         nfds = count - 3; /* NULL separators */
1674         pfds = g_new0 (mono_pollfd, nfds);
1675         mode = idx = 0;
1676         for (i = 0; i < count; i++) {
1677                 obj = mono_array_get (*sockets, MonoObject *, i);
1678                 if (obj == NULL) {
1679                         mode++;
1680                         continue;
1681                 }
1682
1683                 if (idx >= nfds) {
1684                         /* The socket array was bogus */
1685                         g_free (pfds);
1686                         *error = WSAEFAULT;
1687                         return;
1688                 }
1689
1690                 pfds [idx].fd = Socket_to_SOCKET (obj);
1691                 pfds [idx].events = (mode == 0) ? MONO_POLLIN : (mode == 1) ? MONO_POLLOUT : POLL_ERRORS;
1692                 idx++;
1693         }
1694
1695         timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1696         start = time (NULL);
1697         do {
1698                 *error = 0;
1699                 ret = mono_poll (pfds, nfds, timeout);
1700                 if (timeout > 0 && ret < 0) {
1701                         int err = errno;
1702                         int sec = time (NULL) - start;
1703
1704                         timeout -= sec * 1000;
1705                         if (timeout < 0)
1706                                 timeout = 0;
1707                         errno = err;
1708                 }
1709
1710                 if (ret == -1 && errno == EINTR) {
1711                         int leave = 0;
1712                         if (thread == NULL)
1713                                 thread = mono_thread_current ();
1714
1715                         leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1716                         
1717                         if (leave != 0) {
1718                                 g_free (pfds);
1719                                 *sockets = NULL;
1720                                 return;
1721                         } else {
1722                                 /* Suspend requested? */
1723                                 mono_thread_interruption_checkpoint ();
1724                         }
1725                         errno = EINTR;
1726                 }
1727         } while (ret == -1 && errno == EINTR);
1728         
1729         if (ret == -1) {
1730 #ifdef PLATFORM_WIN32
1731                 *error = WSAGetLastError ();
1732 #else
1733                 *error = errno_to_WSA (errno, __func__);
1734 #endif
1735                 g_free (pfds);
1736                 return;
1737         }
1738
1739         if (ret == 0) {
1740                 g_free (pfds);
1741                 *sockets = NULL;
1742                 return;
1743         }
1744
1745         sock_arr_class= ((MonoObject *)*sockets)->vtable->klass;
1746         socks_size = ((mono_array_size_t)ret) + 3; /* space for the NULL delimiters */
1747         socks = mono_array_new_full (mono_domain_get (), sock_arr_class, &socks_size, NULL);
1748
1749         mode = idx = 0;
1750         for (i = 0; i < count && ret > 0; i++) {
1751                 mono_pollfd *pfd;
1752
1753                 obj = mono_array_get (*sockets, MonoObject *, i);
1754                 if (obj == NULL) {
1755                         mode++;
1756                         idx++;
1757                         continue;
1758                 }
1759
1760                 pfd = &pfds [i - mode];
1761                 if (pfd->revents == 0)
1762                         continue;
1763
1764                 ret--;
1765                 if (mode == 0 && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
1766                         mono_array_setref (socks, idx++, obj);
1767                 } else if (mode == 1 && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
1768                         mono_array_setref (socks, idx++, obj);
1769                 } else if ((pfd->revents & POLL_ERRORS) != 0) {
1770                         mono_array_setref (socks, idx++, obj);
1771                 }
1772         }
1773
1774         *sockets = socks;
1775         g_free (pfds);
1776 }
1777
1778 static MonoObject* int_to_object (MonoDomain *domain, int val)
1779 {
1780         return mono_value_box (domain, mono_get_int32_class (), &val);
1781 }
1782
1783
1784 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error)
1785 {
1786         int system_level;
1787         int system_name;
1788         int ret;
1789         int val;
1790         socklen_t valsize=sizeof(val);
1791         struct linger linger;
1792         socklen_t lingersize=sizeof(linger);
1793         int time_ms = 0;
1794         socklen_t time_ms_size = sizeof (time_ms);
1795 #ifdef SO_PEERCRED
1796         struct ucred cred;
1797         socklen_t credsize = sizeof(cred);
1798 #endif
1799         MonoDomain *domain=mono_domain_get();
1800         MonoObject *obj;
1801         MonoClass *obj_class;
1802         MonoClassField *field;
1803         
1804         MONO_ARCH_SAVE_REGS;
1805
1806         *error = 0;
1807         
1808         ret=convert_sockopt_level_and_name(level, name, &system_level,
1809                                            &system_name);
1810         if(ret==-1) {
1811                 *error = WSAENOPROTOOPT;
1812                 return;
1813         }
1814         if (ret == -2) {
1815                 *obj_val = int_to_object (domain, 0);
1816                 return;
1817         }
1818         
1819         /* No need to deal with MulticastOption names here, because
1820          * you cant getsockopt AddMembership or DropMembership (the
1821          * int getsockopt will error, causing an exception)
1822          */
1823         switch(name) {
1824         case SocketOptionName_Linger:
1825         case SocketOptionName_DontLinger:
1826                 ret = _wapi_getsockopt(sock, system_level, system_name, &linger,
1827                                &lingersize);
1828                 break;
1829                 
1830         case SocketOptionName_SendTimeout:
1831         case SocketOptionName_ReceiveTimeout:
1832                 ret = _wapi_getsockopt (sock, system_level, system_name, (char *) &time_ms, &time_ms_size);
1833                 break;
1834
1835 #ifdef SO_PEERCRED
1836         case SocketOptionName_PeerCred: 
1837                 ret = _wapi_getsockopt (sock, system_level, system_name, &cred,
1838                                         &credsize);
1839                 break;
1840 #endif
1841
1842         default:
1843                 ret = _wapi_getsockopt (sock, system_level, system_name, &val,
1844                                &valsize);
1845         }
1846         
1847         if(ret==SOCKET_ERROR) {
1848                 *error = WSAGetLastError ();
1849                 return;
1850         }
1851         
1852         switch(name) {
1853         case SocketOptionName_Linger:
1854                 /* build a System.Net.Sockets.LingerOption */
1855                 obj_class=mono_class_from_name(get_socket_assembly (),
1856                                                "System.Net.Sockets",
1857                                                "LingerOption");
1858                 obj=mono_object_new(domain, obj_class);
1859                 
1860                 /* Locate and set the fields "bool enabled" and "int
1861                  * seconds"
1862                  */
1863                 field=mono_class_get_field_from_name(obj_class, "enabled");
1864                 *(guint8 *)(((char *)obj)+field->offset)=linger.l_onoff;
1865
1866                 field=mono_class_get_field_from_name(obj_class, "seconds");
1867                 *(guint32 *)(((char *)obj)+field->offset)=linger.l_linger;
1868                 
1869                 break;
1870                 
1871         case SocketOptionName_DontLinger:
1872                 /* construct a bool int in val - true if linger is off */
1873                 obj = int_to_object (domain, !linger.l_onoff);
1874                 break;
1875                 
1876         case SocketOptionName_SendTimeout:
1877         case SocketOptionName_ReceiveTimeout:
1878                 obj = int_to_object (domain, time_ms);
1879                 break;
1880
1881 #ifdef SO_PEERCRED
1882         case SocketOptionName_PeerCred: 
1883         {
1884                 /* build a Mono.Posix.PeerCred+PeerCredData if
1885                  * possible
1886                  */
1887                 static MonoImage *mono_posix_image = NULL;
1888                 MonoPeerCredData *cred_data;
1889                 
1890                 if (mono_posix_image == NULL) {
1891                         mono_posix_image=mono_image_loaded ("Mono.Posix");
1892                         if (!mono_posix_image) {
1893                                 MonoAssembly *sa = mono_assembly_open ("Mono.Posix.dll", NULL);
1894                                 if (!sa) {
1895                                         *error = WSAENOPROTOOPT;
1896                                         return;
1897                                 } else {
1898                                         mono_posix_image = mono_assembly_get_image (sa);
1899                                 }
1900                         }
1901                 }
1902                 
1903                 obj_class = mono_class_from_name(mono_posix_image,
1904                                                  "Mono.Posix",
1905                                                  "PeerCredData");
1906                 obj = mono_object_new(domain, obj_class);
1907                 cred_data = (MonoPeerCredData *)obj;
1908                 cred_data->pid = cred.pid;
1909                 cred_data->uid = cred.uid;
1910                 cred_data->gid = cred.gid;
1911                 break;
1912         }
1913 #endif
1914
1915         default:
1916                 obj = int_to_object (domain, val);
1917         }
1918
1919         *obj_val=obj;
1920 }
1921
1922 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal(SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *error)
1923 {
1924         int system_level;
1925         int system_name;
1926         int ret;
1927         guchar *buf;
1928         socklen_t valsize;
1929         
1930         MONO_ARCH_SAVE_REGS;
1931
1932         *error = 0;
1933         
1934         ret=convert_sockopt_level_and_name(level, name, &system_level,
1935                                            &system_name);
1936         if(ret==-1) {
1937                 *error = WSAENOPROTOOPT;
1938                 return;
1939         }
1940         if(ret==-2)
1941                 return;
1942
1943         valsize=mono_array_length(*byte_val);
1944         buf=mono_array_addr(*byte_val, guchar, 0);
1945         
1946         ret = _wapi_getsockopt (sock, system_level, system_name, buf, &valsize);
1947         if(ret==SOCKET_ERROR) {
1948                 *error = WSAGetLastError ();
1949         }
1950 }
1951
1952 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
1953 static struct in_addr ipaddress_to_struct_in_addr(MonoObject *ipaddr)
1954 {
1955         struct in_addr inaddr;
1956         MonoClassField *field;
1957         
1958         field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Address");
1959
1960         /* No idea why .net uses a 64bit type to hold a 32bit value...
1961          *
1962          * Internal value of IPAddess is in little-endian order
1963          */
1964         inaddr.s_addr=GUINT_FROM_LE ((guint32)*(guint64 *)(((char *)ipaddr)+field->offset));
1965         
1966         return(inaddr);
1967 }
1968 #endif
1969
1970 #ifdef AF_INET6
1971 static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
1972 {
1973         struct in6_addr in6addr;
1974         MonoClassField *field;
1975         MonoArray *data;
1976         int i;
1977
1978         field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Numbers");
1979         data=*(MonoArray **)(((char *)ipaddr) + field->offset);
1980
1981 /* Solaris has only the 8 bit version. */
1982 #ifndef s6_addr16
1983         for(i=0; i<8; i++) {
1984                 guint16 s = mono_array_get (data, guint16, i);
1985                 in6addr.s6_addr[2 * i] = (s >> 8) & 0xff;
1986                 in6addr.s6_addr[2 * i + 1] = s & 0xff;
1987         }
1988 #else
1989         for(i=0; i<8; i++)
1990                 in6addr.s6_addr16[i] = mono_array_get (data, guint16, i);
1991 #endif
1992         return(in6addr);
1993 }
1994 #endif /* AF_INET6 */
1995
1996 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)
1997 {
1998         int system_level;
1999         int system_name;
2000         int ret;
2001 #ifdef AF_INET6
2002         int sol_ip;
2003         int sol_ipv6;
2004
2005         *error = 0;
2006         
2007 #ifdef HAVE_SOL_IPV6
2008         sol_ipv6 = SOL_IPV6;
2009 #else
2010         {
2011                 struct protoent *pent;
2012                 pent = getprotobyname ("ipv6");
2013                 sol_ipv6 = (pent != NULL) ? pent->p_proto : 41;
2014         }
2015 #endif
2016
2017 #ifdef HAVE_SOL_IP
2018         sol_ip = SOL_IP;
2019 #else
2020         {
2021                 struct protoent *pent;
2022                 pent = getprotobyname ("ip");
2023                 sol_ip = (pent != NULL) ? pent->p_proto : 0;
2024         }
2025 #endif
2026 #endif /* AF_INET6 */
2027
2028         MONO_ARCH_SAVE_REGS;
2029
2030         ret=convert_sockopt_level_and_name(level, name, &system_level,
2031                                            &system_name);
2032         if(ret==-1) {
2033                 *error = WSAENOPROTOOPT;
2034                 return;
2035         }
2036         if(ret==-2){
2037                 return;
2038         }
2039
2040         /* Only one of obj_val, byte_val or int_val has data */
2041         if(obj_val!=NULL) {
2042                 MonoClassField *field;
2043                 struct linger linger;
2044                 int valsize;
2045                 
2046                 switch(name) {
2047                 case SocketOptionName_DontLinger:
2048                         linger.l_onoff=0;
2049                         linger.l_linger=0;
2050                         valsize=sizeof(linger);
2051                         ret = _wapi_setsockopt (sock, system_level,
2052                                                 system_name, &linger, valsize);
2053                         break;
2054                         
2055                 case SocketOptionName_Linger:
2056                         /* Dig out "bool enabled" and "int seconds"
2057                          * fields
2058                          */
2059                         field=mono_class_get_field_from_name(obj_val->vtable->klass, "enabled");
2060                         linger.l_onoff=*(guint8 *)(((char *)obj_val)+field->offset);
2061                         field=mono_class_get_field_from_name(obj_val->vtable->klass, "seconds");
2062                         linger.l_linger=*(guint32 *)(((char *)obj_val)+field->offset);
2063                         
2064                         valsize=sizeof(linger);
2065                         ret = _wapi_setsockopt (sock, system_level,
2066                                                 system_name, &linger, valsize);
2067                         break;
2068                 case SocketOptionName_AddMembership:
2069                 case SocketOptionName_DropMembership:
2070 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2071                 {
2072                         MonoObject *address = NULL;
2073
2074 #ifdef AF_INET6
2075                         if(system_level == sol_ipv6) {
2076                                 struct ipv6_mreq mreq6;
2077
2078                                 /*
2079                                  *      Get group address
2080                                  */
2081                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2082                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2083                                 
2084                                 if(address) {
2085                                         mreq6.ipv6mr_multiaddr = ipaddress_to_struct_in6_addr (address);
2086                                 }
2087
2088                                 field=mono_class_get_field_from_name(obj_val->vtable->klass, "ifIndex");
2089                                 mreq6.ipv6mr_interface =*(guint64 *)(((char *)obj_val)+field->offset);
2090
2091                                 ret = _wapi_setsockopt (sock, system_level,
2092                                                         system_name, &mreq6,
2093                                                         sizeof (mreq6));
2094                         } else if(system_level == sol_ip)
2095 #endif /* AF_INET6 */
2096                         {
2097 #ifdef HAVE_STRUCT_IP_MREQN
2098                                 struct ip_mreqn mreq = {{0}};
2099 #else
2100                                 struct ip_mreq mreq = {{0}};
2101 #endif /* HAVE_STRUCT_IP_MREQN */
2102                         
2103                                 /* pain! MulticastOption holds two IPAddress
2104                                  * members, so I have to dig the value out of
2105                                  * those :-(
2106                                  */
2107                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2108                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2109
2110                                 /* address might not be defined and if so, set the address to ADDR_ANY.
2111                                  */
2112                                 if(address) {
2113                                         mreq.imr_multiaddr = ipaddress_to_struct_in_addr (address);
2114                                 }
2115
2116                                 field = mono_class_get_field_from_name (obj_val->vtable->klass, "local");
2117                                 address = *(gpointer *)(((char *)obj_val) + field->offset);
2118
2119 #ifdef HAVE_STRUCT_IP_MREQN
2120                                 if(address) {
2121                                         mreq.imr_address = ipaddress_to_struct_in_addr (address);
2122                                 }
2123 #else
2124                                 if(address) {
2125                                         mreq.imr_interface = ipaddress_to_struct_in_addr (address);
2126                                 }
2127 #endif /* HAVE_STRUCT_IP_MREQN */
2128                         
2129                                 ret = _wapi_setsockopt (sock, system_level,
2130                                                         system_name, &mreq,
2131                                                         sizeof (mreq));
2132                         }
2133                         break;
2134                 }
2135 #endif /* HAVE_STRUCT_IP_MREQN || HAVE_STRUCT_IP_MREQ */
2136                 default:
2137                         /* Cause an exception to be thrown */
2138                         *error = WSAEINVAL;
2139                         return;
2140                 }
2141         } else if (byte_val!=NULL) {
2142                 int valsize=mono_array_length(byte_val);
2143                 guchar *buf=mono_array_addr(byte_val, guchar, 0);
2144         
2145                 ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
2146                 if(ret==SOCKET_ERROR) {
2147                         *error = WSAGetLastError ();
2148                         return;
2149                 }
2150         } else {
2151                 /* ReceiveTimeout/SendTimeout get here */
2152                 switch(name) {
2153                 case SocketOptionName_DontFragment:
2154 #ifdef HAVE_IP_MTU_DISCOVER
2155                         /* Fiddle with the value slightly if we're
2156                          * turning DF on
2157                          */
2158                         if (int_val == 1) {
2159                                 int_val = IP_PMTUDISC_DO;
2160                         }
2161                         /* Fall through */
2162 #endif
2163                         
2164                 default:
2165                         ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2166                 }
2167         }
2168
2169         if(ret==SOCKET_ERROR) {
2170                 *error = WSAGetLastError ();
2171         }
2172 }
2173
2174 void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock,
2175                                                            gint32 how,
2176                                                            gint32 *error)
2177 {
2178         int ret;
2179         
2180         MONO_ARCH_SAVE_REGS;
2181
2182         *error = 0;
2183         
2184         /* Currently, the values for how (recv=0, send=1, both=2) match
2185          * the BSD API
2186          */
2187         ret = _wapi_shutdown (sock, how);
2188         if(ret==SOCKET_ERROR) {
2189                 *error = WSAGetLastError ();
2190         }
2191 }
2192
2193 gint
2194 ves_icall_System_Net_Sockets_Socket_WSAIoctl (SOCKET sock, gint32 code,
2195                                               MonoArray *input,
2196                                               MonoArray *output, gint32 *error)
2197 {
2198         glong output_bytes = 0;
2199         gchar *i_buffer, *o_buffer;
2200         gint i_len, o_len;
2201         gint ret;
2202
2203         MONO_ARCH_SAVE_REGS;
2204
2205         *error = 0;
2206         
2207         if (code == FIONBIO) {
2208                 /* Invalid command. Must use Socket.Blocking */
2209                 return -1;
2210         }
2211
2212         if (input == NULL) {
2213                 i_buffer = NULL;
2214                 i_len = 0;
2215         } else {
2216                 i_buffer = mono_array_addr (input, gchar, 0);
2217                 i_len = mono_array_length (input);
2218         }
2219
2220         if (output == NULL) {
2221                 o_buffer = NULL;
2222                 o_len = 0;
2223         } else {
2224                 o_buffer = mono_array_addr (output, gchar, 0);
2225                 o_len = mono_array_length (output);
2226         }
2227
2228         ret = WSAIoctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes, NULL, NULL);
2229         if (ret == SOCKET_ERROR) {
2230                 *error = WSAGetLastError ();
2231                 return(-1);
2232         }
2233
2234         return (gint) output_bytes;
2235 }
2236
2237 #ifdef HAVE_SIOCGIFCONF
2238 static gboolean
2239 is_loopback (int family, void *ad)
2240 {
2241         char *ptr = (char *) ad;
2242
2243         if (family == AF_INET) {
2244                 return (ptr [0] == 127);
2245         }
2246 #ifdef AF_INET6
2247         else {
2248                 return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
2249         }
2250 #endif
2251         return FALSE;
2252 }
2253
2254 static void *
2255 get_local_ips (int family, int *nips)
2256 {
2257         int addr_size, offset, fd, i, count;
2258         int max_ifaces = 50; /* 50 interfaces should be enough... */
2259         struct ifconf ifc;
2260         struct ifreq *ifr;
2261         struct ifreq iflags;
2262         char *result, *tmp_ptr;
2263         gboolean ignore_loopback = FALSE;
2264
2265         *nips = 0;
2266         if (family == AF_INET) {
2267                 addr_size = sizeof (struct in_addr);
2268                 offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
2269 #ifdef AF_INET6
2270         } else if (family == AF_INET6) {
2271                 addr_size = sizeof (struct in6_addr);
2272                 offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
2273 #endif
2274         } else {
2275                 return NULL;
2276         }
2277
2278         fd = socket (family, SOCK_STREAM, 0);
2279
2280         ifc.ifc_len = max_ifaces * sizeof (struct ifreq);
2281         ifc.ifc_buf = g_malloc (ifc.ifc_len);
2282         if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) {
2283                 close (fd);
2284                 g_free (ifc.ifc_buf);
2285                 return NULL;
2286         }
2287
2288         count = ifc.ifc_len / sizeof (struct ifreq);
2289         *nips = count;
2290         if (count == 0) {
2291                 g_free (ifc.ifc_buf);
2292                 close (fd);
2293                 return NULL;
2294         }
2295
2296         for (i = 0, ifr = ifc.ifc_req; i < *nips; i++, ifr++) {
2297                 strcpy (iflags.ifr_name, ifr->ifr_name);
2298                 if (ioctl (fd, SIOCGIFFLAGS, &iflags) < 0) {
2299                         continue;
2300                 }
2301
2302                 if ((iflags.ifr_flags & IFF_UP) == 0) {
2303                         ifr->ifr_name [0] = '\0';
2304                         continue;
2305                 }
2306
2307                 if ((iflags.ifr_flags & IFF_LOOPBACK) == 0) {
2308                         ignore_loopback = TRUE;
2309                 }
2310         }
2311
2312         close (fd);
2313         result = g_malloc (addr_size * count);
2314         tmp_ptr = result;
2315         for (i = 0, ifr = ifc.ifc_req; i < count; i++, ifr++) {
2316                 if (ifr->ifr_name [0] == '\0') {
2317                         (*nips)--;
2318                         continue;
2319                 }
2320
2321                 if (ignore_loopback && is_loopback (family, ((char *) &ifr->ifr_addr) + offset)) {
2322                         (*nips)--;
2323                         continue;
2324                 }
2325
2326                 memcpy (tmp_ptr, ((char *) &ifr->ifr_addr) + offset, addr_size);
2327                 tmp_ptr += addr_size;
2328         }
2329
2330         g_free (ifc.ifc_buf);
2331         return result;
2332 }
2333 #else
2334 static void *
2335 get_local_ips (int family, int *nips)
2336 {
2337         *nips = 0;
2338         return NULL;
2339 }
2340
2341 #endif /* HAVE_SIOCGIFCONF */
2342
2343 #ifndef AF_INET6
2344 static gboolean hostent_to_IPHostEntry(struct hostent *he, MonoString **h_name,
2345                                        MonoArray **h_aliases,
2346                                        MonoArray **h_addr_list,
2347                                        gboolean add_local_ips)
2348 {
2349         MonoDomain *domain = mono_domain_get ();
2350         int i = 0;
2351         struct in_addr *local_in = NULL;
2352         int nlocal_in = 0;
2353
2354         if (he != NULL) {
2355                 if(he->h_length!=4 || he->h_addrtype!=AF_INET) {
2356                         return(FALSE);
2357                 }
2358
2359                 *h_name=mono_string_new(domain, he->h_name);
2360
2361                 while(he->h_aliases[i]!=NULL) {
2362                         i++;
2363                 }
2364                 
2365                 *h_aliases=mono_array_new(domain, mono_get_string_class (), i);
2366                 i=0;
2367                 while(he->h_aliases[i]!=NULL) {
2368                         MonoString *alias;
2369                         
2370                         alias=mono_string_new(domain, he->h_aliases[i]);
2371                         mono_array_setref (*h_aliases, i, alias);
2372                         i++;
2373                 }
2374         } else if (!add_local_ips) {
2375                 return FALSE;
2376         }
2377
2378         if (add_local_ips) {
2379                 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2380                 if (nlocal_in) {
2381                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), nlocal_in);
2382                         for (i = 0; i < nlocal_in; i++) {
2383                                 MonoString *addr_string;
2384                                 char addr [16], *ptr;
2385                                 
2386                                 ptr = (char *) &local_in [i];
2387                                 g_snprintf(addr, 16, "%u.%u.%u.%u",
2388                                          (unsigned char) ptr [0],
2389                                          (unsigned char) ptr [1],
2390                                          (unsigned char) ptr [2],
2391                                          (unsigned char) ptr [3]);
2392                                 
2393                                 addr_string = mono_string_new (domain, addr);
2394                                 mono_array_setref (*h_addr_list, i, addr_string);
2395                                 i++;
2396                         }
2397
2398                         g_free (local_in);
2399                 } else if (he == NULL) {
2400                         /* If requesting "" and there are no other interfaces up, MS returns 127.0.0.1 */
2401                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), 1);
2402                         mono_array_setref (*h_addr_list, 0, mono_string_new (domain, "127.0.0.1"));
2403                         return TRUE;
2404                 }
2405         }
2406         
2407         if (nlocal_in == 0 && he != NULL) {
2408                 i = 0;
2409                 while (he->h_addr_list[i]!=NULL) {
2410                         i++;
2411                 }
2412
2413                 *h_addr_list=mono_array_new(domain, mono_get_string_class (), i);
2414                 i=0;
2415                 while(he->h_addr_list[i]!=NULL) {
2416                         MonoString *addr_string;
2417                         char addr[16];
2418                         
2419                         g_snprintf(addr, 16, "%u.%u.%u.%u",
2420                                  (unsigned char)he->h_addr_list[i][0],
2421                                  (unsigned char)he->h_addr_list[i][1],
2422                                  (unsigned char)he->h_addr_list[i][2],
2423                                  (unsigned char)he->h_addr_list[i][3]);
2424                         
2425                         addr_string=mono_string_new(domain, addr);
2426                         mono_array_setref (*h_addr_list, i, addr_string);
2427                         i++;
2428                 }
2429         }
2430
2431         return(TRUE);
2432 }
2433
2434 static gboolean ipaddr_to_IPHostEntry(const char *addr, MonoString **h_name,
2435                                       MonoArray **h_aliases,
2436                                       MonoArray **h_addr_list)
2437 {
2438         MonoDomain *domain = mono_domain_get ();
2439
2440         *h_name=mono_string_new(domain, addr);
2441         *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2442         *h_addr_list=mono_array_new(domain, mono_get_string_class (), 1);
2443         mono_array_setref (*h_addr_list, 0, *h_name);
2444
2445         return(TRUE);
2446 }
2447 #endif
2448
2449 #if defined(AF_INET6) && defined(HAVE_GETHOSTBYNAME2_R)
2450 static gboolean hostent_to_IPHostEntry2(struct hostent *he1,struct hostent *he2, MonoString **h_name,
2451                                 MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
2452 {
2453         MonoDomain *domain = mono_domain_get ();
2454         int i, host_count, host_index, family_hint;
2455         struct in_addr *local_in = NULL;
2456         int nlocal_in = 0;
2457         struct in6_addr *local_in6 = NULL;
2458         int nlocal_in6 = 0;
2459         gboolean from_local = FALSE;
2460
2461         family_hint = get_family_hint ();
2462
2463         /*
2464          * Check if address length and family are correct
2465          */
2466         if (he1 != NULL && (he1->h_length!=4 || he1->h_addrtype!=AF_INET)) {
2467                 return(FALSE);
2468         }
2469
2470         if (he2 != NULL && (he2->h_length!=16 || he2->h_addrtype!=AF_INET6)) {
2471                 return(FALSE);
2472         }
2473
2474         /*
2475          * Get the aliases and host name from he1 or he2 whichever is
2476          * not null, if he1 is not null then take aliases from he1
2477          */
2478         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2479                             family_hint == PF_INET)) {
2480                 *h_name=mono_string_new (domain, he1->h_name);
2481
2482                 i=0;
2483                 while(he1->h_aliases[i]!=NULL) {
2484                         i++;
2485                 }
2486
2487                 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2488                                            i);
2489                 i=0;
2490                 while(he1->h_aliases[i]!=NULL) {
2491                         MonoString *alias;
2492
2493                         alias=mono_string_new (domain, he1->h_aliases[i]);
2494                         mono_array_setref (*h_aliases, i, alias);
2495                         i++;
2496                 }
2497         } else if (he2 != NULL && (family_hint == PF_UNSPEC ||
2498                                    family_hint == PF_INET6)) {
2499                 *h_name=mono_string_new (domain, he2->h_name);
2500
2501                 i=0;
2502                 while(he2->h_aliases [i] != NULL) {
2503                         i++;
2504                 }
2505
2506                 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2507                                            i);
2508                 i=0;
2509                 while(he2->h_aliases[i]!=NULL) {
2510                         MonoString *alias;
2511
2512                         alias=mono_string_new (domain, he2->h_aliases[i]);
2513                         mono_array_setref (*h_aliases, i, alias);
2514                         i++;
2515                 }
2516         } else if (!add_local_ips) {
2517                 return(FALSE);
2518         }
2519
2520         /*
2521          * Count the number of addresses in he1 + he2
2522          */
2523         host_count = 0;
2524         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2525                             family_hint == PF_INET)) {
2526                 i=0;
2527                 while(he1->h_addr_list[i]!=NULL) {
2528                         i++;
2529                         host_count++;
2530                 }
2531         }
2532
2533         if (he2 != NULL && (family_hint == PF_UNSPEC ||
2534                             family_hint == PF_INET6)) {
2535                 i=0;
2536                 while(he2->h_addr_list[i]!=NULL) {
2537                         i++;
2538                         host_count++;
2539                 }
2540         }
2541
2542         /*
2543          * Fills the array
2544          */
2545         host_index = 0;
2546         if (add_local_ips) {
2547                 if (family_hint == PF_UNSPEC || family_hint == PF_INET)
2548                         local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2549
2550                 if (family_hint == PF_UNSPEC || family_hint == PF_INET6)
2551                         local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2552
2553                 if (nlocal_in || nlocal_in6) {
2554                         from_local = TRUE;
2555                         *h_addr_list = mono_array_new (domain, mono_get_string_class (),
2556                                                              nlocal_in + nlocal_in6);
2557
2558                         if (nlocal_in6) {
2559                                 int n;
2560                                 for (n = 0; n < nlocal_in6; n++) {
2561                                         MonoString *addr_string;
2562                                         const char *ret;
2563                                         char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes with the trailing NULL */
2564
2565                                         ret = inet_ntop (AF_INET6, &local_in6 [n], addr, sizeof(addr));
2566
2567                                         if (ret != NULL) {
2568                                                 addr_string = mono_string_new (domain, addr);
2569                                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2570                                                 host_index++;
2571                                         }
2572                                 }
2573                         }
2574
2575                         if (nlocal_in) {
2576                                 int n;
2577                                 for (n = 0; n < nlocal_in; n++) {
2578                                         MonoString *addr_string;
2579                                         const char *ret;
2580                                         char addr[16]; /* INET_ADDRSTRLEN == 16 */
2581
2582                                         ret = inet_ntop (AF_INET, &local_in [n], addr, sizeof(addr));
2583
2584                                         if (ret != NULL) {
2585                                                 addr_string = mono_string_new (domain, addr);
2586                                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2587                                                 host_index++;
2588                                         }
2589                                 }
2590                         }
2591                         g_free (local_in);
2592                         g_free (local_in6);
2593                         return TRUE;
2594                 } else if (he1 == NULL && he2 == NULL) {
2595                         /* If requesting "" and there are no other interfaces up, MS returns 127.0.0.1 */
2596                         *h_addr_list = mono_array_new(domain, mono_get_string_class (), 1);
2597                         mono_array_setref (*h_addr_list, 0, mono_string_new (domain, "127.0.0.1"));
2598                         g_free (local_in);
2599                         g_free (local_in6);
2600                         return TRUE;
2601                 }
2602
2603                 g_free (local_in);
2604                 g_free (local_in6);
2605         }
2606
2607         *h_addr_list=mono_array_new (domain, mono_get_string_class (), host_count);
2608
2609         if (he2 != NULL && (family_hint == PF_UNSPEC ||
2610                             family_hint == PF_INET6)) {
2611                 i = 0;
2612                 while(he2->h_addr_list[i] != NULL) {
2613                         MonoString *addr_string;
2614                         const char *ret;
2615                         char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes long with the trailing NULL */
2616
2617                         ret = inet_ntop (AF_INET6, he2->h_addr_list[i], addr,
2618                                          sizeof(addr));
2619
2620                         if (ret != NULL) {
2621                                 addr_string = mono_string_new (domain, addr);
2622                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2623                                 i++;
2624                                 host_index++;
2625                         }
2626                 }
2627         }
2628
2629         if (he1 != NULL && (family_hint == PF_UNSPEC ||
2630                             family_hint == PF_INET)) {
2631                 i=0;
2632                 while(he1->h_addr_list[i] != NULL) {
2633                         MonoString *addr_string;
2634                         const char *ret;
2635                         char addr[16]; /* INET_ADDRSTRLEN == 16 */
2636
2637                         ret = inet_ntop (AF_INET, he1->h_addr_list[i], addr,
2638                                          sizeof(addr));
2639
2640                         if (ret != NULL) {
2641                                 addr_string=mono_string_new (domain, addr);
2642                                 mono_array_setref (*h_addr_list, host_index, addr_string);
2643                                 i++;
2644                                 host_index++;
2645                         }
2646                 }
2647         }
2648
2649         return(TRUE);
2650 }
2651 #endif
2652
2653 #if defined(AF_INET6)
2654 static gboolean 
2655 addrinfo_to_IPHostEntry(struct addrinfo *info, MonoString **h_name,
2656                                                 MonoArray **h_aliases,
2657                                                 MonoArray **h_addr_list,
2658                                                 gboolean add_local_ips)
2659 {
2660         gint32 count, i;
2661         struct addrinfo *ai = NULL;
2662         struct in_addr *local_in = NULL;
2663         int nlocal_in = 0;
2664         struct in6_addr *local_in6 = NULL;
2665         int nlocal_in6 = 0;
2666         int addr_index;
2667
2668         MonoDomain *domain = mono_domain_get ();
2669
2670         addr_index = 0;
2671         *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2672         if (add_local_ips) {
2673                 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2674                 local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2675                 if (nlocal_in || nlocal_in6) {
2676                         *h_addr_list=mono_array_new(domain, mono_get_string_class (), nlocal_in + nlocal_in6);
2677                         if (nlocal_in) {
2678                                 MonoString *addr_string;
2679                                 char addr [16];
2680                                 int i;
2681
2682                                 for (i = 0; i < nlocal_in; i++) {
2683                                         inet_ntop (AF_INET, &local_in [i], addr, sizeof (addr));
2684                                         addr_string = mono_string_new (domain, addr);
2685                                         mono_array_setref (*h_addr_list, addr_index, addr_string);
2686                                         addr_index++;
2687                                 }
2688                         }
2689
2690                         if (nlocal_in6) {
2691                                 MonoString *addr_string;
2692                                 const char *ret;
2693                                 char addr [48];
2694                                 int i;
2695
2696                                 for (i = 0; i < nlocal_in6; i++) {
2697                                         ret = inet_ntop (AF_INET6, &local_in6 [i], addr, sizeof (addr));
2698                                         if (ret != NULL) {
2699                                                 addr_string = mono_string_new (domain, addr);
2700                                                 mono_array_setref (*h_addr_list, addr_index, addr_string);
2701                                                 addr_index++;
2702                                         }
2703                                 }
2704                         }
2705
2706                         g_free (local_in);
2707                         g_free (local_in6);
2708                         if (info) {
2709                                 freeaddrinfo (info);
2710                         }
2711                         return TRUE;
2712                 }
2713
2714                 g_free (local_in);
2715                 g_free (local_in6);
2716         }
2717
2718         for (count=0, ai=info; ai!=NULL; ai=ai->ai_next) {
2719                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2720                         continue;
2721
2722                 count++;
2723         }
2724
2725         *h_addr_list=mono_array_new(domain, mono_get_string_class (), count);
2726
2727         for (ai=info, i=0; ai!=NULL; ai=ai->ai_next) {
2728                 MonoString *addr_string;
2729                 const char *ret;
2730                 char buffer [48]; /* Max. size for IPv6 */
2731
2732                 if((ai->ai_family != PF_INET) && (ai->ai_family != PF_INET6)) {
2733                         continue;
2734                 }
2735
2736                 if(ai->ai_family == PF_INET) {
2737                         ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr), buffer, 16);
2738                 } else {
2739                         ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in6*)ai->ai_addr)->sin6_addr), buffer, 48);
2740                 }
2741
2742                 if(ret) {
2743                         addr_string=mono_string_new(domain, buffer);
2744                 } else {
2745                         addr_string=mono_string_new(domain, "");
2746                 }
2747
2748                 mono_array_setref (*h_addr_list, addr_index, addr_string);
2749
2750                 if(!i) {
2751                         if (ai->ai_canonname != NULL) {
2752                                 *h_name=mono_string_new(domain, ai->ai_canonname);
2753                         } else {
2754                                 *h_name=mono_string_new(domain, buffer);
2755                         }
2756                 }
2757
2758                 addr_index++;
2759         }
2760
2761         if(info) {
2762                 freeaddrinfo(info);
2763         }
2764
2765         return(TRUE);
2766 }
2767 #endif
2768
2769 #ifdef AF_INET6
2770 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2771 {
2772         gboolean add_local_ips = FALSE;
2773 #ifdef HAVE_SIOCGIFCONF
2774         gchar this_hostname [256];
2775 #endif
2776 #if !defined(HAVE_GETHOSTBYNAME2_R)
2777         struct addrinfo *info = NULL, hints;
2778         char *hostname;
2779         
2780         MONO_ARCH_SAVE_REGS;
2781         
2782         hostname=mono_string_to_utf8 (host);
2783         if (*hostname == '\0')
2784                 add_local_ips = TRUE;
2785 #ifdef HAVE_SIOCGIFCONF
2786         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2787                 if (!strcmp (hostname, this_hostname))
2788                         add_local_ips = TRUE;
2789         }
2790 #endif
2791
2792         memset(&hints, 0, sizeof(hints));
2793         hints.ai_family = get_family_hint ();
2794         hints.ai_socktype = SOCK_STREAM;
2795         hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
2796
2797         if (*hostname && getaddrinfo(hostname, NULL, &hints, &info) == -1) {
2798                 return(FALSE);
2799         }
2800         
2801         g_free(hostname);
2802
2803         return(addrinfo_to_IPHostEntry(info, h_name, h_aliases, h_addr_list, add_local_ips));
2804 #else
2805         struct hostent he1,*hp1, he2, *hp2;
2806         int buffer_size1, buffer_size2;
2807         char *buffer1, *buffer2;
2808         int herr;
2809         gboolean return_value;
2810         char *hostname;
2811         
2812         MONO_ARCH_SAVE_REGS;
2813         
2814         hostname=mono_string_to_utf8 (host);
2815         if (*hostname == '\0')
2816                 add_local_ips = TRUE;
2817
2818 #ifdef HAVE_SIOCGIFCONF
2819         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2820                 if (!strcmp (hostname, this_hostname))
2821                         add_local_ips = TRUE;
2822         }
2823 #endif
2824
2825         buffer_size1 = 512;
2826         buffer_size2 = 512;
2827         buffer1 = g_malloc0(buffer_size1);
2828         buffer2 = g_malloc0(buffer_size2);
2829
2830         hp1 = NULL;
2831         hp2 = NULL;
2832         while (*hostname && gethostbyname2_r(hostname, AF_INET, &he1, buffer1, buffer_size1,
2833                                 &hp1, &herr) == ERANGE) {
2834                 buffer_size1 *= 2;
2835                 buffer1 = g_realloc(buffer1, buffer_size1);
2836         }
2837
2838         if (*hostname && hp1 == NULL)
2839         {
2840                 while (gethostbyname2_r(hostname, AF_INET6, &he2, buffer2,
2841                                         buffer_size2, &hp2, &herr) == ERANGE) {
2842                         buffer_size2 *= 2;
2843                         buffer2 = g_realloc(buffer2, buffer_size2);
2844                 }
2845         }
2846
2847         return_value = hostent_to_IPHostEntry2(hp1, hp2, h_name, h_aliases,
2848                                                h_addr_list, add_local_ips);
2849
2850         g_free(buffer1);
2851         g_free(buffer2);
2852         g_free(hostname);
2853
2854         return(return_value);
2855 #endif /* HAVE_GETHOSTBYNAME2_R */
2856 }
2857 #else /* AF_INET6 */
2858 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2859 {
2860         struct hostent *he;
2861         char *hostname;
2862         gboolean add_local_ips = FALSE;
2863 #ifdef HAVE_SIOCGIFCONF
2864         gchar this_hostname [256];
2865 #endif
2866         
2867         MONO_ARCH_SAVE_REGS;
2868
2869         hostname=mono_string_to_utf8(host);
2870         if (*hostname == '\0')
2871                 add_local_ips = TRUE;
2872 #ifdef HAVE_SIOCGIFCONF
2873         if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2874                 if (!strcmp (hostname, this_hostname))
2875                         add_local_ips = TRUE;
2876         }
2877 #endif
2878
2879         he = NULL;
2880         if (*hostname)
2881                 he = _wapi_gethostbyname (hostname);
2882         g_free(hostname);
2883
2884         if (*hostname && he==NULL)
2885                 return(FALSE);
2886
2887         return(hostent_to_IPHostEntry(he, h_name, h_aliases, h_addr_list, add_local_ips));
2888 }
2889 #endif /* AF_INET6 */
2890
2891 #ifndef HAVE_INET_PTON
2892 static int
2893 inet_pton (int family, const char *address, void *inaddrp)
2894 {
2895         if (family == AF_INET) {
2896 #ifdef HAVE_INET_ATON
2897                 struct in_addr inaddr;
2898                 
2899                 if (!inet_aton (address, &inaddr))
2900                         return 0;
2901                 
2902                 memcpy (inaddrp, &inaddr, sizeof (struct in_addr));
2903                 return 1;
2904 #else
2905                 /* assume the system has inet_addr(), if it doesn't
2906                    have that we're pretty much screwed... */
2907                 guint32 inaddr;
2908                 
2909                 if (!strcmp (address, "255.255.255.255")) {
2910                         /* special-case hack */
2911                         inaddr = 0xffffffff;
2912                 } else {
2913                         inaddr = inet_addr (address);
2914 #ifndef INADDR_NONE
2915 #define INADDR_NONE ((in_addr_t) -1)
2916 #endif
2917                         if (inaddr == INADDR_NONE)
2918                                 return 0;
2919                 }
2920                 
2921                 memcpy (inaddrp, &inaddr, sizeof (guint32));
2922                 return 1;
2923 #endif /* HAVE_INET_ATON */
2924         }
2925         
2926         return -1;
2927 }
2928 #endif /* !HAVE_INET_PTON */
2929
2930 extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2931 {
2932         char *address;
2933         gboolean v1;
2934         
2935 #ifdef AF_INET6
2936         struct sockaddr_in saddr;
2937         struct sockaddr_in6 saddr6;
2938         struct addrinfo *info = NULL, hints;
2939         gint32 family;
2940         char hostname[1024] = {0};
2941         int flags = 0;
2942 #else
2943         struct in_addr inaddr;
2944         struct hostent *he;
2945         gboolean ret;
2946 #endif
2947
2948         v1 = mono_framework_version () == 1;
2949
2950         address = mono_string_to_utf8 (addr);
2951
2952 #ifdef AF_INET6
2953         if (inet_pton (AF_INET, address, &saddr.sin_addr ) <= 0) {
2954                 /* Maybe an ipv6 address */
2955                 if (inet_pton (AF_INET6, address, &saddr6.sin6_addr) <= 0) {
2956                         g_free (address);
2957                         return FALSE;
2958                 }
2959                 else {
2960                         family = AF_INET6;
2961                         saddr6.sin6_family = AF_INET6;
2962                 }
2963         }
2964         else {
2965                 family = AF_INET;
2966                 saddr.sin_family = AF_INET;
2967         }
2968         g_free(address);
2969
2970         if (v1) {
2971                 flags = NI_NAMEREQD;
2972         }
2973         
2974         if(family == AF_INET) {
2975 #if HAVE_SOCKADDR_IN_SIN_LEN
2976                 saddr.sin_len = sizeof (saddr);
2977 #endif
2978                 if(getnameinfo ((struct sockaddr*)&saddr, sizeof(saddr),
2979                                 hostname, sizeof(hostname), NULL, 0,
2980                                 flags) != 0) {
2981                         return(FALSE);
2982                 }
2983         } else if(family == AF_INET6) {
2984 #if HAVE_SOCKADDR_IN6_SIN_LEN
2985                 saddr6.sin6_len = sizeof (saddr6);
2986 #endif
2987                 if(getnameinfo ((struct sockaddr*)&saddr6, sizeof(saddr6),
2988                                 hostname, sizeof(hostname), NULL, 0,
2989                                 flags) != 0) {
2990                         return(FALSE);
2991                 }
2992         }
2993
2994         memset (&hints, 0, sizeof(hints));
2995         hints.ai_family = get_family_hint ();
2996         hints.ai_socktype = SOCK_STREAM;
2997         hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
2998
2999         if( getaddrinfo (hostname, NULL, &hints, &info) == -1 ) {
3000                 return(FALSE);
3001         }
3002
3003         return(addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE));
3004 #else
3005         if (inet_pton (AF_INET, address, &inaddr) <= 0) {
3006                 g_free (address);
3007                 return(FALSE);
3008         }
3009
3010         if ((he = gethostbyaddr ((char *) &inaddr, sizeof (inaddr), AF_INET)) == NULL) {
3011                 if (v1) {
3012                         ret = FALSE;
3013                 } else {
3014                         ret = ipaddr_to_IPHostEntry (address, h_name,
3015                                                      h_aliases, h_addr_list);
3016                 }
3017         } else {
3018                 ret = hostent_to_IPHostEntry (he, h_name, h_aliases,
3019                                               h_addr_list, FALSE);
3020         }
3021
3022         g_free (address);
3023         return(ret);
3024 #endif
3025 }
3026
3027 extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name)
3028 {
3029         gchar hostname[256];
3030         int ret;
3031         
3032         MONO_ARCH_SAVE_REGS;
3033
3034         ret = gethostname (hostname, sizeof (hostname));
3035         if(ret==-1) {
3036                 return(FALSE);
3037         }
3038         
3039         *h_name=mono_string_new(mono_domain_get (), hostname);
3040
3041         return(TRUE);
3042 }
3043
3044 void mono_network_init(void)
3045 {
3046         WSADATA wsadata;
3047         int err;
3048         
3049         err=WSAStartup(MAKEWORD(2,0), &wsadata);
3050         if(err!=0) {
3051                 g_error(G_GNUC_PRETTY_FUNCTION ": Couldn't initialise networking");
3052                 exit(-1);
3053         }
3054
3055 #ifdef DEBUG
3056         g_message(G_GNUC_PRETTY_FUNCTION ": Using socket library: %s", wsadata.szDescription);
3057         g_message(G_GNUC_PRETTY_FUNCTION ": Socket system status: %s", wsadata.szSystemStatus);
3058 #endif
3059 }
3060
3061 void mono_network_cleanup(void)
3062 {
3063         WSACleanup();
3064 }
3065