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