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
17 #ifndef DISABLE_SOCKETS
19 #if defined(__APPLE__) || defined(__FreeBSD__)
20 #define __APPLE_USE_RFC_3542
29 #include <sys/socket.h>
30 #ifdef HAVE_SYS_IOCTL_H
31 #include <sys/ioctl.h>
33 #include <netinet/in.h>
34 #include <netinet/tcp.h>
38 #include <arpa/inet.h>
45 #include <sys/types.h>
47 #include <mono/metadata/object.h>
48 #include <mono/io-layer/io-layer.h>
49 #include <mono/metadata/socket-io.h>
50 #include <mono/metadata/exception.h>
51 #include <mono/metadata/assembly.h>
52 #include <mono/metadata/appdomain.h>
53 #include <mono/metadata/file-io.h>
54 #include <mono/metadata/threads.h>
55 #include <mono/metadata/threads-types.h>
56 #include <mono/metadata/threadpool-ms-io.h>
57 #include <mono/utils/mono-poll.h>
58 /* FIXME change this code to not mess so much with the internals */
59 #include <mono/metadata/class-internals.h>
60 #include <mono/metadata/domain-internals.h>
61 #include <mono/utils/mono-threads.h>
62 #include <mono/utils/mono-memory-model.h>
63 #include <mono/utils/networking.h>
66 #ifdef HAVE_SYS_TIME_H
69 #ifdef HAVE_SYS_IOCTL_H
70 #include <sys/ioctl.h>
79 #ifdef HAVE_SYS_FILIO_H
80 #include <sys/filio.h> /* defines FIONBIO and FIONREAD */
82 #ifdef HAVE_SYS_SOCKIO_H
83 #include <sys/sockio.h> /* defines SIOCATMARK */
89 #ifdef HAVE_GETIFADDRS
90 // <net/if.h> must be included before <ifaddrs.h>
94 #include "mono/io-layer/socket-wrappers.h"
97 /* define LOGDEBUG(...) g_message(__VA_ARGS__) */
100 abort_syscall (gpointer data)
102 mono_thread_info_abort_socket_syscall_for_close ((MonoNativeThreadId) (gsize) data);
106 convert_family (MonoAddressFamily mono_family)
108 switch (mono_family) {
109 case AddressFamily_Unknown:
110 case AddressFamily_ImpLink:
111 case AddressFamily_Pup:
112 case AddressFamily_Chaos:
113 case AddressFamily_Iso:
114 case AddressFamily_Ecma:
115 case AddressFamily_DataKit:
116 case AddressFamily_Ccitt:
117 case AddressFamily_DataLink:
118 case AddressFamily_Lat:
119 case AddressFamily_HyperChannel:
120 case AddressFamily_NetBios:
121 case AddressFamily_VoiceView:
122 case AddressFamily_FireFox:
123 case AddressFamily_Banyan:
124 case AddressFamily_Atm:
125 case AddressFamily_Cluster:
126 case AddressFamily_Ieee12844:
127 case AddressFamily_NetworkDesigners:
128 g_warning ("System.Net.Sockets.AddressFamily has unsupported value 0x%x", mono_family);
130 case AddressFamily_Unspecified:
132 case AddressFamily_Unix:
134 case AddressFamily_InterNetwork:
136 case AddressFamily_AppleTalk:
138 case AddressFamily_InterNetworkV6:
140 case AddressFamily_DecNet:
146 case AddressFamily_Ipx:
152 case AddressFamily_Sna:
158 case AddressFamily_Irda:
165 g_warning ("System.Net.Sockets.AddressFamily has unknown value 0x%x", mono_family);
170 static MonoAddressFamily
171 convert_to_mono_family (guint16 af_family)
175 return AddressFamily_Unspecified;
177 return AddressFamily_Unix;
179 return AddressFamily_InterNetwork;
182 return AddressFamily_Ipx;
186 return AddressFamily_Sna;
190 return AddressFamily_DecNet;
193 return AddressFamily_AppleTalk;
195 return AddressFamily_InterNetworkV6;
198 return AddressFamily_Irda;
201 g_warning ("unknown address family 0x%x", af_family);
202 return AddressFamily_Unknown;
207 convert_type (MonoSocketType mono_type)
210 case SocketType_Stream:
212 case SocketType_Dgram:
222 case SocketType_Seqpacket:
223 return SOCK_SEQPACKET;
224 case SocketType_Unknown:
225 g_warning ("System.Net.Sockets.SocketType has unsupported value 0x%x", mono_type);
228 g_warning ("System.Net.Sockets.SocketType has unknown value 0x%x", mono_type);
234 convert_proto (MonoProtocolType mono_proto)
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) */
248 case ProtocolType_ND:
249 case ProtocolType_Raw:
250 case ProtocolType_Ipx:
251 case ProtocolType_Spx:
252 case ProtocolType_SpxII:
253 case ProtocolType_Unknown:
254 /* These protocols arent */
255 g_warning ("System.Net.Sockets.ProtocolType has unsupported value 0x%x", mono_proto);
262 /* Convert MonoSocketFlags */
264 convert_socketflags (gint32 sflags)
269 /* SocketFlags.None */
272 if (sflags & ~(SocketFlags_OutOfBand | SocketFlags_MaxIOVectorLength | SocketFlags_Peek |
273 SocketFlags_DontRoute | SocketFlags_Partial))
274 /* Contains invalid flag values */
277 if (sflags & SocketFlags_OutOfBand)
279 if (sflags & SocketFlags_Peek)
281 if (sflags & SocketFlags_DontRoute)
282 flags |= MSG_DONTROUTE;
284 /* Ignore Partial - see bug 349688. Don't return -1, because
285 * according to the comment in that bug ms runtime doesn't for
286 * UDP sockets (this means we will silently ignore it for TCP
290 if (sflags & SocketFlags_Partial)
294 /* Don't do anything for MaxIOVectorLength */
295 if (sflags & SocketFlags_MaxIOVectorLength)
303 * 0 on success (mapped mono_level and mono_name to system_level and system_name
305 * -2 on non-fatal error (ie, must ignore)
308 convert_sockopt_level_and_name (MonoSocketOptionLevel mono_level, MonoSocketOptionName mono_name, int *system_level, int *system_name)
310 switch (mono_level) {
311 case SocketOptionLevel_Socket:
312 *system_level = SOL_SOCKET;
315 case SocketOptionName_DontLinger:
316 /* This is SO_LINGER, because the setsockopt
317 * internal call maps DontLinger to SO_LINGER
320 *system_name = SO_LINGER;
322 case SocketOptionName_Debug:
323 *system_name = SO_DEBUG;
326 case SocketOptionName_AcceptConnection:
327 *system_name = SO_ACCEPTCONN;
330 case SocketOptionName_ReuseAddress:
331 *system_name = SO_REUSEADDR;
333 case SocketOptionName_KeepAlive:
334 *system_name = SO_KEEPALIVE;
336 case SocketOptionName_DontRoute:
337 *system_name = SO_DONTROUTE;
339 case SocketOptionName_Broadcast:
340 *system_name = SO_BROADCAST;
342 case SocketOptionName_Linger:
343 *system_name = SO_LINGER;
345 case SocketOptionName_OutOfBandInline:
346 *system_name = SO_OOBINLINE;
348 case SocketOptionName_SendBuffer:
349 *system_name = SO_SNDBUF;
351 case SocketOptionName_ReceiveBuffer:
352 *system_name = SO_RCVBUF;
354 case SocketOptionName_SendLowWater:
355 *system_name = SO_SNDLOWAT;
357 case SocketOptionName_ReceiveLowWater:
358 *system_name = SO_RCVLOWAT;
360 case SocketOptionName_SendTimeout:
361 *system_name = SO_SNDTIMEO;
363 case SocketOptionName_ReceiveTimeout:
364 *system_name = SO_RCVTIMEO;
366 case SocketOptionName_Error:
367 *system_name = SO_ERROR;
369 case SocketOptionName_Type:
370 *system_name = SO_TYPE;
373 case SocketOptionName_PeerCred:
374 *system_name = SO_PEERCRED;
377 case SocketOptionName_ExclusiveAddressUse:
378 #ifdef SO_EXCLUSIVEADDRUSE
379 *system_name = SO_EXCLUSIVEADDRUSE;
382 case SocketOptionName_UseLoopback:
383 #ifdef SO_USELOOPBACK
384 *system_name = SO_USELOOPBACK;
387 case SocketOptionName_MaxConnections:
389 *system_name = SO_MAXCONN;
391 #elif defined(SOMAXCONN)
392 *system_name = SOMAXCONN;
396 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at Socket level", mono_name);
401 case SocketOptionLevel_IP:
402 *system_level = mono_networking_get_ip_protocol ();
405 case SocketOptionName_IPOptions:
406 *system_name = IP_OPTIONS;
409 case SocketOptionName_HeaderIncluded:
410 *system_name = IP_HDRINCL;
414 case SocketOptionName_TypeOfService:
415 *system_name = IP_TOS;
419 case SocketOptionName_IpTimeToLive:
420 *system_name = IP_TTL;
423 case SocketOptionName_MulticastInterface:
424 *system_name = IP_MULTICAST_IF;
426 case SocketOptionName_MulticastTimeToLive:
427 *system_name = IP_MULTICAST_TTL;
429 case SocketOptionName_MulticastLoopback:
430 *system_name = IP_MULTICAST_LOOP;
432 case SocketOptionName_AddMembership:
433 *system_name = IP_ADD_MEMBERSHIP;
435 case SocketOptionName_DropMembership:
436 *system_name = IP_DROP_MEMBERSHIP;
438 #ifdef HAVE_IP_PKTINFO
439 case SocketOptionName_PacketInformation:
440 *system_name = IP_PKTINFO;
442 #endif /* HAVE_IP_PKTINFO */
444 case SocketOptionName_DontFragment:
445 #ifdef HAVE_IP_DONTFRAGMENT
446 *system_name = IP_DONTFRAGMENT;
448 #elif defined HAVE_IP_MTU_DISCOVER
449 /* Not quite the same */
450 *system_name = IP_MTU_DISCOVER;
453 /* If the flag is not available on this system, we can ignore this error */
455 #endif /* HAVE_IP_DONTFRAGMENT */
456 case SocketOptionName_AddSourceMembership:
457 case SocketOptionName_DropSourceMembership:
458 case SocketOptionName_BlockSource:
459 case SocketOptionName_UnblockSource:
460 /* Can't figure out how to map these, so fall
464 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at IP level", mono_name);
469 case SocketOptionLevel_IPv6:
470 *system_level = mono_networking_get_ipv6_protocol ();
473 case SocketOptionName_IpTimeToLive:
474 case SocketOptionName_HopLimit:
475 *system_name = IPV6_UNICAST_HOPS;
477 case SocketOptionName_MulticastInterface:
478 *system_name = IPV6_MULTICAST_IF;
480 case SocketOptionName_MulticastTimeToLive:
481 *system_name = IPV6_MULTICAST_HOPS;
483 case SocketOptionName_MulticastLoopback:
484 *system_name = IPV6_MULTICAST_LOOP;
486 case SocketOptionName_AddMembership:
487 *system_name = IPV6_JOIN_GROUP;
489 case SocketOptionName_DropMembership:
490 *system_name = IPV6_LEAVE_GROUP;
492 case SocketOptionName_IPv6Only:
494 *system_name = IPV6_V6ONLY;
499 case SocketOptionName_PacketInformation:
500 #ifdef HAVE_IPV6_PKTINFO
501 *system_name = IPV6_PKTINFO;
504 case SocketOptionName_HeaderIncluded:
505 case SocketOptionName_IPOptions:
506 case SocketOptionName_TypeOfService:
507 case SocketOptionName_DontFragment:
508 case SocketOptionName_AddSourceMembership:
509 case SocketOptionName_DropSourceMembership:
510 case SocketOptionName_BlockSource:
511 case SocketOptionName_UnblockSource:
512 /* Can't figure out how to map these, so fall
516 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at IPv6 level", mono_name);
519 break; /* SocketOptionLevel_IPv6 */
521 case SocketOptionLevel_Tcp:
522 *system_level = mono_networking_get_tcp_protocol ();
525 case SocketOptionName_NoDelay:
526 *system_name = TCP_NODELAY;
529 /* The documentation is talking complete
530 * bollocks here: rfc-1222 is titled
531 * 'Advancing the NSFNET Routing Architecture'
532 * and doesn't mention either of the words
533 * "expedite" or "urgent".
535 case SocketOptionName_BsdUrgent:
536 case SocketOptionName_Expedited:
539 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at TCP level", mono_name);
544 case SocketOptionLevel_Udp:
545 g_warning ("System.Net.Sockets.SocketOptionLevel has unsupported value 0x%x", mono_level);
548 case SocketOptionName_NoChecksum:
549 case SocketOptionName_ChecksumCoverage:
551 g_warning ("System.Net.Sockets.SocketOptionName 0x%x is not supported at UDP level", mono_name);
558 g_warning ("System.Net.Sockets.SocketOptionLevel has unknown value 0x%x", mono_level);
566 get_socket_assembly (void)
568 MonoDomain *domain = mono_domain_get ();
570 if (domain->socket_assembly == NULL) {
571 MonoImage *socket_assembly;
573 socket_assembly = mono_image_loaded ("System");
574 if (!socket_assembly) {
575 MonoAssembly *sa = mono_assembly_open ("System.dll", NULL);
578 g_assert_not_reached ();
580 socket_assembly = mono_assembly_get_image (sa);
583 mono_atomic_store_release (&domain->socket_assembly, socket_assembly);
586 return domain->socket_assembly;
590 get_family_hint (MonoError *error)
592 MonoDomain *domain = mono_domain_get ();
594 mono_error_init (error);
596 if (!domain->inet_family_hint) {
597 MonoImage *socket_assembly;
598 MonoClass *socket_class;
599 MonoClassField *ipv6_field, *ipv4_field;
600 gint32 ipv6_enabled = -1, ipv4_enabled = -1;
603 socket_assembly = get_socket_assembly ();
604 g_assert (socket_assembly);
606 socket_class = mono_class_load_from_name (socket_assembly, "System.Net.Sockets", "Socket");
608 ipv4_field = mono_class_get_field_from_name (socket_class, "ipv4_supported");
609 g_assert (ipv4_field);
611 ipv6_field = mono_class_get_field_from_name (socket_class, "ipv6_supported");
612 g_assert (ipv6_field);
614 vtable = mono_class_vtable (mono_domain_get (), socket_class);
617 mono_runtime_class_init_full (vtable, error);
618 return_val_if_nok (error, -1);
620 mono_field_static_get_value (vtable, ipv4_field, &ipv4_enabled);
621 mono_field_static_get_value (vtable, ipv6_field, &ipv6_enabled);
623 mono_domain_lock (domain);
624 if (ipv4_enabled == 1 && ipv6_enabled == 1) {
625 domain->inet_family_hint = 1;
626 } else if (ipv4_enabled == 1) {
627 domain->inet_family_hint = 2;
629 domain->inet_family_hint = 3;
631 mono_domain_unlock (domain);
633 switch (domain->inet_family_hint) {
634 case 1: return PF_UNSPEC;
635 case 2: return PF_INET;
636 case 3: return PF_INET6;
643 ves_icall_System_Net_Sockets_Socket_Socket_internal (MonoObject *this_obj, gint32 family, gint32 type, gint32 proto, gint32 *werror)
652 sock_family = convert_family ((MonoAddressFamily)family);
653 if (sock_family == -1) {
654 *werror = WSAEAFNOSUPPORT;
658 sock_proto = convert_proto ((MonoProtocolType)proto);
659 if (sock_proto == -1) {
660 *werror = WSAEPROTONOSUPPORT;
664 sock_type = convert_type ((MonoSocketType)type);
665 if (sock_type == -1) {
666 *werror = WSAESOCKTNOSUPPORT;
670 sock = _wapi_socket (sock_family, sock_type, sock_proto,
671 NULL, 0, WSA_FLAG_OVERLAPPED);
673 if (sock == INVALID_SOCKET) {
674 *werror = WSAGetLastError ();
678 return GUINT_TO_POINTER (sock);
681 /* FIXME: the SOCKET parameter (here and in other functions in this
682 * file) is really an IntPtr which needs to be converted to a guint32.
685 ves_icall_System_Net_Sockets_Socket_Close_internal (SOCKET sock, gint32 *werror)
687 LOGDEBUG (g_message ("%s: closing 0x%x", __func__, sock));
691 /* Clear any pending work item from this socket if the underlying
692 * polling system does not notify when the socket is closed */
693 mono_threadpool_ms_io_remove_socket (GPOINTER_TO_INT (sock));
695 MONO_PREPARE_BLOCKING;
697 MONO_FINISH_BLOCKING;
701 ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal (void)
703 LOGDEBUG (g_message("%s: returning %d", __func__, WSAGetLastError ()));
705 return WSAGetLastError ();
709 ves_icall_System_Net_Sockets_Socket_Available_internal (SOCKET sock, gint32 *werror)
716 /* FIXME: this might require amount to be unsigned long. */
717 ret = ioctlsocket (sock, FIONREAD, &amount);
718 if (ret == SOCKET_ERROR) {
719 *werror = WSAGetLastError ();
727 ves_icall_System_Net_Sockets_Socket_Blocking_internal (SOCKET sock, gboolean block, gint32 *werror)
734 * block == TRUE/FALSE means we will block/not block.
735 * But the ioctlsocket call takes TRUE/FALSE for non-block/block
739 ret = ioctlsocket (sock, FIONBIO, (gulong *)&block);
740 if (ret == SOCKET_ERROR)
741 *werror = WSAGetLastError ();
745 ves_icall_System_Net_Sockets_Socket_Accept_internal (SOCKET sock, gint32 *werror, gboolean blocking)
747 gboolean interrupted;
752 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
758 MONO_PREPARE_BLOCKING;
762 MonoInternalThread *curthread = mono_thread_internal_current ();
763 curthread->interrupt_on_stop = (gpointer)TRUE;
764 newsock = _wapi_accept (sock, NULL, 0);
765 curthread->interrupt_on_stop = (gpointer)FALSE;
768 newsock = _wapi_accept (sock, NULL, 0);
771 MONO_FINISH_BLOCKING;
773 mono_thread_info_uninstall_interrupt (&interrupted);
779 if (newsock == INVALID_SOCKET) {
780 *werror = WSAGetLastError ();
784 return GUINT_TO_POINTER (newsock);
788 ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock, guint32 backlog, gint32 *werror)
794 MONO_PREPARE_BLOCKING;
796 ret = _wapi_listen (sock, backlog);
798 MONO_FINISH_BLOCKING;
800 if (ret == SOCKET_ERROR)
801 *werror = WSAGetLastError ();
804 // Check whether it's ::ffff::0:0.
806 is_ipv4_mapped_any (const struct in6_addr *addr)
810 for (i = 0; i < 10; i++) {
811 if (addr->s6_addr [i])
814 if ((addr->s6_addr [10] != 0xff) || (addr->s6_addr [11] != 0xff))
816 for (i = 12; i < 16; i++) {
817 if (addr->s6_addr [i])
824 create_object_from_sockaddr (struct sockaddr *saddr, int sa_size, gint32 *werror, MonoError *error)
826 MonoDomain *domain = mono_domain_get ();
827 MonoObject *sockaddr_obj;
829 MonoAddressFamily family;
831 mono_error_init (error);
833 /* Build a System.Net.SocketAddress object instance */
834 if (!domain->sockaddr_class)
835 domain->sockaddr_class = mono_class_load_from_name (get_socket_assembly (), "System.Net", "SocketAddress");
836 sockaddr_obj = mono_object_new_checked (domain, domain->sockaddr_class, error);
837 return_val_if_nok (error, NULL);
839 /* Locate the SocketAddress data buffer in the object */
840 if (!domain->sockaddr_data_field) {
841 domain->sockaddr_data_field = mono_class_get_field_from_name (domain->sockaddr_class, "data");
842 g_assert (domain->sockaddr_data_field);
845 /* May be the +2 here is too conservative, as sa_len returns
846 * the length of the entire sockaddr_in/in6, including
847 * sizeof (unsigned short) of the family */
848 /* We can't really avoid the +2 as all code below depends on this size - INCLUDING unix domain sockets.*/
849 data = mono_array_new_cached (domain, mono_get_byte_class (), sa_size + 2);
851 /* The data buffer is laid out as follows:
852 * bytes 0 and 1 are the address family
853 * bytes 2 and 3 are the port info
854 * the rest is the address info
857 family = convert_to_mono_family (saddr->sa_family);
858 if (family == AddressFamily_Unknown) {
859 *werror = WSAEAFNOSUPPORT;
863 mono_array_set (data, guint8, 0, family & 0x0FF);
864 mono_array_set (data, guint8, 1, (family >> 8) & 0x0FF);
866 if (saddr->sa_family == AF_INET) {
867 struct sockaddr_in *sa_in = (struct sockaddr_in *)saddr;
868 guint16 port = ntohs (sa_in->sin_port);
869 guint32 address = ntohl (sa_in->sin_addr.s_addr);
872 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
876 mono_array_set (data, guint8, 2, (port>>8) & 0xff);
877 mono_array_set (data, guint8, 3, (port) & 0xff);
878 mono_array_set (data, guint8, 4, (address>>24) & 0xff);
879 mono_array_set (data, guint8, 5, (address>>16) & 0xff);
880 mono_array_set (data, guint8, 6, (address>>8) & 0xff);
881 mono_array_set (data, guint8, 7, (address) & 0xff);
883 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
886 } else if (saddr->sa_family == AF_INET6) {
887 struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)saddr;
890 guint16 port = ntohs (sa_in->sin6_port);
893 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
897 mono_array_set (data, guint8, 2, (port>>8) & 0xff);
898 mono_array_set (data, guint8, 3, (port) & 0xff);
900 if (is_ipv4_mapped_any (&sa_in->sin6_addr)) {
901 // Map ::ffff:0:0 to :: (bug #5502)
902 for (i = 0; i < 16; i++)
903 mono_array_set (data, guint8, 8 + i, 0);
905 for (i = 0; i < 16; i++) {
906 mono_array_set (data, guint8, 8 + i,
907 sa_in->sin6_addr.s6_addr [i]);
911 mono_array_set (data, guint8, 24, sa_in->sin6_scope_id & 0xff);
912 mono_array_set (data, guint8, 25,
913 (sa_in->sin6_scope_id >> 8) & 0xff);
914 mono_array_set (data, guint8, 26,
915 (sa_in->sin6_scope_id >> 16) & 0xff);
916 mono_array_set (data, guint8, 27,
917 (sa_in->sin6_scope_id >> 24) & 0xff);
919 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
924 else if (saddr->sa_family == AF_UNIX) {
927 for (i = 0; i < sa_size; i++)
928 mono_array_set (data, guint8, i + 2, saddr->sa_data [i]);
930 mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
936 *werror = WSAEAFNOSUPPORT;
942 get_sockaddr_size (int family)
947 if (family == AF_INET) {
948 size = sizeof (struct sockaddr_in);
949 } else if (family == AF_INET6) {
950 size = sizeof (struct sockaddr_in6);
953 else if (family == AF_UNIX) {
954 size = sizeof (struct sockaddr_un);
961 ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal (SOCKET sock, gint32 af, gint32 *werror)
971 salen = get_sockaddr_size (convert_family ((MonoAddressFamily)af));
973 *werror = WSAEAFNOSUPPORT;
976 sa = (salen <= 128) ? (gchar *)alloca (salen) : (gchar *)g_malloc0 (salen);
978 MONO_PREPARE_BLOCKING;
980 ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
982 MONO_FINISH_BLOCKING;
984 if (ret == SOCKET_ERROR) {
985 *werror = WSAGetLastError ();
991 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)));
993 result = create_object_from_sockaddr ((struct sockaddr *)sa, salen, werror, &error);
996 if (!mono_error_ok (&error))
997 mono_error_set_pending_exception (&error);
1002 ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal (SOCKET sock, gint32 af, gint32 *werror)
1012 salen = get_sockaddr_size (convert_family ((MonoAddressFamily)af));
1014 *werror = WSAEAFNOSUPPORT;
1017 sa = (salen <= 128) ? (gchar *)alloca (salen) : (gchar *)g_malloc0 (salen);
1018 /* Note: linux returns just 2 for AF_UNIX. Always. */
1020 MONO_PREPARE_BLOCKING;
1022 ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
1024 MONO_FINISH_BLOCKING;
1026 if (ret == SOCKET_ERROR) {
1027 *werror = WSAGetLastError ();
1033 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)));
1035 result = create_object_from_sockaddr ((struct sockaddr *)sa, salen, werror, &error);
1038 if (!mono_error_ok (&error))
1039 mono_error_set_pending_exception (&error);
1043 static struct sockaddr*
1044 create_sockaddr_from_object (MonoObject *saddr_obj, socklen_t *sa_size, gint32 *werror, MonoError *error)
1046 MonoClassField *field;
1051 mono_error_init (error);
1053 /* Dig the SocketAddress data buffer out of the object */
1054 field = mono_class_get_field_from_name (saddr_obj->vtable->klass, "data");
1055 data = *(MonoArray **)(((char *)saddr_obj) + field->offset);
1057 /* The data buffer is laid out as follows:
1058 * byte 0 is the address family low byte
1059 * byte 1 is the address family high byte
1061 * bytes 2 and 3 are the port info
1062 * the rest is the address info
1064 * the rest is the file name
1066 len = mono_array_length (data);
1068 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1072 family = convert_family ((MonoAddressFamily)(mono_array_get (data, guint8, 0) + (mono_array_get (data, guint8, 1) << 8)));
1073 if (family == AF_INET) {
1074 struct sockaddr_in *sa;
1079 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1083 sa = g_new0 (struct sockaddr_in, 1);
1084 port = (mono_array_get (data, guint8, 2) << 8) +
1085 mono_array_get (data, guint8, 3);
1086 address = (mono_array_get (data, guint8, 4) << 24) +
1087 (mono_array_get (data, guint8, 5) << 16 ) +
1088 (mono_array_get (data, guint8, 6) << 8) +
1089 mono_array_get (data, guint8, 7);
1091 sa->sin_family = family;
1092 sa->sin_addr.s_addr = htonl (address);
1093 sa->sin_port = htons (port);
1095 *sa_size = sizeof (struct sockaddr_in);
1096 return (struct sockaddr *)sa;
1097 } else if (family == AF_INET6) {
1098 struct sockaddr_in6 *sa;
1104 mono_error_set_exception_instance (error, mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1108 sa = g_new0 (struct sockaddr_in6, 1);
1109 port = mono_array_get (data, guint8, 3) +
1110 (mono_array_get (data, guint8, 2) << 8);
1111 scopeid = mono_array_get (data, guint8, 24) +
1112 (mono_array_get (data, guint8, 25) << 8) +
1113 (mono_array_get (data, guint8, 26) << 16) +
1114 (mono_array_get (data, guint8, 27) << 24);
1116 sa->sin6_family = family;
1117 sa->sin6_port = htons (port);
1118 sa->sin6_scope_id = scopeid;
1120 for (i = 0; i < 16; i++)
1121 sa->sin6_addr.s6_addr [i] = mono_array_get (data, guint8, 8 + i);
1123 *sa_size = sizeof (struct sockaddr_in6);
1124 return (struct sockaddr *)sa;
1126 #ifdef HAVE_SYS_UN_H
1127 else if (family == AF_UNIX) {
1128 struct sockaddr_un *sock_un;
1131 /* Need a byte for the '\0' terminator/prefix, and the first
1132 * two bytes hold the SocketAddress family
1134 if (len - 2 >= sizeof (sock_un->sun_path)) {
1135 mono_error_set_exception_instance (error, mono_get_exception_index_out_of_range ());
1139 sock_un = g_new0 (struct sockaddr_un, 1);
1141 sock_un->sun_family = family;
1142 for (i = 0; i < len - 2; i++)
1143 sock_un->sun_path [i] = mono_array_get (data, guint8, i + 2);
1146 return (struct sockaddr *)sock_un;
1150 *werror = WSAEAFNOSUPPORT;
1156 ves_icall_System_Net_Sockets_Socket_Bind_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror)
1159 struct sockaddr *sa;
1165 sa = create_sockaddr_from_object (sockaddr, &sa_size, werror, &error);
1168 if (!mono_error_ok (&error)) {
1169 mono_error_set_pending_exception (&error);
1173 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)));
1175 ret = _wapi_bind (sock, sa, sa_size);
1177 if (ret == SOCKET_ERROR)
1178 *werror = WSAGetLastError ();
1190 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
1191 gint timeout, gint32 *werror)
1193 MonoInternalThread *thread = mono_thread_internal_current ();
1196 gboolean interrupted;
1201 pfds = g_new0 (mono_pollfd, 1);
1202 pfds->fd = GPOINTER_TO_INT (sock);
1205 case SelectModeRead:
1206 pfds->events = MONO_POLLIN;
1208 case SelectModeWrite:
1209 pfds->events = MONO_POLLOUT;
1212 pfds->events = MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL;
1216 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1217 start = time (NULL);
1220 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1227 MONO_PREPARE_BLOCKING;
1229 ret = mono_poll (pfds, 1, timeout);
1231 MONO_FINISH_BLOCKING;
1233 mono_thread_info_uninstall_interrupt (&interrupted);
1240 if (timeout > 0 && ret < 0) {
1242 int sec = time (NULL) - start;
1244 timeout -= sec * 1000;
1252 if (ret == -1 && errno == EINTR) {
1253 if (mono_thread_test_state (thread, (MonoThreadState)(ThreadState_AbortRequested | ThreadState_StopRequested))) {
1258 /* Suspend requested? */
1259 mono_thread_interruption_checkpoint ();
1263 } while (ret == -1 && errno == EINTR);
1267 *werror = WSAGetLastError ();
1269 *werror = errno_to_WSA (errno, __func__);
1280 ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror)
1283 struct sockaddr *sa;
1286 gboolean interrupted;
1290 sa = create_sockaddr_from_object (sockaddr, &sa_size, werror, &error);
1293 if (!mono_error_ok (&error)) {
1294 mono_error_set_pending_exception (&error);
1298 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)));
1300 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1306 MONO_PREPARE_BLOCKING;
1308 ret = _wapi_connect (sock, sa, sa_size);
1310 MONO_FINISH_BLOCKING;
1312 mono_thread_info_uninstall_interrupt (&interrupted);
1318 if (ret == SOCKET_ERROR)
1319 *werror = WSAGetLastError ();
1324 /* These #defines from mswsock.h from wine. Defining them here allows
1325 * us to build this file on a mingw box that doesn't know the magic
1326 * numbers, but still run on a newer windows box that does.
1328 #ifndef WSAID_DISCONNECTEX
1329 #define WSAID_DISCONNECTEX {0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
1330 typedef BOOL (WINAPI *LPFN_DISCONNECTEX)(SOCKET, LPOVERLAPPED, DWORD, DWORD);
1333 #ifndef WSAID_TRANSMITFILE
1334 #define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
1335 typedef BOOL (WINAPI *LPFN_TRANSMITFILE)(SOCKET, HANDLE, DWORD, DWORD, LPOVERLAPPED, LPTRANSMIT_FILE_BUFFERS, DWORD);
1339 ves_icall_System_Net_Sockets_Socket_Disconnect_internal (SOCKET sock, MonoBoolean reuse, gint32 *werror)
1342 glong output_bytes = 0;
1343 GUID disco_guid = WSAID_DISCONNECTEX;
1344 GUID trans_guid = WSAID_TRANSMITFILE;
1345 LPFN_DISCONNECTEX _wapi_disconnectex = NULL;
1346 LPFN_TRANSMITFILE _wapi_transmitfile = NULL;
1347 gboolean interrupted;
1351 LOGDEBUG (g_message("%s: disconnecting from socket %p (reuse %d)", __func__, sock, reuse));
1353 MONO_PREPARE_BLOCKING;
1355 /* I _think_ the extension function pointers need to be looked
1356 * up for each socket. FIXME: check the best way to store
1357 * pointers to functions in managed objects that still works
1358 * on 64bit platforms.
1360 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER, (gchar *)&disco_guid, sizeof (GUID),
1361 (gchar *)&_wapi_disconnectex, sizeof (void *), &output_bytes, NULL, NULL);
1363 MONO_FINISH_BLOCKING;
1366 /* make sure that WSAIoctl didn't put crap in the
1369 _wapi_disconnectex = NULL;
1371 MONO_PREPARE_BLOCKING;
1374 * Use the SIO_GET_EXTENSION_FUNCTION_POINTER to
1375 * determine the address of the disconnect method without
1376 * taking a hard dependency on a single provider
1378 * For an explanation of why this is done, you can read
1379 * the article at http://www.codeproject.com/internet/jbsocketserver3.asp
1381 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER, (gchar *)&trans_guid, sizeof(GUID),
1382 (gchar *)&_wapi_transmitfile, sizeof(void *), &output_bytes, NULL, NULL);
1384 MONO_FINISH_BLOCKING;
1387 _wapi_transmitfile = NULL;
1390 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1396 MONO_PREPARE_BLOCKING;
1398 if (_wapi_disconnectex != NULL) {
1399 if (!_wapi_disconnectex (sock, NULL, TF_REUSE_SOCKET, 0))
1400 *werror = WSAGetLastError ();
1401 } else if (_wapi_transmitfile != NULL) {
1402 if (!_wapi_transmitfile (sock, NULL, 0, 0, NULL, NULL, TF_DISCONNECT | TF_REUSE_SOCKET))
1403 *werror = WSAGetLastError ();
1405 *werror = ERROR_NOT_SUPPORTED;
1408 MONO_FINISH_BLOCKING;
1410 mono_thread_info_uninstall_interrupt (&interrupted);
1416 ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
1422 gboolean interrupted;
1423 MonoInternalThread* curthread G_GNUC_UNUSED = mono_thread_internal_current ();
1427 alen = mono_array_length (buffer);
1428 if (offset > alen - count)
1431 buf = mono_array_addr (buffer, guchar, offset);
1433 recvflags = convert_socketflags (flags);
1434 if (recvflags == -1) {
1435 *werror = WSAEOPNOTSUPP;
1439 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1443 MONO_PREPARE_BLOCKING;
1447 curthread->interrupt_on_stop = (gpointer)TRUE;
1448 ret = _wapi_recv (sock, buf, count, recvflags);
1449 curthread->interrupt_on_stop = (gpointer)FALSE;
1452 ret = _wapi_recv (sock, buf, count, recvflags);
1455 MONO_FINISH_BLOCKING;
1457 mono_thread_info_uninstall_interrupt (&interrupted);
1463 if (ret == SOCKET_ERROR) {
1464 *werror = WSAGetLastError ();
1472 ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
1475 gboolean interrupted;
1478 DWORD recvflags = 0;
1482 wsabufs = mono_array_addr (buffers, WSABUF, 0);
1483 count = mono_array_length (buffers);
1485 recvflags = convert_socketflags (flags);
1486 if (recvflags == -1) {
1487 *werror = WSAEOPNOTSUPP;
1491 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1497 MONO_PREPARE_BLOCKING;
1499 ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
1501 MONO_FINISH_BLOCKING;
1503 mono_thread_info_uninstall_interrupt (&interrupted);
1509 if (ret == SOCKET_ERROR) {
1510 *werror = WSAGetLastError ();
1518 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror)
1525 struct sockaddr *sa;
1527 gboolean interrupted;
1531 alen = mono_array_length (buffer);
1532 if (offset > alen - count)
1535 sa = create_sockaddr_from_object (*sockaddr, &sa_size, werror, &error);
1538 if (!mono_error_ok (&error)) {
1539 mono_error_set_pending_exception (&error);
1543 buf = mono_array_addr (buffer, guchar, offset);
1545 recvflags = convert_socketflags (flags);
1546 if (recvflags == -1) {
1547 *werror = WSAEOPNOTSUPP;
1551 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1558 MONO_PREPARE_BLOCKING;
1560 ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
1562 MONO_FINISH_BLOCKING;
1564 mono_thread_info_uninstall_interrupt (&interrupted);
1571 if (ret==SOCKET_ERROR) {
1573 *werror = WSAGetLastError ();
1577 /* If we didn't get a socket size, then we're probably a
1578 * connected connection-oriented socket and the stack hasn't
1579 * returned the remote address. All we can do is return null.
1582 *sockaddr = create_object_from_sockaddr (sa, sa_size, werror, &error);
1583 if (!mono_error_ok (&error)) {
1584 mono_error_set_pending_exception (&error);
1598 ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
1604 gboolean interrupted;
1608 alen = mono_array_length (buffer);
1609 if (offset > alen - count)
1612 LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
1614 buf = mono_array_addr (buffer, guchar, offset);
1616 LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1618 sendflags = convert_socketflags (flags);
1619 if (sendflags == -1) {
1620 *werror = WSAEOPNOTSUPP;
1624 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1630 MONO_PREPARE_BLOCKING;
1632 ret = _wapi_send (sock, buf, count, sendflags);
1634 MONO_FINISH_BLOCKING;
1636 mono_thread_info_uninstall_interrupt (&interrupted);
1642 if (ret == SOCKET_ERROR) {
1643 *werror = WSAGetLastError ();
1651 ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
1656 DWORD sendflags = 0;
1657 gboolean interrupted;
1661 wsabufs = mono_array_addr (buffers, WSABUF, 0);
1662 count = mono_array_length (buffers);
1664 sendflags = convert_socketflags (flags);
1665 if (sendflags == -1) {
1666 *werror = WSAEOPNOTSUPP;
1670 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1676 MONO_PREPARE_BLOCKING;
1678 ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
1680 MONO_FINISH_BLOCKING;
1682 mono_thread_info_uninstall_interrupt (&interrupted);
1688 if (ret == SOCKET_ERROR) {
1689 *werror = WSAGetLastError ();
1697 ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror)
1704 struct sockaddr *sa;
1706 gboolean interrupted;
1710 alen = mono_array_length (buffer);
1711 if (offset > alen - count) {
1715 sa = create_sockaddr_from_object(sockaddr, &sa_size, werror, &error);
1718 if (!mono_error_ok (&error)) {
1719 mono_error_set_pending_exception (&error);
1723 LOGDEBUG (g_message ("%s: alen: %d", __func__, alen));
1725 buf = mono_array_addr (buffer, guchar, offset);
1727 LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
1729 sendflags = convert_socketflags (flags);
1730 if (sendflags == -1) {
1732 *werror = WSAEOPNOTSUPP;
1736 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1743 MONO_PREPARE_BLOCKING;
1745 ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
1747 MONO_FINISH_BLOCKING;
1749 mono_thread_info_uninstall_interrupt (&interrupted);
1756 if (ret == SOCKET_ERROR)
1757 *werror = WSAGetLastError ();
1765 Socket_to_SOCKET (MonoObject *sockobj)
1767 MonoSafeHandle *safe_handle;
1768 MonoClassField *field;
1770 field = mono_class_get_field_from_name (sockobj->vtable->klass, "safe_handle");
1771 safe_handle = ((MonoSafeHandle *)(*(gpointer *)(((char *)sockobj) + field->offset)));
1773 if (safe_handle == NULL)
1776 return (SOCKET)safe_handle->handle;
1779 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
1782 ves_icall_System_Net_Sockets_Socket_Select_internal (MonoArray **sockets, gint32 timeout, gint32 *werror)
1785 MonoInternalThread *thread = mono_thread_internal_current ();
1792 MonoClass *sock_arr_class;
1795 uintptr_t socks_size;
1796 gboolean interrupted;
1800 /* *sockets -> READ, null, WRITE, null, ERROR, null */
1801 count = mono_array_length (*sockets);
1802 nfds = count - 3; /* NULL separators */
1803 pfds = g_new0 (mono_pollfd, nfds);
1805 for (i = 0; i < count; i++) {
1806 obj = mono_array_get (*sockets, MonoObject *, i);
1813 /* The socket array was bogus */
1815 *werror = WSAEFAULT;
1819 pfds [idx].fd = Socket_to_SOCKET (obj);
1820 pfds [idx].events = (mode == 0) ? MONO_POLLIN : (mode == 1) ? MONO_POLLOUT : POLL_ERRORS;
1824 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1825 start = time (NULL);
1827 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
1834 MONO_PREPARE_BLOCKING;
1836 ret = mono_poll (pfds, nfds, timeout);
1838 MONO_FINISH_BLOCKING;
1840 mono_thread_info_uninstall_interrupt (&interrupted);
1847 if (timeout > 0 && ret < 0) {
1849 int sec = time (NULL) - start;
1851 timeout -= sec * 1000;
1857 if (ret == -1 && errno == EINTR) {
1858 if (mono_thread_test_state (thread, (MonoThreadState)(ThreadState_AbortRequested | ThreadState_StopRequested))) {
1864 /* Suspend requested? */
1865 mono_thread_interruption_checkpoint ();
1869 } while (ret == -1 && errno == EINTR);
1873 *werror = WSAGetLastError ();
1875 *werror = errno_to_WSA (errno, __func__);
1887 sock_arr_class = ((MonoObject *)*sockets)->vtable->klass;
1888 socks_size = ((uintptr_t)ret) + 3; /* space for the NULL delimiters */
1889 socks = mono_array_new_full_checked (mono_domain_get (), sock_arr_class, &socks_size, NULL, &error);
1890 if (!mono_error_ok (&error)) {
1891 mono_error_set_pending_exception (&error);
1897 for (i = 0; i < count && ret > 0; i++) {
1900 obj = mono_array_get (*sockets, MonoObject *, i);
1907 pfd = &pfds [i - mode];
1908 if (pfd->revents == 0)
1912 if (mode == 0 && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
1913 mono_array_setref (socks, idx++, obj);
1914 } else if (mode == 1 && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
1915 mono_array_setref (socks, idx++, obj);
1916 } else if ((pfd->revents & POLL_ERRORS) != 0) {
1917 mono_array_setref (socks, idx++, obj);
1926 int_to_object (MonoDomain *domain, int val)
1928 return mono_value_box (domain, mono_get_int32_class (), &val);
1932 ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *werror)
1934 int system_level = 0;
1935 int system_name = 0;
1938 socklen_t valsize = sizeof (val);
1939 struct linger linger;
1940 socklen_t lingersize = sizeof (linger);
1942 socklen_t time_ms_size = sizeof (time_ms);
1944 # if defined(__OpenBSD__)
1945 struct sockpeercred cred;
1949 socklen_t credsize = sizeof (cred);
1952 MonoDomain *domain = mono_domain_get ();
1954 MonoClass *obj_class;
1955 MonoClassField *field;
1959 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
1960 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
1961 system_level = SOL_SOCKET;
1962 system_name = SO_REUSEADDR;
1967 ret = convert_sockopt_level_and_name ((MonoSocketOptionLevel)level, (MonoSocketOptionName)name, &system_level, &system_name);
1971 *werror = WSAENOPROTOOPT;
1975 *obj_val = int_to_object (domain, 0);
1979 MONO_PREPARE_BLOCKING;
1981 /* No need to deal with MulticastOption names here, because
1982 * you cant getsockopt AddMembership or DropMembership (the
1983 * int getsockopt will error, causing an exception)
1986 case SocketOptionName_Linger:
1987 case SocketOptionName_DontLinger:
1988 ret = _wapi_getsockopt (sock, system_level, system_name, &linger, &lingersize);
1991 case SocketOptionName_SendTimeout:
1992 case SocketOptionName_ReceiveTimeout:
1993 ret = _wapi_getsockopt (sock, system_level, system_name, (char *)&time_ms, &time_ms_size);
1997 case SocketOptionName_PeerCred:
1998 ret = _wapi_getsockopt (sock, system_level, system_name, &cred, &credsize);
2003 ret = _wapi_getsockopt (sock, system_level, system_name, &val, &valsize);
2006 MONO_FINISH_BLOCKING;
2008 if (ret == SOCKET_ERROR) {
2009 *werror = WSAGetLastError ();
2014 case SocketOptionName_Linger:
2015 /* build a System.Net.Sockets.LingerOption */
2016 obj_class = mono_class_load_from_name (get_socket_assembly (),
2017 "System.Net.Sockets",
2019 obj = mono_object_new_checked (domain, obj_class, &error);
2020 if (!mono_error_ok (&error)) {
2021 mono_error_set_pending_exception (&error);
2025 /* Locate and set the fields "bool enabled" and "int
2028 field = mono_class_get_field_from_name(obj_class, "enabled");
2029 *(guint8 *)(((char *)obj)+field->offset) = linger.l_onoff;
2031 field = mono_class_get_field_from_name(obj_class, "lingerTime");
2032 *(guint32 *)(((char *)obj)+field->offset)=linger.l_linger;
2034 case SocketOptionName_DontLinger:
2035 /* construct a bool int in val - true if linger is off */
2036 obj = int_to_object (domain, !linger.l_onoff);
2038 case SocketOptionName_SendTimeout:
2039 case SocketOptionName_ReceiveTimeout:
2040 obj = int_to_object (domain, time_ms);
2044 case SocketOptionName_PeerCred: {
2046 * build a Mono.Posix.PeerCred+PeerCredData if
2049 static MonoImage *mono_posix_image = NULL;
2050 MonoPeerCredData *cred_data;
2052 if (mono_posix_image == NULL) {
2053 mono_posix_image = mono_image_loaded ("Mono.Posix");
2054 if (!mono_posix_image) {
2055 MonoAssembly *sa = mono_assembly_open ("Mono.Posix.dll", NULL);
2057 *werror = WSAENOPROTOOPT;
2060 mono_posix_image = mono_assembly_get_image (sa);
2065 obj_class = mono_class_load_from_name (mono_posix_image,
2068 obj = mono_object_new_checked (domain, obj_class, &error);
2069 if (!mono_error_ok (&error)) {
2070 mono_error_set_pending_exception (&error);
2073 cred_data = (MonoPeerCredData *)obj;
2074 cred_data->pid = cred.pid;
2075 cred_data->uid = cred.uid;
2076 cred_data->gid = cred.gid;
2082 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
2083 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse)
2086 obj = int_to_object (domain, val);
2093 ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal (SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *werror)
2095 int system_level = 0;
2096 int system_name = 0;
2103 ret = convert_sockopt_level_and_name((MonoSocketOptionLevel)level, (MonoSocketOptionName)name, &system_level,
2106 *werror = WSAENOPROTOOPT;
2112 valsize = mono_array_length (*byte_val);
2113 buf = mono_array_addr (*byte_val, guchar, 0);
2115 MONO_PREPARE_BLOCKING;
2117 ret = _wapi_getsockopt (sock, system_level, system_name, buf, &valsize);
2119 MONO_FINISH_BLOCKING;
2121 if (ret == SOCKET_ERROR)
2122 *werror = WSAGetLastError ();
2125 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2126 static struct in_addr
2127 ipaddress_to_struct_in_addr (MonoObject *ipaddr)
2129 struct in_addr inaddr;
2130 MonoClassField *field;
2132 field = mono_class_get_field_from_name (ipaddr->vtable->klass, "m_Address");
2134 /* No idea why .net uses a 64bit type to hold a 32bit value...
2136 * Internal value of IPAddess is in little-endian order
2138 inaddr.s_addr = GUINT_FROM_LE ((guint32)*(guint64 *)(((char *)ipaddr) + field->offset));
2143 static struct in6_addr
2144 ipaddress_to_struct_in6_addr (MonoObject *ipaddr)
2146 struct in6_addr in6addr;
2147 MonoClassField *field;
2151 field = mono_class_get_field_from_name (ipaddr->vtable->klass, "m_Numbers");
2152 data = *(MonoArray **)(((char *)ipaddr) + field->offset);
2154 /* Solaris has only the 8 bit version. */
2156 for (i = 0; i < 8; i++) {
2157 guint16 s = mono_array_get (data, guint16, i);
2158 in6addr.s6_addr[2 * i + 1] = (s >> 8) & 0xff;
2159 in6addr.s6_addr[2 * i] = s & 0xff;
2162 for (i = 0; i < 8; i++)
2163 in6addr.s6_addr16[i] = mono_array_get (data, guint16, i);
2169 #if defined(__APPLE__) || defined(__FreeBSD__)
2172 get_local_interface_id (int family)
2174 #if !defined(HAVE_GETIFADDRS) || !defined(HAVE_IF_NAMETOINDEX)
2177 struct ifaddrs *ifap = NULL, *ptr;
2180 if (getifaddrs (&ifap))
2183 for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
2184 if (!ptr->ifa_addr || !ptr->ifa_name)
2186 if (ptr->ifa_addr->sa_family != family)
2188 if ((ptr->ifa_flags & IFF_LOOPBACK) != 0)
2190 if ((ptr->ifa_flags & IFF_MULTICAST) == 0)
2193 idx = if_nametoindex (ptr->ifa_name);
2202 #endif /* defined(__APPLE__) || defined(__FreeBSD__) */
2205 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)
2207 struct linger linger;
2208 int system_level = 0;
2209 int system_name = 0;
2216 sol_ipv6 = mono_networking_get_ipv6_protocol ();
2217 sol_ip = mono_networking_get_ip_protocol ();
2219 ret = convert_sockopt_level_and_name ((MonoSocketOptionLevel)level, (MonoSocketOptionName)name, &system_level,
2222 #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
2223 if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
2224 system_name = SO_REUSEADDR;
2225 int_val = int_val ? 0 : 1;
2231 *werror = WSAENOPROTOOPT;
2237 /* Only one of obj_val, byte_val or int_val has data */
2239 MonoClassField *field;
2243 case SocketOptionName_Linger:
2244 /* Dig out "bool enabled" and "int lingerTime"
2247 field = mono_class_get_field_from_name (obj_val->vtable->klass, "enabled");
2248 linger.l_onoff = *(guint8 *)(((char *)obj_val) + field->offset);
2249 field = mono_class_get_field_from_name (obj_val->vtable->klass, "lingerTime");
2250 linger.l_linger = *(guint32 *)(((char *)obj_val) + field->offset);
2252 valsize = sizeof (linger);
2253 ret = _wapi_setsockopt (sock, system_level,
2254 system_name, &linger, valsize);
2256 case SocketOptionName_AddMembership:
2257 case SocketOptionName_DropMembership:
2258 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
2260 MonoObject *address = NULL;
2262 if (system_level == sol_ipv6) {
2263 struct ipv6_mreq mreq6;
2268 field = mono_class_get_field_from_name (obj_val->vtable->klass, "m_Group");
2269 address = *(MonoObject **)(((char *)obj_val) + field->offset);
2272 mreq6.ipv6mr_multiaddr = ipaddress_to_struct_in6_addr (address);
2274 field = mono_class_get_field_from_name (obj_val->vtable->klass, "m_Interface");
2275 mreq6.ipv6mr_interface = *(guint64 *)(((char *)obj_val) + field->offset);
2277 #if defined(__APPLE__) || defined(__FreeBSD__)
2281 * Mac OS Lion doesn't allow ipv6mr_interface = 0.
2283 * Tests on Windows and Linux show that the multicast group is only
2284 * joined on one NIC when interface = 0, so we simply use the interface
2285 * id from the first non-loopback interface (this is also what
2286 * Dns.GetHostName (string.Empty) would return).
2288 if (!mreq6.ipv6mr_interface)
2289 mreq6.ipv6mr_interface = get_local_interface_id (AF_INET6);
2292 ret = _wapi_setsockopt (sock, system_level,
2293 system_name, &mreq6,
2295 } else if (system_level == sol_ip) {
2296 #ifdef HAVE_STRUCT_IP_MREQN
2297 struct ip_mreqn mreq = {{0}};
2299 struct ip_mreq mreq = {{0}};
2300 #endif /* HAVE_STRUCT_IP_MREQN */
2303 * pain! MulticastOption holds two IPAddress
2304 * members, so I have to dig the value out of
2307 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
2308 address = *(MonoObject **)(((char *)obj_val) + field->offset);
2310 /* address might not be defined and if so, set the address to ADDR_ANY.
2313 mreq.imr_multiaddr = ipaddress_to_struct_in_addr (address);
2315 field = mono_class_get_field_from_name (obj_val->vtable->klass, "localAddress");
2316 address = *(MonoObject **)(((char *)obj_val) + field->offset);
2318 #ifdef HAVE_STRUCT_IP_MREQN
2320 mreq.imr_address = ipaddress_to_struct_in_addr (address);
2322 field = mono_class_get_field_from_name (obj_val->vtable->klass, "ifIndex");
2323 mreq.imr_ifindex = *(gint32 *)(((char *)obj_val) + field->offset);
2326 mreq.imr_interface = ipaddress_to_struct_in_addr (address);
2327 #endif /* HAVE_STRUCT_IP_MREQN */
2329 ret = _wapi_setsockopt (sock, system_level,
2335 #endif /* HAVE_STRUCT_IP_MREQN || HAVE_STRUCT_IP_MREQ */
2337 /* Cause an exception to be thrown */
2338 *werror = WSAEINVAL;
2341 } else if (byte_val!=NULL) {
2342 int valsize = mono_array_length (byte_val);
2343 guchar *buf = mono_array_addr (byte_val, guchar, 0);
2346 case SocketOptionName_DontLinger:
2348 linger.l_onoff = (*buf) ? 0 : 1;
2349 linger.l_linger = 0;
2350 ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2352 *werror = WSAEINVAL;
2356 ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
2360 /* ReceiveTimeout/SendTimeout get here */
2362 case SocketOptionName_DontLinger:
2363 linger.l_onoff = !int_val;
2364 linger.l_linger = 0;
2365 ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
2367 case SocketOptionName_MulticastInterface:
2369 #ifdef HAVE_STRUCT_IP_MREQN
2370 int_val = GUINT32_FROM_BE (int_val);
2371 if ((int_val & 0xff000000) == 0) {
2372 /* int_val is interface index */
2373 struct ip_mreqn mreq = {{0}};
2374 mreq.imr_ifindex = int_val;
2375 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &mreq, sizeof (mreq));
2378 int_val = GUINT32_TO_BE (int_val);
2379 #endif /* HAVE_STRUCT_IP_MREQN */
2380 #endif /* HOST_WIN32 */
2381 /* int_val is in_addr */
2382 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2384 case SocketOptionName_DontFragment:
2385 #ifdef HAVE_IP_MTU_DISCOVER
2386 /* Fiddle with the value slightly if we're
2390 int_val = IP_PMTUDISC_DO;
2395 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2399 if (ret == SOCKET_ERROR)
2400 *werror = WSAGetLastError ();
2404 ves_icall_System_Net_Sockets_Socket_Shutdown_internal (SOCKET sock, gint32 how, gint32 *werror)
2407 gboolean interrupted;
2411 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
2417 MONO_PREPARE_BLOCKING;
2419 /* Currently, the values for how (recv=0, send=1, both=2) match the BSD API */
2420 ret = _wapi_shutdown (sock, how);
2422 MONO_FINISH_BLOCKING;
2424 mono_thread_info_uninstall_interrupt (&interrupted);
2430 if (ret == SOCKET_ERROR)
2431 *werror = WSAGetLastError ();
2435 ves_icall_System_Net_Sockets_Socket_IOControl_internal (SOCKET sock, gint32 code, MonoArray *input, MonoArray *output, gint32 *werror)
2437 glong output_bytes = 0;
2438 gchar *i_buffer, *o_buffer;
2444 if ((guint32)code == FIONBIO)
2445 /* Invalid command. Must use Socket.Blocking */
2448 if (input == NULL) {
2452 i_buffer = mono_array_addr (input, gchar, 0);
2453 i_len = mono_array_length (input);
2456 if (output == NULL) {
2460 o_buffer = mono_array_addr (output, gchar, 0);
2461 o_len = mono_array_length (output);
2464 MONO_PREPARE_BLOCKING;
2466 ret = WSAIoctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes, NULL, NULL);
2468 MONO_FINISH_BLOCKING;
2470 if (ret == SOCKET_ERROR) {
2471 *werror = WSAGetLastError ();
2475 return (gint)output_bytes;
2479 addrinfo_to_IPHostEntry(MonoAddressInfo *info, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
2482 MonoAddressEntry *ai = NULL;
2483 struct in_addr *local_in = NULL;
2485 struct in6_addr *local_in6 = NULL;
2488 MonoDomain *domain = mono_domain_get ();
2491 *h_aliases = mono_array_new (domain, mono_get_string_class (), 0);
2492 if (add_local_ips) {
2493 local_in = (struct in_addr *) mono_get_local_interfaces (AF_INET, &nlocal_in);
2494 local_in6 = (struct in6_addr *) mono_get_local_interfaces (AF_INET6, &nlocal_in6);
2495 if (nlocal_in || nlocal_in6) {
2496 char addr [INET6_ADDRSTRLEN];
2497 *h_addr_list = mono_array_new (domain, mono_get_string_class (), nlocal_in + nlocal_in6);
2499 MonoString *addr_string;
2502 for (i = 0; i < nlocal_in; i++) {
2504 mono_address_init (&maddr, AF_INET, &local_in [i]);
2505 if (mono_networking_addr_to_str (&maddr, addr, sizeof (addr))) {
2506 addr_string = mono_string_new (domain, addr);
2507 mono_array_setref (*h_addr_list, addr_index, addr_string);
2514 MonoString *addr_string;
2517 for (i = 0; i < nlocal_in6; i++) {
2519 mono_address_init (&maddr, AF_INET6, &local_in6 [i]);
2520 if (mono_networking_addr_to_str (&maddr, addr, sizeof (addr))) {
2521 addr_string = mono_string_new (domain, addr);
2522 mono_array_setref (*h_addr_list, addr_index, addr_string);
2531 mono_free_address_info (info);
2539 for (count = 0, ai = info->entries; ai != NULL; ai = ai->next) {
2540 if (ai->family != AF_INET && ai->family != AF_INET6)
2545 *h_addr_list = mono_array_new (domain, mono_get_string_class (), count);
2547 for (ai = info->entries, i = 0; ai != NULL; ai = ai->next) {
2549 MonoString *addr_string;
2550 char buffer [INET6_ADDRSTRLEN]; /* Max. size for IPv6 */
2552 if ((ai->family != PF_INET) && (ai->family != PF_INET6))
2555 mono_address_init (&maddr, ai->family, &ai->address);
2556 if (mono_networking_addr_to_str (&maddr, buffer, sizeof (buffer)))
2557 addr_string = mono_string_new (domain, buffer);
2559 addr_string = mono_string_new (domain, "");
2561 mono_array_setref (*h_addr_list, addr_index, addr_string);
2565 if (ai->canonical_name != NULL) {
2566 *h_name = mono_string_new (domain, ai->canonical_name);
2568 *h_name = mono_string_new (domain, buffer);
2576 mono_free_address_info (info);
2582 get_addrinfo_family_hint (MonoError *error)
2586 mono_error_init (error);
2588 hint = get_family_hint (error);
2589 return_val_if_nok (error, 0);
2593 return MONO_HINT_UNSPECIFIED;
2595 return MONO_HINT_IPV4;
2598 return MONO_HINT_IPV6;
2601 g_error ("invalid hint");
2607 ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2609 gboolean add_local_ips = FALSE, add_info_ok = TRUE;
2610 gchar this_hostname [256];
2611 MonoAddressInfo *info = NULL;
2612 char *hostname = mono_string_to_utf8 (host);
2616 hint = get_addrinfo_family_hint (&error);
2617 if (!mono_error_ok (&error)) {
2618 mono_error_set_pending_exception (&error);
2622 if (*hostname == '\0') {
2623 add_local_ips = TRUE;
2627 if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2628 if (!strcmp (hostname, this_hostname)) {
2629 add_local_ips = TRUE;
2634 if (*hostname && mono_get_address_info (hostname, 0, MONO_HINT_CANONICAL_NAME | hint, &info))
2635 add_info_ok = FALSE;
2640 return addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, add_local_ips);
2645 ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2648 struct sockaddr_in saddr;
2649 struct sockaddr_in6 saddr6;
2650 MonoAddressInfo *info = NULL;
2652 gint32 family, hint;
2653 gchar hostname [NI_MAXHOST] = { 0 };
2656 address = mono_string_to_utf8 (addr);
2658 if (inet_pton (AF_INET, address, &saddr.sin_addr ) == 1) {
2660 saddr.sin_family = AF_INET;
2661 } else if (inet_pton (AF_INET6, address, &saddr6.sin6_addr) == 1) {
2663 saddr6.sin6_family = AF_INET6;
2671 MONO_PREPARE_BLOCKING;
2675 #if HAVE_SOCKADDR_IN_SIN_LEN
2676 saddr.sin_len = sizeof (saddr);
2678 ret = getnameinfo ((struct sockaddr*)&saddr, sizeof (saddr), hostname, sizeof (hostname), NULL, 0, 0) == 0;
2682 #if HAVE_SOCKADDR_IN6_SIN_LEN
2683 saddr6.sin6_len = sizeof (saddr6);
2685 ret = getnameinfo ((struct sockaddr*)&saddr6, sizeof (saddr6), hostname, sizeof (hostname), NULL, 0, 0) == 0;
2689 g_assert_not_reached ();
2692 MONO_FINISH_BLOCKING;
2697 hint = get_addrinfo_family_hint (&error);
2698 if (!mono_error_ok (&error)) {
2699 mono_error_set_pending_exception (&error);
2702 if (mono_get_address_info (hostname, 0, hint | MONO_HINT_CANONICAL_NAME | MONO_HINT_CONFIGURED_ONLY, &info) != 0)
2705 return addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE);
2709 ves_icall_System_Net_Dns_GetHostName_internal (MonoString **h_name)
2711 gchar hostname [NI_MAXHOST] = { 0 };
2714 ret = gethostname (hostname, sizeof (hostname));
2718 *h_name = mono_string_new (mono_domain_get (), hostname);
2724 ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
2729 gboolean interrupted;
2730 TRANSMIT_FILE_BUFFERS buffers;
2732 if (filename == NULL)
2735 /* FIXME: replace file by a proper fd that we can call open and close on, as they are interruptible */
2737 file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &werror);
2739 if (file == INVALID_HANDLE_VALUE) {
2740 SetLastError (werror);
2744 memset (&buffers, 0, sizeof (buffers));
2745 if (pre_buffer != NULL) {
2746 buffers.Head = mono_array_addr (pre_buffer, guchar, 0);
2747 buffers.HeadLength = mono_array_length (pre_buffer);
2749 if (post_buffer != NULL) {
2750 buffers.Tail = mono_array_addr (post_buffer, guchar, 0);
2751 buffers.TailLength = mono_array_length (post_buffer);
2754 mono_thread_info_install_interrupt (abort_syscall, (gpointer) (gsize) mono_native_thread_id_get (), &interrupted);
2757 SetLastError (WSAEINTR);
2761 MONO_PREPARE_BLOCKING;
2763 ret = TransmitFile (sock, file, 0, 0, NULL, &buffers, flags);
2765 MONO_FINISH_BLOCKING;
2767 mono_thread_info_uninstall_interrupt (&interrupted);
2770 SetLastError (WSAEINTR);
2774 MONO_PREPARE_BLOCKING;
2778 MONO_FINISH_BLOCKING;
2784 ves_icall_System_Net_Sockets_Socket_SupportPortReuse (void)
2786 #if defined (SO_REUSEPORT) || defined (HOST_WIN32)
2794 mono_network_init (void)
2796 mono_networking_init ();
2800 mono_network_cleanup (void)
2802 _wapi_cleanup_networking ();
2803 mono_networking_shutdown ();
2807 icall_cancel_blocking_socket_operation (MonoThread *thread)
2809 MonoInternalThread *internal;
2811 internal = thread->internal_thread;
2812 g_assert (internal);
2814 mono_thread_info_abort_socket_syscall_for_close (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
2817 #endif /* #ifndef DISABLE_SOCKETS */