]> git.sesse.net Git - vlc/blob - src/misc/getaddrinfo.c
* src/misc/getaddrinfo.c: WinCE implementation + ipv6 support (not tested).
[vlc] / src / misc / 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., 59 Temple Place - Suite 330, Boston, MA  02111, 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 #else
231             sent = NULL;
232 #endif
233             if (sent == NULL)
234             {
235                 snprintf (serv, servlen, "%u",
236                           (unsigned int)ntohs (addr->sin_port));
237                 serv[servlen - 1] = '\0';
238             }
239         }
240     }
241     return 0;
242 }
243
244 #endif /* if !HAVE_GETNAMEINFO */
245
246
247 #ifndef HAVE_GETADDRINFO
248 /*
249  * This functions must be used to free the memory allocated by getaddrinfo().
250  */
251 static void
252 __freeaddrinfo (struct addrinfo *res)
253 {
254     if (res != NULL)
255     {
256         if (res->ai_canonname != NULL)
257             free (res->ai_canonname);
258         if (res->ai_addr != NULL)
259             free (res->ai_addr);
260         if (res->ai_next != NULL)
261             free (res->ai_next);
262         free (res);
263     }
264 }
265
266
267 /*
268  * Internal function that builds an addrinfo struct.
269  */
270 static struct addrinfo *
271 makeaddrinfo (int af, int type, int proto,
272               const struct sockaddr *addr, size_t addrlen,
273               const char *canonname)
274 {
275     struct addrinfo *res;
276
277     res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
278     if (res != NULL)
279     {
280         res->ai_flags = 0;
281         res->ai_family = af;
282         res->ai_socktype = type;
283         res->ai_protocol = proto;
284         res->ai_addrlen = addrlen;
285         res->ai_addr = malloc (addrlen);
286         res->ai_canonname = NULL;
287         res->ai_next = NULL;
288
289         if (res->ai_addr != NULL)
290         {
291             memcpy (res->ai_addr, addr, addrlen);
292
293             if (canonname != NULL)
294             {
295                 res->ai_canonname = strdup (canonname);
296                 if (res->ai_canonname != NULL)
297                     return res; /* success ! */
298             }
299             else
300                 return res;
301         }
302     }
303     /* failsafe */
304     vlc_freeaddrinfo (res);
305     return NULL;
306 }
307
308
309 static struct addrinfo *
310 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
311 {
312     struct sockaddr_in addr;
313
314     memset (&addr, 0, sizeof (addr));
315     addr.sin_family = AF_INET;
316 # ifdef HAVE_SA_LEN
317     addr.sin_len = sizeof (addr);
318 # endif
319     addr.sin_port = port;
320     addr.sin_addr.s_addr = ip;
321
322     return makeaddrinfo (AF_INET, type, proto,
323                          (struct sockaddr*)&addr, sizeof (addr), name);
324 }
325
326
327 /*
328  * getaddrinfo() non-thread-safe IPv4-only implementation
329  * Address-family-independant hostname to address resolution.
330  *
331  * This is meant for IPv6-unaware systems that do probably not provide
332  * getaddrinfo(), but still have old function gethostbyname().
333  *
334  * Only UDP and TCP over IPv4 are supported here.
335  */
336 static int
337 __getaddrinfo (const char *node, const char *service,
338                const struct addrinfo *hints, struct addrinfo **res)
339 {
340     struct addrinfo *info;
341     u_long ip;
342     u_short port;
343     int protocol = 0, flags = 0;
344     const char *name = NULL;
345
346     if (hints != NULL)
347     {
348         flags = hints->ai_flags;
349
350         if (flags & ~_AI_MASK)
351             return EAI_BADFLAGS;
352         /* only accept AF_INET and AF_UNSPEC */
353         if (hints->ai_family && (hints->ai_family != AF_INET))
354             return EAI_FAMILY;
355
356         /* protocol sanity check */
357         switch (hints->ai_socktype)
358         {
359             case SOCK_STREAM:
360                 protocol = IPPROTO_TCP;
361                 break;
362
363             case SOCK_DGRAM:
364                 protocol = IPPROTO_UDP;
365                 break;
366
367 #ifndef SYS_BEOS
368             case SOCK_RAW:
369 #endif
370             case 0:
371                 break;
372
373             default:
374                 return EAI_SOCKTYPE;
375         }
376         if (hints->ai_protocol && protocol
377          && (protocol != hints->ai_protocol))
378             return EAI_SERVICE;
379     }
380
381     *res = NULL;
382
383     /* default values */
384     if (node == NULL)
385     {
386         if (flags & AI_PASSIVE)
387             ip = htonl (INADDR_ANY);
388         else
389             ip = htonl (INADDR_LOOPBACK);
390     }
391     else
392     if ((ip = inet_addr (node)) == INADDR_NONE)
393     {
394         struct hostent *entry = NULL;
395
396         /* hostname resolution */
397         if (!(flags & AI_NUMERICHOST))
398             entry = gethostbyname (node);
399
400         if (entry == NULL)
401             return EAI_NONAME;
402
403         if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
404             return EAI_FAMILY;
405
406         ip = *((u_long *) entry->h_addr);
407         if (flags & AI_CANONNAME)
408             name = entry->h_name;
409     }
410
411     if ((flags & AI_CANONNAME) && (name == NULL))
412         name = node;
413
414     /* service resolution */
415     if (service == NULL)
416         port = 0;
417     else
418     {
419         long d;
420         char *end;
421
422         d = strtoul (service, &end, 0);
423         if (end[0] /* service is not a number */
424          || (d > 65535))
425         {
426             struct servent *entry;
427             const char *protoname;
428
429             switch (protocol)
430             {
431                 case IPPROTO_TCP:
432                     protoname = "tcp";
433                     break;
434
435                 case IPPROTO_UDP:
436                     protoname = "udp";
437                     break;
438
439                 default:
440                     protoname = NULL;
441             }
442
443             entry = getservbyname (service, protoname);
444             if (entry == NULL)
445                 return EAI_SERVICE;
446
447             port = entry->s_port;
448         }
449         else
450             port = htons ((u_short)d);
451     }
452
453     /* building results... */
454     if ((!protocol) || (protocol == IPPROTO_UDP))
455     {
456         info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
457         if (info == NULL)
458         {
459             errno = ENOMEM;
460             return EAI_SYSTEM;
461         }
462         if (flags & AI_PASSIVE)
463             info->ai_flags |= AI_PASSIVE;
464         *res = info;
465     }
466     if ((!protocol) || (protocol == IPPROTO_TCP))
467     {
468         info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
469         if (info == NULL)
470         {
471             errno = ENOMEM;
472             return EAI_SYSTEM;
473         }
474         info->ai_next = *res;
475         if (flags & AI_PASSIVE)
476             info->ai_flags |= AI_PASSIVE;
477         *res = info;
478     }
479
480     return 0;
481 }
482 #endif /* if !HAVE_GETADDRINFO */
483
484
485 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
486                      char *host, int hostlen, int *portnum, int flags )
487 {
488     char psz_servbuf[6], *psz_serv;
489     int i_servlen, i_val;
490 #if defined( WIN32 ) && !defined( UNDER_CE )
491     /*
492      * Here is the kind of kludge you need to keep binary compatibility among
493      * varying OS versions...
494      */
495     typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
496                                            char*, DWORD, char*, DWORD, int );
497     HINSTANCE wship6_module;
498     GETNAMEINFO ws2_getnameinfo;
499 #endif
500
501     flags |= NI_NUMERICSERV;
502     if( portnum != NULL )
503     {
504         psz_serv = psz_servbuf;
505         i_servlen = sizeof( psz_servbuf );
506     }
507     else
508     {
509         psz_serv = NULL;
510         i_servlen = 0;
511     }
512 #if defined( WIN32 ) && !defined( UNDER_CE )
513     wship6_module = LoadLibrary( "wship6.dll" );
514     if( wship6_module != NULL )
515     {
516         ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( wship6_module,
517                                                        "getnameinfo" );
518
519         if( ws2_getnameinfo != NULL )
520         {
521             i_val = ws2_getnameinfo( sa, salen, host, hostlen, psz_serv,
522                                      i_servlen, flags );
523             FreeLibrary( wship6_module );
524
525             if( portnum != NULL )
526                 *portnum = atoi( psz_serv );
527             return i_val;
528         }
529             
530         FreeLibrary( wship6_module );
531     }
532 #endif
533 #if defined( HAVE_GETNAMEINFO ) || defined( UNDER_CE )
534     i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
535 #else
536     {
537 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
538         static vlc_value_t lock;
539     
540         /* my getnameinfo implementation is not thread-safe as it uses
541          * gethostbyaddr and the likes */
542         vlc_mutex_lock( lock.p_address );
543 #else
544 //# warning FIXME : This is not thread-safe!
545 #endif
546         i_val = __getnameinfo( sa, salen, host, hostlen, psz_serv, i_servlen,
547                                flags );
548 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
549         vlc_mutex_unlock( lock.p_address );
550 # endif
551     }
552 #endif
553
554     if( portnum != NULL )
555         *portnum = atoi( psz_serv );
556
557     return i_val;
558 }
559
560
561 /* TODO: support for setting sin6_scope_id */
562 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
563                      int i_port, const struct addrinfo *p_hints,
564                      struct addrinfo **res )
565 {
566     struct addrinfo hints;
567     char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
568
569     /*
570      * In VLC, we always use port number as integer rather than strings
571      * for historical reasons (and portability).
572      */
573     if( ( i_port > 65535 ) || ( i_port < 0 ) )
574     {
575         msg_Err( p_this, "invalid port number %d specified", i_port );
576         return EAI_SERVICE;
577     }
578
579     /* cannot overflow */
580     snprintf( psz_service, 6, "%d", i_port );
581
582     /* Check if we have to force ipv4 or ipv6 */
583     if( p_hints == NULL )
584         memset( &hints, 0, sizeof( hints ) );
585     else
586         memcpy( &hints, p_hints, sizeof( hints ) );
587
588     if( hints.ai_family == AF_UNSPEC )
589     {
590         vlc_value_t val;
591
592         var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
593         var_Get( p_this, "ipv4", &val );
594         if( val.b_bool )
595             hints.ai_family = AF_INET;
596
597 #ifdef AF_INET6
598         var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
599         var_Get( p_this, "ipv6", &val );
600         if( val.b_bool )
601             hints.ai_family = AF_INET6;
602 #endif
603     }
604
605     /* 
606      * VLC extensions :
607      * - accept "" as NULL
608      * - ignore square brackets
609      */
610     if( ( node == NULL ) || (node[0] == '\0' ) )
611     {
612         psz_node = NULL;
613     }
614     else
615     {
616         strncpy( psz_buf, node, NI_MAXHOST );
617         psz_buf[NI_MAXHOST - 1] = '\0';
618
619         psz_node = psz_buf;
620
621         if( psz_buf[0] == '[' )
622         {
623             char *ptr;
624
625             ptr = strrchr( psz_buf, ']' );
626             if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
627             {
628                 *ptr = '\0';
629                 psz_node++;
630             }
631         }
632     }
633
634 #if defined( WIN32 ) && !defined( UNDER_CE )
635     {
636         typedef int (CALLBACK * GETADDRINFO) ( const char *, const char *,
637                                             const struct addrinfo *,
638                                             struct addrinfo ** );
639         HINSTANCE wship6_module;
640         GETADDRINFO ws2_getaddrinfo;
641          
642         wship6_module = LoadLibrary( "wship6.dll" );
643         if( wship6_module != NULL )
644         {
645             ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( wship6_module,
646                                                         "getaddrinfo" );
647
648             if( ws2_getaddrinfo != NULL )
649             {
650                 int i_ret;
651
652                 i_ret = ws2_getaddrinfo( psz_node, psz_service, &hints, res );
653                 FreeLibrary( wship6_module ); /* is this wise ? */
654                 return i_ret;
655             }
656
657             FreeLibrary( wship6_module );
658         }
659     }
660 #endif
661 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
662     return getaddrinfo( psz_node, psz_service, &hints, res );
663 #else
664 {
665     int i_ret;
666
667     vlc_value_t lock;
668
669     var_Create( p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX );
670     var_Get( p_this->p_libvlc, "getaddrinfo_mutex", &lock );
671     vlc_mutex_lock( lock.p_address );
672
673     i_ret = __getaddrinfo( psz_node, psz_service, &hints, res );
674     vlc_mutex_unlock( lock.p_address );
675     return i_ret;
676 }
677 #endif
678 }
679
680
681 void vlc_freeaddrinfo( struct addrinfo *infos )
682 {
683 #if defined( WIN32 ) && !defined( UNDER_CE )
684     typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
685     HINSTANCE wship6_module;
686     FREEADDRINFO ws2_freeaddrinfo;
687      
688     wship6_module = LoadLibrary( "wship6.dll" );
689     if( wship6_module != NULL )
690     {
691         ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( wship6_module,
692                                                          "freeaddrinfo" );
693
694         /*
695          * NOTE: it is assumed that wship6.dll defines either both
696          * getaddrinfo and freeaddrinfo or none of them.
697          */
698         if( ws2_freeaddrinfo != NULL )
699         {
700             ws2_freeaddrinfo( infos );
701             FreeLibrary( wship6_module );
702             return;
703         }
704
705         FreeLibrary( wship6_module );
706     }
707 #endif
708 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
709     freeaddrinfo( infos );
710 #else
711     __freeaddrinfo( infos );
712 #endif
713 }