Merge pull request #498 from Unroll-Me/master
[mono.git] / mono / metadata / socket-io.c
index e14ae3860d263586b41449655ef6bd45b2095626..5a6848ea1c1ac28cff0037795a399caf63eadd94 100644 (file)
 
 #include <config.h>
 
+#ifndef DISABLE_SOCKETS
+
+#ifdef __APPLE__
+#define __APPLE_USE_RFC_3542
+#endif
+
 #include <glib.h>
 #include <string.h>
 #include <stdlib.h>
@@ -20,7 +26,7 @@
 #include <errno.h>
 
 #include <sys/types.h>
-#ifndef PLATFORM_WIN32 
+#ifndef HOST_WIN32 
 #include <sys/socket.h>
 #include <sys/ioctl.h>
 #include <netinet/in.h>
@@ -35,6 +41,7 @@
 #include <mono/metadata/exception.h>
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/appdomain.h>
+#include <mono/metadata/file-io.h>
 #include <mono/metadata/threads.h>
 #include <mono/metadata/threads-types.h>
 #include <mono/utils/mono-poll.h>
 #include <mono/metadata/class-internals.h>
 #include <mono/metadata/threadpool-internals.h>
 #include <mono/metadata/domain-internals.h>
+#include <mono/utils/mono-threads.h>
+#include <mono/utils/mono-memory-model.h>
 
+#include <time.h>
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/un.h>
 #endif
 
+#ifdef HAVE_GETIFADDRS
+// <net/if.h> must be included before <ifaddrs.h>
+#include <ifaddrs.h>
+#endif
+
 #include "mono/io-layer/socket-wrappers.h"
 
