]> git.sesse.net Git - vlc/blobdiff - src/network/getaddrinfo.c
Revert "correct realloc() usage, on failure realloc will return NULL"
[vlc] / src / network / getaddrinfo.c
index 70183d6b141cf80349c8018d354959dfcce9c3be..5f73492df81c395fbcf65f4b42e527c1a96fd432 100644 (file)
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  *****************************************************************************/
 
-#include <vlc/vlc.h>
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <vlc_common.h>
+#include <vlc_charset.h>
 
 #include <stddef.h> /* size_t */
 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
 #include <stdlib.h> /* malloc(), free(), strtoul() */
 #include <errno.h>
+#include <assert.h>
 
 #ifdef HAVE_SYS_TYPES_H
 #   include <sys/types.h>
 #   define AF_UNSPEC   0
 #endif
 
-#define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
-                  NI_DGRAM)
-#define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
-
 
 #ifndef HAVE_GAI_STRERROR
-static struct
+static const struct
 {
-    int code;
-    const char *msg;
-} const __gai_errlist[] =
+    int        code;
+    const char msg[41];
+} gai_errlist[] =
 {
     { 0,              "Error 0" },
     { EAI_BADFLAGS,   "Invalid flag used" },
@@ -79,21 +81,21 @@ static struct
     { EAI_MEMORY,     "Memory allocation failure" },
     { EAI_OVERFLOW,   "Buffer overflow" },
     { EAI_SYSTEM,     "System error" },
-    { 0,              NULL }
+    { 0,              "" },
 };
 
-static const char *__gai_unknownerr = "Unrecognized error number";
+static const char gai_unknownerr[] = "Unrecognized error number";
 
 /****************************************************************************
  * Converts an EAI_* error code into human readable english text.
  ****************************************************************************/
 const char *vlc_gai_strerror (int errnum)
 {
-    for (unsigned i = 0; __gai_errlist[i].msg != NULL; i++)
-        if (errnum == __gai_errlist[i].code)
-            return __gai_errlist[i].msg;
+    for (unsigned i = 0; *gai_errlist[i].msg; i++)
+        if (errnum == gai_errlist[i].code)
+            return gai_errlist[i].msg;
 
-    return __gai_unknownerr;
+    return gai_unknownerr;
 }
 #else /* ifndef HAVE_GAI_STRERROR */
 const char *vlc_gai_strerror (int errnum)
@@ -103,9 +105,11 @@ const char *vlc_gai_strerror (int errnum)
 #endif
 
 #ifndef HAVE_GETNAMEINFO
+#define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
+                  NI_DGRAM)
 /*
  * getnameinfo() non-thread-safe IPv4-only implementation,
- * Address-family-independant address to hostname translation
+ * Address-family-independent address to hostname translation
  * (reverse DNS lookup in case of IPv4).
  *
  * This is meant for use on old IP-enabled systems that are not IPv6-aware,
@@ -115,9 +119,15 @@ const char *vlc_gai_strerror (int errnum)
  * GNU C library 2.0.x is known to lack this function, even though it defines
  * getaddrinfo().
  */
+#ifdef WIN32
+static int WSAAPI
+stub_getnameinfo (const struct sockaddr *sa, socklen_t salen,
+             char *host, DWORD hostlen, char *serv, DWORD servlen, int flags)
+#else
 static int
-getnameinfo (const struct sockaddr *sa, socklen_t salen,
+stub_getnameinfo (const struct sockaddr *sa, socklen_t salen,
              char *host, int hostlen, char *serv, int servlen, int flags)
+#endif
 {
     if (((size_t)salen < sizeof (struct sockaddr_in))
      || (sa->sa_family != AF_INET))
@@ -144,23 +154,25 @@ getnameinfo (const struct sockaddr *sa, socklen_t salen,
 
             if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
                           (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
-                          ipv4 & 0xff) >= hostlen)
+                          ipv4 & 0xff) >= (int)hostlen)
                 return EAI_OVERFLOW;
         }
 
         if (serv != NULL)
         {
             if (snprintf (serv, servlen, "%u",
-                          (unsigned int)ntohs (addr->sin_port)) >= servlen)
+                          (unsigned int)ntohs (addr->sin_port)) >= (int)servlen)
                 return EAI_OVERFLOW;
         }
     }
     return 0;
 }
