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