2007-04-06 Andreas Faerber <andreas.faerber@web.de>
[mono.git] / mono / metadata / socket-io.c
blobd602f114b9198ceaa3faa97ccefb843c4ce814db
1 /*
2 * socket-io.c: Socket IO internal calls
4 * Authors:
5 * Dick Porter (dick@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * (C) 2001 Ximian, Inc.
9 * Copyright (c) 2005-2006 Novell, Inc. (http://www.novell.com)
12 #include <config.h>
14 #include <glib.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <errno.h>
20 #include <mono/metadata/object.h>
21 #include <mono/io-layer/io-layer.h>
22 #include <mono/metadata/socket-io.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/assembly.h>
25 #include <mono/metadata/appdomain.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/threads-types.h>
28 #include <mono/utils/mono-poll.h>
29 /* FIXME change this code to not mess so much with the internals */
30 #include <mono/metadata/class-internals.h>
31 #include <mono/metadata/threadpool-internals.h>
32 #include <mono/metadata/domain-internals.h>
34 #include <sys/time.h>
35 #ifdef HAVE_SYS_IOCTL_H
36 #include <sys/ioctl.h>
37 #endif
38 #ifdef HAVE_NET_IF_H
39 #include <net/if.h>
40 #endif
42 #ifdef HAVE_NETDB_H
43 #include <netdb.h>
44 #endif
45 #ifdef HAVE_SYS_FILIO_H
46 #include <sys/filio.h> /* defines FIONBIO and FIONREAD */
47 #endif
48 #ifdef HAVE_SYS_SOCKIO_H
49 #include <sys/sockio.h> /* defines SIOCATMARK */
50 #endif
51 #ifdef HAVE_SYS_UN_H
52 #include <sys/un.h>
53 #endif
55 #include "mono/io-layer/socket-wrappers.h"
57 #ifdef PLATFORM_WIN32
58 /* This is a kludge to make this file build under cygwin:
59 * w32api/ws2tcpip.h has definitions for some AF_INET6 values and
60 * prototypes for some but not all required functions (notably
61 * inet_ntop() is missing), but the libws2_32 library is missing the
62 * actual implementations of these functions.
64 #undef AF_INET6
65 #endif
67 #undef DEBUG
69 static gint32 convert_family(MonoAddressFamily mono_family)
71 gint32 family=-1;
73 switch(mono_family) {
74 case AddressFamily_Unknown:
75 case AddressFamily_ImpLink:
76 case AddressFamily_Pup:
77 case AddressFamily_Chaos:
78 case AddressFamily_Iso:
79 case AddressFamily_Ecma:
80 case AddressFamily_DataKit:
81 case AddressFamily_Ccitt:
82 case AddressFamily_DataLink:
83 case AddressFamily_Lat:
84 case AddressFamily_HyperChannel:
85 case AddressFamily_NetBios:
86 case AddressFamily_VoiceView:
87 case AddressFamily_FireFox:
88 case AddressFamily_Banyan:
89 case AddressFamily_Atm:
90 case AddressFamily_Cluster:
91 case AddressFamily_Ieee12844:
92 case AddressFamily_NetworkDesigners:
93 g_warning("System.Net.Sockets.AddressFamily has unsupported value 0x%x", mono_family);
94 break;
96 case AddressFamily_Unspecified:
97 family=AF_UNSPEC;
98 break;
100 case AddressFamily_Unix:
101 family=AF_UNIX;
102 break;
104 case AddressFamily_InterNetwork:
105 family=AF_INET;
106 break;
108 case AddressFamily_Ipx:
109 #ifdef AF_IPX
110 family=AF_IPX;
111 #endif
112 break;
114 case AddressFamily_Sna:
115 family=AF_SNA;
116 break;
118 case AddressFamily_DecNet:
119 family=AF_DECnet;
120 break;
122 case AddressFamily_AppleTalk:
123 family=AF_APPLETALK;
124 break;
126 case AddressFamily_InterNetworkV6:
127 #ifdef AF_INET6
128 family=AF_INET6;
129 #endif
130 break;
131 case AddressFamily_Irda:
132 #ifdef AF_IRDA
133 family=AF_IRDA;
134 #endif
135 break;
136 default:
137 g_warning("System.Net.Sockets.AddressFamily has unknown value 0x%x", mono_family);
140 return(family);
143 static MonoAddressFamily convert_to_mono_family(guint16 af_family)
145 MonoAddressFamily family=AddressFamily_Unknown;
147 switch(af_family) {
148 case AF_UNSPEC:
149 family=AddressFamily_Unspecified;
150 break;
152 case AF_UNIX:
153 family=AddressFamily_Unix;
154 break;
156 case AF_INET:
157 family=AddressFamily_InterNetwork;
158 break;
160 #ifdef AF_IPX
161 case AF_IPX:
162 family=AddressFamily_Ipx;
163 break;
164 #endif
166 case AF_SNA:
167 family=AddressFamily_Sna;
168 break;
170 case AF_DECnet:
171 family=AddressFamily_DecNet;
172 break;
174 case AF_APPLETALK:
175 family=AddressFamily_AppleTalk;
176 break;
178 #ifdef AF_INET6
179 case AF_INET6:
180 family=AddressFamily_InterNetworkV6;
181 break;
182 #endif
184 #ifdef AF_IRDA
185 case AF_IRDA:
186 family=AddressFamily_Irda;
187 break;
188 #endif
189 default:
190 g_warning("unknown address family 0x%x", af_family);
193 return(family);
196 static gint32 convert_type(MonoSocketType mono_type)
198 gint32 type=-1;
200 switch(mono_type) {
201 case SocketType_Stream:
202 type=SOCK_STREAM;
203 break;
205 case SocketType_Dgram:
206 type=SOCK_DGRAM;
207 break;
209 case SocketType_Raw:
210 type=SOCK_RAW;
211 break;
213 case SocketType_Rdm:
214 type=SOCK_RDM;
215 break;
217 case SocketType_Seqpacket:
218 type=SOCK_SEQPACKET;
219 break;
221 case SocketType_Unknown:
222 g_warning("System.Net.Sockets.SocketType has unsupported value 0x%x", mono_type);
223 break;
225 default:
226 g_warning("System.Net.Sockets.SocketType has unknown value 0x%x", mono_type);
229 return(type);
232 static gint32 convert_proto(MonoProtocolType mono_proto)
234 gint32 proto=-1;
236 switch(mono_proto) {
237 case ProtocolType_IP:
238 case ProtocolType_IPv6:
239 case ProtocolType_Icmp:
240 case ProtocolType_Igmp:
241 case ProtocolType_Ggp:
242 case ProtocolType_Tcp:
243 case ProtocolType_Pup:
244 case ProtocolType_Udp:
245 case ProtocolType_Idp:
246 /* These protocols are known (on my system at least) */
247 proto=mono_proto;
248 break;
250 case ProtocolType_ND:
251 case ProtocolType_Raw:
252 case ProtocolType_Ipx:
253 case ProtocolType_Spx:
254 case ProtocolType_SpxII:
255 case ProtocolType_Unknown:
256 /* These protocols arent */
257 g_warning("System.Net.Sockets.ProtocolType has unsupported value 0x%x", mono_proto);
258 break;
260 default:
261 break;
264 return(proto);
267 /* Convert MonoSocketFlags */
268 static gint32 convert_socketflags (gint32 sflags)
270 gint32 flags = 0;
272 if (!sflags)
273 /* SocketFlags.None */
274 return 0;
276 if (sflags & ~(SocketFlags_OutOfBand | SocketFlags_MaxIOVectorLength | SocketFlags_Peek |
277 SocketFlags_DontRoute | SocketFlags_Partial))
278 /* Contains invalid flag values */
279 return -1;
281 if (sflags & SocketFlags_OutOfBand)
282 flags |= MSG_OOB;
283 if (sflags & SocketFlags_Peek)
284 flags |= MSG_PEEK;
285 if (sflags & SocketFlags_DontRoute)
286 flags |= MSG_DONTROUTE;
287 if (sflags & SocketFlags_Partial)
288 #ifdef MSG_MORE
289 flags |= MSG_MORE;
290 #else
291 return -1;
292 #endif
293 if (sflags & SocketFlags_MaxIOVectorLength)
294 /* FIXME: Don't know what to do for MaxIOVectorLength query */
295 return -1;
297 return (flags ? flags : -1);
301 * Returns:
302 * 0 on success (mapped mono_level and mono_name to system_level and system_name
303 * -1 on error
304 * -2 on non-fatal error (ie, must ignore)
306 static gint32 convert_sockopt_level_and_name(MonoSocketOptionLevel mono_level,
307 MonoSocketOptionName mono_name,
308 int *system_level,
309 int *system_name)
311 switch (mono_level) {
312 case SocketOptionLevel_Socket:
313 *system_level = SOL_SOCKET;
315 switch(mono_name) {
316 case SocketOptionName_DontLinger:
317 /* This is SO_LINGER, because the setsockopt
318 * internal call maps DontLinger to SO_LINGER
319 * with l_onoff=0
321 *system_name = SO_LINGER;
322 break;
323 case SocketOptionName_Debug:
324 *system_name = SO_DEBUG;
325 break;
326 #ifdef SO_ACCEPTCONN
327 case SocketOptionName_AcceptConnection:
328 *system_name = SO_ACCEPTCONN;
329 break;
330 #endif
331 case SocketOptionName_ReuseAddress:
332 *system_name = SO_REUSEADDR;
333 break;
334 case SocketOptionName_KeepAlive:
335 *system_name = SO_KEEPALIVE;
336 break;
337 case SocketOptionName_DontRoute:
338 *system_name = SO_DONTROUTE;
339 break;
340 case SocketOptionName_Broadcast:
341 *system_name = SO_BROADCAST;
342 break;
343 case SocketOptionName_Linger:
344 *system_name = SO_LINGER;
345 break;
346 case SocketOptionName_OutOfBandInline:
347 *system_name = SO_OOBINLINE;
348 break;
349 case SocketOptionName_SendBuffer:
350 *system_name = SO_SNDBUF;
351 break;
352 case SocketOptionName_ReceiveBuffer:
353 *system_name = SO_RCVBUF;
354 break;
355 case SocketOptionName_SendLowWater:
356 *system_name = SO_SNDLOWAT;
357 break;
358 case SocketOptionName_ReceiveLowWater:
359 *system_name = SO_RCVLOWAT;
360 break;
361 case SocketOptionName_SendTimeout:
362 *system_name = SO_SNDTIMEO;
363 break;
364 case SocketOptionName_ReceiveTimeout:
365 *system_name = SO_RCVTIMEO;
366 break;
367 case SocketOptionName_Error:
368 *system_name = SO_ERROR;
369 break;
370 case SocketOptionName_Type:
371 *system_name = SO_TYPE;
372 break;
373 #ifdef SO_PEERCRED
374 case SocketOptionName_PeerCred:
375 *system_name = SO_PEERCRED;
376 break;
377 #endif
378 case SocketOptionName_ExclusiveAddressUse:
379 case SocketOptionName_UseLoopback:
380 case SocketOptionName_MaxConnections:
381 /* Can't figure out how to map these, so fall
382 * through
384 default:
385 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at Socket level", mono_name);
386 return(-1);
388 break;
390 case SocketOptionLevel_IP:
391 #ifdef HAVE_SOL_IP
392 *system_level = SOL_IP;
393 #else
394 if (1) {
395 static int cached = 0;
396 static int proto;
398 if (!cached) {
399 struct protoent *pent;
401 pent = getprotobyname ("IP");
402 proto = pent ? pent->p_proto : 0 /* 0 a good default value?? */;
403 cached = 1;
406 *system_level = proto;
408 #endif /* HAVE_SOL_IP */
410 switch(mono_name) {
411 case SocketOptionName_IPOptions:
412 *system_name = IP_OPTIONS;
413 break;
414 #ifdef IP_HDRINCL
415 case SocketOptionName_HeaderIncluded:
416 *system_name = IP_HDRINCL;
417 break;
418 #endif
419 #ifdef IP_TOS
420 case SocketOptionName_TypeOfService:
421 *system_name = IP_TOS;
422 break;
423 #endif
424 #ifdef IP_TTL
425 case SocketOptionName_IpTimeToLive:
426 *system_name = IP_TTL;
427 break;
428 #endif
429 case SocketOptionName_MulticastInterface:
430 *system_name = IP_MULTICAST_IF;
431 break;
432 case SocketOptionName_MulticastTimeToLive:
433 *system_name = IP_MULTICAST_TTL;
434 break;
435 case SocketOptionName_MulticastLoopback:
436 *system_name = IP_MULTICAST_LOOP;
437 break;
438 case SocketOptionName_AddMembership:
439 *system_name = IP_ADD_MEMBERSHIP;
440 break;
441 case SocketOptionName_DropMembership:
442 *system_name = IP_DROP_MEMBERSHIP;
443 break;
444 #ifdef HAVE_IP_PKTINFO
445 case SocketOptionName_PacketInformation:
446 *system_name = IP_PKTINFO;
447 break;
448 #endif /* HAVE_IP_PKTINFO */
450 case SocketOptionName_DontFragment:
451 #ifdef HAVE_IP_DONTFRAGMENT
452 *system_name = IP_DONTFRAGMENT;
453 break;
454 #elif defined HAVE_IP_MTU_DISCOVER
455 /* Not quite the same */
456 *system_name = IP_MTU_DISCOVER;
457 break;
458 #else
459 /* If the flag is not available on this system, we can ignore this error */
460 return (-2);
461 #endif /* HAVE_IP_DONTFRAGMENT */
462 case SocketOptionName_AddSourceMembership:
463 case SocketOptionName_DropSourceMembership:
464 case SocketOptionName_BlockSource:
465 case SocketOptionName_UnblockSource:
466 /* Can't figure out how to map these, so fall
467 * through
469 default:
470 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at IP level", mono_name);
471 return(-1);
473 break;
475 #ifdef AF_INET6
476 case SocketOptionLevel_IPv6:
477 #ifdef HAVE_SOL_IPV6
478 *system_level = SOL_IPV6;
479 #else
480 if (1) {
481 static int cached = 0;
482 static int proto;
484 if (!cached) {
485 struct protoent *pent;
487 pent = getprotobyname ("IPV6");
488 proto = pent ? pent->p_proto : 41 /* 41 a good default value?? */;
489 cached = 1;
492 *system_level = proto;
494 #endif /* HAVE_SOL_IPV6 */
496 switch(mono_name) {
497 case SocketOptionName_IpTimeToLive:
498 *system_name = IPV6_UNICAST_HOPS;
499 break;
500 case SocketOptionName_MulticastInterface:
501 *system_name = IPV6_MULTICAST_IF;
502 break;
503 case SocketOptionName_MulticastTimeToLive:
504 *system_name = IPV6_MULTICAST_HOPS;
505 break;
506 case SocketOptionName_MulticastLoopback:
507 *system_name = IPV6_MULTICAST_LOOP;
508 break;
509 case SocketOptionName_AddMembership:
510 *system_name = IPV6_JOIN_GROUP;
511 break;
512 case SocketOptionName_DropMembership:
513 *system_name = IPV6_LEAVE_GROUP;
514 break;
515 case SocketOptionName_PacketInformation:
516 #ifdef HAVE_IPV6_PKTINFO
517 *system_name = IPV6_PKTINFO;
518 #endif
519 break;
520 case SocketOptionName_HeaderIncluded:
521 case SocketOptionName_IPOptions:
522 case SocketOptionName_TypeOfService:
523 case SocketOptionName_DontFragment:
524 case SocketOptionName_AddSourceMembership:
525 case SocketOptionName_DropSourceMembership:
526 case SocketOptionName_BlockSource:
527 case SocketOptionName_UnblockSource:
528 /* Can't figure out how to map these, so fall
529 * through
531 default:
532 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at IPv6 level", mono_name);
533 return(-1);
536 break; /* SocketOptionLevel_IPv6 */
537 #endif
539 case SocketOptionLevel_Tcp:
540 #ifdef HAVE_SOL_TCP
541 *system_level = SOL_TCP;
542 #else
543 if (1) {
544 static int cached = 0;
545 static int proto;
547 if (!cached) {
548 struct protoent *pent;
550 pent = getprotobyname ("TCP");
551 proto = pent ? pent->p_proto : 6 /* is 6 a good default value?? */;
552 cached = 1;
555 *system_level = proto;
557 #endif /* HAVE_SOL_TCP */
559 switch(mono_name) {
560 case SocketOptionName_NoDelay:
561 *system_name = TCP_NODELAY;
562 break;
563 #if 0
564 /* The documentation is talking complete
565 * bollocks here: rfc-1222 is titled
566 * 'Advancing the NSFNET Routing Architecture'
567 * and doesn't mention either of the words
568 * "expedite" or "urgent".
570 case SocketOptionName_BsdUrgent:
571 case SocketOptionName_Expedited:
572 #endif
573 default:
574 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at TCP level", mono_name);
575 return(-1);
577 break;
579 case SocketOptionLevel_Udp:
580 g_warning("System.Net.Sockets.SocketOptionLevel has unsupported value 0x%x", mono_level);
582 switch(mono_name) {
583 case SocketOptionName_NoChecksum:
584 case SocketOptionName_ChecksumCoverage:
585 default:
586 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at UDP level", mono_name);
587 return(-1);
589 return(-1);
590 break;
592 default:
593 g_warning("System.Net.Sockets.SocketOptionLevel has unknown value 0x%x", mono_level);
594 return(-1);
597 return(0);
600 #define STASH_SYS_ASS(this) \
601 if(system_assembly == NULL) { \
602 system_assembly=mono_image_loaded ("System"); \
603 if (!system_assembly) { \
604 MonoAssembly *sa = mono_assembly_open ("System.dll", NULL); \
605 if (!sa) g_assert_not_reached (); \
606 else {system_assembly = mono_assembly_get_image (sa);} \
610 static MonoImage *system_assembly=NULL;
613 #ifdef AF_INET6
614 static gint32 get_family_hint(void)
616 MonoClass *socket_class;
617 MonoClassField *ipv6_field, *ipv4_field;
618 gint32 ipv6_enabled = -1, ipv4_enabled = -1;
619 MonoVTable *vtable;
621 socket_class = mono_class_from_name (system_assembly,
622 "System.Net.Sockets", "Socket");
623 ipv4_field = mono_class_get_field_from_name (socket_class,
624 "ipv4Supported");
625 ipv6_field = mono_class_get_field_from_name (socket_class,
626 "ipv6Supported");
627 vtable = mono_class_vtable (mono_domain_get (), socket_class);
629 mono_field_static_get_value(vtable, ipv4_field, &ipv4_enabled);
630 mono_field_static_get_value(vtable, ipv6_field, &ipv6_enabled);
632 if(ipv4_enabled == 1 && ipv6_enabled == 1) {
633 return(PF_UNSPEC);
634 } else if(ipv4_enabled == 1) {
635 return(PF_INET);
636 } else {
637 return(PF_INET6);
640 #endif
642 gpointer ves_icall_System_Net_Sockets_Socket_Socket_internal(MonoObject *this, gint32 family, gint32 type, gint32 proto, gint32 *error)
644 SOCKET sock;
645 gint32 sock_family;
646 gint32 sock_proto;
647 gint32 sock_type;
649 MONO_ARCH_SAVE_REGS;
651 STASH_SYS_ASS(this);
653 *error = 0;
655 sock_family=convert_family(family);
656 if(sock_family==-1) {
657 *error = WSAEAFNOSUPPORT;
658 return(NULL);
661 sock_proto=convert_proto(proto);
662 if(sock_proto==-1) {
663 *error = WSAEPROTONOSUPPORT;
664 return(NULL);
667 sock_type=convert_type(type);
668 if(sock_type==-1) {
669 *error = WSAESOCKTNOSUPPORT;
670 return(NULL);
673 sock = _wapi_socket (sock_family, sock_type, sock_proto,
674 NULL, 0, WSA_FLAG_OVERLAPPED);
676 if(sock==INVALID_SOCKET) {
677 *error = WSAGetLastError ();
678 return(NULL);
681 if (sock_family == AF_INET && sock_type == SOCK_DGRAM) {
682 return (GUINT_TO_POINTER (sock));
685 #ifdef AF_INET6
686 if (sock_family == AF_INET6 && sock_type == SOCK_DGRAM) {
687 return (GUINT_TO_POINTER (sock));
689 #endif
691 #ifndef PLATFORM_WIN32
692 /* .net seems to set this by default for SOCK_STREAM,
693 * not for SOCK_DGRAM (see bug #36322)
695 * It seems winsock has a rather different idea of what
696 * SO_REUSEADDR means. If it's set, then a new socket can be
697 * bound over an existing listening socket. There's a new
698 * windows-specific option called SO_EXCLUSIVEADDRUSE but
699 * using that means the socket MUST be closed properly, or a
700 * denial of service can occur. Luckily for us, winsock
701 * behaves as though any other system would when SO_REUSEADDR
702 * is true, so we don't need to do anything else here. See
703 * bug 53992.
706 int ret, true = 1;
708 ret = _wapi_setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &true, sizeof (true));
709 if(ret==SOCKET_ERROR) {
710 *error = WSAGetLastError ();
712 closesocket(sock);
713 return(NULL);
716 #endif
718 return(GUINT_TO_POINTER (sock));
721 /* FIXME: the SOCKET parameter (here and in other functions in this
722 * file) is really an IntPtr which needs to be converted to a guint32.
724 void ves_icall_System_Net_Sockets_Socket_Close_internal(SOCKET sock,
725 gint32 *error)
727 MONO_ARCH_SAVE_REGS;
729 #ifdef DEBUG
730 g_message (G_GNUC_PRETTY_FUNCTION ": closing 0x%x", sock);
731 #endif
733 *error = 0;
735 /* Clear any pending work item from this socket if the underlying
736 * polling system does not notify when the socket is closed */
737 mono_thread_pool_remove_socket (GPOINTER_TO_INT (sock));
738 closesocket(sock);
741 gint32 ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal(void)
743 MONO_ARCH_SAVE_REGS;
745 #ifdef DEBUG
746 g_message(G_GNUC_PRETTY_FUNCTION ": returning %d", WSAGetLastError());
747 #endif
749 return(WSAGetLastError());
752 gint32 ves_icall_System_Net_Sockets_Socket_Available_internal(SOCKET sock,
753 gint32 *error)
755 int ret;
756 gulong amount;
758 MONO_ARCH_SAVE_REGS;
760 *error = 0;
762 ret=ioctlsocket(sock, FIONREAD, &amount);
763 if(ret==SOCKET_ERROR) {
764 *error = WSAGetLastError ();
765 return(0);
768 return(amount);
771 void ves_icall_System_Net_Sockets_Socket_Blocking_internal(SOCKET sock,
772 gboolean block,
773 gint32 *error)
775 int ret;
777 MONO_ARCH_SAVE_REGS;
779 *error = 0;
782 * block == TRUE/FALSE means we will block/not block.
783 * But the ioctlsocket call takes TRUE/FALSE for non-block/block
785 block = !block;
787 ret = ioctlsocket (sock, FIONBIO, (gulong *) &block);
788 if(ret==SOCKET_ERROR) {
789 *error = WSAGetLastError ();
793 gpointer ves_icall_System_Net_Sockets_Socket_Accept_internal(SOCKET sock,
794 gint32 *error)
796 SOCKET newsock;
798 MONO_ARCH_SAVE_REGS;
800 *error = 0;
802 newsock = _wapi_accept (sock, NULL, 0);
803 if(newsock==INVALID_SOCKET) {
804 *error = WSAGetLastError ();
805 return(NULL);
808 return(GUINT_TO_POINTER (newsock));
811 void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock,
812 guint32 backlog,
813 gint32 *error)
815 int ret;
817 MONO_ARCH_SAVE_REGS;
819 *error = 0;
821 ret = _wapi_listen (sock, backlog);
822 if(ret==SOCKET_ERROR) {
823 *error = WSAGetLastError ();
827 static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
828 int sa_size, gint32 *error)
830 MonoDomain *domain = mono_domain_get ();
831 MonoObject *sockaddr_obj;
832 MonoClass *sockaddr_class;
833 MonoClassField *field;
834 MonoArray *data;
835 MonoAddressFamily family;
837 /* Build a System.Net.SocketAddress object instance */
838 sockaddr_class=mono_class_from_name(system_assembly, "System.Net", "SocketAddress");
839 sockaddr_obj=mono_object_new(domain, sockaddr_class);
841 /* Locate the SocketAddress data buffer in the object */
842 field=mono_class_get_field_from_name(sockaddr_class, "data");
844 /* Make sure there is space for the family and size bytes */
845 #ifdef HAVE_SYS_UN_H
846 if (saddr->sa_family == AF_UNIX) {
847 /* sa_len includes the entire sockaddr size, so we don't need the
848 * N bytes (sizeof (unsigned short)) of the family. */
849 data=mono_array_new(domain, mono_get_byte_class (), sa_size);
850 } else
851 #endif
853 /* May be the +2 here is too conservative, as sa_len returns
854 * the length of the entire sockaddr_in/in6, including
855 * sizeof (unsigned short) of the family */
856 data=mono_array_new(domain, mono_get_byte_class (), sa_size+2);
859 /* The data buffer is laid out as follows:
860 * bytes 0 and 1 are the address family
861 * bytes 2 and 3 are the port info
862 * the rest is the address info
865 family=convert_to_mono_family(saddr->sa_family);
866 if(family==AddressFamily_Unknown) {
867 *error = WSAEAFNOSUPPORT;
868 return(NULL);
871 mono_array_set(data, guint8, 0, family & 0x0FF);
872 mono_array_set(data, guint8, 1, (family >> 8) & 0x0FF);
874 if(saddr->sa_family==AF_INET) {
875 struct sockaddr_in *sa_in=(struct sockaddr_in *)saddr;
876 guint16 port=ntohs(sa_in->sin_port);
877 guint32 address=ntohl(sa_in->sin_addr.s_addr);
879 if(sa_size<8) {
880 mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
883 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
884 mono_array_set(data, guint8, 3, (port) & 0xff);
885 mono_array_set(data, guint8, 4, (address>>24) & 0xff);
886 mono_array_set(data, guint8, 5, (address>>16) & 0xff);
887 mono_array_set(data, guint8, 6, (address>>8) & 0xff);
888 mono_array_set(data, guint8, 7, (address) & 0xff);
890 mono_field_set_value (sockaddr_obj, field, data);
892 return(sockaddr_obj);
893 #ifdef AF_INET6
894 } else if (saddr->sa_family == AF_INET6) {
895 struct sockaddr_in6 *sa_in=(struct sockaddr_in6 *)saddr;
896 int i;
898 guint16 port=ntohs(sa_in->sin6_port);
900 if(sa_size<28) {
901 mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
904 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
905 mono_array_set(data, guint8, 3, (port) & 0xff);
907 for(i=0; i<16; i++) {
908 mono_array_set(data, guint8, 8+i,
909 sa_in->sin6_addr.s6_addr[i]);
912 mono_array_set(data, guint8, 24, sa_in->sin6_scope_id & 0xff);
913 mono_array_set(data, guint8, 25,
914 (sa_in->sin6_scope_id >> 8) & 0xff);
915 mono_array_set(data, guint8, 26,
916 (sa_in->sin6_scope_id >> 16) & 0xff);
917 mono_array_set(data, guint8, 27,
918 (sa_in->sin6_scope_id >> 24) & 0xff);
920 mono_field_set_value (sockaddr_obj, field, data);
922 return(sockaddr_obj);
923 #endif
924 #ifdef HAVE_SYS_UN_H
925 } else if (saddr->sa_family == AF_UNIX) {
926 int i;
928 for (i = 0; i < sa_size; i++) {
929 mono_array_set (data, guint8, i+2, saddr->sa_data[i]);
932 mono_field_set_value (sockaddr_obj, field, data);
934 return sockaddr_obj;
935 #endif
936 } else {
937 *error = WSAEAFNOSUPPORT;
938 return(NULL);
942 extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 *error)
944 gchar sa[32]; /* sockaddr in not big enough for sockaddr_in6 */
945 socklen_t salen;
946 int ret;
948 MONO_ARCH_SAVE_REGS;
950 *error = 0;
952 salen=sizeof(sa);
953 ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
955 if(ret==SOCKET_ERROR) {
956 *error = WSAGetLastError ();
957 return(NULL);
960 #ifdef DEBUG
961 g_message(G_GNUC_PRETTY_FUNCTION ": bound to %s port %d", inet_ntoa(((struct sockaddr_in *)&sa)->sin_addr), ntohs(((struct sockaddr_in *)&sa)->sin_port));
962 #endif
964 return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
965 error));
968 extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 *error)
970 gchar sa[32]; /* sockaddr in not big enough for sockaddr_in6 */
971 socklen_t salen;
972 int ret;
974 MONO_ARCH_SAVE_REGS;
976 *error = 0;
978 salen=sizeof(sa);
979 ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
981 if(ret==SOCKET_ERROR) {
982 *error = WSAGetLastError ();
983 return(NULL);
986 #ifdef DEBUG
987 g_message(G_GNUC_PRETTY_FUNCTION ": connected to %s port %d", inet_ntoa(((struct sockaddr_in *)&sa)->sin_addr), ntohs(((struct sockaddr_in *)&sa)->sin_port));
988 #endif
990 return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
991 error));
994 static struct sockaddr *create_sockaddr_from_object(MonoObject *saddr_obj,
995 socklen_t *sa_size,
996 gint32 *error)
998 MonoClassField *field;
999 MonoArray *data;
1000 gint32 family;
1001 int len;
1003 /* Dig the SocketAddress data buffer out of the object */
1004 field=mono_class_get_field_from_name(saddr_obj->vtable->klass, "data");
1005 data=*(MonoArray **)(((char *)saddr_obj) + field->offset);
1007 /* The data buffer is laid out as follows:
1008 * byte 0 is the address family low byte
1009 * byte 1 is the address family high byte
1010 * INET:
1011 * bytes 2 and 3 are the port info
1012 * the rest is the address info
1013 * UNIX:
1014 * the rest is the file name
1016 len = mono_array_length (data);
1017 if (len < 2) {
1018 mono_raise_exception (mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
1021 family = convert_family (mono_array_get (data, guint8, 0) + (mono_array_get (data, guint8, 1) << 8));
1022 if (family == AF_INET) {
1023 struct sockaddr_in *sa;
1024 guint16 port;
1025 guint32 address;
1027 if (len < 8) {
1028 mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1031 sa = g_new0 (struct sockaddr_in, 1);
1032 port = (mono_array_get (data, guint8, 2) << 8) +
1033 mono_array_get (data, guint8, 3);
1034 address = (mono_array_get (data, guint8, 4) << 24) +
1035 (mono_array_get (data, guint8, 5) << 16 ) +
1036 (mono_array_get (data, guint8, 6) << 8) +
1037 mono_array_get (data, guint8, 7);
1039 sa->sin_family = family;
1040 sa->sin_addr.s_addr = htonl (address);
1041 sa->sin_port = htons (port);
1043 *sa_size = sizeof(struct sockaddr_in);
1044 return((struct sockaddr *)sa);
1046 #ifdef AF_INET6
1047 } else if (family == AF_INET6) {
1048 struct sockaddr_in6 *sa;
1049 int i;
1050 guint16 port;
1051 guint32 scopeid;
1053 if (len < 28) {
1054 mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1057 sa = g_new0 (struct sockaddr_in6, 1);
1058 port = mono_array_get (data, guint8, 3) +
1059 (mono_array_get (data, guint8, 2) << 8);
1060 scopeid = mono_array_get (data, guint8, 24) +
1061 (mono_array_get (data, guint8, 25) << 8) +
1062 (mono_array_get (data, guint8, 26) << 16) +
1063 (mono_array_get (data, guint8, 27) << 24);
1065 sa->sin6_family = family;
1066 sa->sin6_port = htons (port);
1067 sa->sin6_scope_id = scopeid;
1069 for(i=0; i<16; i++) {
1070 sa->sin6_addr.s6_addr[i] = mono_array_get (data, guint8, 8+i);
1073 *sa_size = sizeof(struct sockaddr_in6);
1074 return((struct sockaddr *)sa);
1075 #endif
1076 #ifdef HAVE_SYS_UN_H
1077 } else if (family == AF_UNIX) {
1078 struct sockaddr_un *sock_un;
1079 int i;
1081 /* Need a byte for the '\0' terminator/prefix, and the first
1082 * two bytes hold the SocketAddress family
1084 if (len - 2 >= MONO_SIZEOF_SUNPATH) {
1085 mono_raise_exception (mono_get_exception_index_out_of_range ());
1088 sock_un = g_new0 (struct sockaddr_un, 1);
1090 sock_un->sun_family = family;
1091 for (i = 0; i < len - 2; i++) {
1092 sock_un->sun_path [i] = mono_array_get (data, guint8,
1093 i + 2);
1096 *sa_size = len;
1098 return (struct sockaddr *)sock_un;
1099 #endif
1100 } else {
1101 *error = WSAEAFNOSUPPORT;
1102 return(0);
1106 extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1108 struct sockaddr *sa;
1109 socklen_t sa_size;
1110 int ret;
1112 MONO_ARCH_SAVE_REGS;
1114 *error = 0;
1116 sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1117 if (*error != 0) {
1118 return;
1121 #ifdef DEBUG
1122 g_message(G_GNUC_PRETTY_FUNCTION ": binding to %s port %d", inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), ntohs (((struct sockaddr_in *)sa)->sin_port));
1123 #endif
1125 ret = _wapi_bind (sock, sa, sa_size);
1126 if(ret==SOCKET_ERROR) {
1127 *error = WSAGetLastError ();
1130 g_free(sa);
1133 enum {
1134 SelectModeRead,
1135 SelectModeWrite,
1136 SelectModeError
1139 MonoBoolean
1140 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
1141 gint timeout, gint32 *error)
1143 MonoThread *thread = NULL;
1144 mono_pollfd *pfds;
1145 int ret;
1146 time_t start;
1149 MONO_ARCH_SAVE_REGS;
1151 pfds = g_new0 (mono_pollfd, 1);
1152 pfds[0].fd = GPOINTER_TO_INT (sock);
1153 pfds[0].events = (mode == SelectModeRead) ? MONO_POLLIN :
1154 (mode == SelectModeWrite) ? MONO_POLLOUT :
1155 (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL);
1157 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1158 start = time (NULL);
1159 do {
1160 *error = 0;
1162 ret = mono_poll (pfds, 1, timeout);
1163 if (timeout > 0 && ret < 0) {
1164 int err = errno;
1165 int sec = time (NULL) - start;
1167 timeout -= sec * 1000;
1168 if (timeout < 0) {
1169 timeout = 0;
1172 errno = err;
1175 if (ret == -1 && errno == EINTR) {
1176 int leave = 0;
1178 if (thread == NULL) {
1179 thread = mono_thread_current ();
1182 mono_monitor_enter (thread->synch_lock);
1183 leave = ((thread->state & ThreadState_AbortRequested) != 0 ||
1184 (thread->state & ThreadState_StopRequested) != 0);
1185 mono_monitor_exit (thread->synch_lock);
1187 if (leave != 0) {
1188 g_free (pfds);
1189 return(FALSE);
1190 } else {
1191 /* Suspend requested? */
1192 mono_thread_interruption_checkpoint ();
1194 errno = EINTR;
1196 } while (ret == -1 && errno == EINTR);
1198 if (ret == -1) {
1199 #ifdef PLATFORM_WIN32
1200 *error = WSAGetLastError ();
1201 #else
1202 *error = errno_to_WSA (errno, __func__);
1203 #endif
1204 g_free (pfds);
1205 return(FALSE);
1208 g_free (pfds);
1210 if (ret == 0) {
1211 return(FALSE);
1212 } else {
1213 return (TRUE);
1217 extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1219 struct sockaddr *sa;
1220 socklen_t sa_size;
1221 int ret;
1223 MONO_ARCH_SAVE_REGS;
1225 *error = 0;
1227 sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1228 if (*error != 0) {
1229 return;
1232 #ifdef DEBUG
1233 g_message(G_GNUC_PRETTY_FUNCTION ": connecting to %s port %d", inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), ntohs (((struct sockaddr_in *)sa)->sin_port));
1234 #endif
1236 ret = _wapi_connect (sock, sa, sa_size);
1237 if(ret==SOCKET_ERROR) {
1238 *error = WSAGetLastError ();
1241 g_free(sa);
1244 /* These #defines from mswsock.h from wine. Defining them here allows
1245 * us to build this file on a mingw box that doesn't know the magic
1246 * numbers, but still run on a newer windows box that does.
1248 #ifndef WSAID_DISCONNECTEX
1249 #define WSAID_DISCONNECTEX {0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
1250 typedef BOOL (WINAPI *LPFN_DISCONNECTEX)(SOCKET, LPOVERLAPPED, DWORD, DWORD);
1251 #endif
1253 #ifndef WSAID_TRANSMITFILE
1254 #define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
1255 typedef BOOL (WINAPI *LPFN_TRANSMITFILE)(SOCKET, HANDLE, DWORD, DWORD, LPOVERLAPPED, LPTRANSMIT_FILE_BUFFERS, DWORD);
1256 #endif
1258 extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error)
1260 int ret;
1261 glong output_bytes = 0;
1262 GUID disco_guid = WSAID_DISCONNECTEX;
1263 GUID trans_guid = WSAID_TRANSMITFILE;
1264 LPFN_DISCONNECTEX _wapi_disconnectex = NULL;
1265 LPFN_TRANSMITFILE _wapi_transmitfile = NULL;
1266 gboolean bret;
1268 MONO_ARCH_SAVE_REGS;
1270 *error = 0;
1272 #ifdef DEBUG
1273 g_message("%s: disconnecting from socket %p (reuse %d)", __func__,
1274 sock, reuse);
1275 #endif
1277 /* I _think_ the extension function pointers need to be looked
1278 * up for each socket. FIXME: check the best way to store
1279 * pointers to functions in managed objects that still works
1280 * on 64bit platforms.
1282 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1283 (void *)&disco_guid, sizeof(GUID),
1284 (void *)&_wapi_disconnectex, sizeof(void *),
1285 &output_bytes, NULL, NULL);
1286 if (ret != 0) {
1287 /* make sure that WSAIoctl didn't put crap in the
1288 * output pointer
1290 _wapi_disconnectex = NULL;
1292 /* Look up the TransmitFile extension function pointer
1293 * instead of calling TransmitFile() directly, because
1294 * apparently "Several of the extension functions have
1295 * been available since WinSock 1.1 and are exported
1296 * from MSWsock.dll, however it's not advisable to
1297 * link directly to this dll as this ties you to the
1298 * Microsoft WinSock provider. A provider neutral way
1299 * of accessing these extension functions is to load
1300 * them dynamically via WSAIoctl using the
1301 * SIO_GET_EXTENSION_FUNCTION_POINTER op code. This
1302 * should, theoretically, allow you to access these
1303 * functions from any provider that supports them..."
1304 * (http://www.codeproject.com/internet/jbsocketserver3.asp)
1306 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1307 (void *)&trans_guid, sizeof(GUID),
1308 (void *)&_wapi_transmitfile, sizeof(void *),
1309 &output_bytes, NULL, NULL);
1310 if (ret != 0) {
1311 _wapi_transmitfile = NULL;
1315 if (_wapi_disconnectex != NULL) {
1316 bret = _wapi_disconnectex (sock, NULL, TF_REUSE_SOCKET, 0);
1317 } else if (_wapi_transmitfile != NULL) {
1318 bret = _wapi_transmitfile (sock, NULL, 0, 0, NULL, NULL,
1319 TF_DISCONNECT | TF_REUSE_SOCKET);
1320 } else {
1321 *error = ERROR_NOT_SUPPORTED;
1322 return;
1325 if (bret == FALSE) {
1326 *error = WSAGetLastError ();
1330 gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1332 int ret;
1333 guchar *buf;
1334 gint32 alen;
1335 int recvflags=0;
1337 MONO_ARCH_SAVE_REGS;
1339 *error = 0;
1341 alen = mono_array_length (buffer);
1342 if (offset > alen - count) {
1343 return(0);
1346 buf=mono_array_addr(buffer, guchar, offset);
1348 recvflags = convert_socketflags (flags);
1349 if (recvflags == -1) {
1350 *error = WSAEOPNOTSUPP;
1351 return (0);
1354 ret = _wapi_recv (sock, buf, count, recvflags);
1355 if(ret==SOCKET_ERROR) {
1356 *error = WSAGetLastError ();
1357 return(0);
1360 return(ret);
1363 gint32 ves_icall_System_Net_Sockets_Socket_RecvFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error)
1365 int ret;
1366 guchar *buf;
1367 gint32 alen;
1368 int recvflags=0;
1369 struct sockaddr *sa;
1370 socklen_t sa_size;
1372 MONO_ARCH_SAVE_REGS;
1374 *error = 0;
1376 alen = mono_array_length (buffer);
1377 if (offset > alen - count) {
1378 return(0);
1381 sa=create_sockaddr_from_object(*sockaddr, &sa_size, error);
1382 if (*error != 0) {
1383 return(0);
1386 buf=mono_array_addr(buffer, guchar, offset);
1388 recvflags = convert_socketflags (flags);
1389 if (recvflags == -1) {
1390 *error = WSAEOPNOTSUPP;
1391 return (0);
1394 ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
1395 if(ret==SOCKET_ERROR) {
1396 g_free(sa);
1397 *error = WSAGetLastError ();
1398 return(0);
1401 /* If we didn't get a socket size, then we're probably a
1402 * connected connection-oriented socket and the stack hasn't
1403 * returned the remote address. All we can do is return null.
1405 if ( sa_size != 0 )
1406 *sockaddr=create_object_from_sockaddr(sa, sa_size, error);
1407 else
1408 *sockaddr=NULL;
1410 g_free(sa);
1412 return(ret);
1415 gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1417 int ret;
1418 guchar *buf;
1419 gint32 alen;
1420 int sendflags=0;
1422 MONO_ARCH_SAVE_REGS;
1424 *error = 0;
1426 alen = mono_array_length (buffer);
1427 if (offset > alen - count) {
1428 return(0);
1431 #ifdef DEBUG
1432 g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
1433 #endif
1435 buf=mono_array_addr(buffer, guchar, offset);
1437 #ifdef DEBUG
1438 g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
1439 #endif
1441 sendflags = convert_socketflags (flags);
1442 if (sendflags == -1) {
1443 *error = WSAEOPNOTSUPP;
1444 return (0);
1447 ret = _wapi_send (sock, buf, count, sendflags);
1448 if(ret==SOCKET_ERROR) {
1449 *error = WSAGetLastError ();
1450 return(0);
1453 return(ret);
1456 gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error)
1458 int ret;
1459 guchar *buf;
1460 gint32 alen;
1461 int sendflags=0;
1462 struct sockaddr *sa;
1463 socklen_t sa_size;
1465 MONO_ARCH_SAVE_REGS;
1467 *error = 0;
1469 alen = mono_array_length (buffer);
1470 if (offset > alen - count) {
1471 return(0);
1474 sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1475 if(*error != 0) {
1476 return(0);
1479 #ifdef DEBUG
1480 g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
1481 #endif
1483 buf=mono_array_addr(buffer, guchar, offset);
1485 #ifdef DEBUG
1486 g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
1487 #endif
1489 sendflags = convert_socketflags (flags);
1490 if (sendflags == -1) {
1491 *error = WSAEOPNOTSUPP;
1492 return (0);
1495 ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
1496 if(ret==SOCKET_ERROR) {
1497 *error = WSAGetLastError ();
1500 g_free(sa);
1502 return(ret);
1505 static SOCKET Socket_to_SOCKET(MonoObject *sockobj)
1507 SOCKET sock;
1508 MonoClassField *field;
1510 field=mono_class_get_field_from_name(sockobj->vtable->klass, "socket");
1511 sock=*(SOCKET *)(((char *)sockobj)+field->offset);
1513 return(sock);
1516 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
1517 void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error)
1519 MonoThread *thread = NULL;
1520 MonoObject *obj;
1521 mono_pollfd *pfds;
1522 int nfds, idx;
1523 int ret;
1524 int i, count;
1525 int mode;
1526 MonoClass *sock_arr_class;
1527 MonoArray *socks;
1528 time_t start;
1530 MONO_ARCH_SAVE_REGS;
1532 /* *sockets -> READ, null, WRITE, null, ERROR, null */
1533 count = mono_array_length (*sockets);
1534 nfds = count - 3; /* NULL separators */
1535 pfds = g_new0 (mono_pollfd, nfds);
1536 mode = idx = 0;
1537 for (i = 0; i < count; i++) {
1538 obj = mono_array_get (*sockets, MonoObject *, i);
1539 if (obj == NULL) {
1540 mode++;
1541 continue;
1544 if (idx >= nfds) {
1545 /* The socket array was bogus */
1546 g_free (pfds);
1547 *error = WSAEFAULT;
1548 return;
1551 pfds [idx].fd = GPOINTER_TO_INT (Socket_to_SOCKET (obj));
1552 pfds [idx].events = (mode == 0) ? MONO_POLLIN : (mode == 1) ? MONO_POLLOUT : POLL_ERRORS;
1553 idx++;
1556 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1557 start = time (NULL);
1558 do {
1559 *error = 0;
1560 ret = mono_poll (pfds, nfds, timeout);
1561 if (timeout > 0 && ret < 0) {
1562 int err = errno;
1563 int sec = time (NULL) - start;
1565 timeout -= sec * 1000;
1566 if (timeout < 0)
1567 timeout = 0;
1568 errno = err;
1571 if (ret == -1 && errno == EINTR) {
1572 int leave = 0;
1573 if (thread == NULL)
1574 thread = mono_thread_current ();
1576 mono_monitor_enter (thread->synch_lock);
1577 leave = ((thread->state & ThreadState_AbortRequested) != 0 ||
1578 (thread->state & ThreadState_StopRequested) != 0);
1579 mono_monitor_exit (thread->synch_lock);
1580 if (leave != 0) {
1581 g_free (pfds);
1582 *sockets = NULL;
1583 return;
1584 } else {
1585 /* Suspend requested? */
1586 mono_thread_interruption_checkpoint ();
1588 errno = EINTR;
1590 } while (ret == -1 && errno == EINTR);
1592 if (ret == -1) {
1593 #ifdef PLATFORM_WIN32
1594 *error = WSAGetLastError ();
1595 #else
1596 *error = errno_to_WSA (errno, __func__);
1597 #endif
1598 g_free (pfds);
1599 return;
1602 if (ret == 0) {
1603 g_free (pfds);
1604 *sockets = NULL;
1605 return;
1608 sock_arr_class= ((MonoObject *)*sockets)->vtable->klass;
1609 ret += 3; /* space for the NULL delimiters */
1610 socks = mono_array_new_full (mono_domain_get (), sock_arr_class, (guint32*)&ret, NULL);
1611 ret -= 3;
1612 mode = idx = 0;
1613 for (i = 0; i < count && ret > 0; i++) {
1614 mono_pollfd *pfd;
1616 obj = mono_array_get (*sockets, MonoObject *, i);
1617 if (obj == NULL) {
1618 mode++;
1619 idx++;
1620 continue;
1623 pfd = &pfds [i - mode];
1624 if (pfd->revents == 0)
1625 continue;
1627 ret--;
1628 if (mode == 0 && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
1629 mono_array_setref (socks, idx++, obj);
1630 } else if (mode == 1 && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
1631 mono_array_setref (socks, idx++, obj);
1632 } else if ((pfd->revents & POLL_ERRORS) != 0) {
1633 mono_array_setref (socks, idx++, obj);
1637 *sockets = socks;
1638 g_free (pfds);
1641 static MonoObject* int_to_object (MonoDomain *domain, int val)
1643 return mono_value_box (domain, mono_get_int32_class (), &val);
1647 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error)
1649 int system_level;
1650 int system_name;
1651 int ret;
1652 int val;
1653 socklen_t valsize=sizeof(val);
1654 struct linger linger;
1655 socklen_t lingersize=sizeof(linger);
1656 int time_ms = 0;
1657 socklen_t time_ms_size = sizeof (time_ms);
1658 #ifdef SO_PEERCRED
1659 struct ucred cred;
1660 socklen_t credsize = sizeof(cred);
1661 #endif
1662 MonoDomain *domain=mono_domain_get();
1663 MonoObject *obj;
1664 MonoClass *obj_class;
1665 MonoClassField *field;
1667 MONO_ARCH_SAVE_REGS;
1669 *error = 0;
1671 ret=convert_sockopt_level_and_name(level, name, &system_level,
1672 &system_name);
1673 if(ret==-1) {
1674 *error = WSAENOPROTOOPT;
1675 return;
1677 if (ret == -2) {
1678 *obj_val = int_to_object (domain, 0);
1679 return;
1682 /* No need to deal with MulticastOption names here, because
1683 * you cant getsockopt AddMembership or DropMembership (the
1684 * int getsockopt will error, causing an exception)
1686 switch(name) {
1687 case SocketOptionName_Linger:
1688 case SocketOptionName_DontLinger:
1689 ret = _wapi_getsockopt(sock, system_level, system_name, &linger,
1690 &lingersize);
1691 break;
1693 case SocketOptionName_SendTimeout:
1694 case SocketOptionName_ReceiveTimeout:
1695 ret = _wapi_getsockopt (sock, system_level, system_name, (char *) &time_ms, &time_ms_size);
1696 break;
1698 #ifdef SO_PEERCRED
1699 case SocketOptionName_PeerCred:
1700 ret = _wapi_getsockopt (sock, system_level, system_name, &cred,
1701 &credsize);
1702 break;
1703 #endif
1705 default:
1706 ret = _wapi_getsockopt (sock, system_level, system_name, &val,
1707 &valsize);
1710 if(ret==SOCKET_ERROR) {
1711 *error = WSAGetLastError ();
1712 return;
1715 switch(name) {
1716 case SocketOptionName_Linger:
1717 /* build a System.Net.Sockets.LingerOption */
1718 obj_class=mono_class_from_name(system_assembly,
1719 "System.Net.Sockets",
1720 "LingerOption");
1721 obj=mono_object_new(domain, obj_class);
1723 /* Locate and set the fields "bool enabled" and "int
1724 * seconds"
1726 field=mono_class_get_field_from_name(obj_class, "enabled");
1727 *(guint8 *)(((char *)obj)+field->offset)=linger.l_onoff;
1729 field=mono_class_get_field_from_name(obj_class, "seconds");
1730 *(guint32 *)(((char *)obj)+field->offset)=linger.l_linger;
1732 break;
1734 case SocketOptionName_DontLinger:
1735 /* construct a bool int in val - true if linger is off */
1736 obj = int_to_object (domain, !linger.l_onoff);
1737 break;
1739 case SocketOptionName_SendTimeout:
1740 case SocketOptionName_ReceiveTimeout:
1741 obj = int_to_object (domain, time_ms);
1742 break;
1744 #ifdef SO_PEERCRED
1745 case SocketOptionName_PeerCred:
1747 /* build a Mono.Posix.PeerCred+PeerCredData if
1748 * possible
1750 static MonoImage *mono_posix_image = NULL;
1751 MonoPeerCredData *cred_data;
1753 if (mono_posix_image == NULL) {
1754 mono_posix_image=mono_image_loaded ("Mono.Posix");
1755 if (!mono_posix_image) {
1756 MonoAssembly *sa = mono_assembly_open ("Mono.Posix.dll", NULL);
1757 if (!sa) {
1758 *error = WSAENOPROTOOPT;
1759 return;
1760 } else {
1761 mono_posix_image = mono_assembly_get_image (sa);
1766 obj_class = mono_class_from_name(mono_posix_image,
1767 "Mono.Posix",
1768 "PeerCredData");
1769 obj = mono_object_new(domain, obj_class);
1770 cred_data = (MonoPeerCredData *)obj;
1771 cred_data->pid = cred.pid;
1772 cred_data->uid = cred.uid;
1773 cred_data->gid = cred.gid;
1774 break;
1776 #endif
1778 default:
1779 obj = int_to_object (domain, val);
1782 *obj_val=obj;
1785 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal(SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *error)
1787 int system_level;
1788 int system_name;
1789 int ret;
1790 guchar *buf;
1791 socklen_t valsize;
1793 MONO_ARCH_SAVE_REGS;
1795 *error = 0;
1797 ret=convert_sockopt_level_and_name(level, name, &system_level,
1798 &system_name);
1799 if(ret==-1) {
1800 *error = WSAENOPROTOOPT;
1801 return;
1803 if(ret==-2)
1804 return;
1806 valsize=mono_array_length(*byte_val);
1807 buf=mono_array_addr(*byte_val, guchar, 0);
1809 ret = _wapi_getsockopt (sock, system_level, system_name, buf, &valsize);
1810 if(ret==SOCKET_ERROR) {
1811 *error = WSAGetLastError ();
1815 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
1816 static struct in_addr ipaddress_to_struct_in_addr(MonoObject *ipaddr)
1818 struct in_addr inaddr;
1819 MonoClassField *field;
1821 field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Address");
1823 /* No idea why .net uses a 64bit type to hold a 32bit value...
1825 * Internal value of IPAddess is in little-endian order
1827 inaddr.s_addr=GUINT_FROM_LE ((guint32)*(guint64 *)(((char *)ipaddr)+field->offset));
1829 return(inaddr);
1831 #endif
1833 #ifdef AF_INET6
1834 static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
1836 struct in6_addr in6addr;
1837 MonoClassField *field;
1838 MonoArray *data;
1839 int i;
1841 field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Numbers");
1842 data=*(MonoArray **)(((char *)ipaddr) + field->offset);
1844 /* Solaris has only the 8 bit version. */
1845 #ifndef s6_addr16
1846 for(i=0; i<8; i++) {
1847 guint16 s = mono_array_get (data, guint16, i);
1848 in6addr.s6_addr[2 * i] = (s >> 8) & 0xff;
1849 in6addr.s6_addr[2 * i + 1] = s & 0xff;
1851 #else
1852 for(i=0; i<8; i++)
1853 in6addr.s6_addr16[i] = mono_array_get (data, guint16, i);
1854 #endif
1855 return(in6addr);
1857 #endif /* AF_INET6 */
1859 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)
1861 int system_level;
1862 int system_name;
1863 int ret;
1864 #ifdef AF_INET6
1865 int sol_ip;
1866 int sol_ipv6;
1868 *error = 0;
1870 #ifdef HAVE_SOL_IPV6
1871 sol_ipv6 = SOL_IPV6;
1872 #else
1874 struct protoent *pent;
1875 pent = getprotobyname ("ipv6");
1876 sol_ipv6 = (pent != NULL) ? pent->p_proto : 41;
1878 #endif
1880 #ifdef HAVE_SOL_IP
1881 sol_ip = SOL_IP;
1882 #else
1884 struct protoent *pent;
1885 pent = getprotobyname ("ip");
1886 sol_ip = (pent != NULL) ? pent->p_proto : 0;
1888 #endif
1889 #endif /* AF_INET6 */
1891 MONO_ARCH_SAVE_REGS;
1893 ret=convert_sockopt_level_and_name(level, name, &system_level,
1894 &system_name);
1895 if(ret==-1) {
1896 *error = WSAENOPROTOOPT;
1897 return;
1899 if(ret==-2){
1900 return;
1903 /* Only one of obj_val, byte_val or int_val has data */
1904 if(obj_val!=NULL) {
1905 MonoClassField *field;
1906 struct linger linger;
1907 int valsize;
1909 switch(name) {
1910 case SocketOptionName_DontLinger:
1911 linger.l_onoff=0;
1912 linger.l_linger=0;
1913 valsize=sizeof(linger);
1914 ret = _wapi_setsockopt (sock, system_level,
1915 system_name, &linger, valsize);
1916 break;
1918 case SocketOptionName_Linger:
1919 /* Dig out "bool enabled" and "int seconds"
1920 * fields
1922 field=mono_class_get_field_from_name(obj_val->vtable->klass, "enabled");
1923 linger.l_onoff=*(guint8 *)(((char *)obj_val)+field->offset);
1924 field=mono_class_get_field_from_name(obj_val->vtable->klass, "seconds");
1925 linger.l_linger=*(guint32 *)(((char *)obj_val)+field->offset);
1927 valsize=sizeof(linger);
1928 ret = _wapi_setsockopt (sock, system_level,
1929 system_name, &linger, valsize);
1930 break;
1931 case SocketOptionName_AddMembership:
1932 case SocketOptionName_DropMembership:
1933 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
1935 MonoObject *address = NULL;
1937 #ifdef AF_INET6
1938 if(system_level == sol_ipv6) {
1939 struct ipv6_mreq mreq6;
1942 * Get group address
1944 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
1945 address = *(gpointer *)(((char *)obj_val) + field->offset);
1947 if(address) {
1948 mreq6.ipv6mr_multiaddr = ipaddress_to_struct_in6_addr (address);
1951 field=mono_class_get_field_from_name(obj_val->vtable->klass, "ifIndex");
1952 mreq6.ipv6mr_interface =*(guint64 *)(((char *)obj_val)+field->offset);
1954 ret = _wapi_setsockopt (sock, system_level,
1955 system_name, &mreq6,
1956 sizeof (mreq6));
1957 } else if(system_level == sol_ip)
1958 #endif /* AF_INET6 */
1960 #ifdef HAVE_STRUCT_IP_MREQN
1961 struct ip_mreqn mreq = {{0}};
1962 #else
1963 struct ip_mreq mreq = {{0}};
1964 #endif /* HAVE_STRUCT_IP_MREQN */
1966 /* pain! MulticastOption holds two IPAddress
1967 * members, so I have to dig the value out of
1968 * those :-(
1970 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
1971 address = *(gpointer *)(((char *)obj_val) + field->offset);
1973 /* address might not be defined and if so, set the address to ADDR_ANY.
1975 if(address) {
1976 mreq.imr_multiaddr = ipaddress_to_struct_in_addr (address);
1979 field = mono_class_get_field_from_name (obj_val->vtable->klass, "local");
1980 address = *(gpointer *)(((char *)obj_val) + field->offset);
1982 #ifdef HAVE_STRUCT_IP_MREQN
1983 if(address) {
1984 mreq.imr_address = ipaddress_to_struct_in_addr (address);
1986 #else
1987 if(address) {
1988 mreq.imr_interface = ipaddress_to_struct_in_addr (address);
1990 #endif /* HAVE_STRUCT_IP_MREQN */
1992 ret = _wapi_setsockopt (sock, system_level,
1993 system_name, &mreq,
1994 sizeof (mreq));
1996 break;
1998 #endif /* HAVE_STRUCT_IP_MREQN || HAVE_STRUCT_IP_MREQ */
1999 default:
2000 /* Cause an exception to be thrown */
2001 *error = WSAEINVAL;
2002 return;
2004 } else if (byte_val!=NULL) {
2005 int valsize=mono_array_length(byte_val);
2006 guchar *buf=mono_array_addr(byte_val, guchar, 0);
2008 ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
2009 if(ret==SOCKET_ERROR) {
2010 *error = WSAGetLastError ();
2011 return;
2013 } else {
2014 /* ReceiveTimeout/SendTimeout get here */
2015 switch(name) {
2016 case SocketOptionName_DontFragment:
2017 #ifdef HAVE_IP_MTU_DISCOVER
2018 /* Fiddle with the value slightly if we're
2019 * turning DF on
2021 if (int_val == 1) {
2022 int_val = IP_PMTUDISC_DO;
2024 /* Fall through */
2025 #endif
2027 default:
2028 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2032 if(ret==SOCKET_ERROR) {
2033 *error = WSAGetLastError ();
2037 void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock,
2038 gint32 how,
2039 gint32 *error)
2041 int ret;
2043 MONO_ARCH_SAVE_REGS;
2045 *error = 0;
2047 /* Currently, the values for how (recv=0, send=1, both=2) match
2048 * the BSD API
2050 ret = _wapi_shutdown (sock, how);
2051 if(ret==SOCKET_ERROR) {
2052 *error = WSAGetLastError ();
2056 gint
2057 ves_icall_System_Net_Sockets_Socket_WSAIoctl (SOCKET sock, gint32 code,
2058 MonoArray *input,
2059 MonoArray *output, gint32 *error)
2061 glong output_bytes = 0;
2062 gchar *i_buffer, *o_buffer;
2063 gint i_len, o_len;
2064 gint ret;
2066 MONO_ARCH_SAVE_REGS;
2068 *error = 0;
2070 if (code == FIONBIO) {
2071 /* Invalid command. Must use Socket.Blocking */
2072 return -1;
2075 if (input == NULL) {
2076 i_buffer = NULL;
2077 i_len = 0;
2078 } else {
2079 i_buffer = mono_array_addr (input, gchar, 0);
2080 i_len = mono_array_length (input);
2083 if (output == NULL) {
2084 o_buffer = NULL;
2085 o_len = 0;
2086 } else {
2087 o_buffer = mono_array_addr (output, gchar, 0);
2088 o_len = mono_array_length (output);
2091 ret = WSAIoctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes, NULL, NULL);
2092 if (ret == SOCKET_ERROR) {
2093 *error = WSAGetLastError ();
2094 return(-1);
2097 return (gint) output_bytes;
2100 #ifdef HAVE_SIOCGIFCONF
2101 static gboolean
2102 is_loopback (int family, void *ad)
2104 char *ptr = (char *) ad;
2106 if (family == AF_INET) {
2107 return (ptr [0] == 127);
2109 #ifdef AF_INET6
2110 else {
2111 return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
2113 #endif
2114 return FALSE;
2117 static void *
2118 get_local_ips (int family, int *nips)
2120 int addr_size, offset, fd, i, count;
2121 int max_ifaces = 50; /* 50 interfaces should be enough... */
2122 struct ifconf ifc;
2123 struct ifreq *ifr;
2124 struct ifreq iflags;
2125 char *result, *tmp_ptr;
2126 gboolean ignore_loopback = FALSE;
2128 *nips = 0;
2129 if (family == AF_INET) {
2130 addr_size = sizeof (struct in_addr);
2131 offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
2132 #ifdef AF_INET6
2133 } else if (family == AF_INET6) {
2134 addr_size = sizeof (struct in6_addr);
2135 offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
2136 #endif
2137 } else {
2138 return NULL;
2141 fd = socket (family, SOCK_STREAM, 0);
2143 ifc.ifc_len = max_ifaces * sizeof (struct ifreq);
2144 ifc.ifc_buf = g_malloc (ifc.ifc_len);
2145 if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) {
2146 close (fd);
2147 g_free (ifc.ifc_buf);
2148 return NULL;
2151 count = ifc.ifc_len / sizeof (struct ifreq);
2152 *nips = count;
2153 if (count == 0) {
2154 g_free (ifc.ifc_buf);
2155 close (fd);
2156 return NULL;
2159 for (i = 0, ifr = ifc.ifc_req; i < *nips; i++, ifr++) {
2160 strcpy (iflags.ifr_name, ifr->ifr_name);
2161 if (ioctl (fd, SIOCGIFFLAGS, &iflags) < 0) {
2162 continue;
2165 if ((iflags.ifr_flags & IFF_UP) == 0) {
2166 ifr->ifr_name [0] = '\0';
2167 continue;
2170 if ((iflags.ifr_flags & IFF_LOOPBACK) == 0) {
2171 ignore_loopback = TRUE;
2175 close (fd);
2176 result = g_malloc (addr_size * count);
2177 tmp_ptr = result;
2178 for (i = 0, ifr = ifc.ifc_req; i < count; i++, ifr++) {
2179 if (ifr->ifr_name [0] == '\0') {
2180 (*nips)--;
2181 continue;
2184 if (ignore_loopback && is_loopback (family, ((char *) &ifr->ifr_addr) + offset)) {
2185 (*nips)--;
2186 continue;
2189 memcpy (tmp_ptr, ((char *) &ifr->ifr_addr) + offset, addr_size);
2190 tmp_ptr += addr_size;
2193 g_free (ifc.ifc_buf);
2194 return result;
2196 #else
2197 static void *
2198 get_local_ips (int family, int *nips)
2200 *nips = 0;
2201 return NULL;
2204 #endif /* HAVE_SIOCGIFCONF */
2206 #ifndef AF_INET6
2207 static gboolean hostent_to_IPHostEntry(struct hostent *he, MonoString **h_name,
2208 MonoArray **h_aliases,
2209 MonoArray **h_addr_list,
2210 gboolean add_local_ips)
2212 MonoDomain *domain = mono_domain_get ();
2213 int i;
2214 struct in_addr *local_in = NULL;
2215 int nlocal_in = 0;
2217 if(he->h_length!=4 || he->h_addrtype!=AF_INET) {
2218 return(FALSE);
2221 *h_name=mono_string_new(domain, he->h_name);
2223 i=0;
2224 while(he->h_aliases[i]!=NULL) {
2225 i++;
2228 *h_aliases=mono_array_new(domain, mono_get_string_class (), i);
2229 i=0;
2230 while(he->h_aliases[i]!=NULL) {
2231 MonoString *alias;
2233 alias=mono_string_new(domain, he->h_aliases[i]);
2234 mono_array_setref (*h_aliases, i, alias);
2235 i++;
2238 if (add_local_ips) {
2239 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2240 if (nlocal_in) {
2241 *h_addr_list = mono_array_new(domain, mono_get_string_class (), nlocal_in);
2242 for (i = 0; i < nlocal_in; i++) {
2243 MonoString *addr_string;
2244 char addr [16], *ptr;
2246 ptr = (char *) &local_in [i];
2247 g_snprintf(addr, 16, "%u.%u.%u.%u",
2248 (unsigned char) ptr [0],
2249 (unsigned char) ptr [1],
2250 (unsigned char) ptr [2],
2251 (unsigned char) ptr [3]);
2253 addr_string = mono_string_new (domain, addr);
2254 mono_array_setref (*h_addr_list, i, addr_string);
2255 i++;
2258 g_free (local_in);
2262 if (nlocal_in == 0) {
2263 i = 0;
2264 while (he->h_addr_list[i]!=NULL) {
2265 i++;
2268 *h_addr_list=mono_array_new(domain, mono_get_string_class (), i);
2269 i=0;
2270 while(he->h_addr_list[i]!=NULL) {
2271 MonoString *addr_string;
2272 char addr[16];
2274 g_snprintf(addr, 16, "%u.%u.%u.%u",
2275 (unsigned char)he->h_addr_list[i][0],
2276 (unsigned char)he->h_addr_list[i][1],
2277 (unsigned char)he->h_addr_list[i][2],
2278 (unsigned char)he->h_addr_list[i][3]);
2280 addr_string=mono_string_new(domain, addr);
2281 mono_array_setref (*h_addr_list, i, addr_string);
2282 i++;
2286 return(TRUE);
2289 static gboolean ipaddr_to_IPHostEntry(const char *addr, MonoString **h_name,
2290 MonoArray **h_aliases,
2291 MonoArray **h_addr_list)
2293 MonoDomain *domain = mono_domain_get ();
2295 *h_name=mono_string_new(domain, addr);
2296 *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2297 *h_addr_list=mono_array_new(domain, mono_get_string_class (), 1);
2298 mono_array_setref (*h_addr_list, 0, *h_name);
2300 return(TRUE);
2302 #endif
2304 #if defined(AF_INET6) && defined(HAVE_GETHOSTBYNAME2_R)
2305 static gboolean hostent_to_IPHostEntry2(struct hostent *he1,struct hostent *he2, MonoString **h_name,
2306 MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
2308 MonoDomain *domain = mono_domain_get ();
2309 int i, host_count, host_index, family_hint;
2310 struct in_addr *local_in = NULL;
2311 int nlocal_in = 0;
2312 struct in6_addr *local_in6 = NULL;
2313 int nlocal_in6 = 0;
2314 gboolean from_local = FALSE;
2316 family_hint = get_family_hint ();
2318 if(he1 == NULL && he2 == NULL) {
2319 return(FALSE);
2323 * Check if address length and family are correct
2325 if (he1 != NULL && (he1->h_length!=4 || he1->h_addrtype!=AF_INET)) {
2326 return(FALSE);
2329 if (he2 != NULL && (he2->h_length!=16 || he2->h_addrtype!=AF_INET6)) {
2330 return(FALSE);
2334 * Get the aliases and host name from he1 or he2 whichever is
2335 * not null, if he1 is not null then take aliases from he1
2337 if (he1 != NULL && (family_hint == PF_UNSPEC ||
2338 family_hint == PF_INET)) {
2339 *h_name=mono_string_new (domain, he1->h_name);
2341 i=0;
2342 while(he1->h_aliases[i]!=NULL) {
2343 i++;
2346 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2348 i=0;
2349 while(he1->h_aliases[i]!=NULL) {
2350 MonoString *alias;
2352 alias=mono_string_new (domain, he1->h_aliases[i]);
2353 mono_array_setref (*h_aliases, i, alias);
2354 i++;
2356 } else if (he2 != NULL && (family_hint == PF_UNSPEC ||
2357 family_hint == PF_INET6)) {
2358 *h_name=mono_string_new (domain, he2->h_name);
2360 i=0;
2361 while(he2->h_aliases [i] != NULL) {
2362 i++;
2365 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2367 i=0;
2368 while(he2->h_aliases[i]!=NULL) {
2369 MonoString *alias;
2371 alias=mono_string_new (domain, he2->h_aliases[i]);
2372 mono_array_setref (*h_aliases, i, alias);
2373 i++;
2375 } else {
2376 return(FALSE);
2380 * Count the number of addresses in he1 + he2
2382 host_count = 0;
2383 if (he1 != NULL && (family_hint == PF_UNSPEC ||
2384 family_hint == PF_INET)) {
2385 i=0;
2386 while(he1->h_addr_list[i]!=NULL) {
2387 i++;
2388 host_count++;
2392 if (he2 != NULL && (family_hint == PF_UNSPEC ||
2393 family_hint == PF_INET6)) {
2394 i=0;
2395 while(he2->h_addr_list[i]!=NULL) {
2396 i++;
2397 host_count++;
2402 * Fills the array
2404 host_index = 0;
2405 if (add_local_ips) {
2406 if (family_hint == PF_UNSPEC || family_hint == PF_INET)
2407 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2409 if (family_hint == PF_UNSPEC || family_hint == PF_INET6)
2410 local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2412 if (nlocal_in || nlocal_in6) {
2413 from_local = TRUE;
2414 *h_addr_list = mono_array_new (domain, mono_get_string_class (),
2415 nlocal_in + nlocal_in6);
2417 if (nlocal_in6) {
2418 int n;
2419 for (n = 0; n < nlocal_in6; n++) {
2420 MonoString *addr_string;
2421 const char *ret;
2422 char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes with the trailing NULL */
2424 ret = inet_ntop (AF_INET6, &local_in6 [n], addr, sizeof(addr));
2426 if (ret != NULL) {
2427 addr_string = mono_string_new (domain, addr);
2428 mono_array_setref (*h_addr_list, host_index, addr_string);
2429 host_index++;
2434 if (nlocal_in) {
2435 int n;
2436 for (n = 0; n < nlocal_in; n++) {
2437 MonoString *addr_string;
2438 const char *ret;
2439 char addr[16]; /* INET_ADDRSTRLEN == 16 */
2441 ret = inet_ntop (AF_INET, &local_in [n], addr, sizeof(addr));
2443 if (ret != NULL) {
2444 addr_string = mono_string_new (domain, addr);
2445 mono_array_setref (*h_addr_list, host_index, addr_string);
2446 host_index++;
2450 g_free (local_in);
2451 g_free (local_in6);
2452 return TRUE;
2455 g_free (local_in);
2456 g_free (local_in6);
2459 *h_addr_list=mono_array_new (domain, mono_get_string_class (), host_count);
2461 if (he2 != NULL && (family_hint == PF_UNSPEC ||
2462 family_hint == PF_INET6)) {
2463 i = 0;
2464 while(he2->h_addr_list[i] != NULL) {
2465 MonoString *addr_string;
2466 const char *ret;
2467 char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes long with the trailing NULL */
2469 ret = inet_ntop (AF_INET6, he2->h_addr_list[i], addr,
2470 sizeof(addr));
2472 if (ret != NULL) {
2473 addr_string = mono_string_new (domain, addr);
2474 mono_array_setref (*h_addr_list, host_index, addr_string);
2475 i++;
2476 host_index++;
2481 if (he1 != NULL && (family_hint == PF_UNSPEC ||
2482 family_hint == PF_INET)) {
2483 i=0;
2484 while(he1->h_addr_list[i] != NULL) {
2485 MonoString *addr_string;
2486 const char *ret;
2487 char addr[16]; /* INET_ADDRSTRLEN == 16 */
2489 ret = inet_ntop (AF_INET, he1->h_addr_list[i], addr,
2490 sizeof(addr));
2492 if (ret != NULL) {
2493 addr_string=mono_string_new (domain, addr);
2494 mono_array_setref (*h_addr_list, host_index, addr_string);
2495 i++;
2496 host_index++;
2501 return(TRUE);
2503 #endif
2505 #if defined(AF_INET6)
2506 static gboolean
2507 addrinfo_to_IPHostEntry(struct addrinfo *info, MonoString **h_name,
2508 MonoArray **h_aliases,
2509 MonoArray **h_addr_list,
2510 gboolean add_local_ips)
2512 gint32 count, i;
2513 struct addrinfo *ai = NULL;
2514 struct in_addr *local_in = NULL;
2515 int nlocal_in = 0;
2516 struct in6_addr *local_in6 = NULL;
2517 int nlocal_in6 = 0;
2518 int addr_index;
2520 MonoDomain *domain = mono_domain_get ();
2522 addr_index = 0;
2523 *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2524 if (add_local_ips) {
2525 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2526 local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2527 if (nlocal_in || nlocal_in6) {
2528 *h_addr_list=mono_array_new(domain, mono_get_string_class (), nlocal_in + nlocal_in6);
2529 if (nlocal_in) {
2530 MonoString *addr_string;
2531 char addr [16];
2532 int i;
2534 for (i = 0; i < nlocal_in; i++) {
2535 inet_ntop (AF_INET, &local_in [i], addr, sizeof (addr));
2536 addr_string = mono_string_new (domain, addr);
2537 mono_array_setref (*h_addr_list, addr_index, addr_string);
2538 addr_index++;
2542 if (nlocal_in6) {
2543 MonoString *addr_string;
2544 const char *ret;
2545 char addr [48];
2546 int i;
2548 for (i = 0; i < nlocal_in6; i++) {
2549 ret = inet_ntop (AF_INET6, &local_in6 [i], addr, sizeof (addr));
2550 if (ret != NULL) {
2551 addr_string = mono_string_new (domain, addr);
2552 mono_array_setref (*h_addr_list, addr_index, addr_string);
2553 addr_index++;
2558 g_free (local_in);
2559 g_free (local_in6);
2560 if (info) {
2561 freeaddrinfo (info);
2563 return TRUE;
2566 g_free (local_in);
2567 g_free (local_in6);
2570 for (count=0, ai=info; ai!=NULL; ai=ai->ai_next) {
2571 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2572 continue;
2574 count++;
2577 *h_addr_list=mono_array_new(domain, mono_get_string_class (), count);
2579 for (ai=info, i=0; ai!=NULL; ai=ai->ai_next) {
2580 MonoString *addr_string;
2581 const char *ret;
2582 char buffer [48]; /* Max. size for IPv6 */
2584 if((ai->ai_family != PF_INET) && (ai->ai_family != PF_INET6)) {
2585 continue;
2588 if(ai->ai_family == PF_INET) {
2589 ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr), buffer, 16);
2590 } else {
2591 ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in6*)ai->ai_addr)->sin6_addr), buffer, 48);
2594 if(ret) {
2595 addr_string=mono_string_new(domain, buffer);
2596 } else {
2597 addr_string=mono_string_new(domain, "");
2600 mono_array_setref (*h_addr_list, addr_index, addr_string);
2602 if(!i && ai->ai_canonname != NULL) {
2603 *h_name=mono_string_new(domain, ai->ai_canonname);
2606 addr_index++;
2609 if(info) {
2610 freeaddrinfo(info);
2613 return(TRUE);
2615 #endif
2617 #ifdef AF_INET6
2618 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2620 gboolean add_local_ips = FALSE;
2621 #ifdef HAVE_SIOCGIFCONF
2622 gchar this_hostname [256];
2623 #endif
2624 #if !defined(HAVE_GETHOSTBYNAME2_R)
2625 struct addrinfo *info = NULL, hints;
2626 char *hostname;
2628 MONO_ARCH_SAVE_REGS;
2630 hostname=mono_string_to_utf8 (host);
2631 #ifdef HAVE_SIOCGIFCONF
2632 if (gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2633 if (!strcmp (hostname, this_hostname))
2634 add_local_ips = TRUE;
2636 #endif
2638 memset(&hints, 0, sizeof(hints));
2639 hints.ai_family = get_family_hint ();
2640 hints.ai_socktype = SOCK_STREAM;
2641 hints.ai_flags = AI_CANONNAME;
2643 if (getaddrinfo(hostname, NULL, &hints, &info) == -1) {
2644 return(FALSE);
2647 g_free(hostname);
2649 return(addrinfo_to_IPHostEntry(info, h_name, h_aliases, h_addr_list, add_local_ips));
2650 #else
2651 struct hostent he1,*hp1, he2, *hp2;
2652 int buffer_size1, buffer_size2;
2653 char *buffer1, *buffer2;
2654 int herr;
2655 gboolean return_value;
2656 char *hostname;
2658 MONO_ARCH_SAVE_REGS;
2660 hostname=mono_string_to_utf8 (host);
2662 #ifdef HAVE_SIOCGIFCONF
2663 if (gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2664 if (!strcmp (hostname, this_hostname))
2665 add_local_ips = TRUE;
2667 #endif
2669 buffer_size1 = 512;
2670 buffer_size2 = 512;
2671 buffer1 = g_malloc0(buffer_size1);
2672 buffer2 = g_malloc0(buffer_size2);
2674 while (gethostbyname2_r(hostname, AF_INET, &he1, buffer1, buffer_size1,
2675 &hp1, &herr) == ERANGE) {
2676 buffer_size1 *= 2;
2677 buffer1 = g_realloc(buffer1, buffer_size1);
2680 if (hp1 == NULL)
2682 while (gethostbyname2_r(hostname, AF_INET6, &he2, buffer2,
2683 buffer_size2, &hp2, &herr) == ERANGE) {
2684 buffer_size2 *= 2;
2685 buffer2 = g_realloc(buffer2, buffer_size2);
2688 else
2689 hp2 = NULL;
2691 return_value = hostent_to_IPHostEntry2(hp1, hp2, h_name, h_aliases,
2692 h_addr_list, add_local_ips);
2694 g_free(buffer1);
2695 g_free(buffer2);
2696 g_free(hostname);
2698 return(return_value);
2699 #endif /* HAVE_GETHOSTBYNAME2_R */
2701 #else /* AF_INET6 */
2702 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2704 struct hostent *he;
2705 char *hostname;
2706 gboolean add_local_ips = FALSE;
2707 #ifdef HAVE_SIOCGIFCONF
2708 gchar this_hostname [256];
2709 #endif
2711 MONO_ARCH_SAVE_REGS;
2713 hostname=mono_string_to_utf8(host);
2714 #ifdef HAVE_SIOCGIFCONF
2715 if (gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2716 if (!strcmp (hostname, this_hostname))
2717 add_local_ips = TRUE;
2719 #endif
2721 he = _wapi_gethostbyname (hostname);
2722 g_free(hostname);
2724 if(he==NULL) {
2725 return(FALSE);
2728 return(hostent_to_IPHostEntry(he, h_name, h_aliases, h_addr_list, add_local_ips));
2730 #endif /* AF_INET6 */
2732 #ifndef HAVE_INET_PTON
2733 static int
2734 inet_pton (int family, const char *address, void *inaddrp)
2736 if (family == AF_INET) {
2737 #ifdef HAVE_INET_ATON
2738 struct in_addr inaddr;
2740 if (!inet_aton (address, &inaddr))
2741 return 0;
2743 memcpy (inaddrp, &inaddr, sizeof (struct in_addr));
2744 return 1;
2745 #else
2746 /* assume the system has inet_addr(), if it doesn't
2747 have that we're pretty much screwed... */
2748 guint32 inaddr;
2750 if (!strcmp (address, "255.255.255.255")) {
2751 /* special-case hack */
2752 inaddr = 0xffffffff;
2753 } else {
2754 inaddr = inet_addr (address);
2755 #ifndef INADDR_NONE
2756 #define INADDR_NONE ((in_addr_t) -1)
2757 #endif
2758 if (inaddr == INADDR_NONE)
2759 return 0;
2762 memcpy (inaddrp, &inaddr, sizeof (guint32));
2763 return 1;
2764 #endif /* HAVE_INET_ATON */
2767 return -1;
2769 #endif /* !HAVE_INET_PTON */
2771 extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2773 char *address;
2774 const char *version;
2775 gboolean v1;
2777 #ifdef AF_INET6
2778 struct sockaddr_in saddr;
2779 struct sockaddr_in6 saddr6;
2780 struct addrinfo *info = NULL, hints;
2781 gint32 family;
2782 char hostname[1024] = {0};
2783 int flags = 0;
2784 #else
2785 struct in_addr inaddr;
2786 struct hostent *he;
2787 gboolean ret;
2788 #endif
2790 MONO_ARCH_SAVE_REGS;
2792 version = mono_get_runtime_info ()->framework_version;
2793 v1 = (version[0] == '1');
2795 address = mono_string_to_utf8 (addr);
2797 #ifdef AF_INET6
2798 if (inet_pton (AF_INET, address, &saddr.sin_addr ) <= 0) {
2799 /* Maybe an ipv6 address */
2800 if (inet_pton (AF_INET6, address, &saddr6.sin6_addr) <= 0) {
2801 g_free (address);
2802 return FALSE;
2804 else {
2805 family = AF_INET6;
2806 saddr6.sin6_family = AF_INET6;
2809 else {
2810 family = AF_INET;
2811 saddr.sin_family = AF_INET;
2813 g_free(address);
2815 if (v1) {
2816 flags = NI_NAMEREQD;
2819 if(family == AF_INET) {
2820 if(getnameinfo ((struct sockaddr*)&saddr, sizeof(saddr),
2821 hostname, sizeof(hostname), NULL, 0,
2822 flags) != 0) {
2823 return(FALSE);
2825 } else if(family == AF_INET6) {
2826 if(getnameinfo ((struct sockaddr*)&saddr6, sizeof(saddr6),
2827 hostname, sizeof(hostname), NULL, 0,
2828 flags) != 0) {
2829 return(FALSE);
2833 memset (&hints, 0, sizeof(hints));
2834 hints.ai_family = get_family_hint ();
2835 hints.ai_socktype = SOCK_STREAM;
2836 hints.ai_flags = AI_CANONNAME;
2838 if( getaddrinfo (hostname, NULL, &hints, &info) == -1 ) {
2839 return(FALSE);
2842 return(addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE));
2843 #else
2844 if (inet_pton (AF_INET, address, &inaddr) <= 0) {
2845 g_free (address);
2846 return(FALSE);
2849 if ((he = gethostbyaddr ((char *) &inaddr, sizeof (inaddr), AF_INET)) == NULL) {
2850 if (v1) {
2851 ret = FALSE;
2852 } else {
2853 ret = ipaddr_to_IPHostEntry (address, h_name,
2854 h_aliases, h_addr_list);
2856 } else {
2857 ret = hostent_to_IPHostEntry (he, h_name, h_aliases,
2858 h_addr_list, FALSE);
2861 g_free (address);
2862 return(ret);
2863 #endif
2866 extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name)
2868 gchar hostname[256];
2869 int ret;
2871 MONO_ARCH_SAVE_REGS;
2873 ret = gethostname (hostname, sizeof (hostname));
2874 if(ret==-1) {
2875 return(FALSE);
2878 *h_name=mono_string_new(mono_domain_get (), hostname);
2880 return(TRUE);
2883 void mono_network_init(void)
2885 WSADATA wsadata;
2886 int err;
2888 err=WSAStartup(MAKEWORD(2,0), &wsadata);
2889 if(err!=0) {
2890 g_error(G_GNUC_PRETTY_FUNCTION ": Couldn't initialise networking");
2891 exit(-1);
2894 #ifdef DEBUG
2895 g_message(G_GNUC_PRETTY_FUNCTION ": Using socket library: %s", wsadata.szDescription);
2896 g_message(G_GNUC_PRETTY_FUNCTION ": Socket system status: %s", wsadata.szSystemStatus);
2897 #endif
2900 void mono_network_cleanup(void)
2902 WSACleanup();