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