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