-#ifdef PLATFORM_WIN32
+#if defined(HOST_WIN32)
 /* This is a kludge to make this file build under cygwin:
  * w32api/ws2tcpip.h has definitions for some AF_INET6 values and
  * prototypes for some but not all required functions (notably
 #undef AF_INET6
 #endif
 
-#ifdef PLATFORM_ANDROID
-// not yet actually implemented...
-#undef AF_INET6
-#endif
+#define LOGDEBUG(...)  
+/* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
 
-#undef DEBUG
+/* 
+ * Some older versions of libc provide IPV6 support without defining the AI_ADDRCONFIG
+ * flag for getaddrinfo.
+ */
+#ifndef AI_ADDRCONFIG
+#define AI_ADDRCONFIG 0
+#endif
 
 static gint32 convert_family(MonoAddressFamily mono_family)
 {
@@ -131,11 +150,15 @@ static gint32 convert_family(MonoAddressFamily mono_family)
                break;
                
        case AddressFamily_Sna:
+#ifdef AF_SNA
                family=AF_SNA;
+#endif
                break;
                
        case AddressFamily_DecNet:
+#ifdef AF_DECnet
                family=AF_DECnet;
+#endif
                break;
                
        case AddressFamily_AppleTalk:
@@ -182,13 +205,17 @@ static MonoAddressFamily convert_to_mono_family(guint16 af_family)
                break;
 #endif
                
+#ifdef AF_SNA
        case AF_SNA:
                family=AddressFamily_Sna;
                break;
+#endif
                
+#ifdef AF_DECnet
        case AF_DECnet:
                family=AddressFamily_DecNet;
                break;
+#endif
                
        case AF_APPLETALK:
                family=AddressFamily_AppleTalk;
@@ -230,7 +257,9 @@ static gint32 convert_type(MonoSocketType mono_type)
                break;
 
        case SocketType_Rdm:
+#ifdef SOCK_RDM
                type=SOCK_RDM;
+#endif
                break;
 
        case SocketType_Seqpacket:
@@ -531,6 +560,7 @@ static gint32 convert_sockopt_level_and_name(MonoSocketOptionLevel mono_level,
 
                switch(mono_name) {
                case SocketOptionName_IpTimeToLive:
+               case SocketOptionName_HopLimit:
                        *system_name = IPV6_UNICAST_HOPS;
                        break;
                case SocketOptionName_MulticastInterface:
@@ -635,42 +665,25 @@ static gint32 convert_sockopt_level_and_name(MonoSocketOptionLevel mono_level,
 
 static MonoImage *get_socket_assembly (void)
 {
-       static const char *version = NULL;
-       static gboolean moonlight;
-       static MonoImage *socket_assembly = NULL;
-       
-       if (version == NULL) {
-               version = mono_get_runtime_info ()->framework_version;
-               moonlight = !strcmp (version, "2.1");
-       }
+       MonoDomain *domain = mono_domain_get ();
        
-       if (socket_assembly == NULL) {
-               if (moonlight) {
-                       socket_assembly = mono_image_loaded ("System.Net");
-                       if (!socket_assembly) {
-                               MonoAssembly *sa = mono_assembly_open ("System.Net.dll", NULL);
-                       
-                               if (!sa) {
-                                       g_assert_not_reached ();
-                               } else {
-                                       socket_assembly = mono_assembly_get_image (sa);
-                               }
-                       }
-               } else {
-                       socket_assembly = mono_image_loaded ("System");
-                       if (!socket_assembly) {
-                               MonoAssembly *sa = mono_assembly_open ("System.dll", NULL);
-                       
-                               if (!sa) {
-                                       g_assert_not_reached ();
-                               } else {
-                                       socket_assembly = mono_assembly_get_image (sa);
-                               }
+       if (domain->socket_assembly == NULL) {
+               MonoImage *socket_assembly;
+
+               socket_assembly = mono_image_loaded ("System");
+               if (!socket_assembly) {
+                       MonoAssembly *sa = mono_assembly_open ("System.dll", NULL);
+               
+                       if (!sa) {
+                               g_assert_not_reached ();
+                       } else {
+                               socket_assembly = mono_assembly_get_image (sa);
                        }
                }
+               mono_atomic_store_release (&domain->socket_assembly, socket_assembly);
        }
        
-       return(socket_assembly);
+       return domain->socket_assembly;
 }
 
 #ifdef AF_INET6
@@ -688,6 +701,7 @@ static gint32 get_family_hint(void)
                ipv4_field = mono_class_get_field_from_name (socket_class, "ipv4Supported");
                ipv6_field = mono_class_get_field_from_name (socket_class, "ipv6Supported");
                vtable = mono_class_vtable (mono_domain_get (), socket_class);
+               g_assert (vtable);
                mono_runtime_class_init (vtable);
 
                mono_field_static_get_value (vtable, ipv4_field, &ipv4_enabled);
@@ -771,9 +785,7 @@ void ves_icall_System_Net_Sockets_Socket_Close_internal(SOCKET sock,
 {
        MONO_ARCH_SAVE_REGS;
 
-#ifdef DEBUG
-       g_message (G_GNUC_PRETTY_FUNCTION ": closing 0x%x", sock);
-#endif
+       LOGDEBUG (g_message ("%s: closing 0x%x", __func__, sock));
 
        *error = 0;
 
@@ -787,9 +799,7 @@ gint32 ves_icall_System_Net_Sockets_SocketException_WSAGetLastError_internal(voi
 {
        MONO_ARCH_SAVE_REGS;
 
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": returning %d", WSAGetLastError());
-#endif
+       LOGDEBUG (g_message("%s: returning %d", __func__, WSAGetLastError()));
 
        return(WSAGetLastError());
 }
@@ -804,14 +814,7 @@ gint32 ves_icall_System_Net_Sockets_Socket_Available_internal(SOCKET sock,
 
        *error = 0;
        
-#if defined(PLATFORM_MACOSX)
-       {
-               socklen_t optlen = sizeof (amount);
-               ret=getsockopt (sock, SOL_SOCKET, SO_NREAD, &amount, &optlen);
-       }
-#else
        ret=ioctlsocket(sock, FIONREAD, &amount);
-#endif
        if(ret==SOCKET_ERROR) {
                *error = WSAGetLastError ();
                return(0);
@@ -851,45 +854,16 @@ gpointer ves_icall_System_Net_Sockets_Socket_Accept_internal(SOCKET sock,
        MONO_ARCH_SAVE_REGS;
 
        *error = 0;
-
-#ifdef PLATFORM_WIN32
-       /* Several applications are getting stuck during shutdown on Windows 
-        * when an accept call is on a background thread.
-        * 
-        */
-       if (blocking) {
-               MonoThread* curthread = mono_thread_current ();
-
-               if (curthread) {
-                       for (;;) {
-                               int selectret;
-                               int optlen = sizeof (gint);
-                               TIMEVAL timeout; 
-                               fd_set readfds;
-                               FD_ZERO (&readfds);
-                               FD_SET(sock, &readfds);
-                               timeout.tv_sec = 0;
-                               timeout.tv_usec = 1000;
-                               selectret = select (0, &readfds, NULL, NULL, &timeout);
-                               if (selectret > 0)
-                                       break;
-                               if (curthread->state & ThreadState_StopRequested)
-                                       return NULL;
-                               /* A negative return from select means that an error has occurred.
-                                * Let _wapi_accept handle that.*/
-                               if (selectret != 0)
-                                       break;
-                               /* The socket's state may have changed.  If it is no longer listening, stop.*/
-                               if (!getsockopt (sock, SOL_SOCKET, SO_ACCEPTCONN, (char*)&selectret, &optlen)) {
-                                       if (!selectret)
-                                               break;
-                               }
-                       }
-               }
+#ifdef HOST_WIN32
+       {
+               MonoInternalThread* curthread = mono_thread_internal_current ();
+               curthread->interrupt_on_stop = (gpointer)TRUE;
+               newsock = _wapi_accept (sock, NULL, 0);
+               curthread->interrupt_on_stop = (gpointer)FALSE;
        }
-#endif
-       
+#else
        newsock = _wapi_accept (sock, NULL, 0);
+#endif
        if(newsock==INVALID_SOCKET) {
                *error = WSAGetLastError ();
                return(NULL);
@@ -914,38 +888,54 @@ void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock,
        }
 }
 
+#ifdef AF_INET6
+// Check whether it's ::ffff::0:0.
+static gboolean
+is_ipv4_mapped_any (const struct in6_addr *addr)
+{
+       int i;
+       
+       for (i = 0; i < 10; i++) {
+               if (addr->s6_addr [i])
+                       return FALSE;
+       }
+       if ((addr->s6_addr [10] != 0xff) || (addr->s6_addr [11] != 0xff))
+               return FALSE;
+       for (i = 12; i < 16; i++) {
+               if (addr->s6_addr [i])
+                       return FALSE;
+       }
+       return TRUE;
+}
+#endif
+
 static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
                                               int sa_size, gint32 *error)
 {
        MonoDomain *domain = mono_domain_get ();
        MonoObject *sockaddr_obj;
-       MonoClass *sockaddr_class;
-       MonoClassField *field;
        MonoArray *data;
        MonoAddressFamily family;
 
        /* Build a System.Net.SocketAddress object instance */
-       sockaddr_class=mono_class_from_name_cached (get_socket_assembly (), "System.Net", "SocketAddress");
-       sockaddr_obj=mono_object_new(domain, sockaddr_class);
+       if (!domain->sockaddr_class) {
+               domain->sockaddr_class=mono_class_from_name (get_socket_assembly (), "System.Net", "SocketAddress");
+               g_assert (domain->sockaddr_class);
+       }
+       sockaddr_obj=mono_object_new(domain, domain->sockaddr_class);
        
        /* Locate the SocketAddress data buffer in the object */
-       field=mono_class_get_field_from_name_cached (sockaddr_class, "data");
-
-       /* Make sure there is space for the family and size bytes */
-#ifdef HAVE_SYS_UN_H
-       if (saddr->sa_family == AF_UNIX) {
-               /* sa_len includes the entire sockaddr size, so we don't need the
-                * N bytes (sizeof (unsigned short)) of the family. */
-               data=mono_array_new_cached(domain, mono_get_byte_class (), sa_size);
-       } else
-#endif
-       {
-               /* May be the +2 here is too conservative, as sa_len returns
-                * the length of the entire sockaddr_in/in6, including
-                * sizeof (unsigned short) of the family */
-               data=mono_array_new_cached(domain, mono_get_byte_class (), sa_size+2);
+       if (!domain->sockaddr_data_field) {
+               domain->sockaddr_data_field=mono_class_get_field_from_name (domain->sockaddr_class, "data");
+               g_assert (domain->sockaddr_data_field);
        }
 
+       /* May be the +2 here is too conservative, as sa_len returns
+        * the length of the entire sockaddr_in/in6, including
+        * sizeof (unsigned short) of the family */
+       /* We can't really avoid the +2 as all code below depends on this size - INCLUDING unix domain sockets.*/
+       data=mono_array_new_cached(domain, mono_get_byte_class (), sa_size+2);
+
        /* The data buffer is laid out as follows:
         * bytes 0 and 1 are the address family
         * bytes 2 and 3 are the port info
@@ -977,7 +967,7 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
                mono_array_set(data, guint8, 6, (address>>8) & 0xff);
                mono_array_set(data, guint8, 7, (address) & 0xff);
        
-               mono_field_set_value (sockaddr_obj, field, data);
+               mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
 
                return(sockaddr_obj);
 #ifdef AF_INET6
@@ -993,10 +983,17 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
 
                mono_array_set(data, guint8, 2, (port>>8) & 0xff);
                mono_array_set(data, guint8, 3, (port) & 0xff);
-
-               for(i=0; i<16; i++) {
-                       mono_array_set(data, guint8, 8+i,
-                                      sa_in->sin6_addr.s6_addr[i]);
+               
+               if (is_ipv4_mapped_any (&sa_in->sin6_addr)) {
+                       // Map ::ffff:0:0 to :: (bug #5502)
+                       for(i=0; i<16; i++) {
+                               mono_array_set(data, guint8, 8+i, 0);
+                       }
+               } else {
+                       for(i=0; i<16; i++) {
+                               mono_array_set(data, guint8, 8+i,
+                                              sa_in->sin6_addr.s6_addr[i]);
+                       }
                }
 
                mono_array_set(data, guint8, 24, sa_in->sin6_scope_id & 0xff);
@@ -1007,7 +1004,7 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
                mono_array_set(data, guint8, 27,
                               (sa_in->sin6_scope_id >> 24) & 0xff);
 
-               mono_field_set_value (sockaddr_obj, field, data);
+               mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
 
                return(sockaddr_obj);
 #endif
@@ -1019,7 +1016,7 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
                        mono_array_set (data, guint8, i+2, saddr->sa_data[i]);
                }
                
-               mono_field_set_value (sockaddr_obj, field, data);
+               mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
 
                return sockaddr_obj;
 #endif
@@ -1029,56 +1026,92 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
        }
 }
 
-extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 *error)
+static int
+get_sockaddr_size (int family)
 {
-       gchar sa[32];   /* sockaddr in not big enough for sockaddr_in6 */
+       int size;
+
+       size = 0;
+       if (family == AF_INET) {
+               size = sizeof (struct sockaddr_in);
+#ifdef AF_INET6
+       } else if (family == AF_INET6) {
+               size = sizeof (struct sockaddr_in6);
+#endif
+#ifdef HAVE_SYS_UN_H
+       } else if (family == AF_UNIX) {
+               size = sizeof (struct sockaddr_un);
+#endif
+       }
+       return size;
+}
+
+extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 af, gint32 *error)
+{
+       gchar *sa;
        socklen_t salen;
        int ret;
+       MonoObject *result;
        
        MONO_ARCH_SAVE_REGS;
 
        *error = 0;
        
-       salen=sizeof(sa);
+       salen = get_sockaddr_size (convert_family (af));
+       if (salen == 0) {
+               *error = WSAEAFNOSUPPORT;
+               return NULL;
+       }
+       sa = (salen <= 128) ? alloca (salen) : g_malloc0 (salen);
        ret = _wapi_getsockname (sock, (struct sockaddr *)sa, &salen);
        
        if(ret==SOCKET_ERROR) {
                *error = WSAGetLastError ();
+               if (salen > 128)
+                       g_free (sa);
                return(NULL);
        }
        
-#ifdef DEBUG
-       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));
-#endif
+       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)));
 
-       return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
-                                          error));
+       result = create_object_from_sockaddr((struct sockaddr *)sa, salen, error);
+       if (salen > 128)
+               g_free (sa);
+       return result;
 }
 
-extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 *error)
+extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 af, gint32 *error)
 {
-       gchar sa[32];   /* sockaddr in not big enough for sockaddr_in6 */
+       gchar *sa;
        socklen_t salen;
        int ret;
+       MonoObject *result;
        
        MONO_ARCH_SAVE_REGS;
 
        *error = 0;
        
-       salen=sizeof(sa);
+       salen = get_sockaddr_size (convert_family (af));
+       if (salen == 0) {
+               *error = WSAEAFNOSUPPORT;
+               return NULL;
+       }
+       sa = (salen <= 128) ? alloca (salen) : g_malloc0 (salen);
+       /* Note: linux returns just 2 for AF_UNIX. Always. */
        ret = _wapi_getpeername (sock, (struct sockaddr *)sa, &salen);
-       
        if(ret==SOCKET_ERROR) {
                *error = WSAGetLastError ();
+               if (salen > 128)
+                       g_free (sa);
                return(NULL);
        }
        
-#ifdef DEBUG
-       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));
-#endif
+       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)));
 