-
+#undef getnameinfo
+#define getnameifo stub_getnameinfo
 #endif /* if !HAVE_GETNAMEINFO */
 
 #ifndef HAVE_GETADDRINFO
+#define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
 /*
  * Converts the current herrno error value into an EAI_* error code.
  * That error code is normally returned by getnameinfo() or getaddrinfo().
@@ -191,18 +203,18 @@ gai_error_from_herrno (void)
 /*
  * This functions must be used to free the memory allocated by getaddrinfo().
  */
-static void freeaddrinfo (struct addrinfo *res)
+#ifdef WIN32
+static void WSAAPI stub_freeaddrinfo (struct addrinfo *res)
+#else
+static void stub_freeaddrinfo (struct addrinfo *res)
+#endif
 {
-    if (res != NULL)
-    {
-        if (res->ai_canonname != NULL)
-            free (res->ai_canonname);
-        if (res->ai_addr != NULL)
-            free (res->ai_addr);
-        if (res->ai_next != NULL)
-            free (res->ai_next);
-        free (res);
-    }
+    if (res == NULL)
+        return;
+    free (res->ai_canonname);
+    free (res->ai_addr);
+    free (res->ai_next);
+    free (res);
 }
 
 
@@ -268,16 +280,22 @@ makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
 
 /*
  * getaddrinfo() non-thread-safe IPv4-only implementation
- * Address-family-independant hostname to address resolution.
+ * Address-family-independent hostname to address resolution.
  *
  * This is meant for IPv6-unaware systems that do probably not provide
  * getaddrinfo(), but still have old function gethostbyname().
  *
  * Only UDP and TCP over IPv4 are supported here.
  */
+#ifdef WIN32
+static int WSAAPI
+stub_getaddrinfo (const char *node, const char *service,
+             const struct addrinfo *hints, struct addrinfo **res)
+#else
 static int
