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