-       return(create_object_from_sockaddr((struct sockaddr *)sa, salen,
-                                          error));
+       result = create_object_from_sockaddr((struct sockaddr *)sa, salen, error);
+       if (salen > 128)
+               g_free (sa);
+       return result;
 }
 
 static struct sockaddr *create_sockaddr_from_object(MonoObject *saddr_obj,
@@ -1208,9 +1241,7 @@ extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoO
                return;
        }
 
-#ifdef DEBUG
-       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));
-#endif
+       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)));
 
        ret = _wapi_bind (sock, sa, sa_size);
        if(ret==SOCKET_ERROR) {
@@ -1230,7 +1261,7 @@ MonoBoolean
 ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
                                                   gint timeout, gint32 *error)
 {
-       MonoThread *thread = NULL;
+       MonoInternalThread *thread = NULL;
        mono_pollfd *pfds;
        int ret;
        time_t start;
@@ -1266,7 +1297,7 @@ ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
                        int leave = 0;
 
                        if (thread == NULL) {
-                               thread = mono_thread_current ();
+                               thread = mono_thread_internal_current ();
                        }
                        
                        leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
@@ -1283,7 +1314,7 @@ ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
        } while (ret == -1 && errno == EINTR);
 
        if (ret == -1) {
-#ifdef PLATFORM_WIN32
+#ifdef HOST_WIN32
                *error = WSAGetLastError ();
 #else
                *error = errno_to_WSA (errno, __func__);
@@ -1316,9 +1347,7 @@ extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, Mo
                return;
        }
        
