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