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