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