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