]> git.sesse.net Git - vlc/blob - src/network/getaddrinfo.c
- Fix thread safety problem in [18812]
[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 #include <vlc/vlc.h>
26
27 #include <stddef.h> /* size_t */
28 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
29 #include <stdlib.h> /* malloc(), free(), strtoul() */
30 #include <errno.h>
31
32 #ifdef HAVE_SYS_TYPES_H
33 #   include <sys/types.h>
34 #endif
35 #ifdef HAVE_ARPA_INET_H
36 #   include <arpa/inet.h>
37 #endif
38 #ifdef HAVE_NETINET_IN_H
39 #   include <netinet/in.h>
40 #endif
41 #ifdef HAVE_UNISTD_H
42 #   include <unistd.h>
43 #endif
44
45 #include <vlc_network.h>
46
47 #ifndef NO_ADDRESS
48 #   define NO_ADDRESS  NO_DATA
49 #endif
50 #ifndef INADDR_NONE
51 #   define INADDR_NONE 0xFFFFFFFF
52 #endif
53 #ifndef AF_UNSPEC
54 #   define AF_UNSPEC   0
55 #endif
56
57 #define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
58                   NI_DGRAM)
59 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
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 WIN32
106 #if !(defined (HAVE_GETNAMEINFO) && defined (HAVE_GETADDRINFO))
107 /*
108  * Converts the current herrno error value into an EAI_* error code.
109  * That error code is normally returned by getnameinfo() or getaddrinfo().
110  */
111 static int
112 gai_error_from_herrno (void)
113 {
114     switch (h_errno)
115     {
116         case HOST_NOT_FOUND:
117             return EAI_NONAME;
118
119         case NO_ADDRESS:
120 # if (NO_ADDRESS != NO_DATA)
121         case NO_DATA:
122 # endif
123             return EAI_NODATA;
124
125         case NO_RECOVERY:
126             return EAI_FAIL;
127
128         case TRY_AGAIN:
129             return EAI_AGAIN;
130     }
131     return EAI_SYSTEM;
132 }
133 #endif /* if !(HAVE_GETNAMEINFO && HAVE_GETADDRINFO) */
134
135 #ifndef HAVE_GETNAMEINFO
136 /*
137  * getnameinfo() non-thread-safe IPv4-only implementation,
138  * Address-family-independant address to hostname translation
139  * (reverse DNS lookup in case of IPv4).
140  *
141  * This is meant for use on old IP-enabled systems that are not IPv6-aware,
142  * and probably do not have getnameinfo(), but have the old gethostbyaddr()
143  * function.
144  *
145  * GNU C library 2.0.x is known to lack this function, even though it defines
146  * getaddrinfo().
147  */
148 static int
149 getnameinfo (const struct sockaddr *sa, socklen_t salen,
150              char *host, int hostlen, char *serv, int servlen, int flags)
151 {
152     if (((size_t)salen < sizeof (struct sockaddr_in))
153      || (sa->sa_family != AF_INET))
154         return EAI_FAMILY;
155     else if (flags & (~_NI_MASK))
156         return EAI_BADFLAGS;
157     else
158     {
159         const struct sockaddr_in *addr;
160
161         addr = (const struct sockaddr_in *)sa;
162
163         if (host != NULL)
164         {
165             /* host name resolution */
166             if (!(flags & NI_NUMERICHOST))
167             {
168                 if (flags & NI_NAMEREQD)
169                     return EAI_NONAME;
170             }
171
172             /* inet_ntoa() is not thread-safe, do not use it */
173             uint32_t ipv4 = ntohl (addr->sin_addr.s_addr);
174
175             if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
176                           (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
177                           ipv4 & 0xff) >= hostlen)
178                 return EAI_OVERFLOW;
179         }
180
181         if (serv != NULL)
182         {
183             if (snprintf (serv, servlen, "%u",
184                           (unsigned int)ntohs (addr->sin_port)) >= servlen)
185                 return EAI_OVERFLOW;
186         }
187     }
188     return 0;
189 }
190
191 #endif /* if !HAVE_GETNAMEINFO */
192
193 #ifndef HAVE_GETADDRINFO
194 /*
195  * This functions must be used to free the memory allocated by getaddrinfo().
196  */
197 static void freeaddrinfo (struct addrinfo *res)
198 {
199     if (res != NULL)
200     {
201         if (res->ai_canonname != NULL)
202             free (res->ai_canonname);
203         if (res->ai_addr != NULL)
204             free (res->ai_addr);
205         if (res->ai_next != NULL)
206             free (res->ai_next);
207         free (res);
208     }
209 }
210
211
212 /*
213  * Internal function that builds an addrinfo struct.
214  */
215 static struct addrinfo *
216 makeaddrinfo (int af, int type, int proto,
217               const struct sockaddr *addr, size_t addrlen,
218               const char *canonname)
219 {
220     struct addrinfo *res;
221
222     res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
223     if (res != NULL)
224     {
225         res->ai_flags = 0;
226         res->ai_family = af;
227         res->ai_socktype = type;
228         res->ai_protocol = proto;
229         res->ai_addrlen = addrlen;
230         res->ai_addr = malloc (addrlen);
231         res->ai_canonname = NULL;
232         res->ai_next = NULL;
233
234         if (res->ai_addr != NULL)
235         {
236             memcpy (res->ai_addr, addr, addrlen);
237
238             if (canonname != NULL)
239             {
240                 res->ai_canonname = strdup (canonname);
241                 if (res->ai_canonname != NULL)
242                     return res; /* success ! */
243             }
244             else
245                 return res;
246         }
247     }
248     /* failsafe */
249     vlc_freeaddrinfo (res);
250     return NULL;
251 }
252
253
254 static struct addrinfo *
255 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
256 {
257     struct sockaddr_in addr;
258
259     memset (&addr, 0, sizeof (addr));
260     addr.sin_family = AF_INET;
261 # ifdef HAVE_SA_LEN
262     addr.sin_len = sizeof (addr);
263 # endif
264     addr.sin_port = port;
265     addr.sin_addr.s_addr = ip;
266
267     return makeaddrinfo (AF_INET, type, proto,
268                          (struct sockaddr*)&addr, sizeof (addr), name);
269 }
270
271
272 /*
273  * getaddrinfo() non-thread-safe IPv4-only implementation
274  * Address-family-independant hostname to address resolution.
275  *
276  * This is meant for IPv6-unaware systems that do probably not provide
277  * getaddrinfo(), but still have old function gethostbyname().
278  *
279  * Only UDP and TCP over IPv4 are supported here.
280  */
281 static int
282 getaddrinfo (const char *node, const char *service,
283              const struct addrinfo *hints, struct addrinfo **res)
284 {
285     struct addrinfo *info;
286     u_long ip;
287     u_short port;
288     int protocol = 0, flags = 0;
289     const char *name = NULL;
290
291 #ifdef WIN32
292     /*
293      * Maybe you knew already that Winsock does not handle TCP/RST packets
294      * properly, so that when a TCP connection fails, it will wait until it
295      * times out even if the remote host did return a TCP/RST. However, it
296      * still sees the TCP/RST as the error code is 10061 instead of 10060.
297      * Basically, we have the stupid brainfucked behavior with DNS queries...
298      * When the recursive DNS server returns an error, Winsock waits about
299      * 2 seconds before it returns to the callers, even though it should know
300      * that is pointless. I'd like to know how come this hasn't been fixed
301      * for the past decade, or maybe not.
302      *
303      * Anyway, this is causing a severe delay when the SAP listener tries
304      * to resolve more than ten IPv6 numeric addresses. Modern systems will
305      * eventually realize that it is an IPv6 address, and won't try to resolve
306      * it as a IPv4 address via the Domain Name Service. Old systems
307      * (including Windows XP without the IPv6 stack) will not. It is normally
308      * not an issue as the DNS server usually returns an error very quickly.
309      * But it IS a severe issue on Windows, given the bug explained above.
310      * So here comes one more bug-to-bug Windows compatibility fix.
311      */
312     if ((node != NULL) && (strchr (node, ':') != NULL))
313        return EAI_NONAME;
314 #endif
315
316     if (hints != NULL)
317     {
318         flags = hints->ai_flags;
319
320         if (flags & ~_AI_MASK)
321             return EAI_BADFLAGS;
322         /* only accept AF_INET and AF_UNSPEC */
323         if (hints->ai_family && (hints->ai_family != AF_INET))
324             return EAI_FAMILY;
325
326         /* protocol sanity check */
327         switch (hints->ai_socktype)
328         {
329             case SOCK_STREAM:
330                 protocol = IPPROTO_TCP;
331                 break;
332
333             case SOCK_DGRAM:
334                 protocol = IPPROTO_UDP;
335                 break;
336
337 #ifndef SOCK_RAW
338             case SOCK_RAW:
339 #endif
340             case 0:
341                 break;
342
343             default:
344                 return EAI_SOCKTYPE;
345         }
346         if (hints->ai_protocol && protocol
347          && (protocol != hints->ai_protocol))
348             return EAI_SERVICE;
349     }
350
351     *res = NULL;
352
353     /* default values */
354     if (node == NULL)
355     {
356         if (flags & AI_PASSIVE)
357             ip = htonl (INADDR_ANY);
358         else
359             ip = htonl (INADDR_LOOPBACK);
360     }
361     else
362     if ((ip = inet_addr (node)) == INADDR_NONE)
363     {
364         struct hostent *entry = NULL;
365
366         /* hostname resolution */
367         if (!(flags & AI_NUMERICHOST))
368             entry = gethostbyname (node);
369
370         if (entry == NULL)
371             return EAI_NONAME;
372
373         if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
374             return EAI_FAMILY;
375
376         ip = *((u_long *) entry->h_addr);
377         if (flags & AI_CANONNAME)
378             name = entry->h_name;
379     }
380
381     if ((flags & AI_CANONNAME) && (name == NULL))
382         name = node;
383
384     /* service resolution */
385     if (service == NULL)
386         port = 0;
387     else
388     {
389         long d;
390         char *end;
391
392         d = strtoul (service, &end, 0);
393         if (end[0] /* service is not a number */
394          || (d > 65535))
395         {
396             struct servent *entry;
397             const char *protoname;
398
399             switch (protocol)
400             {
401                 case IPPROTO_TCP:
402                     protoname = "tcp";
403                     break;
404
405                 case IPPROTO_UDP:
406                     protoname = "udp";
407                     break;
408
409                 default:
410                     protoname = NULL;
411             }
412
413             entry = getservbyname (service, protoname);
414             if (entry == NULL)
415                 return EAI_SERVICE;
416
417             port = entry->s_port;
418         }
419         else
420             port = htons ((u_short)d);
421     }
422
423     /* building results... */
424     if ((!protocol) || (protocol == IPPROTO_UDP))
425     {
426         info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
427         if (info == NULL)
428         {
429             errno = ENOMEM;
430             return EAI_SYSTEM;
431         }
432         if (flags & AI_PASSIVE)
433             info->ai_flags |= AI_PASSIVE;
434         *res = info;
435     }
436     if ((!protocol) || (protocol == IPPROTO_TCP))
437     {
438         info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
439         if (info == NULL)
440         {
441             errno = ENOMEM;
442             return EAI_SYSTEM;
443         }
444         info->ai_next = *res;
445         if (flags & AI_PASSIVE)
446             info->ai_flags |= AI_PASSIVE;
447         *res = info;
448     }
449
450     return 0;
451 }
452 #endif /* if !HAVE_GETADDRINFO */
453 #endif
454
455 #if defined( WIN32 ) && !defined( UNDER_CE )
456     /*
457      * Here is the kind of kludge you need to keep binary compatibility among
458      * varying OS versions...
459      */
460 typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
461                                            char*, DWORD, char*, DWORD, int );
462 typedef int (CALLBACK * GETADDRINFO) (const char *, const char *,
463                                           const struct addrinfo *,
464                                           struct addrinfo **);
465
466 typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
467
468
469 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
470                char *host, DWORD hostlen, char *serv, DWORD servlen, int flags );
471
472 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
473                const struct addrinfo *hints, struct addrinfo **res);
474
475 static WINAPI void _ws2_freeaddrinfo_bind( struct addrinfo *infos );
476
477 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
478 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
479 static FREEADDRINFO ws2_freeaddrinfo;
480
481 static FARPROC ws2_find_api (const char *name)
482 {
483     FARPROC f = NULL;
484
485     HMODULE m = GetModuleHandle ("WS2_32");
486     if (m != NULL)
487         f = GetProcAddress (m, name);
488
489     if (f == NULL)
490     {
491         /* Windows 2K IPv6 preview */
492         m = LoadLibrary ("WSHIP6");
493         if (m != NULL)
494             f = GetProcAddress (m, name);
495     }
496
497     return f;
498 }
499
500 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
501                char *host, DWORD hostlen, char *serv, DWORD servlen, int flags )
502 {
503     GETNAMEINFO entry = (GETNAMEINFO)ws2_find_api ("getnameinfo");
504     if (entry != NULL)
505     {
506         ws2_getnameinfo = entry;
507         return entry (sa, salen, host, hostlen, serv, servlen, flags);
508     }
509     /* return a possible error if API is not found */
510     WSASetLastError (WSAEAFNOSUPPORT);
511     return EAI_FAMILY;
512 }
513
514 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
515                const struct addrinfo *hints, struct addrinfo **res)
516 {
517     GETADDRINFO entry = (GETADDRINFO)ws2_find_api ("getaddrinfo");
518     FREEADDRINFO freentry = (FREEADDRINFO)ws2_find_api ("freeaddrinfo");
519
520     if ((entry != NULL) && (freentry != NULL))
521     {
522         ws2_freeaddrinfo = freentry;
523         ws2_getaddrinfo = entry;
524         return entry (node, service, hints, res);
525     }
526     /* return a possible error if API is not found */
527     WSASetLastError (WSAHOST_NOT_FOUND);
528     return EAI_NONAME;
529 }
530 #endif
531
532
533
534 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
535                      char *host, int hostlen, int *portnum, int flags )
536 {
537     char psz_servbuf[6], *psz_serv;
538     int i_servlen, i_val;
539
540     flags |= NI_NUMERICSERV;
541     if( portnum != NULL )
542     {
543         psz_serv = psz_servbuf;
544         i_servlen = sizeof( psz_servbuf );
545     }
546     else
547     {
548         psz_serv = NULL;
549         i_servlen = 0;
550     }
551
552 #ifndef WIN32
553     i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
554 #else
555     i_val = ws2_getnameinfo (sa, salen, host, hostlen, psz_serv, i_servlen, flags);
556 #endif
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 (ws2_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 #elif defined (WIN32)
672     return ws2_getaddrinfo (psz_node, psz_service, &hints, res);
673 #else
674     int ret;
675     vlc_value_t lock;
676
677     var_Create (p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX);
678     var_Get (p_this->p_libvlc, "getaddrinfo_mutex", &lock);
679     vlc_mutex_lock (lock.p_address);
680
681     int ret = getaddrinfo (psz_node, psz_service, &hints, res);
682     vlc_mutex_unlock (lock.p_address);
683     return ret;
684 #endif
685 }
686
687
688 void vlc_freeaddrinfo( struct addrinfo *infos )
689 {
690 #ifndef WIN32
691     freeaddrinfo (infos);
692 #else
693     ws2_freeaddrinfo (infos);
694 #endif
695 }