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