]> git.sesse.net Git - vlc/blob - src/network/getaddrinfo.c
Bug to really-stupid-and-worrisomely-not-fixed-for-more-than-ten-years
[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-2004 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> /* strncpy(), 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 "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_SYSTEM,     "System error" },
81     { 0,              NULL }
82 };
83
84 static const char *__gai_unknownerr = "Unrecognized error number";
85
86 /****************************************************************************
87  * Converts an EAI_* error code into human readable english text.
88  ****************************************************************************/
89 const char *vlc_gai_strerror( int errnum )
90 {
91     int i;
92
93     for (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 # undef _EAI_POSITIVE_MAX
100 #else /* ifndef HAVE_GAI_STRERROR */
101 const char *vlc_gai_strerror( int errnum )
102 {
103     return gai_strerror( errnum );
104 }
105 #endif
106
107 #if !(defined (HAVE_GETNAMEINFO) && defined (HAVE_GETADDRINFO))
108 /*
109  * Converts the current herrno error value into an EAI_* error code.
110  * That error code is normally returned by getnameinfo() or getaddrinfo().
111  */
112 static int
113 gai_error_from_herrno( void )
114 {
115     switch(h_errno)
116     {
117         case HOST_NOT_FOUND:
118             return EAI_NONAME;
119
120         case NO_ADDRESS:
121 # if (NO_ADDRESS != NO_DATA)
122         case NO_DATA:
123 # endif
124             return EAI_NODATA;
125
126         case NO_RECOVERY:
127             return EAI_FAIL;
128
129         case TRY_AGAIN:
130             return EAI_AGAIN;
131     }
132     return EAI_SYSTEM;
133 }
134 #endif /* if !(HAVE_GETNAMEINFO && HAVE_GETADDRINFO) */
135
136 #ifndef HAVE_GETNAMEINFO
137 /*
138  * getnameinfo() non-thread-safe IPv4-only implementation,
139  * Address-family-independant address to hostname translation
140  * (reverse DNS lookup in case of IPv4).
141  *
142  * This is meant for use on old IP-enabled systems that are not IPv6-aware,
143  * and probably do not have getnameinfo(), but have the old gethostbyaddr()
144  * function.
145  *
146  * GNU C library 2.0.x is known to lack this function, even though it defines
147  * getaddrinfo().
148  */
149 static int
150 __getnameinfo( const struct sockaddr *sa, socklen_t salen,
151                char *host, int hostlen, char *serv, int servlen, int flags )
152 {
153     if (((unsigned)salen < sizeof (struct sockaddr_in))
154      || (sa->sa_family != AF_INET))
155         return EAI_FAMILY;
156     else if (flags & (~_NI_MASK))
157         return EAI_BADFLAGS;
158     else
159     {
160         const struct sockaddr_in *addr;
161
162         addr = (const struct sockaddr_in *)sa;
163
164         if (host != NULL)
165         {
166             int solved = 0;
167
168             /* host name resolution */
169             if (!(flags & NI_NUMERICHOST))
170             {
171                 struct hostent *hent;
172
173                 hent = gethostbyaddr ((const void*)&addr->sin_addr,
174                                       4, AF_INET);
175
176                 if (hent != NULL)
177                 {
178                     strncpy (host, hent->h_name, hostlen);
179                     host[hostlen - 1] = '\0';
180
181                     /*
182                      * only keep first part of hostname
183                      * if user don't want fully qualified
184                      * domain name
185                      */
186                     if (flags & NI_NOFQDN)
187                     {
188                         char *ptr;
189
190                         ptr = strchr (host, '.');
191                         if (ptr != NULL)
192                             *ptr = 0;
193                     }
194
195                     solved = 1;
196                 }
197                 else if (flags & NI_NAMEREQD)
198                     return gai_error_from_herrno ();
199             }
200
201             if (!solved)
202             {
203                 /* inet_ntoa() can't fail */
204                 strncpy (host, inet_ntoa (addr->sin_addr), hostlen);
205                 host[hostlen - 1] = '\0';
206             }
207         }
208
209         if (serv != NULL)
210         {
211             struct servent *sent = NULL;
212
213 #ifndef SYS_BEOS /* No getservbyport() */
214             int solved = 0;
215
216             /* service name resolution */
217             if (!(flags & NI_NUMERICSERV))
218             {
219
220                 sent = getservbyport(addr->sin_port,
221                                      (flags & NI_DGRAM)
222                                      ? "udp" : "tcp");
223                 if (sent != NULL)
224                 {
225                     strncpy (serv, sent->s_name, servlen);
226                     serv[servlen - 1] = 0;
227                     solved = 1;
228                 }
229             }
230             if (sent == NULL)
231 #endif
232             {
233                 snprintf (serv, servlen, "%u",
234                           (unsigned int)ntohs (addr->sin_port));
235                 serv[servlen - 1] = '\0';
236             }
237         }
238     }
239     return 0;
240 }
241
242 #endif /* if !HAVE_GETNAMEINFO */
243
244
245 #ifndef HAVE_GETADDRINFO
246 /*
247  * This functions must be used to free the memory allocated by getaddrinfo().
248  */
249 static void
250 __freeaddrinfo (struct addrinfo *res)
251 {
252     if (res != NULL)
253     {
254         if (res->ai_canonname != NULL)
255             free (res->ai_canonname);
256         if (res->ai_addr != NULL)
257             free (res->ai_addr);
258         if (res->ai_next != NULL)
259             free (res->ai_next);
260         free (res);
261     }
262 }
263
264
265 /*
266  * Internal function that builds an addrinfo struct.
267  */
268 static struct addrinfo *
269 makeaddrinfo (int af, int type, int proto,
270               const struct sockaddr *addr, size_t addrlen,
271               const char *canonname)
272 {
273     struct addrinfo *res;
274
275     res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
276     if (res != NULL)
277     {
278         res->ai_flags = 0;
279         res->ai_family = af;
280         res->ai_socktype = type;
281         res->ai_protocol = proto;
282         res->ai_addrlen = addrlen;
283         res->ai_addr = malloc (addrlen);
284         res->ai_canonname = NULL;
285         res->ai_next = NULL;
286
287         if (res->ai_addr != NULL)
288         {
289             memcpy (res->ai_addr, addr, addrlen);
290
291             if (canonname != NULL)
292             {
293                 res->ai_canonname = strdup (canonname);
294                 if (res->ai_canonname != NULL)
295                     return res; /* success ! */
296             }
297             else
298                 return res;
299         }
300     }
301     /* failsafe */
302     vlc_freeaddrinfo (res);
303     return NULL;
304 }
305
306
307 static struct addrinfo *
308 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
309 {
310     struct sockaddr_in addr;
311
312     memset (&addr, 0, sizeof (addr));
313     addr.sin_family = AF_INET;
314 # ifdef HAVE_SA_LEN
315     addr.sin_len = sizeof (addr);
316 # endif
317     addr.sin_port = port;
318     addr.sin_addr.s_addr = ip;
319
320     return makeaddrinfo (AF_INET, type, proto,
321                          (struct sockaddr*)&addr, sizeof (addr), name);
322 }
323
324
325 /*
326  * getaddrinfo() non-thread-safe IPv4-only implementation
327  * Address-family-independant hostname to address resolution.
328  *
329  * This is meant for IPv6-unaware systems that do probably not provide
330  * getaddrinfo(), but still have old function gethostbyname().
331  *
332  * Only UDP and TCP over IPv4 are supported here.
333  */
334 static int
335 __getaddrinfo (const char *node, const char *service,
336                const struct addrinfo *hints, struct addrinfo **res)
337 {
338     struct addrinfo *info;
339     u_long ip;
340     u_short port;
341     int protocol = 0, flags = 0;
342     const char *name = NULL;
343
344 #ifdef WIN32
345     /*
346      * Maybe you knew already that Winsock does not handle TCP/RST packets
347      * properly, so that when a TCP connection fails, it will wait until it
348      * times out even if the remote host did return a TCP/RST. However, it
349      * still sees the TCP/RST as the error code is 10061 instead of 10060.
350      * Basically, we have the stupid brainfucked behavior with DNS queries...
351      * When the recursive DNS server returns an error, Winsock waits about
352      * 2 seconds before it returns to the callers, even though it should know
353      * that is pointless. I'd like to know how come this hasn't been fixed
354      * for the past decade, or maybe not.
355      *
356      * Anyway, this is causing a severe delay when the SAP listener tries
357      * to resolve more than ten IPv6 numeric addresses. Modern systems will
358      * eventually realize that it is an IPv6 address, and won't try to resolve
359      * it as a IPv4 address via the Domain Name Service. Old systems
360      * (including Windows XP without the IPv6 stack) will not. It is normally
361      * not an issue as the DNS server usually returns an error very quickly.
362      * But it IS a severe issue on Windows, given the bug explained above.
363      * So here comes one more bug-to-bug Windows compatibility fix.
364      */
365     if ((node != NULL) && (strchr (node, ':') != NULL))
366        return EAI_NONAME;
367 #endif
368
369     if (hints != NULL)
370     {
371         flags = hints->ai_flags;
372
373         if (flags & ~_AI_MASK)
374             return EAI_BADFLAGS;
375         /* only accept AF_INET and AF_UNSPEC */
376         if (hints->ai_family && (hints->ai_family != AF_INET))
377             return EAI_FAMILY;
378
379         /* protocol sanity check */
380         switch (hints->ai_socktype)
381         {
382             case SOCK_STREAM:
383                 protocol = IPPROTO_TCP;
384                 break;
385
386             case SOCK_DGRAM:
387                 protocol = IPPROTO_UDP;
388                 break;
389
390 #ifndef SYS_BEOS
391             case SOCK_RAW:
392 #endif
393             case 0:
394                 break;
395
396             default:
397                 return EAI_SOCKTYPE;
398         }
399         if (hints->ai_protocol && protocol
400          && (protocol != hints->ai_protocol))
401             return EAI_SERVICE;
402     }
403
404     *res = NULL;
405
406     /* default values */
407     if (node == NULL)
408     {
409         if (flags & AI_PASSIVE)
410             ip = htonl (INADDR_ANY);
411         else
412             ip = htonl (INADDR_LOOPBACK);
413     }
414     else
415     if ((ip = inet_addr (node)) == INADDR_NONE)
416     {
417         struct hostent *entry = NULL;
418
419         /* hostname resolution */
420         if (!(flags & AI_NUMERICHOST))
421             entry = gethostbyname (node);
422
423         if (entry == NULL)
424             return EAI_NONAME;
425
426         if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
427             return EAI_FAMILY;
428
429         ip = *((u_long *) entry->h_addr);
430         if (flags & AI_CANONNAME)
431             name = entry->h_name;
432     }
433
434     if ((flags & AI_CANONNAME) && (name == NULL))
435         name = node;
436
437     /* service resolution */
438     if (service == NULL)
439         port = 0;
440     else
441     {
442         long d;
443         char *end;
444
445         d = strtoul (service, &end, 0);
446         if (end[0] /* service is not a number */
447          || (d > 65535))
448         {
449             struct servent *entry;
450             const char *protoname;
451
452             switch (protocol)
453             {
454                 case IPPROTO_TCP:
455                     protoname = "tcp";
456                     break;
457
458                 case IPPROTO_UDP:
459                     protoname = "udp";
460                     break;
461
462                 default:
463                     protoname = NULL;
464             }
465
466             entry = getservbyname (service, protoname);
467             if (entry == NULL)
468                 return EAI_SERVICE;
469
470             port = entry->s_port;
471         }
472         else
473             port = htons ((u_short)d);
474     }
475
476     /* building results... */
477     if ((!protocol) || (protocol == IPPROTO_UDP))
478     {
479         info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
480         if (info == NULL)
481         {
482             errno = ENOMEM;
483             return EAI_SYSTEM;
484         }
485         if (flags & AI_PASSIVE)
486             info->ai_flags |= AI_PASSIVE;
487         *res = info;
488     }
489     if ((!protocol) || (protocol == IPPROTO_TCP))
490     {
491         info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
492         if (info == NULL)
493         {
494             errno = ENOMEM;
495             return EAI_SYSTEM;
496         }
497         info->ai_next = *res;
498         if (flags & AI_PASSIVE)
499             info->ai_flags |= AI_PASSIVE;
500         *res = info;
501     }
502
503     return 0;
504 }
505 #endif /* if !HAVE_GETADDRINFO */
506
507
508 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
509                      char *host, int hostlen, int *portnum, int flags )
510 {
511     char psz_servbuf[6], *psz_serv;
512     int i_servlen, i_val;
513 #if defined( WIN32 ) && !defined( UNDER_CE )
514     /*
515      * Here is the kind of kludge you need to keep binary compatibility among
516      * varying OS versions...
517      */
518     typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
519                                            char*, DWORD, char*, DWORD, int );
520     HINSTANCE wship6_module;
521     GETNAMEINFO ws2_getnameinfo;
522 #endif
523
524     flags |= NI_NUMERICSERV;
525     if( portnum != NULL )
526     {
527         psz_serv = psz_servbuf;
528         i_servlen = sizeof( psz_servbuf );
529     }
530     else
531     {
532         psz_serv = NULL;
533         i_servlen = 0;
534     }
535 #if defined( WIN32 ) && !defined( UNDER_CE )
536     wship6_module = LoadLibrary( "wship6.dll" );
537     if( wship6_module != NULL )
538     {
539         ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( wship6_module,
540                                                        "getnameinfo" );
541
542         if( ws2_getnameinfo != NULL )
543         {
544             i_val = ws2_getnameinfo( sa, salen, host, hostlen, psz_serv,
545                                      i_servlen, flags );
546             FreeLibrary( wship6_module );
547
548             if( portnum != NULL )
549                 *portnum = atoi( psz_serv );
550             return i_val;
551         }
552             
553         FreeLibrary( wship6_module );
554     }
555 #endif
556 #if defined( HAVE_GETNAMEINFO ) || defined( UNDER_CE )
557     i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
558 #else
559     {
560 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
561         static vlc_value_t lock;
562     
563         /* my getnameinfo implementation is not thread-safe as it uses
564          * gethostbyaddr and the likes */
565         vlc_mutex_lock( lock.p_address );
566 #else
567 //# warning FIXME : This is not thread-safe!
568 #endif
569         i_val = __getnameinfo( sa, salen, host, hostlen, psz_serv, i_servlen,
570                                flags );
571 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
572         vlc_mutex_unlock( lock.p_address );
573 # endif
574     }
575 #endif
576
577     if( portnum != NULL )
578         *portnum = atoi( psz_serv );
579
580     return i_val;
581 }
582
583
584 /* TODO: support for setting sin6_scope_id */
585 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
586                      int i_port, const struct addrinfo *p_hints,
587                      struct addrinfo **res )
588 {
589     struct addrinfo hints;
590     char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
591
592     /*
593      * In VLC, we always use port number as integer rather than strings
594      * for historical reasons (and portability).
595      */
596     if( ( i_port > 65535 ) || ( i_port < 0 ) )
597     {
598         msg_Err( p_this, "invalid port number %d specified", i_port );
599         return EAI_SERVICE;
600     }
601
602     /* cannot overflow */
603     snprintf( psz_service, 6, "%d", i_port );
604
605     /* Check if we have to force ipv4 or ipv6 */
606     if( p_hints == NULL )
607         memset( &hints, 0, sizeof( hints ) );
608     else
609         memcpy( &hints, p_hints, sizeof( hints ) );
610
611     if( hints.ai_family == AF_UNSPEC )
612     {
613         vlc_value_t val;
614
615         var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
616         var_Get( p_this, "ipv4", &val );
617         if( val.b_bool )
618             hints.ai_family = AF_INET;
619
620 #ifdef AF_INET6
621         var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
622         var_Get( p_this, "ipv6", &val );
623         if( val.b_bool )
624             hints.ai_family = AF_INET6;
625 #endif
626     }
627
628     /* 
629      * VLC extensions :
630      * - accept "" as NULL
631      * - ignore square brackets
632      */
633     if( ( node == NULL ) || (node[0] == '\0' ) )
634     {
635         psz_node = NULL;
636     }
637     else
638     {
639         strncpy( psz_buf, node, NI_MAXHOST );
640         psz_buf[NI_MAXHOST - 1] = '\0';
641
642         psz_node = psz_buf;
643
644         if( psz_buf[0] == '[' )
645         {
646             char *ptr;
647
648             ptr = strrchr( psz_buf, ']' );
649             if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
650             {
651                 *ptr = '\0';
652                 psz_node++;
653             }
654         }
655     }
656
657 #if defined( WIN32 ) && !defined( UNDER_CE )
658     {
659         typedef int (CALLBACK * GETADDRINFO) ( const char *, const char *,
660                                             const struct addrinfo *,
661                                             struct addrinfo ** );
662         HINSTANCE wship6_module;
663         GETADDRINFO ws2_getaddrinfo;
664
665         wship6_module = LoadLibrary( "wship6.dll" );
666         if( wship6_module != NULL )
667         {
668             ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( wship6_module,
669                                                         "getaddrinfo" );
670
671             if( ws2_getaddrinfo != NULL )
672             {
673                 int i_ret;
674
675                 i_ret = ws2_getaddrinfo( psz_node, psz_service, &hints, res );
676                 FreeLibrary( wship6_module ); /* is this wise ? */
677                 return i_ret;
678             }
679
680             FreeLibrary( wship6_module );
681         }
682     }
683 #endif
684 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
685 # ifdef AI_IDN
686     /* Run-time I18n Domain Names support */
687     {
688         static vlc_bool_t i_idn = VLC_TRUE; /* beware of thread-safety */
689
690         if( i_idn )
691         {
692             int i_ret;
693
694             hints.ai_flags |= AI_IDN;
695             i_ret = getaddrinfo( psz_node, psz_service, &hints, res );
696
697             if( i_ret != EAI_BADFLAGS )
698                 return i_ret;
699
700             /* libidn not available: disable and retry without it */
701
702             /* NOTE: Using i_idn here would not be thread-safe */
703             hints.ai_flags &= ~AI_IDN;
704             i_idn = VLC_FALSE;
705             msg_Dbg( p_this, "I18n Domain Names not supported - disabled" );
706         }
707     }
708 # endif
709     return getaddrinfo( psz_node, psz_service, &hints, res );
710 #else
711 {
712     int i_ret;
713
714     vlc_value_t lock;
715
716     var_Create( p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX );
717     var_Get( p_this->p_libvlc, "getaddrinfo_mutex", &lock );
718     vlc_mutex_lock( lock.p_address );
719
720     i_ret = __getaddrinfo( psz_node, psz_service, &hints, res );
721     vlc_mutex_unlock( lock.p_address );
722     return i_ret;
723 }
724 #endif
725 }
726
727
728 void vlc_freeaddrinfo( struct addrinfo *infos )
729 {
730 #if defined( WIN32 ) && !defined( UNDER_CE )
731     typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
732     HINSTANCE wship6_module;
733     FREEADDRINFO ws2_freeaddrinfo;
734      
735     wship6_module = LoadLibrary( "wship6.dll" );
736     if( wship6_module != NULL )
737     {
738         ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( wship6_module,
739                                                          "freeaddrinfo" );
740
741         /*
742          * NOTE: it is assumed that wship6.dll defines either both
743          * getaddrinfo and freeaddrinfo or none of them.
744          */
745         if( ws2_freeaddrinfo != NULL )
746         {
747             ws2_freeaddrinfo( infos );
748             FreeLibrary( wship6_module );
749             return;
750         }
751
752         FreeLibrary( wship6_module );
753     }
754 #endif
755 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
756     freeaddrinfo( infos );
757 #else
758     __freeaddrinfo( infos );
759 #endif
760 }