2 * socket-io.c: Socket IO internal calls
5 * Dick Porter (dick@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * (C) 2001 Ximian, Inc.
9 * Copyright (c) 2005-2006 Novell, Inc. (http://www.novell.com)
22 #include <mono/metadata/object.h>
23 #include <mono/io-layer/io-layer.h>
24 #include <mono/metadata/socket-io.h>
25 #include <mono/metadata/exception.h>
26 #include <mono/metadata/assembly.h>
27 #include <mono/metadata/appdomain.h>
28 #include <mono/metadata/threads.h>
29 #include <mono/metadata/threads-types.h>
30 #include <mono/utils/mono-poll.h>
31 /* FIXME change this code to not mess so much with the internals */
32 #include <mono/metadata/class-internals.h>
33 #include <mono/metadata/threadpool-internals.h>
34 #include <mono/metadata/domain-internals.h>
36 #ifdef HAVE_SYS_TIME_H
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
49 #ifdef HAVE_SYS_FILIO_H
50 #include <sys/filio.h> /* defines FIONBIO and FIONREAD */
52 #ifdef HAVE_SYS_SOCKIO_H
53 #include <sys/sockio.h> /* defines SIOCATMARK */
59 #include "mono/io-layer/socket-wrappers.h"
62 /* This is a kludge to make this file build under cygwin:
63 * w32api/ws2tcpip.h has definitions for some AF_INET6 values and
64 * prototypes for some but not all required functions (notably
65 * inet_ntop() is missing), but the libws2_32 library is missing the
66 * actual implementations of these functions.
73 static gint32 convert_family(MonoAddressFamily mono_family)
78 case AddressFamily_Unknown:
79 case AddressFamily_ImpLink:
80 case AddressFamily_Pup:
81 case AddressFamily_Chaos:
82 case AddressFamily_Iso:
83 case AddressFamily_Ecma:
84 case AddressFamily_DataKit:
85 case AddressFamily_Ccitt:
86 case AddressFamily_DataLink:
87 case AddressFamily_Lat:
88 case AddressFamily_HyperChannel:
89 case AddressFamily_NetBios:
90 case AddressFamily_VoiceView:
91 case AddressFamily_FireFox:
92 case AddressFamily_Banyan:
93 case AddressFamily_Atm:
94 case AddressFamily_Cluster:
95 case AddressFamily_Ieee12844:
96 case AddressFamily_NetworkDesigners:
97 g_warning("System.Net.Sockets.AddressFamily has unsupported value 0x%x", mono_family);
100 case AddressFamily_Unspecified:
104 case AddressFamily_Unix:
108 case AddressFamily_InterNetwork:
112 case AddressFamily_Ipx:
118 case AddressFamily_Sna:
122 case AddressFamily_DecNet:
126 case AddressFamily_AppleTalk:
130 case AddressFamily_InterNetworkV6:
135 case AddressFamily_Irda:
141 g_warning("System.Net.Sockets.AddressFamily has unknown value 0x%x", mono_family);
147 static MonoAddressFamily convert_to_mono_family(guint16 af_family)
149 MonoAddressFamily family=AddressFamily_Unknown;
153 family=AddressFamily_Unspecified;
157 family=AddressFamily_Unix;
161 family=AddressFamily_InterNetwork;
166 family=AddressFamily_Ipx;
171 family=AddressFamily_Sna;
175 family=AddressFamily_DecNet;
179 family=AddressFamily_AppleTalk;
184 family=AddressFamily_InterNetworkV6;
190 family=AddressFamily_Irda;
194 g_warning("unknown address family 0x%x", af_family);
200 static gint32 convert_type(MonoSocketType mono_type)
205 case SocketType_Stream:
209 case SocketType_Dgram:
221 case SocketType_Seqpacket:
225 case SocketType_Unknown:
226 g_warning("System.Net.Sockets.SocketType has unsupported value 0x%x", mono_type);
230 g_warning("System.Net.Sockets.SocketType has unknown value 0x%x", mono_type);
236 static gint32 convert_proto(MonoProtocolType mono_proto)
241 case ProtocolType_IP:
242 case ProtocolType_IPv6:
243 case ProtocolType_Icmp:
244 case ProtocolType_Igmp:
245 case ProtocolType_Ggp:
246 case ProtocolType_Tcp:
247 case ProtocolType_Pup:
248 case ProtocolType_Udp:
249 case ProtocolType_Idp:
250 /* These protocols are known (on my system at least) */
254 case ProtocolType_ND:
255 case ProtocolType_Raw:
256 case ProtocolType_Ipx:
257 case ProtocolType_Spx:
258 case ProtocolType_SpxII:
259 case ProtocolType_Unknown:
260 /* These protocols arent */
261 g_warning("System.Net.Sockets.ProtocolType has unsupported value 0x%x", mono_proto);
271 /* Convert MonoSocketFlags */
272 static gint32 convert_socketflags (gint32 sflags)
277 /* SocketFlags.None */
280 if (sflags & ~(SocketFlags_OutOfBand | SocketFlags_MaxIOVectorLength | SocketFlags_Peek |
281 SocketFlags_DontRoute | SocketFlags_Partial))
282 /* Contains invalid flag values */
285 if (sflags & SocketFlags_OutOfBand)
287 if (sflags & SocketFlags_Peek)
289 if (sflags & SocketFlags_DontRoute)
290 flags |= MSG_DONTROUTE;
291 if (sflags & SocketFlags_Partial)
297 if (sflags & SocketFlags_MaxIOVectorLength)
298 /* FIXME: Don't know what to do for MaxIOVectorLength query */
301 return (flags ? flags : -1);
306 * 0 on success (mapped mono_level and mono_name to system_level and system_name
308 * -2 on non-fatal error (ie, must ignore)
310 static gint32 convert_sockopt_level_and_name(MonoSocketOptionLevel mono_level,
311 MonoSocketOptionName mono_name,
315 switch (mono_level) {
316 case SocketOptionLevel_Socket:
317 *system_level = SOL_SOCKET;
320 case SocketOptionName_DontLinger:
321 /* This is SO_LINGER, because the setsockopt
322 * internal call maps DontLinger to SO_LINGER
325 *system_name = SO_LINGER;
327 case SocketOptionName_Debug:
328 *system_name = SO_DEBUG;
331 case SocketOptionName_AcceptConnection:
332 *system_name = SO_ACCEPTCONN;
335 case SocketOptionName_ReuseAddress:
336 *system_name = SO_REUSEADDR;
338 case SocketOptionName_KeepAlive:
339 *system_name = SO_KEEPALIVE;
341 case SocketOptionName_DontRoute:
342 *system_name = SO_DONTROUTE;
344 case SocketOptionName_Broadcast:
345 *system_name = SO_BROADCAST;
347 case SocketOptionName_Linger:
348 *system_name = SO_LINGER;
350 case SocketOptionName_OutOfBandInline:
351 *system_name = SO_OOBINLINE;
353 case SocketOptionName_SendBuffer:
354 *system_name = SO_SNDBUF;
356 case SocketOptionName_ReceiveBuffer:
357 *system_name = SO_RCVBUF;
359 case SocketOptionName_SendLowWater:
360 *system_name = SO_SNDLOWAT;
362 case SocketOptionName_ReceiveLowWater:
363 *system_name = SO_RCVLOWAT;
365 case SocketOptionName_SendTimeout:
366 *system_name = SO_SNDTIMEO;
368 case SocketOptionName_ReceiveTimeout:
369 *system_name = SO_RCVTIMEO;
371 case SocketOptionName_Error:
372 *system_name = SO_ERROR;
374 case SocketOptionName_Type:
375 *system_name = SO_TYPE;
378 case SocketOptionName_PeerCred:
379 *system_name = SO_PEERCRED;
382 case SocketOptionName_ExclusiveAddressUse:
383 case SocketOptionName_UseLoopback:
384 case SocketOptionName_MaxConnections:
385 /* Can't figure out how to map these, so fall
389 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at Socket level", mono_name);
394 case SocketOptionLevel_IP:
396 *system_level = SOL_IP;
399 static int cached = 0;
403 struct protoent *pent;
405 pent = getprotobyname ("IP");
406 proto = pent ? pent->p_proto : 0 /* 0 a good default value?? */;
410 *system_level = proto;
412 #endif /* HAVE_SOL_IP */
415 case SocketOptionName_IPOptions:
416 *system_name = IP_OPTIONS;
419 case SocketOptionName_HeaderIncluded:
420 *system_name = IP_HDRINCL;
424 case SocketOptionName_TypeOfService:
425 *system_name = IP_TOS;
429 case SocketOptionName_IpTimeToLive:
430 *system_name = IP_TTL;
433 case SocketOptionName_MulticastInterface:
434 *system_name = IP_MULTICAST_IF;
436 case SocketOptionName_MulticastTimeToLive:
437 *system_name = IP_MULTICAST_TTL;
439 case SocketOptionName_MulticastLoopback:
440 *system_name = IP_MULTICAST_LOOP;
442 case SocketOptionName_AddMembership:
443 *system_name = IP_ADD_MEMBERSHIP;
445 case SocketOptionName_DropMembership:
446 *system_name = IP_DROP_MEMBERSHIP;
448 #ifdef HAVE_IP_PKTINFO
449 case SocketOptionName_PacketInformation:
450 *system_name = IP_PKTINFO;
452 #endif /* HAVE_IP_PKTINFO */
454 case SocketOptionName_DontFragment:
455 #ifdef HAVE_IP_DONTFRAGMENT
456 *system_name = IP_DONTFRAGMENT;
458 #elif defined HAVE_IP_MTU_DISCOVER
459 /* Not quite the same */
460 *system_name = IP_MTU_DISCOVER;
463 /* If the flag is not available on this system, we can ignore this error */
465 #endif /* HAVE_IP_DONTFRAGMENT */
466 case SocketOptionName_AddSourceMembership:
467 case SocketOptionName_DropSourceMembership:
468 case SocketOptionName_BlockSource:
469 case SocketOptionName_UnblockSource:
470 /* Can't figure out how to map these, so fall
474 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at IP level", mono_name);
480 case SocketOptionLevel_IPv6:
482 *system_level = SOL_IPV6;
485 static int cached = 0;
489 struct protoent *pent;
491 pent = getprotobyname ("IPV6");
492 proto = pent ? pent->p_proto : 41 /* 41 a good default value?? */;
496 *system_level = proto;
498 #endif /* HAVE_SOL_IPV6 */
501 case SocketOptionName_IpTimeToLive:
502 *system_name = IPV6_UNICAST_HOPS;
504 case SocketOptionName_MulticastInterface:
505 *system_name = IPV6_MULTICAST_IF;
507 case SocketOptionName_MulticastTimeToLive:
508 *system_name = IPV6_MULTICAST_HOPS;
510 case SocketOptionName_MulticastLoopback:
511 *system_name = IPV6_MULTICAST_LOOP;
513 case SocketOptionName_AddMembership:
514 *system_name = IPV6_JOIN_GROUP;
516 case SocketOptionName_DropMembership:
517 *system_name = IPV6_LEAVE_GROUP;
519 case SocketOptionName_PacketInformation:
520 #ifdef HAVE_IPV6_PKTINFO
521 *system_name = IPV6_PKTINFO;
524 case SocketOptionName_HeaderIncluded:
525 case SocketOptionName_IPOptions:
526 case SocketOptionName_TypeOfService:
527 case SocketOptionName_DontFragment:
528 case SocketOptionName_AddSourceMembership:
529 case SocketOptionName_DropSourceMembership:
530 case SocketOptionName_BlockSource:
531 case SocketOptionName_UnblockSource:
532 /* Can't figure out how to map these, so fall
536 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at IPv6 level", mono_name);
540 break; /* SocketOptionLevel_IPv6 */
543 case SocketOptionLevel_Tcp:
545 *system_level = SOL_TCP;
548 static int cached = 0;
552 struct protoent *pent;
554 pent = getprotobyname ("TCP");
555 proto = pent ? pent->p_proto : 6 /* is 6 a good default value?? */;
559 *system_level = proto;
561 #endif /* HAVE_SOL_TCP */
564 case SocketOptionName_NoDelay:
565 *system_name = TCP_NODELAY;
568 /* The documentation is talking complete
569 * bollocks here: rfc-1222 is titled
570 * 'Advancing the NSFNET Routing Architecture'
571 * and doesn't mention either of the words
572 * "expedite" or "urgent".
574 case SocketOptionName_BsdUrgent:
575 case SocketOptionName_Expedited:
578 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at TCP level", mono_name);
583 case SocketOptionLevel_Udp:
584 g_warning("System.Net.Sockets.SocketOptionLevel has unsupported value 0x%x", mono_level);
587 case SocketOptionName_NoChecksum:
588 case SocketOptionName_ChecksumCoverage:
590 g_warning("System.Net.Sockets.SocketOptionName 0x%x is not supported at UDP level", mono_name);
597 g_warning("System.Net.Sockets.SocketOptionLevel has unknown value 0x%x", mono_level);
604 #define STASH_SYS_ASS(this) \
605 if(system_assembly == NULL) { \
606 system_assembly=mono_image_loaded ("System"); \
607 if (!system_assembly) { \
608 MonoAssembly *sa = mono_assembly_open ("System.dll", NULL); \
609 if (!sa) g_assert_not_reached (); \
610 else {system_assembly = mono_assembly_get_image (sa);} \
614 static MonoImage *system_assembly=NULL;
618 static gint32 get_family_hint(void)
620 MonoClass *socket_class;
621 MonoClassField *ipv6_field, *ipv4_field;
622 gint32 ipv6_enabled = -1, ipv4_enabled = -1;
625 socket_class = mono_class_from_name (system_assembly,
626 "System.Net.Sockets", "Socket");
627 ipv4_field = mono_class_get_field_from_name (socket_class,
629 ipv6_field = mono_class_get_field_from_name (socket_class,
631 vtable = mono_class_vtable (mono_domain_get (), socket_class);
633 mono_field_static_get_value(vtable, ipv4_field, &ipv4_enabled);
634 mono_field_static_get_value(vtable, ipv6_field, &ipv6_enabled);
636 if(ipv4_enabled == 1 && ipv6_enabled == 1) {
638 } else if(ipv4_enabled == 1) {
646 gpointer ves_icall_System_Net_Sockets_Socket_Socket_internal(MonoObject *this, gint32 family, gint32 type, gint32 proto, gint32 *error)
659 sock_family=convert_family(family);
660 if(sock_family==-1) {
661 *error = WSAEAFNOSUPPORT;
665 sock_proto=convert_proto(proto);
667 *error = WSAEPROTONOSUPPORT;
671 sock_type=convert_type(type);
673 *error = WSAESOCKTNOSUPPORT;
677 sock = _wapi_socket (sock_family, sock_type, sock_proto,
678 NULL, 0, WSA_FLAG_OVERLAPPED);
680 if(sock==INVALID_SOCKET) {
681 *error = WSAGetLastError ();
685 if (sock_family == AF_INET && sock_type == SOCK_DGRAM) {
686 return (GUINT_TO_POINTER (sock));
690 if (sock_family == AF_INET6 && sock_type == SOCK_DGRAM) {
691 return (GUINT_TO_POINTER (sock));
695 return(GUINT_TO_POINTER (sock));
698 /* FIXME: the SOCKET parameter (here and in other functions in this
699 * file) is really an IntPtr which needs to be converted to a guint32.
701 void ves_icall_System_Net_Sockets_Socket_Close_internal(SOCKET sock,
707 g_message (G_GNUC_PRETTY_FUNCTION ": closing 0x%x", sock);
712 /* Clear any pending work item from this socket if the underlying
713 * polling system does not notify when the socket is closed */
714 mono_thread_pool_remove_socket (GPOINTER_TO_INT (sock));
718 gint32 ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal(void)
723 g_message(G_GNUC_PRETTY_FUNCTION ": returning %d", WSAGetLastError());
726 return(WSAGetLastError());
729 gint32 ves_icall_System_Net_Sockets_Socket_Available_internal(SOCKET sock,
739 ret=ioctlsocket(sock, FIONREAD, &amount);
740 if(ret==SOCKET_ERROR) {
741 *error = WSAGetLastError ();
748 void ves_icall_System_Net_Sockets_Socket_Blocking_internal(SOCKET sock,
759 * block == TRUE/FALSE means we will block/not block.
760 * But the ioctlsocket call takes TRUE/FALSE for non-block/block
764 ret = ioctlsocket (sock, FIONBIO, (gulong *) &block);
765 if(ret==SOCKET_ERROR) {
766 *error = WSAGetLastError ();
770 gpointer ves_icall_System_Net_Sockets_Socket_Accept_internal(SOCKET sock,
779 newsock = _wapi_accept (sock, NULL, 0);
780 if(newsock==INVALID_SOCKET) {
781 *error = WSAGetLastError ();
785 return(GUINT_TO_POINTER (newsock));
788 void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock,
798 ret = _wapi_listen (sock, backlog);
799 if(ret==SOCKET_ERROR) {
800 *error = WSAGetLastError ();
804 static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
805 int sa_size, gint32 *error)
807 MonoDomain *domain = mono_domain_get ();
808 MonoObject *sockaddr_obj;
809 MonoClass *sockaddr_class;
810 MonoClassField *field;
812 MonoAddressFamily family;
814 /* Build a System.Net.SocketAddress object instance */
815 sockaddr_class=mono_class_from_name(system_assembly, "System.Net", "SocketAddress");
816 sockaddr_obj=mono_object_new(domain, sockaddr_class);
818 /* Locate the SocketAddress data buffer in the object */
819 field=mono_class_get_field_from_name(sockaddr_class, "data");
821 /* Make sure there is space for the family and size bytes */
823 if (saddr->sa_family == AF_UNIX) {
824 /* sa_len includes the entire sockaddr size, so we don't need the
825 * N bytes (sizeof (unsigned short)) of the family. */
826 data=mono_array_new(domain, mono_get_byte_class (), sa_size);
830 /* May be the +2 here is too conservative, as sa_len returns
831 * the length of the entire sockaddr_in/in6, including
832 * sizeof (unsigned short) of the family */
833 data=mono_array_new(domain, mono_get_byte_class (), sa_size+2);
836 /* The data buffer is laid out as follows:
837 * bytes 0 and 1 are the address family
838 * bytes 2 and 3 are the port info
839 * the rest is the address info
842 family=convert_to_mono_family(saddr->sa_family);
843 if(family==AddressFamily_Unknown) {
844 *error = WSAEAFNOSUPPORT;
848 mono_array_set(data, guint8, 0, family & 0x0FF);
849 mono_array_set(data, guint8, 1, (family >> 8) & 0x0FF);
851 if(saddr->sa_family==AF_INET) {
852 struct sockaddr_in *sa_in=(struct sockaddr_in *)saddr;
853 guint16 port=ntohs(sa_in->sin_port);
854 guint32 address=ntohl(sa_in->sin_addr.s_addr);
857 mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
860 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
861 mono_array_set(data, guint8, 3, (port) & 0xff);
862 mono_array_set(data, guint8, 4, (address>>24) & 0xff);
863 mono_array_set(data, guint8, 5, (address>>16) & 0xff);
864 mono_array_set(data, guint8, 6, (address>>8) & 0xff);
865 mono_array_set(data, guint8, 7, (address) & 0xff);
867 mono_field_set_value (sockaddr_obj, field, data);
869 return(sockaddr_obj);
871 } else if (saddr->sa_family == AF_INET6) {
872 struct sockaddr_in6 *sa_in=(struct sockaddr_in6 *)saddr;
875 guint16 port=ntohs(sa_in->sin6_port);
878 mono_raise_exception((MonoException *)mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
881 mono_array_set(data, guint8, 2, (port>>8) & 0xff);
882 mono_array_set(data, guint8, 3, (port) & 0xff);
884 for(i=0; i<16; i++) {
885 mono_array_set(data, guint8, 8+i,
886 sa_in->sin6_addr.s6_addr[i]);
889 mono_array_set(data, guint8, 24, sa_in->sin6_scope_id & 0xff);
890 mono_array_set(data, guint8, 25,
891 (sa_in->sin6_scope_id >> 8) & 0xff);
892 mono_array_set(data, guint8, 26,
893 (sa_in->sin6_scope_id >> 16) & 0xff);
894 mono_array_set(data, guint8, 27,
895 (sa_in->sin6_scope_id >> 24) & 0xff);
897 mono_field_set_value (sockaddr_obj, field, data);
899 return(sockaddr_obj);
902 } else if (saddr->sa_family == AF_UNIX) {
905 for (i = 0; i < sa_size; i++) {
906 mono_array_set (data, guint8, i+2, saddr->sa_data[i]);
909 mono_field_set_value (sockaddr_obj, field, data);
914 *error = WSAEAFNOSUPPORT;
919 extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 *error)
921 gchar sa[32]; /* sockaddr in not big enough for sockaddr_in6 */
930 ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
932 if(ret==SOCKET_ERROR) {
933 *error = WSAGetLastError ();
938 g_message(G_GNUC_PRETTY_FUNCTION ": bound to %s port %d", inet_ntoa(((struct sockaddr_in *)&sa)->sin_addr), ntohs(((struct sockaddr_in *)&sa)->sin_port));
941 return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
945 extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 *error)
947 gchar sa[32]; /* sockaddr in not big enough for sockaddr_in6 */
956 ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
958 if(ret==SOCKET_ERROR) {
959 *error = WSAGetLastError ();
964 g_message(G_GNUC_PRETTY_FUNCTION ": connected to %s port %d", inet_ntoa(((struct sockaddr_in *)&sa)->sin_addr), ntohs(((struct sockaddr_in *)&sa)->sin_port));
967 return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
971 static struct sockaddr *create_sockaddr_from_object(MonoObject *saddr_obj,
975 MonoClassField *field;
980 /* Dig the SocketAddress data buffer out of the object */
981 field=mono_class_get_field_from_name(saddr_obj->vtable->klass, "data");
982 data=*(MonoArray **)(((char *)saddr_obj) + field->offset);
984 /* The data buffer is laid out as follows:
985 * byte 0 is the address family low byte
986 * byte 1 is the address family high byte
988 * bytes 2 and 3 are the port info
989 * the rest is the address info
991 * the rest is the file name
993 len = mono_array_length (data);
995 mono_raise_exception (mono_exception_from_name(mono_get_corlib (), "System", "SystemException"));
998 family = convert_family (mono_array_get (data, guint8, 0) + (mono_array_get (data, guint8, 1) << 8));
999 if (family == AF_INET) {
1000 struct sockaddr_in *sa;
1005 mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1008 sa = g_new0 (struct sockaddr_in, 1);
1009 port = (mono_array_get (data, guint8, 2) << 8) +
1010 mono_array_get (data, guint8, 3);
1011 address = (mono_array_get (data, guint8, 4) << 24) +
1012 (mono_array_get (data, guint8, 5) << 16 ) +
1013 (mono_array_get (data, guint8, 6) << 8) +
1014 mono_array_get (data, guint8, 7);
1016 sa->sin_family = family;
1017 sa->sin_addr.s_addr = htonl (address);
1018 sa->sin_port = htons (port);
1020 *sa_size = sizeof(struct sockaddr_in);
1021 return((struct sockaddr *)sa);
1024 } else if (family == AF_INET6) {
1025 struct sockaddr_in6 *sa;
1031 mono_raise_exception (mono_exception_from_name (mono_get_corlib (), "System", "SystemException"));
1034 sa = g_new0 (struct sockaddr_in6, 1);
1035 port = mono_array_get (data, guint8, 3) +
1036 (mono_array_get (data, guint8, 2) << 8);
1037 scopeid = mono_array_get (data, guint8, 24) +
1038 (mono_array_get (data, guint8, 25) << 8) +
1039 (mono_array_get (data, guint8, 26) << 16) +
1040 (mono_array_get (data, guint8, 27) << 24);
1042 sa->sin6_family = family;
1043 sa->sin6_port = htons (port);
1044 sa->sin6_scope_id = scopeid;
1046 for(i=0; i<16; i++) {
1047 sa->sin6_addr.s6_addr[i] = mono_array_get (data, guint8, 8+i);
1050 *sa_size = sizeof(struct sockaddr_in6);
1051 return((struct sockaddr *)sa);
1053 #ifdef HAVE_SYS_UN_H
1054 } else if (family == AF_UNIX) {
1055 struct sockaddr_un *sock_un;
1058 /* Need a byte for the '\0' terminator/prefix, and the first
1059 * two bytes hold the SocketAddress family
1061 if (len - 2 >= MONO_SIZEOF_SUNPATH) {
1062 mono_raise_exception (mono_get_exception_index_out_of_range ());
1065 sock_un = g_new0 (struct sockaddr_un, 1);
1067 sock_un->sun_family = family;
1068 for (i = 0; i < len - 2; i++) {
1069 sock_un->sun_path [i] = mono_array_get (data, guint8,
1075 return (struct sockaddr *)sock_un;
1078 *error = WSAEAFNOSUPPORT;
1083 extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1085 struct sockaddr *sa;
1089 MONO_ARCH_SAVE_REGS;
1093 sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1099 g_message(G_GNUC_PRETTY_FUNCTION ": binding to %s port %d", inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), ntohs (((struct sockaddr_in *)sa)->sin_port));
1102 ret = _wapi_bind (sock, sa, sa_size);
1103 if(ret==SOCKET_ERROR) {
1104 *error = WSAGetLastError ();
1117 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
1118 gint timeout, gint32 *error)
1120 MonoThread *thread = NULL;
1126 MONO_ARCH_SAVE_REGS;
1128 pfds = g_new0 (mono_pollfd, 1);
1129 pfds[0].fd = GPOINTER_TO_INT (sock);
1130 pfds[0].events = (mode == SelectModeRead) ? MONO_POLLIN :
1131 (mode == SelectModeWrite) ? MONO_POLLOUT :
1132 (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL);
1134 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1135 start = time (NULL);
1139 ret = mono_poll (pfds, 1, timeout);
1140 if (timeout > 0 && ret < 0) {
1142 int sec = time (NULL) - start;
1144 timeout -= sec * 1000;
1152 if (ret == -1 && errno == EINTR) {
1155 if (thread == NULL) {
1156 thread = mono_thread_current ();
1159 leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1165 /* Suspend requested? */
1166 mono_thread_interruption_checkpoint ();
1170 } while (ret == -1 && errno == EINTR);
1173 #ifdef PLATFORM_WIN32
1174 *error = WSAGetLastError ();
1176 *error = errno_to_WSA (errno, __func__);
1191 extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error)
1193 struct sockaddr *sa;
1197 MONO_ARCH_SAVE_REGS;
1201 sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1207 g_message(G_GNUC_PRETTY_FUNCTION ": connecting to %s port %d", inet_ntoa(((struct sockaddr_in *)sa)->sin_addr), ntohs (((struct sockaddr_in *)sa)->sin_port));
1210 ret = _wapi_connect (sock, sa, sa_size);
1211 if(ret==SOCKET_ERROR) {
1212 *error = WSAGetLastError ();
1218 /* These #defines from mswsock.h from wine. Defining them here allows
1219 * us to build this file on a mingw box that doesn't know the magic
1220 * numbers, but still run on a newer windows box that does.
1222 #ifndef WSAID_DISCONNECTEX
1223 #define WSAID_DISCONNECTEX {0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
1224 typedef BOOL (WINAPI *LPFN_DISCONNECTEX)(SOCKET, LPOVERLAPPED, DWORD, DWORD);
1227 #ifndef WSAID_TRANSMITFILE
1228 #define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
1229 typedef BOOL (WINAPI *LPFN_TRANSMITFILE)(SOCKET, HANDLE, DWORD, DWORD, LPOVERLAPPED, LPTRANSMIT_FILE_BUFFERS, DWORD);
1232 extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error)
1235 glong output_bytes = 0;
1236 GUID disco_guid = WSAID_DISCONNECTEX;
1237 GUID trans_guid = WSAID_TRANSMITFILE;
1238 LPFN_DISCONNECTEX _wapi_disconnectex = NULL;
1239 LPFN_TRANSMITFILE _wapi_transmitfile = NULL;
1242 MONO_ARCH_SAVE_REGS;
1247 g_message("%s: disconnecting from socket %p (reuse %d)", __func__,
1251 /* I _think_ the extension function pointers need to be looked
1252 * up for each socket. FIXME: check the best way to store
1253 * pointers to functions in managed objects that still works
1254 * on 64bit platforms.
1256 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1257 (void *)&disco_guid, sizeof(GUID),
1258 (void *)&_wapi_disconnectex, sizeof(void *),
1259 &output_bytes, NULL, NULL);
1261 /* make sure that WSAIoctl didn't put crap in the
1264 _wapi_disconnectex = NULL;
1266 /* Look up the TransmitFile extension function pointer
1267 * instead of calling TransmitFile() directly, because
1268 * apparently "Several of the extension functions have
1269 * been available since WinSock 1.1 and are exported
1270 * from MSWsock.dll, however it's not advisable to
1271 * link directly to this dll as this ties you to the
1272 * Microsoft WinSock provider. A provider neutral way
1273 * of accessing these extension functions is to load
1274 * them dynamically via WSAIoctl using the
1275 * SIO_GET_EXTENSION_FUNCTION_POINTER op code. This
1276 * should, theoretically, allow you to access these
1277 * functions from any provider that supports them..."
1278 * (http://www.codeproject.com/internet/jbsocketserver3.asp)
1280 ret = WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
1281 (void *)&trans_guid, sizeof(GUID),
1282 (void *)&_wapi_transmitfile, sizeof(void *),
1283 &output_bytes, NULL, NULL);
1285 _wapi_transmitfile = NULL;
1289 if (_wapi_disconnectex != NULL) {
1290 bret = _wapi_disconnectex (sock, NULL, TF_REUSE_SOCKET, 0);
1291 } else if (_wapi_transmitfile != NULL) {
1292 bret = _wapi_transmitfile (sock, NULL, 0, 0, NULL, NULL,
1293 TF_DISCONNECT | TF_REUSE_SOCKET);
1295 *error = ERROR_NOT_SUPPORTED;
1299 if (bret == FALSE) {
1300 *error = WSAGetLastError ();
1304 gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1311 MONO_ARCH_SAVE_REGS;
1315 alen = mono_array_length (buffer);
1316 if (offset > alen - count) {
1320 buf=mono_array_addr(buffer, guchar, offset);
1322 recvflags = convert_socketflags (flags);
1323 if (recvflags == -1) {
1324 *error = WSAEOPNOTSUPP;
1328 ret = _wapi_recv (sock, buf, count, recvflags);
1329 if(ret==SOCKET_ERROR) {
1330 *error = WSAGetLastError ();
1337 gint32 ves_icall_System_Net_Sockets_Socket_RecvFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error)
1343 struct sockaddr *sa;
1346 MONO_ARCH_SAVE_REGS;
1350 alen = mono_array_length (buffer);
1351 if (offset > alen - count) {
1355 sa=create_sockaddr_from_object(*sockaddr, &sa_size, error);
1360 buf=mono_array_addr(buffer, guchar, offset);
1362 recvflags = convert_socketflags (flags);
1363 if (recvflags == -1) {
1364 *error = WSAEOPNOTSUPP;
1368 ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
1369 if(ret==SOCKET_ERROR) {
1371 *error = WSAGetLastError ();
1375 /* If we didn't get a socket size, then we're probably a
1376 * connected connection-oriented socket and the stack hasn't
1377 * returned the remote address. All we can do is return null.
1380 *sockaddr=create_object_from_sockaddr(sa, sa_size, error);
1389 gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error)
1396 MONO_ARCH_SAVE_REGS;
1400 alen = mono_array_length (buffer);
1401 if (offset > alen - count) {
1406 g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
1409 buf=mono_array_addr(buffer, guchar, offset);
1412 g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
1415 sendflags = convert_socketflags (flags);
1416 if (sendflags == -1) {
1417 *error = WSAEOPNOTSUPP;
1421 ret = _wapi_send (sock, buf, count, sendflags);
1422 if(ret==SOCKET_ERROR) {
1423 *error = WSAGetLastError ();
1430 gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error)
1436 struct sockaddr *sa;
1439 MONO_ARCH_SAVE_REGS;
1443 alen = mono_array_length (buffer);
1444 if (offset > alen - count) {
1448 sa=create_sockaddr_from_object(sockaddr, &sa_size, error);
1454 g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
1457 buf=mono_array_addr(buffer, guchar, offset);
1460 g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
1463 sendflags = convert_socketflags (flags);
1464 if (sendflags == -1) {
1465 *error = WSAEOPNOTSUPP;
1469 ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
1470 if(ret==SOCKET_ERROR) {
1471 *error = WSAGetLastError ();
1479 static SOCKET Socket_to_SOCKET(MonoObject *sockobj)
1482 MonoClassField *field;
1484 field=mono_class_get_field_from_name(sockobj->vtable->klass, "socket");
1485 sock=*(SOCKET *)(((char *)sockobj)+field->offset);
1490 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
1491 void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error)
1493 MonoThread *thread = NULL;
1500 MonoClass *sock_arr_class;
1504 MONO_ARCH_SAVE_REGS;
1506 /* *sockets -> READ, null, WRITE, null, ERROR, null */
1507 count = mono_array_length (*sockets);
1508 nfds = count - 3; /* NULL separators */
1509 pfds = g_new0 (mono_pollfd, nfds);
1511 for (i = 0; i < count; i++) {
1512 obj = mono_array_get (*sockets, MonoObject *, i);
1519 /* The socket array was bogus */
1525 pfds [idx].fd = GPOINTER_TO_INT (Socket_to_SOCKET (obj));
1526 pfds [idx].events = (mode == 0) ? MONO_POLLIN : (mode == 1) ? MONO_POLLOUT : POLL_ERRORS;
1530 timeout = (timeout >= 0) ? (timeout / 1000) : -1;
1531 start = time (NULL);
1534 ret = mono_poll (pfds, nfds, timeout);
1535 if (timeout > 0 && ret < 0) {
1537 int sec = time (NULL) - start;
1539 timeout -= sec * 1000;
1545 if (ret == -1 && errno == EINTR) {
1548 thread = mono_thread_current ();
1550 leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
1557 /* Suspend requested? */
1558 mono_thread_interruption_checkpoint ();
1562 } while (ret == -1 && errno == EINTR);
1565 #ifdef PLATFORM_WIN32
1566 *error = WSAGetLastError ();
1568 *error = errno_to_WSA (errno, __func__);
1580 sock_arr_class= ((MonoObject *)*sockets)->vtable->klass;
1581 ret += 3; /* space for the NULL delimiters */
1582 socks = mono_array_new_full (mono_domain_get (), sock_arr_class, (guint32*)&ret, NULL);
1585 for (i = 0; i < count && ret > 0; i++) {
1588 obj = mono_array_get (*sockets, MonoObject *, i);
1595 pfd = &pfds [i - mode];
1596 if (pfd->revents == 0)
1600 if (mode == 0 && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
1601 mono_array_setref (socks, idx++, obj);
1602 } else if (mode == 1 && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
1603 mono_array_setref (socks, idx++, obj);
1604 } else if ((pfd->revents & POLL_ERRORS) != 0) {
1605 mono_array_setref (socks, idx++, obj);
1613 static MonoObject* int_to_object (MonoDomain *domain, int val)
1615 return mono_value_box (domain, mono_get_int32_class (), &val);
1619 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error)
1625 socklen_t valsize=sizeof(val);
1626 struct linger linger;
1627 socklen_t lingersize=sizeof(linger);
1629 socklen_t time_ms_size = sizeof (time_ms);
1632 socklen_t credsize = sizeof(cred);
1634 MonoDomain *domain=mono_domain_get();
1636 MonoClass *obj_class;
1637 MonoClassField *field;
1639 MONO_ARCH_SAVE_REGS;
1643 ret=convert_sockopt_level_and_name(level, name, &system_level,
1646 *error = WSAENOPROTOOPT;
1650 *obj_val = int_to_object (domain, 0);
1654 /* No need to deal with MulticastOption names here, because
1655 * you cant getsockopt AddMembership or DropMembership (the
1656 * int getsockopt will error, causing an exception)
1659 case SocketOptionName_Linger:
1660 case SocketOptionName_DontLinger:
1661 ret = _wapi_getsockopt(sock, system_level, system_name, &linger,
1665 case SocketOptionName_SendTimeout:
1666 case SocketOptionName_ReceiveTimeout:
1667 ret = _wapi_getsockopt (sock, system_level, system_name, (char *) &time_ms, &time_ms_size);
1671 case SocketOptionName_PeerCred:
1672 ret = _wapi_getsockopt (sock, system_level, system_name, &cred,
1678 ret = _wapi_getsockopt (sock, system_level, system_name, &val,
1682 if(ret==SOCKET_ERROR) {
1683 *error = WSAGetLastError ();
1688 case SocketOptionName_Linger:
1689 /* build a System.Net.Sockets.LingerOption */
1690 obj_class=mono_class_from_name(system_assembly,
1691 "System.Net.Sockets",
1693 obj=mono_object_new(domain, obj_class);
1695 /* Locate and set the fields "bool enabled" and "int
1698 field=mono_class_get_field_from_name(obj_class, "enabled");
1699 *(guint8 *)(((char *)obj)+field->offset)=linger.l_onoff;
1701 field=mono_class_get_field_from_name(obj_class, "seconds");
1702 *(guint32 *)(((char *)obj)+field->offset)=linger.l_linger;
1706 case SocketOptionName_DontLinger:
1707 /* construct a bool int in val - true if linger is off */
1708 obj = int_to_object (domain, !linger.l_onoff);
1711 case SocketOptionName_SendTimeout:
1712 case SocketOptionName_ReceiveTimeout:
1713 obj = int_to_object (domain, time_ms);
1717 case SocketOptionName_PeerCred:
1719 /* build a Mono.Posix.PeerCred+PeerCredData if
1722 static MonoImage *mono_posix_image = NULL;
1723 MonoPeerCredData *cred_data;
1725 if (mono_posix_image == NULL) {
1726 mono_posix_image=mono_image_loaded ("Mono.Posix");
1727 if (!mono_posix_image) {
1728 MonoAssembly *sa = mono_assembly_open ("Mono.Posix.dll", NULL);
1730 *error = WSAENOPROTOOPT;
1733 mono_posix_image = mono_assembly_get_image (sa);
1738 obj_class = mono_class_from_name(mono_posix_image,
1741 obj = mono_object_new(domain, obj_class);
1742 cred_data = (MonoPeerCredData *)obj;
1743 cred_data->pid = cred.pid;
1744 cred_data->uid = cred.uid;
1745 cred_data->gid = cred.gid;
1751 obj = int_to_object (domain, val);
1757 void ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal(SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *error)
1765 MONO_ARCH_SAVE_REGS;
1769 ret=convert_sockopt_level_and_name(level, name, &system_level,
1772 *error = WSAENOPROTOOPT;
1778 valsize=mono_array_length(*byte_val);
1779 buf=mono_array_addr(*byte_val, guchar, 0);
1781 ret = _wapi_getsockopt (sock, system_level, system_name, buf, &valsize);
1782 if(ret==SOCKET_ERROR) {
1783 *error = WSAGetLastError ();
1787 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
1788 static struct in_addr ipaddress_to_struct_in_addr(MonoObject *ipaddr)
1790 struct in_addr inaddr;
1791 MonoClassField *field;
1793 field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Address");
1795 /* No idea why .net uses a 64bit type to hold a 32bit value...
1797 * Internal value of IPAddess is in little-endian order
1799 inaddr.s_addr=GUINT_FROM_LE ((guint32)*(guint64 *)(((char *)ipaddr)+field->offset));
1806 static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
1808 struct in6_addr in6addr;
1809 MonoClassField *field;
1813 field=mono_class_get_field_from_name(ipaddr->vtable->klass, "m_Numbers");
1814 data=*(MonoArray **)(((char *)ipaddr) + field->offset);
1816 /* Solaris has only the 8 bit version. */
1818 for(i=0; i<8; i++) {
1819 guint16 s = mono_array_get (data, guint16, i);
1820 in6addr.s6_addr[2 * i] = (s >> 8) & 0xff;
1821 in6addr.s6_addr[2 * i + 1] = s & 0xff;
1825 in6addr.s6_addr16[i] = mono_array_get (data, guint16, i);
1829 #endif /* AF_INET6 */
1831 void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, gint32 level, gint32 name, MonoObject *obj_val, MonoArray *byte_val, gint32 int_val, gint32 *error)
1842 #ifdef HAVE_SOL_IPV6
1843 sol_ipv6 = SOL_IPV6;
1846 struct protoent *pent;
1847 pent = getprotobyname ("ipv6");
1848 sol_ipv6 = (pent != NULL) ? pent->p_proto : 41;
1856 struct protoent *pent;
1857 pent = getprotobyname ("ip");
1858 sol_ip = (pent != NULL) ? pent->p_proto : 0;
1861 #endif /* AF_INET6 */
1863 MONO_ARCH_SAVE_REGS;
1865 ret=convert_sockopt_level_and_name(level, name, &system_level,
1868 *error = WSAENOPROTOOPT;
1875 /* Only one of obj_val, byte_val or int_val has data */
1877 MonoClassField *field;
1878 struct linger linger;
1882 case SocketOptionName_DontLinger:
1885 valsize=sizeof(linger);
1886 ret = _wapi_setsockopt (sock, system_level,
1887 system_name, &linger, valsize);
1890 case SocketOptionName_Linger:
1891 /* Dig out "bool enabled" and "int seconds"
1894 field=mono_class_get_field_from_name(obj_val->vtable->klass, "enabled");
1895 linger.l_onoff=*(guint8 *)(((char *)obj_val)+field->offset);
1896 field=mono_class_get_field_from_name(obj_val->vtable->klass, "seconds");
1897 linger.l_linger=*(guint32 *)(((char *)obj_val)+field->offset);
1899 valsize=sizeof(linger);
1900 ret = _wapi_setsockopt (sock, system_level,
1901 system_name, &linger, valsize);
1903 case SocketOptionName_AddMembership:
1904 case SocketOptionName_DropMembership:
1905 #if defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ)
1907 MonoObject *address = NULL;
1910 if(system_level == sol_ipv6) {
1911 struct ipv6_mreq mreq6;
1916 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
1917 address = *(gpointer *)(((char *)obj_val) + field->offset);
1920 mreq6.ipv6mr_multiaddr = ipaddress_to_struct_in6_addr (address);
1923 field=mono_class_get_field_from_name(obj_val->vtable->klass, "ifIndex");
1924 mreq6.ipv6mr_interface =*(guint64 *)(((char *)obj_val)+field->offset);
1926 ret = _wapi_setsockopt (sock, system_level,
1927 system_name, &mreq6,
1929 } else if(system_level == sol_ip)
1930 #endif /* AF_INET6 */
1932 #ifdef HAVE_STRUCT_IP_MREQN
1933 struct ip_mreqn mreq = {{0}};
1935 struct ip_mreq mreq = {{0}};
1936 #endif /* HAVE_STRUCT_IP_MREQN */
1938 /* pain! MulticastOption holds two IPAddress
1939 * members, so I have to dig the value out of
1942 field = mono_class_get_field_from_name (obj_val->vtable->klass, "group");
1943 address = *(gpointer *)(((char *)obj_val) + field->offset);
1945 /* address might not be defined and if so, set the address to ADDR_ANY.
1948 mreq.imr_multiaddr = ipaddress_to_struct_in_addr (address);
1951 field = mono_class_get_field_from_name (obj_val->vtable->klass, "local");
1952 address = *(gpointer *)(((char *)obj_val) + field->offset);
1954 #ifdef HAVE_STRUCT_IP_MREQN
1956 mreq.imr_address = ipaddress_to_struct_in_addr (address);
1960 mreq.imr_interface = ipaddress_to_struct_in_addr (address);
1962 #endif /* HAVE_STRUCT_IP_MREQN */
1964 ret = _wapi_setsockopt (sock, system_level,
1970 #endif /* HAVE_STRUCT_IP_MREQN || HAVE_STRUCT_IP_MREQ */
1972 /* Cause an exception to be thrown */
1976 } else if (byte_val!=NULL) {
1977 int valsize=mono_array_length(byte_val);
1978 guchar *buf=mono_array_addr(byte_val, guchar, 0);
1980 ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
1981 if(ret==SOCKET_ERROR) {
1982 *error = WSAGetLastError ();
1986 /* ReceiveTimeout/SendTimeout get here */
1988 case SocketOptionName_DontFragment:
1989 #ifdef HAVE_IP_MTU_DISCOVER
1990 /* Fiddle with the value slightly if we're
1994 int_val = IP_PMTUDISC_DO;
2000 ret = _wapi_setsockopt (sock, system_level, system_name, (char *) &int_val, sizeof (int_val));
2004 if(ret==SOCKET_ERROR) {
2005 *error = WSAGetLastError ();
2009 void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock,
2015 MONO_ARCH_SAVE_REGS;
2019 /* Currently, the values for how (recv=0, send=1, both=2) match
2022 ret = _wapi_shutdown (sock, how);
2023 if(ret==SOCKET_ERROR) {
2024 *error = WSAGetLastError ();
2029 ves_icall_System_Net_Sockets_Socket_WSAIoctl (SOCKET sock, gint32 code,
2031 MonoArray *output, gint32 *error)
2033 glong output_bytes = 0;
2034 gchar *i_buffer, *o_buffer;
2038 MONO_ARCH_SAVE_REGS;
2042 if (code == FIONBIO) {
2043 /* Invalid command. Must use Socket.Blocking */
2047 if (input == NULL) {
2051 i_buffer = mono_array_addr (input, gchar, 0);
2052 i_len = mono_array_length (input);
2055 if (output == NULL) {
2059 o_buffer = mono_array_addr (output, gchar, 0);
2060 o_len = mono_array_length (output);
2063 ret = WSAIoctl (sock, code, i_buffer, i_len, o_buffer, o_len, &output_bytes, NULL, NULL);
2064 if (ret == SOCKET_ERROR) {
2065 *error = WSAGetLastError ();
2069 return (gint) output_bytes;
2072 #ifdef HAVE_SIOCGIFCONF
2074 is_loopback (int family, void *ad)
2076 char *ptr = (char *) ad;
2078 if (family == AF_INET) {
2079 return (ptr [0] == 127);
2083 return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
2090 get_local_ips (int family, int *nips)
2092 int addr_size, offset, fd, i, count;
2093 int max_ifaces = 50; /* 50 interfaces should be enough... */
2096 struct ifreq iflags;
2097 char *result, *tmp_ptr;
2098 gboolean ignore_loopback = FALSE;
2101 if (family == AF_INET) {
2102 addr_size = sizeof (struct in_addr);
2103 offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
2105 } else if (family == AF_INET6) {
2106 addr_size = sizeof (struct in6_addr);
2107 offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
2113 fd = socket (family, SOCK_STREAM, 0);
2115 ifc.ifc_len = max_ifaces * sizeof (struct ifreq);
2116 ifc.ifc_buf = g_malloc (ifc.ifc_len);
2117 if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) {
2119 g_free (ifc.ifc_buf);
2123 count = ifc.ifc_len / sizeof (struct ifreq);
2126 g_free (ifc.ifc_buf);
2131 for (i = 0, ifr = ifc.ifc_req; i < *nips; i++, ifr++) {
2132 strcpy (iflags.ifr_name, ifr->ifr_name);
2133 if (ioctl (fd, SIOCGIFFLAGS, &iflags) < 0) {
2137 if ((iflags.ifr_flags & IFF_UP) == 0) {
2138 ifr->ifr_name [0] = '\0';
2142 if ((iflags.ifr_flags & IFF_LOOPBACK) == 0) {
2143 ignore_loopback = TRUE;
2148 result = g_malloc (addr_size * count);
2150 for (i = 0, ifr = ifc.ifc_req; i < count; i++, ifr++) {
2151 if (ifr->ifr_name [0] == '\0') {
2156 if (ignore_loopback && is_loopback (family, ((char *) &ifr->ifr_addr) + offset)) {
2161 memcpy (tmp_ptr, ((char *) &ifr->ifr_addr) + offset, addr_size);
2162 tmp_ptr += addr_size;
2165 g_free (ifc.ifc_buf);
2170 get_local_ips (int family, int *nips)
2176 #endif /* HAVE_SIOCGIFCONF */
2179 static gboolean hostent_to_IPHostEntry(struct hostent *he, MonoString **h_name,
2180 MonoArray **h_aliases,
2181 MonoArray **h_addr_list,
2182 gboolean add_local_ips)
2184 MonoDomain *domain = mono_domain_get ();
2186 struct in_addr *local_in = NULL;
2189 if(he->h_length!=4 || he->h_addrtype!=AF_INET) {
2193 *h_name=mono_string_new(domain, he->h_name);
2196 while(he->h_aliases[i]!=NULL) {
2200 *h_aliases=mono_array_new(domain, mono_get_string_class (), i);
2202 while(he->h_aliases[i]!=NULL) {
2205 alias=mono_string_new(domain, he->h_aliases[i]);
2206 mono_array_setref (*h_aliases, i, alias);
2210 if (add_local_ips) {
2211 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2213 *h_addr_list = mono_array_new(domain, mono_get_string_class (), nlocal_in);
2214 for (i = 0; i < nlocal_in; i++) {
2215 MonoString *addr_string;
2216 char addr [16], *ptr;
2218 ptr = (char *) &local_in [i];
2219 g_snprintf(addr, 16, "%u.%u.%u.%u",
2220 (unsigned char) ptr [0],
2221 (unsigned char) ptr [1],
2222 (unsigned char) ptr [2],
2223 (unsigned char) ptr [3]);
2225 addr_string = mono_string_new (domain, addr);
2226 mono_array_setref (*h_addr_list, i, addr_string);
2234 if (nlocal_in == 0) {
2236 while (he->h_addr_list[i]!=NULL) {
2240 *h_addr_list=mono_array_new(domain, mono_get_string_class (), i);
2242 while(he->h_addr_list[i]!=NULL) {
2243 MonoString *addr_string;
2246 g_snprintf(addr, 16, "%u.%u.%u.%u",
2247 (unsigned char)he->h_addr_list[i][0],
2248 (unsigned char)he->h_addr_list[i][1],
2249 (unsigned char)he->h_addr_list[i][2],
2250 (unsigned char)he->h_addr_list[i][3]);
2252 addr_string=mono_string_new(domain, addr);
2253 mono_array_setref (*h_addr_list, i, addr_string);
2261 static gboolean ipaddr_to_IPHostEntry(const char *addr, MonoString **h_name,
2262 MonoArray **h_aliases,
2263 MonoArray **h_addr_list)
2265 MonoDomain *domain = mono_domain_get ();
2267 *h_name=mono_string_new(domain, addr);
2268 *h_aliases=mono_array_new(domain, mono_get_string_class (), 0);
2269 *h_addr_list=mono_array_new(domain, mono_get_string_class (), 1);
2270 mono_array_setref (*h_addr_list, 0, *h_name);
2276 #if defined(AF_INET6) && defined(HAVE_GETHOSTBYNAME2_R)
2277 static gboolean hostent_to_IPHostEntry2(struct hostent *he1,struct hostent *he2, MonoString **h_name,
2278 MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
2280 MonoDomain *domain = mono_domain_get ();
2281 int i, host_count, host_index, family_hint;
2282 struct in_addr *local_in = NULL;
2284 struct in6_addr *local_in6 = NULL;
2286 gboolean from_local = FALSE;
2288 family_hint = get_family_hint ();
2290 if(he1 == NULL && he2 == NULL) {
2295 * Check if address length and family are correct
2297 if (he1 != NULL && (he1->h_length!=4 || he1->h_addrtype!=AF_INET)) {
2301 if (he2 != NULL && (he2->h_length!=16 || he2->h_addrtype!=AF_INET6)) {
2306 * Get the aliases and host name from he1 or he2 whichever is
2307 * not null, if he1 is not null then take aliases from he1
2309 if (he1 != NULL && (family_hint == PF_UNSPEC ||
2310 family_hint == PF_INET)) {
2311 *h_name=mono_string_new (domain, he1->h_name);
2314 while(he1->h_aliases[i]!=NULL) {
2318 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2321 while(he1->h_aliases[i]!=NULL) {
2324 alias=mono_string_new (domain, he1->h_aliases[i]);
2325 mono_array_setref (*h_aliases, i, alias);
2328 } else if (he2 != NULL && (family_hint == PF_UNSPEC ||
2329 family_hint == PF_INET6)) {
2330 *h_name=mono_string_new (domain, he2->h_name);
2333 while(he2->h_aliases [i] != NULL) {
2337 *h_aliases=mono_array_new (domain, mono_get_string_class (),
2340 while(he2->h_aliases[i]!=NULL) {
2343 alias=mono_string_new (domain, he2->h_aliases[i]);
2344 mono_array_setref (*h_aliases, i, alias);
2352 * Count the number of addresses in he1 + he2
2355 if (he1 != NULL && (family_hint == PF_UNSPEC ||
2356 family_hint == PF_INET)) {
2358 while(he1->h_addr_list[i]!=NULL) {
2364 if (he2 != NULL && (family_hint == PF_UNSPEC ||
2365 family_hint == PF_INET6)) {
2367 while(he2->h_addr_list[i]!=NULL) {
2377 if (add_local_ips) {
2378 if (family_hint == PF_UNSPEC || family_hint == PF_INET)
2379 local_in = (struct in_addr *) get_local_ips (AF_INET, &nlocal_in);
2381 if (family_hint == PF_UNSPEC || family_hint == PF_INET6)
2382 local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2384 if (nlocal_in || nlocal_in6) {
2386 *h_addr_list = mono_array_new (domain, mono_get_string_class (),
2387 nlocal_in + nlocal_in6);
2391 for (n = 0; n < nlocal_in6; n++) {
2392 MonoString *addr_string;
2394 char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes with the trailing NULL */
2396 ret = inet_ntop (AF_INET6, &local_in6 [n], addr, sizeof(addr));
2399 addr_string = mono_string_new (domain, addr);
2400 mono_array_setref (*h_addr_list, host_index, addr_string);
2408 for (n = 0; n < nlocal_in; n++) {
2409 MonoString *addr_string;
2411 char addr[16]; /* INET_ADDRSTRLEN == 16 */
2413 ret = inet_ntop (AF_INET, &local_in [n], addr, sizeof(addr));
2416 addr_string = mono_string_new (domain, addr);
2417 mono_array_setref (*h_addr_list, host_index, addr_string);
2431 *h_addr_list=mono_array_new (domain, mono_get_string_class (), host_count);
2433 if (he2 != NULL && (family_hint == PF_UNSPEC ||
2434 family_hint == PF_INET6)) {
2436 while(he2->h_addr_list[i] != NULL) {
2437 MonoString *addr_string;
2439 char addr[48]; /* INET6_ADDRSTRLEN == 46, but IPv6 addresses can be 48 bytes long with the trailing NULL */
2441 ret = inet_ntop (AF_INET6, he2->h_addr_list[i], addr,
2445 addr_string = mono_string_new (domain, addr);
2446 mono_array_setref (*h_addr_list, host_index, addr_string);
2453 if (he1 != NULL && (family_hint == PF_UNSPEC ||
2454 family_hint == PF_INET)) {
2456 while(he1->h_addr_list[i] != NULL) {
2457 MonoString *addr_string;
2459 char addr[16]; /* INET_ADDRSTRLEN == 16 */
2461 ret = inet_ntop (AF_INET, he1->h_addr_list[i], addr,
2465 addr_string=mono_string_new (domain, addr);
2466 mono_array_setref (*h_addr_list, host_index, addr_string);
2477 #if defined(AF_INET6)
2479 addrinfo_to_IPHostEntry(struct addrinfo *info, MonoString **h_name,
2480 MonoArray **h_aliases,
2481 MonoArray **h_addr_list,
2482 gboolean add_local_ips)
2485 struct addrinfo *ai = NULL;
2486 struct in_addr *local_in = NULL;
2488 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 *) get_local_ips (AF_INET, &nlocal_in);
2498 local_in6 = (struct in6_addr *) get_local_ips (AF_INET6, &nlocal_in6);
2499 if (nlocal_in || nlocal_in6) {
2500 *h_addr_list=mono_array_new(domain, mono_get_string_class (), nlocal_in + nlocal_in6);
2502 MonoString *addr_string;
2506 for (i = 0; i < nlocal_in; i++) {
2507 inet_ntop (AF_INET, &local_in [i], addr, sizeof (addr));
2508 addr_string = mono_string_new (domain, addr);
2509 mono_array_setref (*h_addr_list, addr_index, addr_string);
2515 MonoString *addr_string;
2520 for (i = 0; i < nlocal_in6; i++) {
2521 ret = inet_ntop (AF_INET6, &local_in6 [i], addr, sizeof (addr));
2523 addr_string = mono_string_new (domain, addr);
2524 mono_array_setref (*h_addr_list, addr_index, addr_string);
2533 freeaddrinfo (info);
2542 for (count=0, ai=info; ai!=NULL; ai=ai->ai_next) {
2543 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2549 *h_addr_list=mono_array_new(domain, mono_get_string_class (), count);
2551 for (ai=info, i=0; ai!=NULL; ai=ai->ai_next) {
2552 MonoString *addr_string;
2554 char buffer [48]; /* Max. size for IPv6 */
2556 if((ai->ai_family != PF_INET) && (ai->ai_family != PF_INET6)) {
2560 if(ai->ai_family == PF_INET) {
2561 ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr), buffer, 16);
2563 ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in6*)ai->ai_addr)->sin6_addr), buffer, 48);
2567 addr_string=mono_string_new(domain, buffer);
2569 addr_string=mono_string_new(domain, "");
2572 mono_array_setref (*h_addr_list, addr_index, addr_string);
2574 if(!i && ai->ai_canonname != NULL) {
2575 *h_name=mono_string_new(domain, ai->ai_canonname);
2590 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2592 gboolean add_local_ips = FALSE;
2593 #ifdef HAVE_SIOCGIFCONF
2594 gchar this_hostname [256];
2596 #if !defined(HAVE_GETHOSTBYNAME2_R)
2597 struct addrinfo *info = NULL, hints;
2600 MONO_ARCH_SAVE_REGS;
2602 hostname=mono_string_to_utf8 (host);
2603 #ifdef HAVE_SIOCGIFCONF
2604 if (gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2605 if (!strcmp (hostname, this_hostname))
2606 add_local_ips = TRUE;
2610 memset(&hints, 0, sizeof(hints));
2611 hints.ai_family = get_family_hint ();
2612 hints.ai_socktype = SOCK_STREAM;
2613 hints.ai_flags = AI_CANONNAME;
2615 if (getaddrinfo(hostname, NULL, &hints, &info) == -1) {
2621 return(addrinfo_to_IPHostEntry(info, h_name, h_aliases, h_addr_list, add_local_ips));
2623 struct hostent he1,*hp1, he2, *hp2;
2624 int buffer_size1, buffer_size2;
2625 char *buffer1, *buffer2;
2627 gboolean return_value;
2630 MONO_ARCH_SAVE_REGS;
2632 hostname=mono_string_to_utf8 (host);
2634 #ifdef HAVE_SIOCGIFCONF
2635 if (gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2636 if (!strcmp (hostname, this_hostname))
2637 add_local_ips = TRUE;
2643 buffer1 = g_malloc0(buffer_size1);
2644 buffer2 = g_malloc0(buffer_size2);
2646 while (gethostbyname2_r(hostname, AF_INET, &he1, buffer1, buffer_size1,
2647 &hp1, &herr) == ERANGE) {
2649 buffer1 = g_realloc(buffer1, buffer_size1);
2654 while (gethostbyname2_r(hostname, AF_INET6, &he2, buffer2,
2655 buffer_size2, &hp2, &herr) == ERANGE) {
2657 buffer2 = g_realloc(buffer2, buffer_size2);
2663 return_value = hostent_to_IPHostEntry2(hp1, hp2, h_name, h_aliases,
2664 h_addr_list, add_local_ips);
2670 return(return_value);
2671 #endif /* HAVE_GETHOSTBYNAME2_R */
2673 #else /* AF_INET6 */
2674 MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2678 gboolean add_local_ips = FALSE;
2679 #ifdef HAVE_SIOCGIFCONF
2680 gchar this_hostname [256];
2683 MONO_ARCH_SAVE_REGS;
2685 hostname=mono_string_to_utf8(host);
2686 #ifdef HAVE_SIOCGIFCONF
2687 if (gethostname (this_hostname, sizeof (this_hostname)) != -1) {
2688 if (!strcmp (hostname, this_hostname))
2689 add_local_ips = TRUE;
2693 he = _wapi_gethostbyname (hostname);
2700 return(hostent_to_IPHostEntry(he, h_name, h_aliases, h_addr_list, add_local_ips));
2702 #endif /* AF_INET6 */
2704 #ifndef HAVE_INET_PTON
2706 inet_pton (int family, const char *address, void *inaddrp)
2708 if (family == AF_INET) {
2709 #ifdef HAVE_INET_ATON
2710 struct in_addr inaddr;
2712 if (!inet_aton (address, &inaddr))
2715 memcpy (inaddrp, &inaddr, sizeof (struct in_addr));
2718 /* assume the system has inet_addr(), if it doesn't
2719 have that we're pretty much screwed... */
2722 if (!strcmp (address, "255.255.255.255")) {
2723 /* special-case hack */
2724 inaddr = 0xffffffff;
2726 inaddr = inet_addr (address);
2728 #define INADDR_NONE ((in_addr_t) -1)
2730 if (inaddr == INADDR_NONE)
2734 memcpy (inaddrp, &inaddr, sizeof (guint32));
2736 #endif /* HAVE_INET_ATON */
2741 #endif /* !HAVE_INET_PTON */
2743 extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
2746 const char *version;
2750 struct sockaddr_in saddr;
2751 struct sockaddr_in6 saddr6;
2752 struct addrinfo *info = NULL, hints;
2754 char hostname[1024] = {0};
2757 struct in_addr inaddr;
2762 MONO_ARCH_SAVE_REGS;
2764 version = mono_get_runtime_info ()->framework_version;
2765 v1 = (version[0] == '1');
2767 address = mono_string_to_utf8 (addr);
2770 if (inet_pton (AF_INET, address, &saddr.sin_addr ) <= 0) {
2771 /* Maybe an ipv6 address */
2772 if (inet_pton (AF_INET6, address, &saddr6.sin6_addr) <= 0) {
2778 saddr6.sin6_family = AF_INET6;
2783 saddr.sin_family = AF_INET;
2788 flags = NI_NAMEREQD;
2791 if(family == AF_INET) {
2792 #if HAVE_SOCKADDR_IN_SIN_LEN
2793 saddr.sin_len = sizeof (saddr);
2795 if(getnameinfo ((struct sockaddr*)&saddr, sizeof(saddr),
2796 hostname, sizeof(hostname), NULL, 0,
2800 } else if(family == AF_INET6) {
2801 #if HAVE_SOCKADDR_IN6_SIN_LEN
2802 saddr6.sin6_len = sizeof (saddr6);
2804 if(getnameinfo ((struct sockaddr*)&saddr6, sizeof(saddr6),
2805 hostname, sizeof(hostname), NULL, 0,
2811 memset (&hints, 0, sizeof(hints));
2812 hints.ai_family = get_family_hint ();
2813 hints.ai_socktype = SOCK_STREAM;
2814 hints.ai_flags = AI_CANONNAME;
2816 if( getaddrinfo (hostname, NULL, &hints, &info) == -1 ) {
2820 return(addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE));
2822 if (inet_pton (AF_INET, address, &inaddr) <= 0) {
2827 if ((he = gethostbyaddr ((char *) &inaddr, sizeof (inaddr), AF_INET)) == NULL) {
2831 ret = ipaddr_to_IPHostEntry (address, h_name,
2832 h_aliases, h_addr_list);
2835 ret = hostent_to_IPHostEntry (he, h_name, h_aliases,
2836 h_addr_list, FALSE);
2844 extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name)
2846 gchar hostname[256];
2849 MONO_ARCH_SAVE_REGS;
2851 ret = gethostname (hostname, sizeof (hostname));
2856 *h_name=mono_string_new(mono_domain_get (), hostname);
2861 void mono_network_init(void)
2866 err=WSAStartup(MAKEWORD(2,0), &wsadata);
2868 g_error(G_GNUC_PRETTY_FUNCTION ": Couldn't initialise networking");
2873 g_message(G_GNUC_PRETTY_FUNCTION ": Using socket library: %s", wsadata.szDescription);
2874 g_message(G_GNUC_PRETTY_FUNCTION ": Socket system status: %s", wsadata.szSystemStatus);
2878 void mono_network_cleanup(void)