-getaddrinfo (const char *node, const char *service,
+stub_getaddrinfo (const char *node, const char *service,
              const struct addrinfo *hints, struct addrinfo **res)
+#endif
 {
     struct addrinfo *info;
     u_long ip;
@@ -383,38 +401,14 @@ getaddrinfo (const char *node, const char *service,
         port = 0;
     else
     {
-        long d;
+        unsigned long d;
         char *end;
 
         d = strtoul (service, &end, 0);
-        if (end[0] /* service is not a number */
-         || (d > 65535))
-        {
-            struct servent *entry;
-            const char *protoname;
-
-            switch (protocol)
-            {
-                case IPPROTO_TCP:
-                    protoname = "tcp";
-                    break;
-
-                case IPPROTO_UDP:
-                    protoname = "udp";
-                    break;
-
-                default:
-                    protoname = NULL;
-            }
-
-            entry = getservbyname (service, protoname);
-            if (entry == NULL)
-                return EAI_SERVICE;
+        if (end[0] || (d > 65535u))
+            return EAI_SERVICE;
 
-            port = entry->s_port;
-        }
-        else
-            port = htons ((u_short)d);
+        port = htons ((u_short)d);
     }
 
     /* building results... */
@@ -446,6 +440,10 @@ getaddrinfo (const char *node, const char *service,
 
     return 0;
 }
+#undef getaddrinfo
+#define getaddrifo stub_getaddrinfo
+#undef freeaddrinfo
+#define freeaddrifo stub_freeaddrinfo
 #endif /* if !HAVE_GETADDRINFO */
 
 #if defined( WIN32 ) && !defined( UNDER_CE )
@@ -494,43 +492,42 @@ static WSAAPI int _ws2_getnameinfo_bind( const struct sockaddr FAR * sa, socklen
                char FAR *host, DWORD hostlen, char FAR *serv, DWORD servlen, int flags )
 {
     GETNAMEINFO entry = (GETNAMEINFO)ws2_find_api (TEXT("getnameinfo"));
-    if (entry != NULL)
+    int result;
+
+    if (entry == NULL)
     {
-        /* call API before replacing function pointer to avoid crash */
-        int result = entry (sa, salen, host, hostlen, serv, servlen, flags);
-        ws2_getnameinfo = entry;
-        return result;
+        /* not found, use replacement API instead */
+        entry = stub_getnameinfo;
     }
-    return getnameinfo (sa, salen, host, hostlen, serv, servlen, flags);
+    /* call API before replacing function pointer to avoid crash */
+    result = entry (sa, salen, host, hostlen, serv, servlen, flags);
+    ws2_getnameinfo = entry;
+    return result;
 }
 #undef getnameinfo
 #define getnameinfo ws2_getnameinfo
 
-/* So much for using different calling conventions */
-static WSAAPI void call_freeaddrinfo (struct addrinfo *infos)
-{
-    freeaddrinfo (infos);
-}
-
 static WSAAPI int _ws2_getaddrinfo_bind(const char FAR *node, const char FAR *service,
                const struct addrinfo FAR *hints, struct addrinfo FAR * FAR *res)
 {
     GETADDRINFO entry;
     FREEADDRINFO freentry;
+    int result;
 
     entry = (GETADDRINFO)ws2_find_api (TEXT("getaddrinfo"));
     freentry = (FREEADDRINFO)ws2_find_api (TEXT("freeaddrinfo"));
 
-    if ((entry != NULL) && (freentry != NULL))
+    if ((entry == NULL) ||  (freentry == NULL))
     {
-        /* call API before replacing function pointer to avoid crash */
-        int result = entry (node, service, hints, res);
-        ws2_freeaddrinfo = freentry;
-        ws2_getaddrinfo = entry;
-        return result;
+        /* not found, use replacement API instead */
+        entry = stub_getaddrinfo;
+        freentry = stub_freeaddrinfo;
     }
-    ws2_freeaddrinfo = call_freeaddrinfo;
-    return getaddrinfo (node, service, hints, res);
+    /* call API before replacing function pointer to avoid crash */
+    result = entry (node, service, hints, res);
+    ws2_freeaddrinfo = freentry;
+    ws2_getaddrinfo = entry;
+    return result;
 }
 #undef getaddrinfo
 #undef freeaddrinfo
@@ -540,7 +537,6 @@ static WSAAPI int _ws2_getaddrinfo_bind(const char FAR *node, const char FAR *se
 #endif
 
 
-
 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
                      char *host, int hostlen, int *portnum, int flags )
 {
@@ -568,12 +564,24 @@ int vlc_getnameinfo( const struct sockaddr *sa, int salen,
 }
 
 
+/**
+ * Resolves a host name to a list of socket addresses (like getaddrinfo()).
+ *
+ * @param p_this a VLC object
+ * @param node host name to resolve (encoded as UTF-8), or NULL
+ * @param i_port port number for the socket addresses
+ * @param p_hints parameters (see getaddrinfo() manual page)
+ * @param res pointer set to the resulting chained list.
+ * @return 0 on success, a getaddrinfo() error otherwise.
+ * On failure, *res is undefined. On success, it must be freed with
+ * vlc_freeaddrinfo().
+ */
 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
                      int i_port, const struct addrinfo *p_hints,
                      struct addrinfo **res )
 {
     struct addrinfo hints;
-    char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
+    char psz_buf[NI_MAXHOST], psz_service[6];
 
     /*
      * In VLC, we always use port number as integer rather than strings
@@ -589,26 +597,47 @@ int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
     snprintf( psz_service, 6, "%d", i_port );
 
     /* Check if we have to force ipv4 or ipv6 */
-    if( p_hints == NULL )
-        memset( &hints, 0, sizeof( hints ) );
-    else
-        memcpy( &hints, p_hints, sizeof( hints ) );
-
-    if( hints.ai_family == AF_UNSPEC )
+    memset (&hints, 0, sizeof (hints));
+    if (p_hints != NULL)
     {
-        vlc_value_t val;
+        const int safe_flags =
+            AI_PASSIVE |
+            AI_CANONNAME |
+            AI_NUMERICHOST |
+            AI_NUMERICSERV |
+#ifdef AI_ALL
+            AI_ALL |
+#endif
+#ifdef AI_ADDRCONFIG
+            AI_ADDRCONFIG |
+#endif
+#ifdef AI_V4MAPPED
+            AI_V4MAPPED |
+#endif
+            0;
+
+        hints.ai_family = p_hints->ai_family;
+        hints.ai_socktype = p_hints->ai_socktype;
+        hints.ai_protocol = p_hints->ai_protocol;
+        /* Unfortunately, some flags chang the layout of struct addrinfo, so
+         * they cannot be copied blindly from p_hints to &hints. Therefore, we
+         * only copy flags that we know for sure are "safe".
+         */
+        hints.ai_flags = p_hints->ai_flags & safe_flags;
+    }
 
-        var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
-        var_Get( p_this, "ipv4", &val );
-        if( val.b_bool )
-            hints.ai_family = AF_INET;
+    /* We only ever use port *numbers* */
+    hints.ai_flags |= AI_NUMERICSERV;
 
+    if( hints.ai_family == AF_UNSPEC )
+    {
 #ifdef AF_INET6
-        var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
-        var_Get( p_this, "ipv6", &val );
-        if( val.b_bool )
+        if (var_CreateGetBool (p_this, "ipv6"))
             hints.ai_family = AF_INET6;
+        else
 #endif
+        if (var_CreateGetBool (p_this, "ipv4"))
+            hints.ai_family = AF_INET;
     }
 
     /*
@@ -616,29 +645,25 @@ int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
      * - accept "" as NULL
      * - ignore square brackets
      */
-    if( ( node == NULL ) || (node[0] == '\0' ) )
+    if (node != NULL)
     {
-        psz_node = NULL;
-    }
-    else
-    {
-        strlcpy( psz_buf, node, NI_MAXHOST );
-
-        psz_node = psz_buf;
-
-        if( psz_buf[0] == '[' )
+        if (node[0] == '[')
         {
-            char *ptr;
-
-            ptr = strrchr( psz_buf, ']' );
-            if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
+            size_t len = strlen (node + 1);
+            if ((len <= sizeof (psz_buf)) && (node[len] == ']'))
             {
-                *ptr = '\0';
-                psz_node++;
+                assert (len > 0);
+                memcpy (psz_buf, node + 1, len - 1);
+                psz_buf[len - 1] = '\0';
+                node = psz_buf;
             }
         }
+        if (node[0] == '\0')
+            node = NULL;
     }
 
+    int ret;
+    node = ToLocale (node);
 #ifdef WIN32
     /*
      * Winsock tries to resolve numerical IPv4 addresses as AAAA
@@ -647,45 +672,26 @@ int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
     if ((hints.ai_flags & AI_NUMERICHOST) == 0)
     {
         hints.ai_flags |= AI_NUMERICHOST;
-
-        if (getaddrinfo (psz_node, psz_service, &hints, res) == 0)
-            return 0;
-
+        ret = getaddrinfo (node, psz_service, &hints, res);
+        if (ret == 0)
+            goto out;
         hints.ai_flags &= ~AI_NUMERICHOST;
     }
 #endif
-#if defined (HAVE_GETADDRINFO)
-# ifdef AI_IDN
+#ifdef AI_IDN
     /* Run-time I18n Domain Names support */
-    static vlc_bool_t b_idn = VLC_TRUE; /* beware of thread-safety */
-
-    if (b_idn)
-    {
-        hints.ai_flags |= AI_IDN;
-        int ret = getaddrinfo (psz_node, psz_service, &hints, res);
-
-        if (ret != EAI_BADFLAGS)
-            return ret;
-
-        /* IDN not available: disable and retry without it */
-        hints.ai_flags &= ~AI_IDN;
-        b_idn = VLC_FALSE;
-        msg_Info (p_this, "International Domain Names not supported");
-    }
-# endif
-    return getaddrinfo (psz_node, psz_service, &hints, res);
-#else
-    int ret;
-    vlc_value_t lock;
-
-    var_Create (p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX);
-    var_Get (p_this->p_libvlc, "getaddrinfo_mutex", &lock);
-    vlc_mutex_lock (lock.p_address);
+    hints.ai_flags |= AI_IDN;
+    ret = getaddrinfo (node, psz_service, &hints, res);
+    if (ret != EAI_BADFLAGS)
+        goto out;
+    /* IDN not available: disable and retry without it */
+    hints.ai_flags &= ~AI_IDN;
+#endif
+    ret = getaddrinfo (node, psz_service, &hints, res);
 
-    ret = getaddrinfo (psz_node, psz_service, &hints, res);
-    vlc_mutex_unlock (lock.p_address);
+out:
+    LocaleFree (node);
     return ret;
-#endif
 }
 
 
@@ -693,3 +699,87 @@ void vlc_freeaddrinfo( struct addrinfo *infos )
 {
     freeaddrinfo (infos);
 }
+
+/**
+ * inet_pton() replacement
+ */
+int vlc_inet_pton (int af, const char *src, void *dst)
+{
+#ifndef HAVE_INET_PTON
+    /* Windows Vista has inet_pton(), but not XP. */
+    /* We have a pretty good example of abstraction inversion here... */
+    struct addrinfo hints = {
+        .ai_family = af,
+        .ai_socktype = SOCK_DGRAM, /* make sure we have... */
+        .ai_protocol = IPPROTO_UDP, /* ...only one response */
+        .ai_flags = AI_NUMERICHOST,
+    }, *res;
+
+    if (getaddrinfo (src, NULL, &hints, &res))
+        return 0;
+
+    const void *data;
+    size_t len;
+
+    switch (af)
+    {
+        case AF_INET:
+            data = &((const struct sockaddr_in *)res->ai_addr)->sin_addr;
+            len = sizeof (struct in_addr);
+            break;
+#ifdef AF_INET6
+        case AF_INET6:
+            data = &((const struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
+            len = sizeof (struct in6_addr);
+            break;
+#endif
+        default:
+            freeaddrinfo (res);
+            return -1;
+    }
+    memcpy (dst, data, len);
+    freeaddrinfo (res);
+    return 1;
+#else /* HAVE_INET_PTON */
+    return inet_pton( af, src, dst );
+#endif /* HAVE_INET_PTON */
+}
+
+/**
+ * inet_ntop() replacement
+ */
+const char *vlc_inet_ntop (int af, const void *src, char *dst, socklen_t cnt)
+{
+#ifndef HAVE_INET_NTOP
+    int ret = EAI_FAMILY;
+
+    switch (af)
+    {
+#ifdef AF_INET6
+        case AF_INET6:
+            {
+                struct sockaddr_in6 addr;
+                memset (&addr, 0, sizeof(addr));
+                addr.sin6_family = AF_INET6;
+                addr.sin6_addr = *(struct in6_addr *)src;
+                ret = getnameinfo ((struct sockaddr *)&addr, sizeof (addr),
+                                   dst, cnt, NULL, 0, NI_NUMERICHOST);
+            }
+
+#endif
+        case AF_INET:
+            {
+                struct sockaddr_in addr;
+                memset(&addr, 0, sizeof(addr));
+                addr.sin_family = AF_INET;
+                addr.sin_addr = *(struct in_addr *)src;
+                ret = getnameinfo ((struct sockaddr *)&addr, sizeof (addr),
+                                   dst, cnt, NULL, 0, NI_NUMERICHOST);
+            }
+    }
+    return (ret == 0) ? dst : NULL;
+#else /* HAVE_INET_NTOP */
+    return inet_ntop( af, src, dst, cnt );
+#endif /* HAVE_INET_NTOP */
+}
+