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