2 * socket-io.c: Socket IO internal calls
5 * Dick Porter (dick@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11 * This file has been re-licensed under the MIT License:
12 * http://opensource.org/licenses/MIT
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
18 #ifndef DISABLE_SOCKETS
20 #if defined(__APPLE__) || defined(__FreeBSD__)
21 #define __APPLE_USE_RFC_3542
30 #include <sys/socket.h>
31 #ifdef HAVE_SYS_IOCTL_H
32 #include <sys/ioctl.h>
34 #include <netinet/in.h>
35 #include <netinet/tcp.h>
39 #include <arpa/inet.h>
46 #include <sys/types.h>
48 #include <mono/metadata/object.h>
49 #include <mono/io-layer/io-layer.h>
50 #include <mono/metadata/socket-io.h>
51 #include <mono/metadata/exception.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/appdomain.h>
54 #include <mono/metadata/file-io.h>
55 #include <mono/metadata/threads.h>
56 #include <mono/metadata/threads-types.h>
57 #include <mono/metadata/threadpool-ms-io.h>
58 #include <mono/utils/mono-poll.h>
59 /* FIXME change this code to not mess so much with the internals */
60 #include <mono/metadata/class-internals.h>
61 #include <mono/metadata/domain-internals.h>
62 #include <mono/utils/mono-threads.h>
63 #include <mono/utils/mono-memory-model.h>
64 #include <mono/utils/networking.h>
67 #ifdef HAVE_SYS_TIME_H
70 #ifdef HAVE_SYS_IOCTL_H
71 #include <sys/ioctl.h>
80 #ifdef HAVE_SYS_FILIO_H
81 #include <sys/filio.h> /* defines FIONBIO and FIONREAD */
83 #ifdef HAVE_SYS_SOCKIO_H
84 #include <sys/sockio.h> /* defines SIOCATMARK */
90 #ifdef HAVE_GETIFADDRS
91 // <net/if.h> must be included before <ifaddrs.h>
95 #include "mono/io-layer/socket-wrappers.h"
98 /* define LOGDEBUG(...) g_message(__VA_ARGS__) */
101 abort_syscall (gpointer data)
103 mono_thread_info_abort_socket_syscall_for_close ((MonoNativeThreadId) (gsize) data);
107 convert_family (MonoAddressFamily mono_family)
109 switch (mono_family) {
110 case AddressFamily_Unknown:
111 case AddressFamily_ImpLink:
112 case AddressFamily_Pup:
113 case AddressFamily_Chaos:
114 case AddressFamily_Iso:
115 case AddressFamily_Ecma:
116 case AddressFamily_DataKit:
117 case AddressFamily_Ccitt:
118 case AddressFamily_DataLink:
119 case AddressFamily_Lat:
120 case AddressFamily_HyperChannel:
121 case AddressFamily_NetBios:
122 case AddressFamily_VoiceView:
123 case AddressFamily_FireFox:
124 case AddressFamily_Banyan:
125 case AddressFamily_Atm:
126 case AddressFamily_Cluster:
127 case AddressFamily_Ieee12844:
128 case AddressFamily_NetworkDesigners:
129 g_warning ("System.Net.Sockets.AddressFamily has unsupported value 0x%x", mono_family);
131 case AddressFamily_Unspecified:
133 case AddressFamily_Unix:
135 case AddressFamily_InterNetwork:
137 case AddressFamily_AppleTalk:
139 case AddressFamily_InterNetworkV6:
141 case AddressFamily_DecNet:
147 case AddressFamily_Ipx:
153 case AddressFamily_Sna:
159 case AddressFamily_Irda:
166 g_warning ("System.Net.Sockets.AddressFamily has unknown value 0x%x", mono_family);
171 static MonoAddressFamily
172 convert_to_mono_family (guint16 af_family)
176 return AddressFamily_Unspecified;
178 return AddressFamily_Unix;
180 return AddressFamily_InterNetwork;
183 return AddressFamily_Ipx;
187 return AddressFamily_Sna;
191 return AddressFamily_DecNet;
194 return AddressFamily_AppleTalk;
196 return AddressFamily_InterNetworkV6;
199 return AddressFamily_Irda;
202 g_warning ("unknown address family 0x%x", af_family);
203 return AddressFamily_Unknown;
208 convert_type (MonoSocketType mono_type)
211 case SocketType_Stream:
213 case SocketType_Dgram:
223 case SocketType_Seqpacket:
224 return SOCK_SEQPACKET;
225 case SocketType_Unknown:
226 g_warning ("System.Net.Sockets.SocketType has unsupported value 0x%x", mono_type);
229 g_warning ("System.Net.Sockets.SocketType has unknown value 0x%x", mono_type);
235 convert_proto (MonoProtocolType mono_proto)
237 switch (mono_proto) {
238 case ProtocolType_IP:
239 case ProtocolType_IPv6:
240 case ProtocolType_Icmp:
241 case ProtocolType_Igmp:
242 case ProtocolType_Ggp:
243 case ProtocolType_Tcp:
244 case ProtocolType_Pup:
245 case ProtocolType_Udp:
246 case ProtocolType_Idp:
247 /* These protocols are known (on my system at least) */
249 case ProtocolType_ND:
250 case ProtocolType_Raw:
251 case ProtocolType_Ipx:
252 case ProtocolType_Spx:
253 case ProtocolType_SpxII:
254 case ProtocolType_Unknown:
255 /* These protocols arent */
256 g_warning ("System.Net.Sockets.ProtocolType has unsupported value 0x%x", mono_proto);
263 /* Convert MonoSocketFlags */
265 convert_socketflags (gint32 sflags)
270 /* SocketFlags.None */
273 if (sflags & ~(SocketFlags_OutOfBand | SocketFlags_MaxIOVectorLength | SocketFlags_Peek |
274 SocketFlags_DontRoute | SocketFlags_Partial))
275 /* Contains invalid flag values */
278 if (sflags & SocketFlags_OutOfBand)
280 if (sflags & SocketFlags_Peek)
282 if (sflags & SocketFlags_DontRoute)
283 flags |= MSG_DONTROUTE;
285 /* Ignore Partial - see bug 349688. Don't return -1, because
286 * according to the comment in that bug ms runtime doesn't for
287 * UDP sockets (this means we will silently ignore it for TCP
291 if (sflags & SocketFlags_Partial)
295 /* Don't do anything for MaxIOVectorLength */
296 if (sflags & SocketFlags_MaxIOVectorLength)
304 * 0 on success (mapped mono_level and mono_name to system_level and system_name
306 * -2 on non-fatal error (ie, must ignore)
309 convert_sockopt_level_and_name (MonoSocketOptionLevel mono_level, MonoSocketOptionName mono_name, int *system_level, int *system_name)
311 switch (mono_level) {
312 case SocketOptionLevel_Socket:
313 *system_level = SOL_SOCKET;
316 case SocketOptionName_DontLinger:
317 /* This is SO_LINGER, because the setsockopt
318 * internal call maps DontLinger to SO_LINGER
321 *system_name = SO_LINGER;
323 case SocketOptionName_Debug:
324 *system_name = SO_DEBUG;
327 case SocketOptionName_AcceptConnection:
328 *system_name = SO_ACCEPTCONN;
331 case SocketOptionName_ReuseAddress:
332 *system_name = SO_REUSEADDR;
334 case SocketOptionName_KeepAlive:
335 *system_name = SO_KEEPALIVE;
337 case SocketOptionName_DontRoute:
338 *system_name = SO_DONTROUTE;
340 case SocketOptionName_Broadcast:
341 *system_name = SO_BROADCAST;
343 case SocketOptionName_Linger:
344 *system_name = SO_LINGER;
346 case SocketOptionName_OutOfBandInline:
347 *system_name = SO_OOBINLINE;
349 case SocketOptionName_SendBuffer:
350 *system_name = SO_SNDBUF;
352 case SocketOptionName_ReceiveBuffer:
353 *system_name = SO_RCVBUF;
355 case SocketOptionName_SendLowWater:
356 *system_name = SO_SNDLOWAT;
358 case SocketOptionName_ReceiveLowWater:
359 *system_name = SO_RCVLOWAT;
361 case SocketOptionName_SendTimeout:
362 *system_name = SO_SNDTIMEO;
364 case SocketOptionName_ReceiveTimeout:
365 *system_name = SO_RCVTIMEO;
367 case SocketOptionName_Error:
368 *system_name = SO_ERROR;
370 case SocketOptionName_Type:
371 *system_name = SO_TYPE;
374 case SocketOptionName_PeerCred:
375 *system_name = SO_PEERCRED;
378 case SocketOptionName_ExclusiveAddressUse:
379 #ifdef SO_EXCLUSIVEADDRUSE
380 *system_name = SO_EXCLUSIVEADDRUSE;
383 case SocketOptionName_UseLoopback:
384 #ifdef SO_USELOOPBACK
385 *system_name = SO_USELOOPBACK;
388 case SocketOptionName_MaxConnections:
390 *system_name = SO_MAXCONN;
392 #elif defined(SOMAXCONN)
393 *system_name = SOMAXCONN;
397 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at Socket level", mono_name);
402 case SocketOptionLevel_IP:
403 *system_level = mono_networking_get_ip_protocol ();
406 case SocketOptionName_IPOptions:
407 *system_name = IP_OPTIONS;
410 case SocketOptionName_HeaderIncluded:
411 *system_name = IP_HDRINCL;
415 case SocketOptionName_TypeOfService:
416 *system_name = IP_TOS;
420 case SocketOptionName_IpTimeToLive:
421 *system_name = IP_TTL;
424 case SocketOptionName_MulticastInterface:
425 *system_name = IP_MULTICAST_IF;
427 case SocketOptionName_MulticastTimeToLive:
428 *system_name = IP_MULTICAST_TTL;
430 case SocketOptionName_MulticastLoopback:
431 *system_name = IP_MULTICAST_LOOP;
433 case SocketOptionName_AddMembership:
434 *system_name = IP_ADD_MEMBERSHIP;
436 case SocketOptionName_DropMembership:
437 *system_name = IP_DROP_MEMBERSHIP;
439 #ifdef HAVE_IP_PKTINFO
440 case SocketOptionName_PacketInformation:
441 *system_name = IP_PKTINFO;
443 #endif /* HAVE_IP_PKTINFO */
445 case SocketOptionName_DontFragment:
446 #ifdef HAVE_IP_DONTFRAGMENT
447 *system_name = IP_DONTFRAGMENT;
449 #elif defined HAVE_IP_MTU_DISCOVER
450 /* Not quite the same */
451 *system_name = IP_MTU_DISCOVER;
454 /* If the flag is not available on this system, we can ignore this error */
456 #endif /* HAVE_IP_DONTFRAGMENT */
457 case SocketOptionName_AddSourceMembership:
458 case SocketOptionName_DropSourceMembership:
459 case SocketOptionName_BlockSource:
460 case SocketOptionName_UnblockSource:
461 /* Can't figure out how to map these, so fall
465 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at IP level", mono_name);
470 case SocketOptionLevel_IPv6:
471 *system_level = mono_networking_get_ipv6_protocol ();
474 case SocketOptionName_IpTimeToLive:
475 case SocketOptionName_HopLimit:
476 *system_name = IPV6_UNICAST_HOPS;
478 case SocketOptionName_MulticastInterface:
479 *system_name = IPV6_MULTICAST_IF;
481 case SocketOptionName_MulticastTimeToLive:
482 *system_name = IPV6_MULTICAST_HOPS;
484 case SocketOptionName_MulticastLoopback:
485 *system_name = IPV6_MULTICAST_LOOP;
487 case SocketOptionName_AddMembership:
488 *system_name = IPV6_JOIN_GROUP;
490 case SocketOptionName_DropMembership:
491 *system_name = IPV6_LEAVE_GROUP;
493 case SocketOptionName_IPv6Only:
495 *system_name = IPV6_V6ONLY;
500 case SocketOptionName_PacketInformation:
501 #ifdef HAVE_IPV6_PKTINFO
502 *system_name = IPV6_PKTINFO;
505 case SocketOptionName_HeaderIncluded:
506 case SocketOptionName_IPOptions:
507 case SocketOptionName_TypeOfService:
508 case SocketOptionName_DontFragment:
509 case SocketOptionName_AddSourceMembership:
510 case SocketOptionName_DropSourceMembership:
511 case SocketOptionName_BlockSource:
512 case SocketOptionName_UnblockSource:
513 /* Can't figure out how to map these, so fall
517 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at IPv6 level", mono_name);
520 break; /* SocketOptionLevel_IPv6 */
522 case SocketOptionLevel_Tcp:
523 *system_level = mono_networking_get_tcp_protocol ();
526 case SocketOptionName_NoDelay:
527 *system_name = TCP_NODELAY;
530 /* The documentation is talking complete
531 * bollocks here: rfc-1222 is titled
532 * 'Advancing the NSFNET Routing Architecture'
533 * and doesn't mention either of the words
534 * "expedite" or "urgent".
536 case SocketOptionName_BsdUrgent:
537 case SocketOptionName_Expedited:
540 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at TCP level", mono_name);
545 case SocketOptionLevel_Udp:
546 g_warning ("System.Net.Sockets.SocketOptionLevel has unsupported value 0x%x", mono_level);
549 case SocketOptionName_NoChecksum:
550 case SocketOptionName_ChecksumCoverage:
552 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at UDP level", mono_name);
559 g_warning ("System.Net.Sockets.SocketOptionLevel has unknown value 0x%x", mono_level);
567 get_socket_assembly (void)
569 MonoDomain *domain = mono_domain_get ();
571 if (domain->socket_assembly == NULL) {
572 MonoImage *socket_assembly;
574 socket_assembly = mono_image_loaded ("System");
575 if (!socket_assembly) {
576 MonoAssembly *sa = mono_assembly_open ("System.dll", NULL);
579 g_assert_not_reached ();
581 socket_assembly = mono_assembly_get_image (sa);
584 mono_atomic_store_release (&domain->socket_assembly, socket_assembly);
587 return domain->socket_assembly;
591 get_family_hint (MonoError *error)
593 MonoDomain *domain = mono_domain_get ();
595 mono_error_init (error);
597 if (!domain->inet_family_hint) {
598 MonoImage *socket_assembly;
599 MonoClass *socket_class;
600 MonoClassField *ipv6_field, *ipv4_field;
601 gint32 ipv6_enabled = -1, ipv4_enabled = -1;
604 socket_assembly = get_socket_assembly ();
605 g_assert (socket_assembly);
607 socket_class = mono_class_load_from_name (socket_assembly, "System.Net.Sockets", "Socket");
609 ipv4_field = mono_class_get_field_from_name (socket_class, "ipv4_supported");
610 g_assert (ipv4_field);
612 ipv6_field = mono_class_get_field_from_name (socket_class, "ipv6_supported");
613 g_assert (ipv6_field);
615 vtable = mono_class_vtable (mono_domain_get (), socket_class);
618 mono_runtime_class_init_full (vtable, error);
619 return_val_if_nok (error, -1);
621 mono_field_static_get_value (vtable, ipv4_field, &ipv4_enabled);
622 mono_field_static_get_value (vtable, ipv6_field, &ipv6_enabled);
624 mono_domain_lock (domain);
625 if (ipv4_enabled == 1 && ipv6_enabled == 1) {
626 domain->inet_family_hint = 1;
627 } else if (ipv4_enabled == 1) {
628 domain->inet_family_hint = 2;
630 domain->inet_family_hint = 3;
632 mono_domain_unlock (domain);
634 switch (domain->inet_family_hint) {
635 case 1: return PF_UNSPEC;
636 case 2: return PF_INET;
637 case 3: return PF_INET6;
644 ves_icall_System_Net_Sockets_Socket_Socket_internal (MonoObject *this_obj, gint32 family, gint32 type, gint32 proto, gint32 *werror)
653 sock_family = convert_family ((MonoAddressFamily)family);
654 if (sock_family == -1) {
655 *werror = WSAEAFNOSUPPORT;
659 sock_proto = convert_proto ((MonoProtocolType)proto);
660 if (sock_proto == -1) {
661 *werror = WSAEPROTONOSUPPORT;
665 sock_type = convert_type ((MonoSocketType)type);
666 if (sock_type == -1) {
667 *werror = WSAESOCKTNOSUPPORT;
671 sock = _wapi_socket (sock_family, sock_type, sock_proto,
672 NULL, 0, WSA_FLAG_OVERLAPPED);
674 if (sock == INVALID_SOCKET) {
675 *werror = WSAGetLastError ();
679 return GUINT_TO_POINTER (sock);
682 /* FIXME: the SOCKET parameter (here and in other functions in this
683 * file) is really an IntPtr which needs to be converted to a guint32.
686 ves_icall_System_Net_Sockets_Socket_Close_internal (SOCKET sock, gint32 *werror)
688 LOGDEBUG (g_message ("%s: closing 0x%x", __func__, sock));
692 /* Clear any pending work item from this socket if the underlying
693 * polling system does not notify when the socket is closed */
694 mono_threadpool_ms_io_remove_socket (GPOINTER_TO_INT (sock));
696 MONO_PREPARE_BLOCKING;
698 MONO_FINISH_BLOCKING;
702 ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal (void)
704 LOGDEBUG (g_message("%s: returning %d", __func__, WSAGetLastError ()));
706 return WSAGetLastError ();
710 ves_icall_System_Net_Sockets_Socket_Available_internal (SOCKET sock, gint32 *werror)
717 /* FIXME: this might require amount to be unsigned long. */
718 ret = ioctlsocket (sock, FIONREAD, &amount);
719 if (ret == SOCKET_ERROR) {
720 *werror = WSAGetLastError ();
728 ves_icall_System_Net_Sockets_Socket_Blocking_internal (SOCKET sock, gboolean block, gint32 *werror)
735 * block == TRUE/FALSE means we will block/not block.
736 * But the ioctlsocket call takes TRUE/FALSE for non-block/block
740 ret = ioctlsocket (sock, FIONBIO, (gulong *)&block);
741 if (ret == SOCKET_ERROR)
742 *werror = WSAGetLastError ();
746 ves_icall_System_Net_Sockets_Socket_Accept_internal (SOCKET sock, gint32 *werror, gboolean blocking)
748 gboolean interrupted;
753 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
759 MONO_PREPARE_BLOCKING;
763 MonoInternalThread *curthread = mono_thread_internal_current ();
764 curthread->interrupt_on_stop = (gpointer)TRUE;
765 newsock = _wapi_accept (sock, NULL, 0);
766 curthread->interrupt_on_stop = (gpointer)FALSE;
769 newsock = _wapi_accept (sock, NULL, 0);
772 MONO_FINISH_BLOCKING;
774 mono_thread_info_uninstall_interrupt (&interrupted);
780 if (newsock == INVALID_SOCKET) {
781 *werror = WSAGetLastError ();
785 return GUINT_TO_POINTER (newsock);
789 ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock, guint32 backlog, gint32 *werror)
795 MONO_PREPARE_BLOCKING;
797 ret = _wapi_listen (sock, backlog);
799 MONO_FINISH_BLOCKING;
801 if (ret == SOCKET_ERROR)
802 *werror = WSAGetLastError ();
805 // Check whether it's ::ffff::0:0.
807 is_ipv4_mapped_any (const struct in6_addr *addr)
811 for (i = 0; i < 10; i++) {
812 if (addr->s6_addr [i])
815 if ((addr->s6_addr [10] != 0xff) || (addr->s6_addr [11] != 0xff))
817 for (i = 12; i < 16; i++) {
818 if (addr->s6_addr [i])
825 create_object_from_sockaddr (struct sockaddr *saddr, int sa_size, gint32 *werror, MonoError *error)
827 MonoDomain *domain = mono_domain_get ();
828 MonoObject *sockaddr_obj;
830 MonoAddressFamily family;
832 mono_error_init (error);
834 /* Build a System.Net.SocketAddress object instance */
835 if (!domain->sockaddr_class)
836 domain->sockaddr_class = mono_class_load_from_name (get_socket_assembly (), "System.Net", "SocketAddress");
837 sockaddr_obj = mono_object_new_checked (domain, domain->sockaddr_class, error);
838 return_val_if_nok (error, NULL);
840 /* Locate the SocketAddress data buffer in the object */
841 if (!domain->sockaddr_data_field) {
842 domain->sockaddr_data_field = mono_class_get_field_from_name (domain->sockaddr_class, "data");
843 g_assert (domain->sockaddr_data_field);
846 /* May be the +2 here is too conservative, as sa_len returns
847 * the length of the entire sockaddr_in/in6, including
848 * sizeof (unsigned short) of the family */
849 /* We can't really avoid the +2 as all code below depends on this size - INCLUDING unix domain sockets.*/
850 data = mono_array_new_cached (domain, mono_get_byte_class (), sa_size + 2);
852 /* The data buffer is laid out as follows:
853 * bytes 0 and 1 are the address family
854 * bytes 2 and 3 are the port info
855 * the rest is the address info
858 family = convert_to_mono_family (saddr->sa_family);
859 if (family == AddressFamily_Unknown) {
860 *werror = WSAEAFNOSUPPORT;
864 mono_array_set (data, guint8, 0, family & 0x0FF);
865 mono_array_set (data, guint8, 1, (family >> 8) & 0x0FF);
867 if (saddr->sa_family == AF_INET) {
868 struct sockaddr_in *sa_in = (struct sockaddr_in *)saddr;
869 guint16 port = ntohs (sa_in->sin_port);
870 guint32 address = ntohl (sa_in->sin_addr.s_addr);
873 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
877 mono_array_set (data, guint8, 2, (port>>8) & 0xff);
878 mono_array_set (data, guint8, 3, (port) & 0xff);
879 mono_array_set (data, guint8, 4, (address>>24) & 0xff);
880 mono_array_set (data, guint8, 5, (address>>16) & 0xff);
881 mono_array_set (data, guint8, 6, (address>>8) & 0xff);
882 mono_array_set (data, guint8, 7, (address) & 0xff);
884 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
887 } else if (saddr->sa_family == AF_INET6) {
888 struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)saddr;
891 guint16 port = ntohs (sa_in->sin6_port);
894 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
898 mono_array_set (data, guint8, 2, (port>>8) & 0xff);
899 mono_array_set (data, guint8, 3, (port) & 0xff);
901 if (is_ipv4_mapped_any (&sa_in->sin6_addr)) {
902 // Map ::ffff:0:0 to :: (bug #5502)
903 for (i = 0; i < 16; i++)
904 mono_array_set (data, guint8, 8 + i, 0);
906 for (i = 0; i < 16; i++) {
907 mono_array_set (data, guint8, 8 + i,
908 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, domain->sockaddr_data_field, data);
925 else if (saddr->sa_family == AF_UNIX) {
928 for (i = 0; i < sa_size; i++)
929 mono_array_set (data, guint8, i + 2, saddr->sa_data [i]);
931 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
937 *werror = WSAEAFNOSUPPORT;
943 get_sockaddr_size (int family)
948 if (family == AF_INET) {
949 size = sizeof (struct sockaddr_in);
950 } else if (family == AF_INET6) {
951 size = sizeof (struct sockaddr_in6);
954 else if (family == AF_UNIX) {
955 size = sizeof (struct sockaddr_un);
962 ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal (SOCKET sock, gint32 af, gint32 *werror)
972 salen = get_sockaddr_size (convert_family ((MonoAddressFamily)af));
974 *werror = WSAEAFNOSUPPORT;
977 sa = (salen <= 128) ? (gchar *)alloca (salen) : (gchar *)g_malloc0 (salen);
979 MONO_PREPARE_BLOCKING;
981 ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
983 MONO_FINISH_BLOCKING;
985 if (ret == SOCKET_ERROR) {
986 *werror = WSAGetLastError ();
992 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)));
994 result = create_object_from_sockaddr ((struct sockaddr *)sa, salen, werror, &error);
997 if (!mono_error_ok (&error))
998 mono_error_set_pending_exception (&error);
1003 ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal (SOCKET sock, gint32 af, gint32 *werror)
1013 salen = get_sockaddr_size (convert_family ((MonoAddressFamily)af));
1015 *werror = WSAEAFNOSUPPORT;
1018 sa = (salen <= 128) ? (gchar *)alloca (salen) : (gchar *)g_malloc0 (salen);
1019 /* Note: linux returns just 2 for AF_UNIX. Always. */
1021 MONO_PREPARE_BLOCKING;
1023 ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
1025 MONO_FINISH_BLOCKING;
1027 if (ret == SOCKET_ERROR) {
1028 *werror = WSAGetLastError ();
1034 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)));
1036 result = create_object_from_sockaddr ((struct sockaddr *)sa, salen, werror, &error);
1039 if (!mono_error_ok (&error))
1040 mono_error_set_pending_exception (&error);
1044 static struct sockaddr*
1045 create_sockaddr_from_object (MonoObject *saddr_obj, socklen_t *sa_size, gint32 *werror, MonoError *error)
1047 MonoClassField *field;
1052 mono_error_init (error);
1054 /* Dig the SocketAddress data buffer out of the object */
1055 field = mono_class_get_field_from_name (saddr_obj->vtable->klass, "data");
1056 data = *(MonoArray **)(((char *)saddr_obj) + field->offset);
1058 /* The data buffer is laid out as follows:
1059 * byte 0 is the address family low byte
1060 * byte 1 is the address family high byte
1062 * bytes 2 and 3 are the port info
1063 * the rest is the address info
1065 * the rest is the file name
1067 len = mono_array_length (data);
1069 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1073 family = convert_family ((MonoAddressFamily)(mono_array_get (data, guint8, 0) + (mono_array_get (data, guint8, 1) << 8)));
1074 if (family == AF_INET) {
1075 struct sockaddr_in *sa;
1080 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1084 sa = g_new0 (struct sockaddr_in, 1);
1085 port = (mono_array_get (data, guint8, 2) << 8) +
1086 mono_array_get (data, guint8, 3);
1087 address = (mono_array_get (data, guint8, 4) << 24) +
1088 (mono_array_get (data, guint8, 5) << 16 ) +
1089 (mono_array_get (data, guint8, 6) << 8) +
1090 mono_array_get (data, guint8, 7);
1092 sa->sin_family = family;
1093 sa->sin_addr.s_addr = htonl (address);
1094 sa->sin_port = htons (port);
1096 *sa_size = sizeof (struct sockaddr_in);
1097 return (struct sockaddr *)sa;
1098 } else if (family == AF_INET6) {
1099 struct sockaddr_in6 *sa;
1105 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1109 sa = g_new0 (struct sockaddr_in6, 1);
1110 port = mono_array_get (data, guint8, 3) +
1111 (mono_array_get (data, guint8, 2) << 8);
1112 scopeid = mono_array_get (data, guint8, 24) +
1113 (mono_array_get (data, guint8, 25) << 8) +
1114 (mono_array_get (data, guint8, 26) << 16) +
1115 (mono_array_get (data, guint8, 27) << 24);
1117 sa->sin6_family = family;
1118 sa->sin6_port = htons (port);
1119 sa->sin6_scope_id = scopeid;
1121 for (i = 0; i < 16; i++)
1122 sa->sin6_addr.s6_addr [i] = mono_array_get (data, guint8, 8 + i);
1124 *sa_size = sizeof (struct sockaddr_in6);
1125 return (struct sockaddr *)sa;
1127 #ifdef HAVE_SYS_UN_H
1128 else if (family == AF_UNIX) {
1129 struct sockaddr_un *sock_un;
1132 /* Need a byte for the '\0' terminator/prefix, and the first
1133 * two bytes hold the SocketAddress family
1135 if (len - 2 >= sizeof (sock_un->sun_path)) {
1136 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
1140 sock_un = g_new0 (struct sockaddr_un, 1);
1142 sock_un->sun_family = family;
1143 for (i = 0; i < len - 2; i++)
1144 sock_un->sun_path [i] = mono_array_get (data, guint8, i + 2);
1147 return (struct sockaddr *)sock_un;
1151 *werror = WSAEAFNOSUPPORT;
1157 ves_icall_System_Net_Sockets_Socket_Bind_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror)
1160 struct sockaddr *sa;
1166 sa = create_sockaddr_from_object (sockaddr, &sa_size, werror, &error);
1169 if (!mono_error_ok (&error)) {
1170 mono_error_set_pending_exception (&error);
1174 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)));
1176 ret = _wapi_bind (sock, sa, sa_size);
1178 if (ret == SOCKET_ERROR)
1179 *werror = WSAGetLastError ();
1191 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
1192 gint timeout, gint32 *werror)
1194 MonoInternalThread *thread = mono_thread_internal_current ();
1197 gboolean interrupted;
1202 pfds = g_new0 (mono_pollfd, 1);
1203 pfds->fd = GPOINTER_TO_INT (sock);
1206 case SelectModeRead:
1207 pfds->events = MONO_POLLIN;
1209 case SelectModeWrite:
1210 pfds->events = MONO_POLLOUT;
1213 pfds->events = MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL;
1217 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1218 start = time (NULL);
1221 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1228 MONO_PREPARE_BLOCKING;
1230 ret = mono_poll (pfds, 1, timeout);
1232 MONO_FINISH_BLOCKING;
1234 mono_thread_info_uninstall_interrupt (&interrupted);
1241 if (timeout > 0 && ret < 0) {
1243 int sec = time (NULL) - start;
1245 timeout -= sec * 1000;
1253 if (ret == -1 && errno == EINTR) {
1254 if (mono_thread_test_state (thread, (MonoThreadState)(ThreadState_AbortRequested | ThreadState_StopRequested))) {
1259 /* Suspend requested? */
1260 mono_thread_interruption_checkpoint ();
1264 } while (ret == -1 && errno == EINTR);
1268 *werror = WSAGetLastError ();
1270 *werror = errno_to_WSA (errno, __func__);
1281 ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror)
1284 struct sockaddr *sa;
1287 gboolean interrupted;
1291 sa = create_sockaddr_from_object (sockaddr, &sa_size, werror, &error);
1294 if (!mono_error_ok (&error)) {
1295 mono_error_set_pending_exception (&error);
1299 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)));
1301 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1307 MONO_PREPARE_BLOCKING;
1309 ret = _wapi_connect (sock, sa, sa_size);
1311 MONO_FINISH_BLOCKING;
1313 mono_thread_info_uninstall_interrupt (&interrupted);
1319 if (ret == SOCKET_ERROR)
1320 *werror = WSAGetLastError ();
1325 /* These #defines from mswsock.h from wine. Defining them here allows
1326 * us to build this file on a mingw box that doesn't know the magic
1327 * numbers, but still run on a newer windows box that does.
1329 #ifndef WSAID_DISCONNECTEX
1330 #define WSAID_DISCONNECTEX {0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
1331 typedef BOOL (WINAPI *LPFN_DISCONNECTEX)(SOCKET, LPOVERLAPPED, DWORD, DWORD);
1334 #ifndef WSAID_TRANSMITFILE
1335 #define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
1336 typedef BOOL (WINAPI *LPFN_TRANSMITFILE)(SOCKET, HANDLE, DWORD, DWORD, LPOVERLAPPED, LPTRANSMIT_FILE_BUFFERS, DWORD);
1340 ves_icall_System_Net_Sockets_Socket_Disconnect_internal (SOCKET sock, MonoBoolean reuse, gint32 *werror)
1343 glong output_bytes = 0;
1344 GUID disco_guid = WSAID_DISCONNECTEX;
1345 GUID trans_guid = WSAID_TRANSMITFILE;
1346 LPFN_DISCONNECTEX _wapi_disconnectex = NULL;
1347 LPFN_TRANSMITFILE _wapi_transmitfile = NULL;
1348 gboolean interrupted;
1352 LOGDEBUG (g_message("%s: disconnecting from socket %p (reuse %d)", __func__, sock, reuse));
1354 MONO_PREPARE_BLOCKING;
1356 /* I _think_ the extension function pointers need to be looked
1357 * up for each socket. FIXME: check the best way to store
1358 * pointers to functions in managed objects that still works
1359 * on 64bit platforms.
1361 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER, (gchar *)&disco_guid, sizeof (GUID),
1362 (gchar *)&_wapi_disconnectex, sizeof (void *), &output_bytes, NULL, NULL);
1364 MONO_FINISH_BLOCKING;
1367 /* make sure that WSAIoctl didn't put crap in the
1370 _wapi_disconnectex = NULL;
1372 MONO_PREPARE_BLOCKING;
1375 * Use the SIO_GET_EXTENSION_FUNCTION_POINTER to
1376 * determine the address of the disconnect method without
1377 * taking a hard dependency on a single provider
1379 * For an explanation of why this is done, you can read
1380 * the article at http://www.codeproject.com/internet/jbsocketserver3.asp
1382 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER, (gchar *)&trans_guid, sizeof(GUID),
1383 (gchar *)&_wapi_transmitfile, sizeof(void *), &output_bytes, NULL, NULL);
1385 MONO_FINISH_BLOCKING;
1388 _wapi_transmitfile = NULL;
1391 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1397 MONO_PREPARE_BLOCKING;
1399 if (_wapi_disconnectex != NULL) {
1400 if (!_wapi_disconnectex (sock, NULL, TF_REUSE_SOCKET, 0))
1401 *werror = WSAGetLastError ();
1402 } else if (_wapi_transmitfile != NULL) {
1403 if (!_wapi_transmitfile (sock, NULL, 0, 0, NULL, NULL, TF_DISCONNECT | TF_REUSE_SOCKET))
1404 *werror = WSAGetLastError ();
1406 *werror = ERROR_NOT_SUPPORTED;
1409 MONO_FINISH_BLOCKING;
1411 mono_thread_info_uninstall_interrupt (&interrupted);
1417 ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
1423 gboolean interrupted;
1424 MonoInternalThread* curthread G_GNUC_UNUSED = mono_thread_internal_current ();
1428 alen = mono_array_length (buffer);
1429 if (offset > alen - count)
1432 buf = mono_array_addr (buffer, guchar, offset);
1434 recvflags = convert_socketflags (flags);
1435 if (recvflags == -1) {
1436 *werror = WSAEOPNOTSUPP;
1440 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1444 MONO_PREPARE_BLOCKING;
1448 curthread->interrupt_on_stop = (gpointer)TRUE;
1449 ret = _wapi_recv (sock, buf, count, recvflags);
1450 curthread->interrupt_on_stop = (gpointer)FALSE;
1453 ret = _wapi_recv (sock, buf, count, recvflags);
1456 MONO_FINISH_BLOCKING;
1458 mono_thread_info_uninstall_interrupt (&interrupted);
1464 if (ret == SOCKET_ERROR) {
1465 *werror = WSAGetLastError ();
1473 ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
1476 gboolean interrupted;
1479 DWORD recvflags = 0;
1483 wsabufs = mono_array_addr (buffers, WSABUF, 0);
1484 count = mono_array_length (buffers);
1486 recvflags = convert_socketflags (flags);
1487 if (recvflags == -1) {
1488 *werror = WSAEOPNOTSUPP;
1492 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1498 MONO_PREPARE_BLOCKING;
1500 ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
1502 MONO_FINISH_BLOCKING;
1504 mono_thread_info_uninstall_interrupt (&interrupted);
1510 if (ret == SOCKET_ERROR) {
1511 *werror = WSAGetLastError ();
1519 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror)
1526 struct sockaddr *sa;
1528 gboolean interrupted;
1532 alen = mono_array_length (buffer);
1533 if (offset > alen - count)
1536 sa = create_sockaddr_from_object (*sockaddr, &sa_size, werror, &error);
1539 if (!mono_error_ok (&error)) {
1540 mono_error_set_pending_exception (&error);
1544 buf = mono_array_addr (buffer, guchar, offset);
1546 recvflags = convert_socketflags (flags);
1547 if (recvflags == -1) {
1548 *werror = WSAEOPNOTSUPP;
1552 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1559 MONO_PREPARE_BLOCKING;
1561 ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
1563 MONO_FINISH_BLOCKING;
1565 mono_thread_info_uninstall_interrupt (&interrupted);
1572 if (ret==SOCKET_ERROR) {
1574 *werror = WSAGetLastError ();
1578 /* If we didn't get a socket size, then we're probably a
1579 * connected connection-oriented socket and the stack hasn't
1580 * returned the remote address. All we can do is return null.
1583 *sockaddr = create_object_from_sockaddr (sa, sa_size, werror, &error);
1584 if (!mono_error_ok (&error)) {
1585 mono_error_set_pending_exception (&error);
1599 ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
1605 gboolean interrupted;
1609 alen = mono_array_length (buffer);
1610 if (offset > alen - count)
1613 LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
1615 buf = mono_array_addr (buffer, guchar, offset);
1617 LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1619 sendflags = convert_socketflags (flags);
1620 if (sendflags == -1) {
1621 *werror = WSAEOPNOTSUPP;
1625 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1631 MONO_PREPARE_BLOCKING;
1633 ret = _wapi_send (sock, buf, count, sendflags);
1635 MONO_FINISH_BLOCKING;
1637 mono_thread_info_uninstall_interrupt (&interrupted);
1643 if (ret == SOCKET_ERROR) {
1644 *werror = WSAGetLastError ();
1652 ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
1657 DWORD sendflags = 0;
1658 gboolean interrupted;
1662 wsabufs = mono_array_addr (buffers, WSABUF, 0);
1663 count = mono_array_length (buffers);
1665 sendflags = convert_socketflags (flags);
1666 if (sendflags == -1) {
1667 *werror = WSAEOPNOTSUPP;
1671 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1677 MONO_PREPARE_BLOCKING;
1679 ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
1681 MONO_FINISH_BLOCKING;
1683 mono_thread_info_uninstall_interrupt (&interrupted);
1689 if (ret == SOCKET_ERROR) {
1690 *werror = WSAGetLastError ();
1698 ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror)
1705 struct sockaddr *sa;
1707 gboolean interrupted;
1711 alen = mono_array_length (buffer);
1712 if (offset > alen - count) {
1716 sa = create_sockaddr_from_object(sockaddr, &sa_size, werror, &error);
1719 if (!mono_error_ok (&error)) {
1720 mono_error_set_pending_exception (&error);
1724 LOGDEBUG (g_message ("%s: alen: %d", __func__, alen));
1726 buf = mono_array_addr (buffer, guchar, offset);
1728 LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1730 sendflags = convert_socketflags (flags);
1731 if (sendflags == -1) {
1733 *werror = WSAEOPNOTSUPP;
1737 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1744 MONO_PREPARE_BLOCKING;
1746 ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
1748 MONO_FINISH_BLOCKING;
1750 mono_thread_info_uninstall_interrupt (&interrupted);
1757 if (ret == SOCKET_ERROR)
1758 *werror = WSAGetLastError ();
1766 Socket_to_SOCKET (MonoObject *sockobj)
1768 MonoSafeHandle *safe_handle;
1769 MonoClassField *field;
1771 field = mono_class_get_field_from_name (sockobj->vtable->klass, "safe_handle");
1772 safe_handle = ((MonoSafeHandle *)(*(gpointer *)(((char *)sockobj) + field->offset)));
1774 if (safe_handle == NULL)
1777 return (SOCKET)safe_handle->handle;
1780 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
1783 ves_icall_System_Net_Sockets_Socket_Select_internal (MonoArray **sockets, gint32 timeout, gint32 *werror)
1786 MonoInternalThread *thread = mono_thread_internal_current ();
1793 MonoClass *sock_arr_class;
1796 uintptr_t socks_size;
1797 gboolean interrupted;
1801 /* *sockets -> READ, null, WRITE, null, ERROR, null */
1802 count = mono_array_length (*sockets);
1803 nfds = count - 3; /* NULL separators */
1804 pfds = g_new0 (mono_pollfd, nfds);
1806 for (i = 0; i < count; i++) {
1807 obj = mono_array_get (*sockets, MonoObject *, i);
1814 /* The socket array was bogus */
1816 *werror = WSAEFAULT;
1820 pfds [idx].fd = Socket_to_SOCKET (obj);
1821 pfds [idx].events = (mode == 0) ? MONO_POLLIN : (mode == 1) ? MONO_POLLOUT : POLL_ERRORS;
1825 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1826 start = time (NULL);
1828 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1835 MONO_PREPARE_BLOCKING;
1837 ret = mono_poll (pfds, nfds, timeout);
1839 MONO_FINISH_BLOCKING;
1841 mono_thread_info_uninstall_interrupt (&interrupted);
1848 if (timeout > 0 && ret < 0) {
1850 int sec = time (NULL) - start;
1852 timeout -= sec * 1000;
1858 if (ret == -1 && errno == EINTR) {
1859 if (mono_thread_test_state (thread, (MonoThreadState)(ThreadState_AbortRequested | ThreadState_StopRequested))) {
1865 /* Suspend requested? */
1866 mono_thread_interruption_checkpoint ();
1870 } while (ret == -1 && errno == EINTR);
1874 *werror = WSAGetLastError ();
1876 *werror = errno_to_WSA (errno, __func__);
1888 sock_arr_class = ((MonoObject *)*sockets)->vtable->klass;
1889 socks_size = ((uintptr_t)ret) + 3; /* space for the NULL delimiters */
1890 socks = mono_array_new_full_checked (mono_domain_get (), sock_arr_class, &socks_size, NULL, &error);
1891 if (!mono_error_ok (&error)) {
1892 mono_error_set_pending_exception (&error);
1898 for (i = 0; i < count && ret > 0; i++) {
1901 obj = mono_array_get (*sockets, MonoObject *, i);
1908 pfd = &pfds [i - mode];
1909 if (pfd->revents == 0)
1913 if (mode == 0 && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
1914 mono_array_setref (socks, idx++, obj);
1915 } else if (mode == 1 && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
1916 mono_array_setref (socks, idx++, obj);
1917 } else if ((pfd->revents & POLL_ERRORS) != 0) {
1918 mono_array_setref (socks, idx++, obj);
1927 int_to_object (MonoDomain *domain, int val)
1930 MonoObject *result = mono_value_box_checked (domain, mono_get_int32_class (), &val, &error);
1931 mono_error_raise_exception (&error); /* FIXME don't raise here */
1936 ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *werror)
1938 int system_level = 0;
1939 int system_name = 0;
1942 socklen_t valsize = sizeof (val);
1943 struct linger linger;
1944 socklen_t lingersize = sizeof (linger);
1946 socklen_t time_ms_size = sizeof (time_ms);
1948 # if defined(__OpenBSD__)
1949 struct sockpeercred cred;
1953 socklen_t credsize = sizeof (cred);
1956 MonoDomain *domain = mono_domain_get ();
1958 MonoClass *obj_class;
1959 MonoClassField *field;
1963 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
1964 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
1965 system_level = SOL_SOCKET;
1966 system_name = SO_REUSEADDR;
1971 ret = convert_sockopt_level_and_name ((MonoSocketOptionLevel)level, (MonoSocketOptionName)name, &system_level, &system_name);
1975 *werror = WSAENOPROTOOPT;
1979 *obj_val = int_to_object (domain, 0);
1983 MONO_PREPARE_BLOCKING;
1985 /* No need to deal with MulticastOption names here, because
1986 * you cant getsockopt AddMembership or DropMembership (the
1987 * int getsockopt will error, causing an exception)
1990 case SocketOptionName_Linger:
1991 case SocketOptionName_DontLinger:
1992 ret = _wapi_getsockopt (sock, system_level, system_name, &linger, &lingersize);
1995 case SocketOptionName_SendTimeout:
1996 case SocketOptionName_ReceiveTimeout:
1997 ret = _wapi_getsockopt (sock, system_level, system_name, (char *)&time_ms, &time_ms_size);
2001 case SocketOptionName_PeerCred:
2002 ret = _wapi_getsockopt (sock, system_level, system_name, &cred, &credsize);
2007 ret = _wapi_getsockopt (sock, system_level, system_name, &val, &valsize);
2010 MONO_FINISH_BLOCKING;
2012 if (ret == SOCKET_ERROR) {
2013 *werror = WSAGetLastError ();
2018 case SocketOptionName_Linger:
2019 /* build a System.Net.Sockets.LingerOption */
2020 obj_class = mono_class_load_from_name (get_socket_assembly (),
2021 "System.Net.Sockets",
2023 obj = mono_object_new_checked (domain, obj_class, &error);
2024 if (!mono_error_ok (&error)) {
2025 mono_error_set_pending_exception (&error);
2029 /* Locate and set the fields "bool enabled" and "int
2032 field = mono_class_get_field_from_name(obj_class, "enabled");
2033 *(guint8 *)(((char *)obj)+field->offset) = linger.l_onoff;
2035 field = mono_class_get_field_from_name(obj_class, "lingerTime");
2036 *(guint32 *)(((char *)obj)+field->offset)=linger.l_linger;
2038 case SocketOptionName_DontLinger:
2039 /* construct a bool int in val - true if linger is off */
2040 obj = int_to_object (domain, !linger.l_onoff);
2042 case SocketOptionName_SendTimeout:
2043 case SocketOptionName_ReceiveTimeout:
2044 obj = int_to_object (domain, time_ms);
2048 case SocketOptionName_PeerCred: {
2050 * build a Mono.Posix.PeerCred+PeerCredData if
2053 static MonoImage *mono_posix_image = NULL;
2054 MonoPeerCredData *cred_data;
2056 if (mono_posix_image == NULL) {
2057 mono_posix_image = mono_image_loaded ("Mono.Posix");
2058 if (!mono_posix_image) {
2059 MonoAssembly *sa = mono_assembly_open ("Mono.Posix.dll", NULL);
2061 *werror = WSAENOPROTOOPT;
2064 mono_posix_image = mono_assembly_get_image (sa);
2069 obj_class = mono_class_load_from_name (mono_posix_image,
2072 obj = mono_object_new_checked (domain, obj_class, &error);
2073 if (!mono_error_ok (&error)) {
2074 mono_error_set_pending_exception (&error);
2077 cred_data = (MonoPeerCredData *)obj;
2078 cred_data->pid = cred.pid;
2079 cred_data->uid = cred.uid;
2080 cred_data->gid = cred.gid;
2086 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
2087 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse)
2090 obj = int_to_object (domain, val);
2097 ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal (SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *werror)
2099 int system_level = 0;
2100 int system_name = 0;
2107 ret = convert_sockopt_level_and_name((MonoSocketOptionLevel)level, (MonoSocketOptionName)name, &system_level,
2110 *werror = WSAENOPROTOOPT;
2116 valsize = mono_array_length (*byte_val);
2117 buf = mono_array_addr (*byte_val, guchar, 0);
2119 MONO_PREPARE_BLOCKING;
2121 ret = _wapi_getsockopt (sock, system_level, system_name, buf, &valsize);
2123 MONO_FINISH_BLOCKING;
2125 if (ret == SOCKET_ERROR)
2126 *werror = WSAGetLastError ();
2129 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2130 static struct in_addr
2131 ipaddress_to_struct_in_addr (MonoObject *ipaddr)
2133 struct in_addr inaddr;
2134 MonoClassField *field;
2136 field = mono_class_get_field_from_name (ipaddr->vtable->klass, "m_Address");
2138 /* No idea why .net uses a 64bit type to hold a 32bit value...
2140 * Internal value of IPAddess is in little-endian order
2142 inaddr.s_addr = GUINT_FROM_LE ((guint32)*(guint64 *)(((char *)ipaddr) + field->offset));
2147 static struct in6_addr
2148 ipaddress_to_struct_in6_addr (MonoObject *ipaddr)
2150 struct in6_addr in6addr;
2151 MonoClassField *field;
2155 field = mono_class_get_field_from_name (ipaddr->vtable->klass, "m_Numbers");
2156 data = *(MonoArray **)(((char *)ipaddr) + field->offset);
2158 /* Solaris has only the 8 bit version. */
2160 for (i = 0; i < 8; i++) {
2161 guint16 s = mono_array_get (data, guint16, i);
2162 in6addr.s6_addr[2 * i + 1] = (s >> 8) & 0xff;
2163 in6addr.s6_addr[2 * i] = s & 0xff;
2166 for (i = 0; i < 8; i++)
2167 in6addr.s6_addr16[i] = mono_array_get (data, guint16, i);
2173 #if defined(__APPLE__) || defined(__FreeBSD__)
2176 get_local_interface_id (int family)
2178 #if !defined(HAVE_GETIFADDRS) || !defined(HAVE_IF_NAMETOINDEX)
2181 struct ifaddrs *ifap = NULL, *ptr;
2184 if (getifaddrs (&ifap))
2187 for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
2188 if (!ptr->ifa_addr || !ptr->ifa_name)
2190 if (ptr->ifa_addr->sa_family != family)
2192 if ((ptr->ifa_flags & IFF_LOOPBACK) != 0)
2194 if ((ptr->ifa_flags & IFF_MULTICAST) == 0)
2197 idx = if_nametoindex (ptr->ifa_name);
2206 #endif /* defined(__APPLE__) || defined(__FreeBSD__) */
2209 ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal (SOCKET sock, gint32 level, gint32 name, MonoObject *obj_val, MonoArray *byte_val, gint32 int_val, gint32 *werror)
2211 struct linger linger;
2212 int system_level = 0;
2213 int system_name = 0;
2220 sol_ipv6 = mono_networking_get_ipv6_protocol ();
2221 sol_ip = mono_networking_get_ip_protocol ();
2223 ret = convert_sockopt_level_and_name ((MonoSocketOptionLevel)level, (MonoSocketOptionName)name, &system_level,
2226 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
2227 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
2228 system_name = SO_REUSEADDR;
2229 int_val = int_val ? 0 : 1;
2235 *werror = WSAENOPROTOOPT;
2241 /* Only one of obj_val, byte_val or int_val has data */
2243 MonoClassField *field;
2247 case SocketOptionName_Linger:
2248 /* Dig out "bool enabled" and "int lingerTime"
2251 field = mono_class_get_field_from_name (obj_val->vtable->klass, "enabled");
2252 linger.l_onoff = *(guint8 *)(((char *)obj_val) + field->offset);
2253 field = mono_class_get_field_from_name (obj_val->vtable->klass, "lingerTime");
2254 linger.l_linger = *(guint32 *)(((char *)obj_val) + field->offset);
2256 valsize = sizeof (linger);
2257 ret = _wapi_setsockopt (sock, system_level,
2258 system_name, &linger, valsize);
2260 case SocketOptionName_AddMembership:
2261 case SocketOptionName_DropMembership:
2262 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2264 MonoObject *address = NULL;
2266 if (system_level == sol_ipv6) {
2267 struct ipv6_mreq mreq6;
2272 field = mono_class_get_field_from_name (obj_val->vtable->klass, "m_Group");
2273 address = *(MonoObject **)(((char *)obj_val) + field->offset);
2276 mreq6.ipv6mr_multiaddr = ipaddress_to_struct_in6_addr (address);
2278 field = mono_class_get_field_from_name (obj_val->vtable->klass, "m_Interface");
2279 mreq6.ipv6mr_interface = *(guint64 *)(((char *)obj_val) + field->offset);
2281 #if defined(__APPLE__) || defined(__FreeBSD__)
2285 * Mac OS Lion doesn't allow ipv6mr_interface = 0.
2287 * Tests on Windows and Linux show that the multicast group is only
2288 * joined on one NIC when interface = 0, so we simply use the interface
2289 * id from the first non-loopback interface (this is also what
2290 * Dns.GetHostName (string.Empty) would return).
2292 if (!mreq6.ipv6mr_interface)
2293 mreq6.ipv6mr_interface = get_local_interface_id (AF_INET6);
2296 ret = _wapi_setsockopt (sock, system_level,
2297 system_name, &mreq6,
2299 } else if (system_level == sol_ip) {
2300 #ifdef HAVE_STRUCT_IP_MREQN
2301 struct ip_mreqn mreq = {{0}};
2303 struct ip_mreq mreq = {{0}};
2304 #endif /* HAVE_STRUCT_IP_MREQN */
2307 * pain! MulticastOption holds two IPAddress
2308 * members, so I have to dig the value out of
2311 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2312 address = *(MonoObject **)(((char *)obj_val) + field->offset);
2314 /* address might not be defined and if so, set the address to ADDR_ANY.
2317 mreq.imr_multiaddr = ipaddress_to_struct_in_addr (address);
2319 field = mono_class_get_field_from_name (obj_val->vtable->klass, "localAddress");
2320 address = *(MonoObject **)(((char *)obj_val) + field->offset);
2322 #ifdef HAVE_STRUCT_IP_MREQN
2324 mreq.imr_address = ipaddress_to_struct_in_addr (address);
2326 field = mono_class_get_field_from_name (obj_val->vtable->klass, "ifIndex");
2327 mreq.imr_ifindex = *(gint32 *)(((char *)obj_val) + field->offset);
2330 mreq.imr_interface = ipaddress_to_struct_in_addr (address);
2331 #endif /* HAVE_STRUCT_IP_MREQN */
2333 ret = _wapi_setsockopt (sock, system_level,
2339 #endif /* HAVE_STRUCT_IP_MREQN || HAVE_STRUCT_IP_MREQ */
2341 /* Cause an exception to be thrown */
2342 *werror = WSAEINVAL;
2345 } else if (byte_val!=NULL) {
2346 int valsize = mono_array_length (byte_val);
2347 guchar *buf = mono_array_addr (byte_val, guchar, 0);
2350 case SocketOptionName_DontLinger:
2352 linger.l_onoff = (*buf) ? 0 : 1;
2353 linger.l_linger = 0;
2354 ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2356 *werror = WSAEINVAL;
2360 ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
2364 /* ReceiveTimeout/SendTimeout get here */
2366 case SocketOptionName_DontLinger:
2367 linger.l_onoff = !int_val;
2368 linger.l_linger = 0;
2369 ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2371 case SocketOptionName_MulticastInterface:
2373 #ifdef HAVE_STRUCT_IP_MREQN
2374 int_val = GUINT32_FROM_BE (int_val);
2375 if ((int_val & 0xff000000) == 0) {
2376 /* int_val is interface index */
2377 struct ip_mreqn mreq = {{0}};
2378 mreq.imr_ifindex = int_val;
2379 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &mreq, sizeof (mreq));
2382 int_val = GUINT32_TO_BE (int_val);
2383 #endif /* HAVE_STRUCT_IP_MREQN */
2384 #endif /* HOST_WIN32 */
2385 /* int_val is in_addr */
2386 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2388 case SocketOptionName_DontFragment:
2389 #ifdef HAVE_IP_MTU_DISCOVER
2390 /* Fiddle with the value slightly if we're
2394 int_val = IP_PMTUDISC_DO;
2399 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2403 if (ret == SOCKET_ERROR)
2404 *werror = WSAGetLastError ();
2408 ves_icall_System_Net_Sockets_Socket_Shutdown_internal (SOCKET sock, gint32 how, gint32 *werror)
2411 gboolean interrupted;
2415 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
2421 MONO_PREPARE_BLOCKING;
2423 /* Currently, the values for how (recv=0, send=1, both=2) match the BSD API */
2424 ret = _wapi_shutdown (sock, how);
2426 MONO_FINISH_BLOCKING;
2428 mono_thread_info_uninstall_interrupt (&interrupted);
2434 if (ret == SOCKET_ERROR)
2435 *werror = WSAGetLastError ();
2439 ves_icall_System_Net_Sockets_Socket_IOControl_internal (SOCKET sock, gint32 code, MonoArray *input, MonoArray *output, gint32 *werror)
2441 glong output_bytes = 0;
2442 gchar *i_buffer, *o_buffer;
2448 if ((guint32)code == FIONBIO)
2449 /* Invalid command. Must use Socket.Blocking */
2452 if (input == NULL) {
2456 i_buffer = mono_array_addr (input, gchar, 0);
2457 i_len = mono_array_length (input);
2460 if (output == NULL) {
2464 o_buffer = mono_array_addr (output, gchar, 0);
2465 o_len = mono_array_length (output);
2468 MONO_PREPARE_BLOCKING;
2470 ret = WSAIoctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes, NULL, NULL);
2472 MONO_FINISH_BLOCKING;
2474 if (ret == SOCKET_ERROR) {
2475 *werror = WSAGetLastError ();
2479 return (gint)output_bytes;
2483 addrinfo_to_IPHostEntry(MonoAddressInfo *info, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
2486 MonoAddressEntry *ai = NULL;
2487 struct in_addr *local_in = NULL;
2489 struct in6_addr *local_in6 = NULL;
2492 MonoDomain *domain = mono_domain_get ();
2495 *h_aliases = mono_array_new (domain, mono_get_string_class (), 0);
2496 if (add_local_ips) {
2497 local_in = (struct in_addr *) mono_get_local_interfaces (AF_INET, &nlocal_in);
2498 local_in6 = (struct in6_addr *) mono_get_local_interfaces (AF_INET6, &nlocal_in6);
2499 if (nlocal_in || nlocal_in6) {
2500 char addr [INET6_ADDRSTRLEN];
2501 *h_addr_list = mono_array_new (domain, mono_get_string_class (), nlocal_in + nlocal_in6);
2503 MonoString *addr_string;
2506 for (i = 0; i < nlocal_in; i++) {
2508 mono_address_init (&maddr, AF_INET, &local_in [i]);
2509 if (mono_networking_addr_to_str (&maddr, addr, sizeof (addr))) {
2510 addr_string = mono_string_new (domain, addr);
2511 mono_array_setref (*h_addr_list, addr_index, addr_string);
2518 MonoString *addr_string;
2521 for (i = 0; i < nlocal_in6; i++) {
2523 mono_address_init (&maddr, AF_INET6, &local_in6 [i]);
2524 if (mono_networking_addr_to_str (&maddr, addr, sizeof (addr))) {
2525 addr_string = mono_string_new (domain, addr);
2526 mono_array_setref (*h_addr_list, addr_index, addr_string);
2535 mono_free_address_info (info);
2543 for (count = 0, ai = info->entries; ai != NULL; ai = ai->next) {
2544 if (ai->family != AF_INET && ai->family != AF_INET6)
2549 *h_addr_list = mono_array_new (domain, mono_get_string_class (), count);
2551 for (ai = info->entries, i = 0; ai != NULL; ai = ai->next) {
2553 MonoString *addr_string;
2554 char buffer [INET6_ADDRSTRLEN]; /* Max. size for IPv6 */
2556 if ((ai->family != PF_INET) && (ai->family != PF_INET6))
2559 mono_address_init (&maddr, ai->family, &ai->address);
2560 if (mono_networking_addr_to_str (&maddr, buffer, sizeof (buffer)))
2561 addr_string = mono_string_new (domain, buffer);
2563 addr_string = mono_string_new (domain, "");
2565 mono_array_setref (*h_addr_list, addr_index, addr_string);
2569 if (ai->canonical_name != NULL) {
2570 *h_name = mono_string_new (domain, ai->canonical_name);
2572 *h_name = mono_string_new (domain, buffer);
2580 mono_free_address_info (info);
2586 get_addrinfo_family_hint (MonoError *error)
2590 mono_error_init (error);
2592 hint = get_family_hint (error);
2593 return_val_if_nok (error, 0);
2597 return MONO_HINT_UNSPECIFIED;
2599 return MONO_HINT_IPV4;
2602 return MONO_HINT_IPV6;
2605 g_error ("invalid hint");
2611 ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2613 gboolean add_local_ips = FALSE, add_info_ok = TRUE;
2614 gchar this_hostname [256];
2615 MonoAddressInfo *info = NULL;
2616 char *hostname = mono_string_to_utf8 (host);
2620 hint = get_addrinfo_family_hint (&error);
2621 if (!mono_error_ok (&error)) {
2622 mono_error_set_pending_exception (&error);
2626 if (*hostname == '\0') {
2627 add_local_ips = TRUE;
2631 if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2632 if (!strcmp (hostname, this_hostname)) {
2633 add_local_ips = TRUE;
2638 if (*hostname && mono_get_address_info (hostname, 0, MONO_HINT_CANONICAL_NAME | hint, &info))
2639 add_info_ok = FALSE;
2644 return addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, add_local_ips);
2649 ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2652 struct sockaddr_in saddr;
2653 struct sockaddr_in6 saddr6;
2654 MonoAddressInfo *info = NULL;
2656 gint32 family, hint;
2657 gchar hostname [NI_MAXHOST] = { 0 };
2660 address = mono_string_to_utf8 (addr);
2662 if (inet_pton (AF_INET, address, &saddr.sin_addr ) == 1) {
2664 saddr.sin_family = AF_INET;
2665 } else if (inet_pton (AF_INET6, address, &saddr6.sin6_addr) == 1) {
2667 saddr6.sin6_family = AF_INET6;
2675 MONO_PREPARE_BLOCKING;
2679 #if HAVE_SOCKADDR_IN_SIN_LEN
2680 saddr.sin_len = sizeof (saddr);
2682 ret = getnameinfo ((struct sockaddr*)&saddr, sizeof (saddr), hostname, sizeof (hostname), NULL, 0, 0) == 0;
2686 #if HAVE_SOCKADDR_IN6_SIN_LEN
2687 saddr6.sin6_len = sizeof (saddr6);
2689 ret = getnameinfo ((struct sockaddr*)&saddr6, sizeof (saddr6), hostname, sizeof (hostname), NULL, 0, 0) == 0;
2693 g_assert_not_reached ();
2696 MONO_FINISH_BLOCKING;
2701 hint = get_addrinfo_family_hint (&error);
2702 if (!mono_error_ok (&error)) {
2703 mono_error_set_pending_exception (&error);
2706 if (mono_get_address_info (hostname, 0, hint | MONO_HINT_CANONICAL_NAME | MONO_HINT_CONFIGURED_ONLY, &info) != 0)
2709 return addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE);
2713 ves_icall_System_Net_Dns_GetHostName_internal (MonoString **h_name)
2715 gchar hostname [NI_MAXHOST] = { 0 };
2718 ret = gethostname (hostname, sizeof (hostname));
2722 *h_name = mono_string_new (mono_domain_get (), hostname);
2728 ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
2733 gboolean interrupted;
2734 TRANSMIT_FILE_BUFFERS buffers;
2736 if (filename == NULL)
2739 /* FIXME: replace file by a proper fd that we can call open and close on, as they are interruptible */
2741 file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &werror);
2743 if (file == INVALID_HANDLE_VALUE) {
2744 SetLastError (werror);
2748 memset (&buffers, 0, sizeof (buffers));
2749 if (pre_buffer != NULL) {
2750 buffers.Head = mono_array_addr (pre_buffer, guchar, 0);
2751 buffers.HeadLength = mono_array_length (pre_buffer);
2753 if (post_buffer != NULL) {
2754 buffers.Tail = mono_array_addr (post_buffer, guchar, 0);
2755 buffers.TailLength = mono_array_length (post_buffer);
2758 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
2761 SetLastError (WSAEINTR);
2765 MONO_PREPARE_BLOCKING;
2767 ret = TransmitFile (sock, file, 0, 0, NULL, &buffers, flags);
2769 MONO_FINISH_BLOCKING;
2771 mono_thread_info_uninstall_interrupt (&interrupted);
2774 SetLastError (WSAEINTR);
2778 MONO_PREPARE_BLOCKING;
2782 MONO_FINISH_BLOCKING;
2788 ves_icall_System_Net_Sockets_Socket_SupportPortReuse (void)
2790 #if defined (SO_REUSEPORT) || defined (HOST_WIN32)
2798 mono_network_init (void)
2800 mono_networking_init ();
2804 mono_network_cleanup (void)
2806 _wapi_cleanup_networking ();
2807 mono_networking_shutdown ();
2811 icall_cancel_blocking_socket_operation (MonoThread *thread)
2813 MonoInternalThread *internal;
2815 internal = thread->internal_thread;
2816 g_assert (internal);
2818 mono_thread_info_abort_socket_syscall_for_close (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
2821 #endif /* #ifndef DISABLE_SOCKETS */