-#ifdef DEBUG
-       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));
-#endif
+       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)));
 
        ret = _wapi_connect (sock, sa, sa_size);
        if(ret==SOCKET_ERROR) {
@@ -1356,10 +1385,7 @@ extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock,
 
        *error = 0;
        
-#ifdef DEBUG
-       g_message("%s: disconnecting from socket %p (reuse %d)", __func__,
-                 sock, reuse);
-#endif
+       LOGDEBUG (g_message("%s: disconnecting from socket %p (reuse %d)", __func__, sock, reuse));
 
        /* I _think_ the extension function pointers need to be looked
         * up for each socket.  FIXME: check the best way to store
@@ -1437,8 +1463,18 @@ gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArr
                *error = WSAEOPNOTSUPP;
                return (0);
        }
-               
+
+#ifdef HOST_WIN32
+       {
+               MonoInternalThread* curthread = mono_thread_internal_current ();
+               curthread->interrupt_on_stop = (gpointer)TRUE;
+               ret = _wapi_recv (sock, buf, count, recvflags);
+               curthread->interrupt_on_stop = (gpointer)FALSE;
+       }
+#else
        ret = _wapi_recv (sock, buf, count, recvflags);
+#endif
+
        if(ret==SOCKET_ERROR) {
                *error = WSAGetLastError ();
                return(0);
@@ -1544,15 +1580,11 @@ gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray
                return(0);
        }
 
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
-#endif
+       LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
        
        buf=mono_array_addr(buffer, guchar, offset);
 
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
-#endif
+       LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
 
        sendflags = convert_socketflags (flags);
        if (sendflags == -1) {
@@ -1621,15 +1653,11 @@ gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArra
                return(0);
        }
        
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": alen: %d", alen);
-#endif
+       LOGDEBUG (g_message("%s: alen: %d", __func__, alen));
        
        buf=mono_array_addr(buffer, guchar, offset);
 
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": Sending %d bytes", count);
-#endif
+       LOGDEBUG (g_message("%s: Sending %d bytes", __func__, count));
 
        sendflags = convert_socketflags (flags);
        if (sendflags == -1) {
@@ -1661,7 +1689,7 @@ static SOCKET Socket_to_SOCKET(MonoObject *sockobj)
 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
 void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error)
 {
-       MonoThread *thread = NULL;
+       MonoInternalThread *thread = NULL;
        MonoObject *obj;
        mono_pollfd *pfds;
        int nfds, idx;
@@ -1671,7 +1699,7 @@ void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gi
        MonoClass *sock_arr_class;
        MonoArray *socks;
        time_t start;
-       mono_array_size_t socks_size;
+       uintptr_t socks_size;
        
        MONO_ARCH_SAVE_REGS;
 
@@ -1717,7 +1745,7 @@ void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gi
                if (ret == -1 && errno == EINTR) {
                        int leave = 0;
                        if (thread == NULL)
-                               thread = mono_thread_current ();
+                               thread = mono_thread_internal_current ();
 
                        leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
                        
@@ -1734,7 +1762,7 @@ void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gi
        } while (ret == -1 && errno == EINTR);
        
        if (ret == -1) {
-#ifdef PLATFORM_WIN32
+#ifdef HOST_WIN32
                *error = WSAGetLastError ();
 #else
                *error = errno_to_WSA (errno, __func__);
@@ -1750,7 +1778,7 @@ void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gi
        }
 
        sock_arr_class= ((MonoObject *)*sockets)->vtable->klass;
-       socks_size = ((mono_array_size_t)ret) + 3; /* space for the NULL delimiters */
+       socks_size = ((uintptr_t)ret) + 3; /* space for the NULL delimiters */
        socks = mono_array_new_full (mono_domain_get (), sock_arr_class, &socks_size, NULL);
 
        mode = idx = 0;
@@ -1800,7 +1828,11 @@ void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET soc
        int time_ms = 0;
        socklen_t time_ms_size = sizeof (time_ms);
 #ifdef SO_PEERCRED
+#  if defined(__OpenBSD__)
+       struct sockpeercred cred;
+#  else
        struct ucred cred;
+#  endif
        socklen_t credsize = sizeof(cred);
 #endif
        MonoDomain *domain=mono_domain_get();
@@ -1812,8 +1844,18 @@ void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET soc
 
        *error = 0;
        
-       ret=convert_sockopt_level_and_name(level, name, &system_level,
-                                          &system_name);
+#if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
+       if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
+               system_level = SOL_SOCKET;
+               system_name = SO_REUSEADDR;
+               ret = 0;
+       } else
+#endif
+       {
+
+               ret = convert_sockopt_level_and_name (level, name, &system_level, &system_name);
+       }
+
        if(ret==-1) {
                *error = WSAENOPROTOOPT;
                return;
@@ -1920,9 +1962,12 @@ void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET soc
 #endif
 
        default:
+#if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
+               if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse)
+                       val = val ? 0 : 1;
+#endif
                obj = int_to_object (domain, val);
        }
