]> git.sesse.net Git - vlc/blob - src/network/getaddrinfo.c
Merge branch 'master' of git@git.videolan.org:vlc
[vlc] / src / network / getaddrinfo.c
1 /*****************************************************************************
2  * getaddrinfo.c: getaddrinfo/getnameinfo replacement functions
3  *****************************************************************************
4  * Copyright (C) 2005 the VideoLAN team
5  * Copyright (C) 2002-2007 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Author: Rémi Denis-Courmont <rem # videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <vlc/vlc.h>
30
31 #include <stddef.h> /* size_t */
32 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
33 #include <stdlib.h> /* malloc(), free(), strtoul() */
34 #include <errno.h>
35
36 #ifdef HAVE_SYS_TYPES_H
37 #   include <sys/types.h>
38 #endif
39 #ifdef HAVE_ARPA_INET_H
40 #   include <arpa/inet.h>
41 #endif
42 #ifdef HAVE_NETINET_IN_H
43 #   include <netinet/in.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #   include <unistd.h>
47 #endif
48
49 #include <vlc_network.h>
50
51 #ifndef NO_ADDRESS
52 #   define NO_ADDRESS  NO_DATA
53 #endif
54 #ifndef INADDR_NONE
55 #   define INADDR_NONE 0xFFFFFFFF
56 #endif
57 #ifndef AF_UNSPEC
58 #   define AF_UNSPEC   0
59 #endif
60
61
62 #ifndef HAVE_GAI_STRERROR
63 static struct
64 {
65     int code;
66     const char *msg;
67 } const __gai_errlist[] =
68 {
69     { 0,              "Error 0" },
70     { EAI_BADFLAGS,   "Invalid flag used" },
71     { EAI_NONAME,     "Host or service not found" },
72     { EAI_AGAIN,      "Temporary name service failure" },
73     { EAI_FAIL,       "Non-recoverable name service failure" },
74     { EAI_NODATA,     "No data for host name" },
75     { EAI_FAMILY,     "Unsupported address family" },
76     { EAI_SOCKTYPE,   "Unsupported socket type" },
77     { EAI_SERVICE,    "Incompatible service for socket type" },
78     { EAI_ADDRFAMILY, "Unavailable address family for host name" },
79     { EAI_MEMORY,     "Memory allocation failure" },
80     { EAI_OVERFLOW,   "Buffer overflow" },
81     { EAI_SYSTEM,     "System error" },
82     { 0,              NULL }
83 };
84
85 static const char *__gai_unknownerr = "Unrecognized error number";
86
87 /****************************************************************************
88  * Converts an EAI_* error code into human readable english text.
89  ****************************************************************************/
90 const char *vlc_gai_strerror (int errnum)
91 {
92     for (unsigned i = 0; __gai_errlist[i].msg != NULL; i++)
93         if (errnum == __gai_errlist[i].code)
94             return __gai_errlist[i].msg;
95
96     return __gai_unknownerr;
97 }
98 #else /* ifndef HAVE_GAI_STRERROR */
99 const char *vlc_gai_strerror (int errnum)
100 {
101     return gai_strerror (errnum);
102 }
103 #endif
104
105 #ifndef HAVE_GETNAMEINFO
106 #define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
107                   NI_DGRAM)
108 /*
109  * getnameinfo() non-thread-safe IPv4-only implementation,
110  * Address-family-independant address to hostname translation
111  * (reverse DNS lookup in case of IPv4).
112  *
113  * This is meant for use on old IP-enabled systems that are not IPv6-aware,
114  * and probably do not have getnameinfo(), but have the old gethostbyaddr()
115  * function.
116  *
117  * GNU C library 2.0.x is known to lack this function, even though it defines
118  * getaddrinfo().
119  */
120 #ifdef WIN32
121 static int WSAAPI
122 getnameinfo (const struct sockaddr *sa, socklen_t salen,
123              char *host, DWORD hostlen, char *serv, DWORD servlen, int flags)
124 #else
125 static int
126 getnameinfo (const struct sockaddr *sa, socklen_t salen,
127              char *host, int hostlen, char *serv, int servlen, int flags)
128 #endif
129 {
130     if (((size_t)salen < sizeof (struct sockaddr_in))
131      || (sa->sa_family != AF_INET))
132         return EAI_FAMILY;
133     else if (flags & (~_NI_MASK))
134         return EAI_BADFLAGS;
135     else
136     {
137         const struct sockaddr_in *addr;
138
139         addr = (const struct sockaddr_in *)sa;
140
141         if (host != NULL)
142         {
143             /* host name resolution */
144             if (!(flags & NI_NUMERICHOST))
145             {
146                 if (flags & NI_NAMEREQD)
147                     return EAI_NONAME;
148             }
149
150             /* inet_ntoa() is not thread-safe, do not use it */
151             uint32_t ipv4 = ntohl (addr->sin_addr.s_addr);
152
153             if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
154                           (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
155                           ipv4 & 0xff) >= (int)hostlen)
156                 return EAI_OVERFLOW;
157         }
158
159         if (serv != NULL)
160         {
161             if (snprintf (serv, servlen, "%u",
162                           (unsigned int)ntohs (addr->sin_port)) >= (int)servlen)
163                 return EAI_OVERFLOW;
164         }
165     }
166     return 0;
167 }
168
169 #endif /* if !HAVE_GETNAMEINFO */
170
171 #ifndef HAVE_GETADDRINFO
172 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
173 /*
174  * Converts the current herrno error value into an EAI_* error code.
175  * That error code is normally returned by getnameinfo() or getaddrinfo().
176  */
177 static int
178 gai_error_from_herrno (void)
179 {
180     switch (h_errno)
181     {
182         case HOST_NOT_FOUND:
183             return EAI_NONAME;
184
185         case NO_ADDRESS:
186 # if (NO_ADDRESS != NO_DATA)
187         case NO_DATA:
188 # endif
189             return EAI_NODATA;
190
191         case NO_RECOVERY:
192             return EAI_FAIL;
193
194         case TRY_AGAIN:
195             return EAI_AGAIN;
196     }
197     return EAI_SYSTEM;
198 }
199
200 /*
201  * This functions must be used to free the memory allocated by getaddrinfo().
202  */
203 #ifdef WIN32
204 static void WSAAPI freeaddrinfo (struct addrinfo *res)
205 #else
206 static void freeaddrinfo (struct addrinfo *res)
207 #endif
208 {
209     if (res != NULL)
210     {
211         if (res->ai_canonname != NULL)
212             free (res->ai_canonname);
213         if (res->ai_addr != NULL)
214             free (res->ai_addr);
215         if (res->ai_next != NULL)
216             free (res->ai_next);
217         free (res);
218     }
219 }
220
221
222 /*
223  * Internal function that builds an addrinfo struct.
224  */
225 static struct addrinfo *
226 makeaddrinfo (int af, int type, int proto,
227               const struct sockaddr *addr, size_t addrlen,
228               const char *canonname)
229 {
230     struct addrinfo *res;
231
232     res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
233     if (res != NULL)
234     {
235         res->ai_flags = 0;
236         res->ai_family = af;
237         res->ai_socktype = type;
238         res->ai_protocol = proto;
239         res->ai_addrlen = addrlen;
240         res->ai_addr = malloc (addrlen);
241         res->ai_canonname = NULL;
242         res->ai_next = NULL;
243
244         if (res->ai_addr != NULL)
245         {
246             memcpy (res->ai_addr, addr, addrlen);
247
248             if (canonname != NULL)
249             {
250                 res->ai_canonname = strdup (canonname);
251                 if (res->ai_canonname != NULL)
252                     return res; /* success ! */
253             }
254             else
255                 return res;
256         }
257     }
258     /* failsafe */
259     vlc_freeaddrinfo (res);
260     return NULL;
261 }
262
263
264 static struct addrinfo *
265 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
266 {
267     struct sockaddr_in addr;
268
269     memset (&addr, 0, sizeof (addr));
270     addr.sin_family = AF_INET;
271 # ifdef HAVE_SA_LEN
272     addr.sin_len = sizeof (addr);
273 # endif
274     addr.sin_port = port;
275     addr.sin_addr.s_addr = ip;
276
277     return makeaddrinfo (AF_INET, type, proto,
278                          (struct sockaddr*)&addr, sizeof (addr), name);
279 }
280
281
282 /*
283  * getaddrinfo() non-thread-safe IPv4-only implementation
284  * Address-family-independant hostname to address resolution.
285  *
286  * This is meant for IPv6-unaware systems that do probably not provide
287  * getaddrinfo(), but still have old function gethostbyname().
288  *
289  * Only UDP and TCP over IPv4 are supported here.
290  */
291 #ifdef WIN32
292 static int WSAAPI
293 getaddrinfo (const char *node, const char *service,
294              const struct addrinfo *hints, struct addrinfo **res)
295 #else
296 static int
297 getaddrinfo (const char *node, const char *service,
298              const struct addrinfo *hints, struct addrinfo **res)
299 #endif
300 {
301     struct addrinfo *info;
302     u_long ip;
303     u_short port;
304     int protocol = 0, flags = 0;
305     const char *name = NULL;
306
307 #ifdef WIN32
308     /*
309      * Maybe you knew already that Winsock does not handle TCP/RST packets
310      * properly, so that when a TCP connection fails, it will wait until it
311      * times out even if the remote host did return a TCP/RST. However, it
312      * still sees the TCP/RST as the error code is 10061 instead of 10060.
313      * Basically, we have the stupid brainfucked behavior with DNS queries...
314      * When the recursive DNS server returns an error, Winsock waits about
315      * 2 seconds before it returns to the callers, even though it should know
316      * that is pointless. I'd like to know how come this hasn't been fixed
317      * for the past decade, or maybe not.
318      *
319      * Anyway, this is causing a severe delay when the SAP listener tries
320      * to resolve more than ten IPv6 numeric addresses. Modern systems will
321      * eventually realize that it is an IPv6 address, and won't try to resolve
322      * it as a IPv4 address via the Domain Name Service. Old systems
323      * (including Windows XP without the IPv6 stack) will not. It is normally
324      * not an issue as the DNS server usually returns an error very quickly.
325      * But it IS a severe issue on Windows, given the bug explained above.
326      * So here comes one more bug-to-bug Windows compatibility fix.
327      */
328     if ((node != NULL) && (strchr (node, ':') != NULL))
329        return EAI_NONAME;
330 #endif
331
332     if (hints != NULL)
333     {
334         flags = hints->ai_flags;
335
336         if (flags & ~_AI_MASK)
337             return EAI_BADFLAGS;
338         /* only accept AF_INET and AF_UNSPEC */
339         if (hints->ai_family && (hints->ai_family != AF_INET))
340             return EAI_FAMILY;
341
342         /* protocol sanity check */
343         switch (hints->ai_socktype)
344         {
345             case SOCK_STREAM:
346                 protocol = IPPROTO_TCP;
347                 break;
348
349             case SOCK_DGRAM:
350                 protocol = IPPROTO_UDP;
351                 break;
352
353 #ifndef SOCK_RAW
354             case SOCK_RAW:
355 #endif
356             case 0:
357                 break;
358
359             default:
360                 return EAI_SOCKTYPE;
361         }
362         if (hints->ai_protocol && protocol
363          && (protocol != hints->ai_protocol))
364             return EAI_SERVICE;
365     }
366
367     *res = NULL;
368
369     /* default values */
370     if (node == NULL)
371     {
372         if (flags & AI_PASSIVE)
373             ip = htonl (INADDR_ANY);
374         else
375             ip = htonl (INADDR_LOOPBACK);
376     }
377     else
378     if ((ip = inet_addr (node)) == INADDR_NONE)
379     {
380         struct hostent *entry = NULL;
381
382         /* hostname resolution */
383         if (!(flags & AI_NUMERICHOST))
384             entry = gethostbyname (node);
385
386         if (entry == NULL)
387             return gai_error_from_herrno ();
388
389         if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
390             return EAI_FAMILY;
391
392         ip = *((u_long *) entry->h_addr);
393         if (flags & AI_CANONNAME)
394             name = entry->h_name;
395     }
396
397     if ((flags & AI_CANONNAME) && (name == NULL))
398         name = node;
399
400     /* service resolution */
401     if (service == NULL)
402         port = 0;
403     else
404     {
405         unsigned long d;
406         char *end;
407
408         d = strtoul (service, &end, 0);
409         if (end[0] || (d > 65535u))
410             return EAI_SERVICE;
411
412         port = htons ((u_short)d);
413     }
414
415     /* building results... */
416     if ((!protocol) || (protocol == IPPROTO_UDP))
417     {
418         info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
419         if (info == NULL)
420         {
421             errno = ENOMEM;
422             return EAI_SYSTEM;
423         }
424         if (flags & AI_PASSIVE)
425             info->ai_flags |= AI_PASSIVE;
426         *res = info;
427     }
428     if ((!protocol) || (protocol == IPPROTO_TCP))
429     {
430         info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
431         if (info == NULL)
432         {
433             errno = ENOMEM;
434             return EAI_SYSTEM;
435         }
436         info->ai_next = *res;
437         if (flags & AI_PASSIVE)
438             info->ai_flags |= AI_PASSIVE;
439         *res = info;
440     }
441
442     return 0;
443 }
444 #endif /* if !HAVE_GETADDRINFO */
445
446 #if defined( WIN32 ) && !defined( UNDER_CE )
447     /*
448      * Here is the kind of kludge you need to keep binary compatibility among
449      * varying OS versions...
450      */
451 typedef int (WSAAPI * GETNAMEINFO) ( const struct sockaddr FAR *, socklen_t,
452                                            char FAR *, DWORD, char FAR *, DWORD, int );
453 typedef int (WSAAPI * GETADDRINFO) (const char FAR *, const char FAR *,
454                                           const struct addrinfo FAR *,
455                                           struct addrinfo FAR * FAR *);
456
457 typedef void (WSAAPI * FREEADDRINFO) ( struct addrinfo FAR * );
458
459 static int WSAAPI _ws2_getnameinfo_bind ( const struct sockaddr FAR *, socklen_t,
460                                            char FAR *, DWORD, char FAR *, DWORD, int );
461 static int WSAAPI _ws2_getaddrinfo_bind (const char FAR *, const char FAR *,
462                                           const struct addrinfo FAR *,
463                                           struct addrinfo FAR * FAR *);
464
465 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
466 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
467 static FREEADDRINFO ws2_freeaddrinfo;
468
469 static FARPROC ws2_find_api (LPCTSTR name)
470 {
471     FARPROC f = NULL;
472
473     HMODULE m = GetModuleHandle (TEXT("WS2_32"));
474     if (m != NULL)
475         f = GetProcAddress (m, name);
476
477     if (f == NULL)
478     {
479         /* Windows 2K IPv6 preview */
480         m = LoadLibrary (TEXT("WSHIP6"));
481         if (m != NULL)
482             f = GetProcAddress (m, name);
483     }
484
485     return f;
486 }
487
488 static WSAAPI int _ws2_getnameinfo_bind( const struct sockaddr FAR * sa, socklen_t salen,
489                char FAR *host, DWORD hostlen, char FAR *serv, DWORD servlen, int flags )
490 {
491     GETNAMEINFO entry = (GETNAMEINFO)ws2_find_api (TEXT("getnameinfo"));
492     int result;
493
494     if (entry == NULL)
495     {
496         /* not found, use replacement API instead */
497     entry = getnameinfo;
498
499     }
500     /* call API before replacing function pointer to avoid crash */
501     result = entry (sa, salen, host, hostlen, serv, servlen, flags);
502     ws2_getnameinfo = entry;
503     return result;
504 }
505 #undef getnameinfo
506 #define getnameinfo ws2_getnameinfo
507
508 static WSAAPI int _ws2_getaddrinfo_bind(const char FAR *node, const char FAR *service,
509                const struct addrinfo FAR *hints, struct addrinfo FAR * FAR *res)
510 {
511     GETADDRINFO entry;
512     FREEADDRINFO freentry;
513     int result;
514
515     entry = (GETADDRINFO)ws2_find_api (TEXT("getaddrinfo"));
516     freentry = (FREEADDRINFO)ws2_find_api (TEXT("freeaddrinfo"));
517
518     if ((entry == NULL) ||  (freentry == NULL))
519     {
520         /* not found, use replacement API instead */
521     entry = getaddrinfo;
522     freentry = freeaddrinfo;
523     }
524     /* call API before replacing function pointer to avoid crash */
525     result = entry (node, service, hints, res);
526     ws2_freeaddrinfo = freentry;
527     ws2_getaddrinfo = entry;
528     return result;
529 }
530 #undef getaddrinfo
531 #undef freeaddrinfo
532 #define getaddrinfo ws2_getaddrinfo
533 #define freeaddrinfo ws2_freeaddrinfo
534 #define HAVE_GETADDRINFO
535 #endif
536
537
538
539 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
540                      char *host, int hostlen, int *portnum, int flags )
541 {
542     char psz_servbuf[6], *psz_serv;
543     int i_servlen, i_val;
544
545     flags |= NI_NUMERICSERV;
546     if( portnum != NULL )
547     {
548         psz_serv = psz_servbuf;
549         i_servlen = sizeof( psz_servbuf );
550     }
551     else
552     {
553         psz_serv = NULL;
554         i_servlen = 0;
555     }
556
557     i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
558
559     if( portnum != NULL )
560         *portnum = atoi( psz_serv );
561
562     return i_val;
563 }
564
565
566 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
567                      int i_port, const struct addrinfo *p_hints,
568                      struct addrinfo **res )
569 {
570     struct addrinfo hints;
571     char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
572
573     /*
574      * In VLC, we always use port number as integer rather than strings
575      * for historical reasons (and portability).
576      */
577     if( ( i_port > 65535 ) || ( i_port < 0 ) )
578     {
579         msg_Err( p_this, "invalid port number %d specified", i_port );
580         return EAI_SERVICE;
581     }
582
583     /* cannot overflow */
584     snprintf( psz_service, 6, "%d", i_port );
585
586     /* Check if we have to force ipv4 or ipv6 */
587     memset (&hints, 0, sizeof (hints));
588     if (p_hints != NULL)
589     {
590         const int safe_flags =
591             AI_PASSIVE |
592             AI_CANONNAME |
593             AI_NUMERICHOST |
594 #ifdef AI_NUMERICSERV
595             AI_NUMERICSERV |
596 #endif
597 #ifdef AI_ALL
598             AI_ALL |
599 #endif
600 #ifdef AI_ADDRCONFIG
601             AI_ADDRCONFIG |
602 #endif
603 #ifdef AI_V4MAPPED
604             AI_V4MAPPED |
605 #endif
606             0;
607
608         hints.ai_family = p_hints->ai_family;
609         hints.ai_socktype = p_hints->ai_socktype;
610         hints.ai_protocol = p_hints->ai_protocol;
611         /* Unfortunately, some flags chang the layout of struct addrinfo, so
612          * they cannot be copied blindly from p_hints to &hints. Therefore, we
613          * only copy flags that we know for sure are "safe".
614          */
615         hints.ai_flags = p_hints->ai_flags & safe_flags;
616     }
617
618 #ifdef AI_NUMERICSERV
619     /* We only ever use port *numbers* */
620     hints.ai_flags |= AI_NUMERICSERV;
621 #endif
622
623     if( hints.ai_family == AF_UNSPEC )
624     {
625         vlc_value_t val;
626
627         var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
628         var_Get( p_this, "ipv4", &val );
629         if( val.b_bool )
630             hints.ai_family = AF_INET;
631
632 #ifdef AF_INET6
633         var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
634         var_Get( p_this, "ipv6", &val );
635         if( val.b_bool )
636             hints.ai_family = AF_INET6;
637 #endif
638     }
639
640     /*
641      * VLC extensions :
642      * - accept "" as NULL
643      * - ignore square brackets
644      */
645     if( ( node == NULL ) || (node[0] == '\0' ) )
646     {
647         psz_node = NULL;
648     }
649     else
650     {
651         strlcpy( psz_buf, node, NI_MAXHOST );
652
653         psz_node = psz_buf;
654
655         if( psz_buf[0] == '[' )
656         {
657             char *ptr;
658
659             ptr = strrchr( psz_buf, ']' );
660             if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
661             {
662                 *ptr = '\0';
663                 psz_node++;
664             }
665         }
666     }
667
668 #ifdef WIN32
669     /*
670      * Winsock tries to resolve numerical IPv4 addresses as AAAA
671      * and IPv6 addresses as A... There comes the bug-to-bug fix.
672      */
673     if ((hints.ai_flags & AI_NUMERICHOST) == 0)
674     {
675         hints.ai_flags |= AI_NUMERICHOST;
676
677         if (getaddrinfo (psz_node, psz_service, &hints, res) == 0)
678             return 0;
679
680         hints.ai_flags &= ~AI_NUMERICHOST;
681     }
682 #endif
683 #if defined (HAVE_GETADDRINFO)
684 # ifdef AI_IDN
685     /* Run-time I18n Domain Names support */
686     static bool b_idn = true; /* beware of thread-safety */
687
688     if (b_idn)
689     {
690         hints.ai_flags |= AI_IDN;
691         int ret = getaddrinfo (psz_node, psz_service, &hints, res);
692
693         if (ret != EAI_BADFLAGS)
694             return ret;
695
696         /* IDN not available: disable and retry without it */
697         hints.ai_flags &= ~AI_IDN;
698         b_idn = false;
699         msg_Info (p_this, "International Domain Names not supported");
700     }
701 # endif
702     return getaddrinfo (psz_node, psz_service, &hints, res);
703 #else
704     int ret;
705     vlc_value_t lock;
706
707     var_Create (p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX);
708     var_Get (p_this->p_libvlc, "getaddrinfo_mutex", &lock);
709     vlc_mutex_lock (lock.p_address);
710
711     ret = getaddrinfo (psz_node, psz_service, &hints, res);
712     vlc_mutex_unlock (lock.p_address);
713     return ret;
714 #endif
715 }
716
717
718 void vlc_freeaddrinfo( struct addrinfo *infos )
719 {
720     freeaddrinfo (infos);
721 }