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