-
        *obj_val=obj;
 }
 
@@ -1972,7 +2017,6 @@ static struct in_addr ipaddress_to_struct_in_addr(MonoObject *ipaddr)
        
        return(inaddr);
 }
-#endif
 
 #ifdef AF_INET6
 static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
@@ -1989,8 +2033,8 @@ static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
 #ifndef s6_addr16
        for(i=0; i<8; i++) {
                guint16 s = mono_array_get (data, guint16, i);
-               in6addr.s6_addr[2 * i] = (s >> 8) & 0xff;
-               in6addr.s6_addr[2 * i + 1] = s & 0xff;
+               in6addr.s6_addr[2 * i + 1] = (s >> 8) & 0xff;
+               in6addr.s6_addr[2 * i] = s & 0xff;
        }
 #else
        for(i=0; i<8; i++)
@@ -1999,9 +2043,47 @@ static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
        return(in6addr);
 }
 #endif /* AF_INET6 */
+#endif
+
+#if defined(HAVE_GETIFADDRS) && defined(HAVE_IF_NAMETOINDEX)
+static int
+get_local_interface_id (int family)
+{
+       struct ifaddrs *ifap = NULL, *ptr;
+       int idx = 0;
+       
+       if (getifaddrs (&ifap)) {
+               return 0;
+       }
+       
+       for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
+               if (!ptr->ifa_addr || !ptr->ifa_name)
+                       continue;
+               if (ptr->ifa_addr->sa_family != family)
+                       continue;
+               if ((ptr->ifa_flags & IFF_LOOPBACK) != 0)
+                       continue;
+               if ((ptr->ifa_flags & IFF_MULTICAST) == 0)
+                       continue;
+                       
+               idx = if_nametoindex (ptr->ifa_name);
+               break;
+       }
+       
+       freeifaddrs (ifap);
+       return idx;
+}
+#else
+static int
+get_local_interface_id (int family)
+{
+       return 0;
+}
+#endif
 
 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)
 {
+       struct linger linger;
        int system_level;
        int system_name;
        int ret;
@@ -2036,6 +2118,15 @@ void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, g
 
        ret=convert_sockopt_level_and_name(level, name, &system_level,
                                           &system_name);
+
+#if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
+       if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
+               system_name = SO_REUSEADDR;
+               int_val = int_val ? 0 : 1;
+               ret = 0;
+       }
+#endif
+
        if(ret==-1) {
                *error = WSAENOPROTOOPT;
                return;
@@ -2047,18 +2138,9 @@ void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, g
        /* Only one of obj_val, byte_val or int_val has data */
        if(obj_val!=NULL) {
                MonoClassField *field;
-               struct linger linger;
                int valsize;
                
                switch(name) {
-               case SocketOptionName_DontLinger:
-                       linger.l_onoff=0;
-                       linger.l_linger=0;
-                       valsize=sizeof(linger);
-                       ret = _wapi_setsockopt (sock, system_level,
-                                               system_name, &linger, valsize);
-                       break;
-                       
                case SocketOptionName_Linger:
                        /* Dig out "bool enabled" and "int seconds"
                         * fields
@@ -2094,7 +2176,22 @@ void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, g
 
                                field=mono_class_get_field_from_name(obj_val->vtable->klass, "ifIndex");
                                mreq6.ipv6mr_interface =*(guint64 *)(((char *)obj_val)+field->offset);
-
+                               
+#if defined(__APPLE__)
+                               /*
+                               * Bug #5504:
+                               *
+                               * Mac OS Lion doesn't allow ipv6mr_interface = 0.
+                               *
+                               * Tests on Windows and Linux show that the multicast group is only
+                               * joined on one NIC when interface = 0, so we simply use the interface
+                               * id from the first non-loopback interface (this is also what
+                               * Dns.GetHostName (string.Empty) would return).
+                               */
+                               if (!mreq6.ipv6mr_interface)
+                                       mreq6.ipv6mr_interface = get_local_interface_id (AF_INET6);
+#endif
+                                       
                                ret = _wapi_setsockopt (sock, system_level,
                                                        system_name, &mreq6,
                                                        sizeof (mreq6));
@@ -2146,17 +2243,31 @@ void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, g
                        return;
                }
        } else if (byte_val!=NULL) {
-               int valsize=mono_array_length(byte_val);
-               guchar *buf=mono_array_addr(byte_val, guchar, 0);
-       
-               ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
-               if(ret==SOCKET_ERROR) {
-                       *error = WSAGetLastError ();
-                       return;
+               int valsize = mono_array_length (byte_val);
+               guchar *buf = mono_array_addr (byte_val, guchar, 0);
+               
+               switch(name) {
+               case SocketOptionName_DontLinger:
+                       if (valsize == 1) {
+                               linger.l_onoff = (*buf) ? 0 : 1;
+                               linger.l_linger = 0;
+                               ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
+                       } else {
+                               *error = WSAEINVAL;
+                       }
+                       break;
+               default:
+                       ret = _wapi_setsockopt (sock, system_level, system_name, buf, valsize);
+                       break;
                }
        } else {
                /* ReceiveTimeout/SendTimeout get here */
                switch(name) {
+               case SocketOptionName_DontLinger:
+                       linger.l_onoff = !int_val;
+                       linger.l_linger = 0;
+                       ret = _wapi_setsockopt (sock, system_level, system_name, &linger, sizeof (linger));
+                       break;
                case SocketOptionName_DontFragment:
 #ifdef HAVE_IP_MTU_DISCOVER
                        /* Fiddle with the value slightly if we're
@@ -2337,6 +2448,76 @@ get_local_ips (int family, int *nips)
        g_free (ifc.ifc_buf);
        return result;
 }
+#elif defined(HAVE_GETIFADDRS)
+static gboolean
+is_loopback (int family, void *ad)
+{
+       char *ptr = (char *) ad;
+
+       if (family == AF_INET) {
+               return (ptr [0] == 127);
+       }
+#ifdef AF_INET6
+       else {
+               return (IN6_IS_ADDR_LOOPBACK ((struct in6_addr *) ptr));
+       }
+#endif
+       return FALSE;
+}
+
+static void *
+get_local_ips (int family, int *nips)
+{
+       struct ifaddrs *ifap = NULL, *ptr;
+       int addr_size, offset, count, i;
+       char *result, *tmp_ptr;
+
+       *nips = 0;
+       if (family == AF_INET) {
+               addr_size = sizeof (struct in_addr);
+               offset = G_STRUCT_OFFSET (struct sockaddr_in, sin_addr);
+#ifdef AF_INET6
+       } else if (family == AF_INET6) {
+               addr_size = sizeof (struct in6_addr);
+               offset = G_STRUCT_OFFSET (struct sockaddr_in6, sin6_addr);
+#endif
+       } else {
+               return NULL;
+       }
+       
+       if (getifaddrs (&ifap)) {
+               return NULL;
+       }
+       
+       count = 0;
+       for (ptr = ifap; ptr; ptr = ptr->ifa_next) {
+               if (!ptr->ifa_addr)
+                       continue;
+               if (ptr->ifa_addr->sa_family != family)
+                       continue;
+               if (is_loopback (family, ((char *) ptr->ifa_addr) + offset))
+                       continue;
+               count++;
+       }
+               
+       result = g_malloc (addr_size * count);
+       tmp_ptr = result;
+       for (i = 0, ptr = ifap; ptr; ptr = ptr->ifa_next) {
+               if (!ptr->ifa_addr)
+                       continue;
+               if (ptr->ifa_addr->sa_family != family)
+                       continue;
+               if (is_loopback (family, ((char *) ptr->ifa_addr) + offset))
+                       continue;
+                       
+               memcpy (tmp_ptr, ((char *) ptr->ifa_addr) + offset, addr_size);
+               tmp_ptr += addr_size;
+       }
+       
+       freeifaddrs (ifap);
+       *nips = count;
+       return result;
+}
 #else
 static void *
 get_local_ips (int family, int *nips)
@@ -2755,6 +2936,7 @@ addrinfo_to_IPHostEntry(struct addrinfo *info, MonoString **h_name,
                mono_array_setref (*h_addr_list, addr_index, addr_string);
 
                if(!i) {
+                       i++;
                        if (ai->ai_canonname != NULL) {
                                *h_name=mono_string_new(domain, ai->ai_canonname);
                        } else {
@@ -2787,19 +2969,23 @@ MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, Mo
        MONO_ARCH_SAVE_REGS;
        
        hostname=mono_string_to_utf8 (host);
-       if (*hostname == '\0')
+       if (*hostname == '\0') {
                add_local_ips = TRUE;
+               *h_name = host;
+       }
 #ifdef HAVE_SIOCGIFCONF
        if (!add_local_ips && gethostname (this_hostname, sizeof (this_hostname)) != -1) {
-               if (!strcmp (hostname, this_hostname))
+               if (!strcmp (hostname, this_hostname)) {
                        add_local_ips = TRUE;
+                       *h_name = host;
+               }
        }
 #endif
 
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = get_family_hint ();
        hints.ai_socktype = SOCK_STREAM;
-       hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
+       hints.ai_flags = AI_CANONNAME;
 
        if (*hostname && getaddrinfo(hostname, NULL, &hints, &info) == -1) {
                return(FALSE);
@@ -2883,9 +3069,13 @@ MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, Mo
        }
 #endif
 
+#ifndef HOST_WIN32
        he = NULL;
        if (*hostname)
                he = _wapi_gethostbyname (hostname);
+#else
+       he = _wapi_gethostbyname (hostname);
+#endif
        g_free(hostname);
 
        if (*hostname && he==NULL)
@@ -2937,7 +3127,6 @@ inet_pton (int family, const char *address, void *inaddrp)
 extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
 {
        char *address;
-       gboolean v1;
        
 #ifdef AF_INET6
        struct sockaddr_in saddr;
@@ -2952,8 +3141,6 @@ extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *a
        gboolean ret;
 #endif
 
-       v1 = mono_framework_version () == 1;
-
        address = mono_string_to_utf8 (addr);
 
 #ifdef AF_INET6
@@ -2974,10 +3161,6 @@ extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *a
        }
        g_free(address);
 
-       if (v1) {
-               flags = NI_NAMEREQD;
-       }
-       
        if(family == AF_INET) {
 #if HAVE_SOCKADDR_IN_SIN_LEN
                saddr.sin_len = sizeof (saddr);
@@ -3015,12 +3198,7 @@ extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *a
        }
 
        if ((he = gethostbyaddr ((char *) &inaddr, sizeof (inaddr), AF_INET)) == NULL) {
-               if (v1) {
-                       ret = FALSE;
-               } else {
-                       ret = ipaddr_to_IPHostEntry (address, h_name,
-                                                    h_aliases, h_addr_list);
-               }
+               ret = ipaddr_to_IPHostEntry (address, h_name, h_aliases, h_addr_list);
        } else {
                ret = hostent_to_IPHostEntry (he, h_name, h_aliases,
                                              h_addr_list, FALSE);
@@ -3048,6 +3226,43 @@ extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_
        return(TRUE);
 }
 
+gboolean
+ves_icall_System_Net_Sockets_Socket_SendFile (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
+{
+       HANDLE file;
+       gint32 error;
+       TRANSMIT_FILE_BUFFERS buffers;
+
+       MONO_ARCH_SAVE_REGS;
+
+       if (filename == NULL)
+               return FALSE;
+
+       file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &error);
+       if (file == INVALID_HANDLE_VALUE) {
+               SetLastError (error);
+               return FALSE;
+       }
+
+       memset (&buffers, 0, sizeof (buffers));
+       if (pre_buffer != NULL) {
+               buffers.Head = mono_array_addr (pre_buffer, guchar, 0);
+               buffers.HeadLength = mono_array_length (pre_buffer);
+       }
+       if (post_buffer != NULL) {
+               buffers.Tail = mono_array_addr (post_buffer, guchar, 0);
+               buffers.TailLength = mono_array_length (post_buffer);
+       }
+
+       if (!TransmitFile (sock, file, 0, 0, NULL, &buffers, flags)) {
+               CloseHandle (file);
+               return FALSE;
+       }
+
+       CloseHandle (file);
+       return TRUE;
+}
+
 void mono_network_init(void)
 {
        WSADATA wsadata;
@@ -3055,14 +3270,12 @@ void mono_network_init(void)
        
        err=WSAStartup(MAKEWORD(2,0), &wsadata);
        if(err!=0) {
-               g_error(G_GNUC_PRETTY_FUNCTION ": Couldn't initialise networking");
+               g_error("%s: Couldn't initialise networking", __func__);
                exit(-1);
        }
 
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": Using socket library: %s", wsadata.szDescription);
-       g_message(G_GNUC_PRETTY_FUNCTION ": Socket system status: %s", wsadata.szSystemStatus);
-#endif
+       LOGDEBUG (g_message("%s: Using socket library: %s", __func__, wsadata.szDescription));
+       LOGDEBUG (g_message("%s: Socket system status: %s", __func__, wsadata.szSystemStatus));
 }
 
 void mono_network_cleanup(void)
@@ -3070,3 +3283,19 @@ void mono_network_cleanup(void)
        WSACleanup();
 }
 
+void
+icall_cancel_blocking_socket_operation (MonoThread *thread)
+{
+       MonoInternalThread *internal = thread->internal_thread;
+       
+       if (mono_thread_info_new_interrupt_enabled ()) {
+               mono_thread_info_abort_socket_syscall_for_close ((MonoNativeThreadId)(gsize)internal->tid);
+       } else {
+#ifndef HOST_WIN32
+               internal->ignore_next_signal = TRUE;
+               mono_thread_kill (internal, mono_thread_get_abort_signal ());           
+#endif
+       }
+}
+
+#endif /* #ifndef DISABLE_SOCKETS */