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