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