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