]> git.sesse.net Git - vlc/blob - src/misc/getaddrinfo.c
* src/misc/net.c,getaddrinfo.c: WinCE build fixes.
[vlc] / src / misc / getaddrinfo.c
1 /*****************************************************************************
2  * getaddrinfo.c: getaddrinfo/getnameinfo replacement functions
3  *****************************************************************************
4  * Copyright (C) 2005 VideoLAN
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 <sys/types.h>
31 #ifdef HAVE_ARPA_INET_H
32 # include <arpa/inet.h>
33 #endif
34 #ifdef HAVE_NETINET_IN_H
35 # include <netinet/in.h>
36 #endif
37 #include <errno.h>
38
39 #if defined( WIN32 ) || defined( UNDER_CE )
40 #   if defined(UNDER_CE) && defined(sockaddr_storage)
41 #       undef sockaddr_storage
42 #   endif
43 #   include <winsock2.h>
44 #   include <ws2tcpip.h>
45 #else
46 #   include <sys/socket.h>
47 #   include <netinet/in.h>
48 #   ifdef HAVE_ARPA_INET_H
49 #       include <arpa/inet.h>
50 #   endif
51 #   include <netdb.h>
52 #endif
53
54 #ifdef HAVE_UNISTD_H
55 #   include <unistd.h>
56 #endif
57
58 #include "network.h"
59
60 #ifdef SYS_BEOS
61 #define NO_ADDRESS  NO_DATA
62 #define PF_INET     AF_INET
63 #define INADDR_NONE 0xFFFFFFFF
64 #define AF_UNSPEC   0
65 #endif
66
67 #define _NI_MASK  (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
68                    NI_DGRAM)
69 # define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
70
71
72 #ifndef HAVE_GAI_STRERROR
73 static struct
74 {
75     int code;
76     const char *msg;
77 } const __gai_errlist[] =
78 {
79     { 0,              "Error 0" },
80     { EAI_BADFLAGS,   "Invalid flag used" },
81     { EAI_NONAME,     "Host or service not found" },
82     { EAI_AGAIN,      "Temporary name service failure" },
83     { EAI_FAIL,       "Non-recoverable name service failure" },
84     { EAI_NODATA,     "No data for host name" },
85     { EAI_FAMILY,     "Unsupported address family" },
86     { EAI_SOCKTYPE,   "Unsupported socket type" },
87     { EAI_SERVICE,    "Incompatible service for socket type" },
88     { EAI_ADDRFAMILY, "Unavailable address family for host name" },
89     { EAI_MEMORY,     "Memory allocation failure" },
90     { EAI_SYSTEM,     "System error" },
91     { 0,              NULL }
92 };
93
94 static const char *__gai_unknownerr = "Unrecognized error number";
95
96 /****************************************************************************
97  * Converts an EAI_* error code into human readable english text.
98  ****************************************************************************/
99 const char *vlc_gai_strerror( int errnum )
100 {
101     int i;
102
103     for (i = 0; __gai_errlist[i].msg != NULL; i++)
104         if (errnum == __gai_errlist[i].code)
105             return __gai_errlist[i].msg;
106
107     return __gai_unknownerr;
108 }
109 # undef _EAI_POSITIVE_MAX
110 #else /* ifndef HAVE_GAI_STRERROR */
111 const char *vlc_gai_strerror( int errnum )
112 {
113     return gai_strerror( errnum );
114 }
115 #endif
116
117 #if !(defined (HAVE_GETNAMEINFO) && defined (HAVE_GETADDRINFO))
118 /*
119  * Converts the current herrno error value into an EAI_* error code.
120  * That error code is normally returned by getnameinfo() or getaddrinfo().
121  */
122 static int
123 gai_error_from_herrno( void )
124 {
125     switch(h_errno)
126     {
127         case HOST_NOT_FOUND:
128             return EAI_NONAME;
129
130         case NO_ADDRESS:
131 # if (NO_ADDRESS != NO_DATA)
132         case NO_DATA:
133 # endif
134             return EAI_NODATA;
135
136         case NO_RECOVERY:
137             return EAI_FAIL;
138
139         case TRY_AGAIN:
140             return EAI_AGAIN;
141     }
142     return EAI_SYSTEM;
143 }
144 #endif /* if !(HAVE_GETNAMEINFO && HAVE_GETADDRINFO) */
145
146 #ifndef HAVE_GETNAMEINFO
147 /*
148  * getnameinfo() non-thread-safe IPv4-only implementation,
149  * Address-family-independant address to hostname translation
150  * (reverse DNS lookup in case of IPv4).
151  *
152  * This is meant for use on old IP-enabled systems that are not IPv6-aware,
153  * and probably do not have getnameinfo(), but have the old gethostbyaddr()
154  * function.
155  *
156  * GNU C library 2.0.x is known to lack this function, even though it defines
157  * getaddrinfo().
158  */
159 static int
160 __getnameinfo( const struct sockaddr *sa, socklen_t salen,
161                char *host, int hostlen, char *serv, int servlen, int flags )
162 {
163     if (((unsigned)salen < sizeof (struct sockaddr_in))
164      || (sa->sa_family != AF_INET))
165         return EAI_FAMILY;
166     else if (flags & (~_NI_MASK))
167         return EAI_BADFLAGS;
168     else
169     {
170         const struct sockaddr_in *addr;
171
172         addr = (const struct sockaddr_in *)sa;
173
174         if (host != NULL)
175         {
176             int solved = 0;
177
178             /* host name resolution */
179             if (!(flags & NI_NUMERICHOST))
180             {
181                 struct hostent *hent;
182
183                 hent = gethostbyaddr ((const void*)&addr->sin_addr,
184                                       4, AF_INET);
185
186                 if (hent != NULL)
187                 {
188                     strncpy (host, hent->h_name, hostlen);
189                     host[hostlen - 1] = '\0';
190
191                     /*
192                      * only keep first part of hostname
193                      * if user don't want fully qualified
194                      * domain name
195                      */
196                     if (flags & NI_NOFQDN)
197                     {
198                         char *ptr;
199
200                         ptr = strchr (host, '.');
201                         if (ptr != NULL)
202                             *ptr = 0;
203                     }
204
205                     solved = 1;
206                 }
207                 else if (flags & NI_NAMEREQD)
208                     return gai_error_from_herrno ();
209             }
210
211             if (!solved)
212             {
213                 /* inet_ntoa() can't fail */
214                 strncpy (host, inet_ntoa (addr->sin_addr), hostlen);
215                 host[hostlen - 1] = '\0';
216             }
217         }
218
219         if (serv != NULL)
220         {
221             struct servent *sent = NULL;
222
223 #ifndef SYS_BEOS /* No getservbyport() */
224             int solved = 0;
225
226             /* service name resolution */
227             if (!(flags & NI_NUMERICSERV))
228             {
229
230                 sent = getservbyport(addr->sin_port,
231                                      (flags & NI_DGRAM)
232                                      ? "udp" : "tcp");
233                 if (sent != NULL)
234                 {
235                     strncpy (serv, sent->s_name, servlen);
236                     serv[servlen - 1] = 0;
237                     solved = 1;
238                 }
239             }
240 #else
241             sent = NULL;
242 #endif
243             if (sent == NULL)
244             {
245                 snprintf (serv, servlen, "%u",
246                           (unsigned int)ntohs (addr->sin_port));
247                 serv[servlen - 1] = '\0';
248             }
249         }
250     }
251     return 0;
252 }
253
254 #endif /* if !HAVE_GETNAMEINFO */
255
256
257 #ifndef HAVE_GETADDRINFO
258 /*
259  * This functions must be used to free the memory allocated by getaddrinfo().
260  */
261 static void
262 __freeaddrinfo (struct addrinfo *res)
263 {
264     if (res != NULL)
265     {
266         if (res->ai_canonname != NULL)
267             free (res->ai_canonname);
268         if (res->ai_addr != NULL)
269             free (res->ai_addr);
270         if (res->ai_next != NULL)
271             free (res->ai_next);
272         free (res);
273     }
274 }
275
276
277 /*
278  * Internal function that builds an addrinfo struct.
279  */
280 static struct addrinfo *
281 makeaddrinfo (int af, int type, int proto,
282               const struct sockaddr *addr, size_t addrlen,
283               const char *canonname)
284 {
285     struct addrinfo *res;
286
287     res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
288     if (res != NULL)
289     {
290         res->ai_flags = 0;
291         res->ai_family = af;
292         res->ai_socktype = type;
293         res->ai_protocol = proto;
294         res->ai_addrlen = addrlen;
295         res->ai_addr = malloc (addrlen);
296         res->ai_canonname = NULL;
297         res->ai_next = NULL;
298
299         if (res->ai_addr != NULL)
300         {
301             memcpy (res->ai_addr, addr, addrlen);
302
303             if (canonname != NULL)
304             {
305                 res->ai_canonname = strdup (canonname);
306                 if (res->ai_canonname != NULL)
307                     return res; /* success ! */
308             }
309             else
310                 return res;
311         }
312     }
313     /* failsafe */
314     vlc_freeaddrinfo (res);
315     return NULL;
316 }
317
318
319 static struct addrinfo *
320 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
321 {
322     struct sockaddr_in addr;
323
324     memset (&addr, 0, sizeof (addr));
325     addr.sin_family = AF_INET;
326 # ifdef HAVE_SA_LEN
327     addr.sin_len = sizeof (addr);
328 # endif
329     addr.sin_port = port;
330     addr.sin_addr.s_addr = ip;
331
332     return makeaddrinfo (PF_INET, type, proto,
333                          (struct sockaddr*)&addr, sizeof (addr), name);
334 }
335
336
337 /*
338  * getaddrinfo() non-thread-safe IPv4-only implementation
339  * Address-family-independant hostname to address resolution.
340  *
341  * This is meant for IPv6-unaware systems that do probably not provide
342  * getaddrinfo(), but still have old function gethostbyname().
343  *
344  * Only UDP and TCP over IPv4 are supported here.
345  */
346 static int
347 __getaddrinfo (const char *node, const char *service,
348                const struct addrinfo *hints, struct addrinfo **res)
349 {
350     struct addrinfo *info;
351     u_long ip;
352     u_short port;
353     int protocol = 0, flags = 0;
354     const char *name = NULL;
355
356     if (hints != NULL)
357     {
358         flags = hints->ai_flags;
359
360         if (flags & ~_AI_MASK)
361             return EAI_BADFLAGS;
362         /* only accept AF_INET and AF_UNSPEC */
363         if (hints->ai_family && (hints->ai_family != AF_INET))
364             return EAI_FAMILY;
365
366         /* protocol sanity check */
367         switch (hints->ai_socktype)
368         {
369             case SOCK_STREAM:
370                 protocol = IPPROTO_TCP;
371                 break;
372
373             case SOCK_DGRAM:
374                 protocol = IPPROTO_UDP;
375                 break;
376
377 #ifndef SYS_BEOS
378             case SOCK_RAW:
379 #endif
380             case 0:
381                 break;
382
383             default:
384                 return EAI_SOCKTYPE;
385         }
386         if (hints->ai_protocol && protocol
387          && (protocol != hints->ai_protocol))
388             return EAI_SERVICE;
389     }
390
391     *res = NULL;
392
393     /* default values */
394     if (node == NULL)
395     {
396         if (flags & AI_PASSIVE)
397             ip = htonl (INADDR_ANY);
398         else
399             ip = htonl (INADDR_LOOPBACK);
400     }
401     else
402     if ((ip = inet_addr (node)) == INADDR_NONE)
403     {
404         struct hostent *entry = NULL;
405
406         /* hostname resolution */
407         if (!(flags & AI_NUMERICHOST))
408             entry = gethostbyname (node);
409
410         if (entry == NULL)
411             return EAI_NONAME;
412
413         if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
414             return EAI_FAMILY;
415
416         ip = *((u_long *) entry->h_addr);
417         if (flags & AI_CANONNAME)
418             name = entry->h_name;
419     }
420
421     if ((flags & AI_CANONNAME) && (name == NULL))
422         name = node;
423
424     /* service resolution */
425     if (service == NULL)
426         port = 0;
427     else
428     {
429         long d;
430         char *end;
431
432         d = strtoul (service, &end, 0);
433         if (end[0] /* service is not a number */
434          || (d > 65535))
435         {
436             struct servent *entry;
437             const char *protoname;
438
439             switch (protocol)
440             {
441                 case IPPROTO_TCP:
442                     protoname = "tcp";
443                     break;
444
445                 case IPPROTO_UDP:
446                     protoname = "udp";
447                     break;
448
449                 default:
450                     protoname = NULL;
451             }
452
453             entry = getservbyname (service, protoname);
454             if (entry == NULL)
455                 return EAI_SERVICE;
456
457             port = entry->s_port;
458         }
459         else
460             port = htons ((u_short)d);
461     }
462
463     /* building results... */
464     if ((!protocol) || (protocol == IPPROTO_UDP))
465     {
466         info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
467         if (info == NULL)
468         {
469             errno = ENOMEM;
470             return EAI_SYSTEM;
471         }
472         if (flags & AI_PASSIVE)
473             info->ai_flags |= AI_PASSIVE;
474         *res = info;
475     }
476     if ((!protocol) || (protocol == IPPROTO_TCP))
477     {
478         info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
479         if (info == NULL)
480         {
481             errno = ENOMEM;
482             return EAI_SYSTEM;
483         }
484         info->ai_next = *res;
485         if (flags & AI_PASSIVE)
486             info->ai_flags |= AI_PASSIVE;
487         *res = info;
488     }
489
490     return 0;
491 }
492 #endif /* if !HAVE_GETADDRINFO */
493
494
495 int vlc_getnameinfo( vlc_object_t *p_this, const struct sockaddr *sa, int salen,
496                      char *host, int hostlen, char *serv, int servlen, int flags )
497 {
498 #ifdef WIN32
499     /*
500      * Here is the kind of kludge you need to keep binary compatibility among
501      * varying OS versions...
502      */
503     typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
504                                            char*, DWORD, char*, DWORD, int );
505     HINSTANCE wship6_module;
506     GETNAMEINFO ws2_getnameinfo;
507      
508     wship6_module = LoadLibrary( "wship6.dll" );
509     if( wship6_module != NULL )
510     {
511         ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( wship6_module,
512                                                        "getnameinfo" );
513
514         if( ws2_getnameinfo != NULL )
515         {
516             int i_val;
517
518             i_val = ws2_getnameinfo( sa, salen, host, hostlen, serv, servlen,
519                                      flags );
520             FreeLibrary( wship6_module );
521             return i_val;
522         }
523             
524         FreeLibrary( wship6_module );
525     }
526 #endif
527 #if HAVE_GETNAMEINFO
528     return getnameinfo( sa, salen, host, hostlen, serv, servlen, flags );
529 #else
530 {
531     vlc_value_t lock;
532     int i_val;
533
534     /* my getnameinfo implementation is not thread-safe as it uses
535      * gethostbyaddr and the likes */
536     var_Create( p_this->p_libvlc, "getnameinfo_mutex", VLC_VAR_MUTEX );
537     var_Get( p_this->p_libvlc, "getnameinfo_mutex", &lock );
538     vlc_mutex_lock( lock.p_address );
539
540     i_val = __getnameinfo( sa, salen, host, hostlen, serv, servlen, flags );
541     vlc_mutex_unlock( lock.p_address );
542     return i_val;
543 }
544 #endif
545 }
546
547
548 /* TODO: support for setting sin6_scope_id */
549 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
550                      const char *service, const struct addrinfo *p_hints,
551                      struct addrinfo **res )
552 {
553     struct addrinfo hints;
554     char psz_buf[NI_MAXHOST], *psz_node;
555
556     /* Check if we have to force ipv4 or ipv6 */
557     if( p_hints == NULL )
558         memset( &hints, 0, sizeof( hints ) );
559     else
560         memcpy( &hints, p_hints, sizeof( hints ) );
561
562     if( hints.ai_family == AF_UNSPEC )
563     {
564         vlc_value_t val;
565
566         var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
567         var_Get( p_this, "ipv4", &val );
568         if( val.b_bool )
569             hints.ai_family = AF_INET;
570
571 #ifdef HAVE_INET_PTON
572         var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
573         var_Get( p_this, "ipv6", &val );
574         if( val.b_bool )
575             hints.ai_family = AF_INET6;
576 #endif
577     }
578
579     /* 
580      * VLC extensions :
581      * - accept "" as NULL
582      * - ignore square brackets
583      */
584     if( ( node == NULL ) || (node[0] == '\0' ) )
585         psz_node = NULL;
586     else
587     {
588         strncpy( psz_buf, node, NI_MAXHOST );
589         psz_buf[NI_MAXHOST - 1] = '\0';
590
591         psz_node = psz_buf;
592
593         if( psz_buf[0] == '[' )
594         {
595             char *ptr;
596
597             ptr = strrchr( psz_buf, ']' );
598             if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
599             {
600                 *ptr = '\0';
601                 psz_node++;
602             }
603         }
604     }
605
606     if( ( service != NULL ) && ( *service == '\0' ) )
607         /* We could put NULL, but you can't have both node and service NULL */
608         service = "0";
609
610 #ifdef WIN32
611     {
612         typedef int (CALLBACK * GETADDRINFO) ( const char *, const char *,
613                                             const struct addrinfo *,
614                                             struct addrinfo ** );
615         HINSTANCE wship6_module;
616         GETADDRINFO ws2_getaddrinfo;
617          
618         wship6_module = LoadLibrary( "wship6.dll" );
619         if( wship6_module != NULL )
620         {
621             ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( wship6_module,
622                                                         "getaddrinfo" );
623
624             if( ws2_getaddrinfo != NULL )
625             {
626                 int i_ret;
627
628                 i_ret = ws2_getaddrinfo( psz_node, service, &hints, res );
629                 FreeLibrary( wship6_module ); /* is this wise ? */
630                 return i_ret;
631             }
632
633             FreeLibrary( wship6_module );
634         }
635     }
636 #endif
637 #if HAVE_GETADDRINFO
638     return getaddrinfo( psz_node, service, &hints, res );
639 #else
640 {
641     int i_ret;
642
643     vlc_value_t lock;
644
645     var_Create( p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX );
646     var_Get( p_this->p_libvlc, "getaddrinfo_mutex", &lock );
647     vlc_mutex_lock( lock.p_address );
648
649     i_ret = __getaddrinfo( psz_node, service, &hints, res );
650     vlc_mutex_unlock( lock.p_address );
651     return i_ret;
652 }
653 #endif
654 }
655
656
657 void vlc_freeaddrinfo( struct addrinfo *infos )
658 {
659 #ifdef WIN32
660     typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
661     HINSTANCE wship6_module;
662     FREEADDRINFO ws2_freeaddrinfo;
663      
664     wship6_module = LoadLibrary( "wship6.dll" );
665     if( wship6_module != NULL )
666     {
667         ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( wship6_module,
668                                                          "freeaddrinfo" );
669
670         /*
671          * NOTE: it is assumed that wship6.dll defines either both
672          * getaddrinfo and freeaddrinfo or none of them.
673          */
674         if( ws2_freeaddrinfo != NULL )
675         {
676             ws2_freeaddrinfo( infos );
677             FreeLibrary( wship6_module );
678             return;
679         }
680
681         FreeLibrary( wship6_module );
682     }
683 #endif
684 #ifdef HAVE_GETADDRINFO
685     freeaddrinfo( infos );
686 #else
687     __freeaddrinfo( infos );
688 #endif
689 }