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