blob: edb4f707e730057d01c10872f01c932c31f42fbf [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
2/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
3
4/*
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * Issues to be discussed:
35 * - Thread safe-ness must be checked.
36 * - Return values. There are nonstandard return values defined and used
37 * in the source code. This is because RFC2553 is silent about which error
38 * code must be returned for which situation.
39 * - IPv4 classful (shortened) form. RFC2553 is silent about it. XNET 5.2
40 * says to use inet_aton() to convert IPv4 numeric to binary (alows
41 * classful form as a result).
42 * current code - disallow classful form for IPv4 (due to use of inet_pton).
43 * - freeaddrinfo(NULL). RFC2553 is silent about it. XNET 5.2 says it is
44 * invalid.
45 * current code - SEGV on freeaddrinfo(NULL)
46 * Note:
47 * - We use getipnodebyname() just for thread-safeness. There's no intent
48 * to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
49 * getipnodebyname().
50 * - The code filters out AFs that are not supported by the kernel,
51 * when globbing NULL hostname (to loopback, or wildcard). Is it the right
52 * thing to do? What is the relationship with post-RFC2553 AI_ADDRCONFIG
53 * in ai_flags?
54 * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
55 * (1) what should we do against numeric hostname (2) what should we do
56 * against NULL hostname (3) what is AI_ADDRCONFIG itself. AF not ready?
57 * non-loopback address configured? global address configured?
58 * - To avoid search order issue, we have a big amount of code duplicate
59 * from gethnamaddr.c and some other places. The issues that there's no
60 * lower layer function to lookup "IPv4 or IPv6" record. Calling
61 * gethostbyname2 from getaddrinfo will end up in wrong search order, as
62 * follows:
63 * - The code makes use of following calls when asked to resolver with
64 * ai_family = PF_UNSPEC:
65 * getipnodebyname(host, AF_INET6);
66 * getipnodebyname(host, AF_INET);
67 * This will result in the following queries if the node is configure to
68 * prefer /etc/hosts than DNS:
69 * lookup /etc/hosts for IPv6 address
70 * lookup DNS for IPv6 address
71 * lookup /etc/hosts for IPv4 address
72 * lookup DNS for IPv4 address
73 * which may not meet people's requirement.
74 * The right thing to happen is to have underlying layer which does
75 * PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
76 * This would result in a bit of code duplicate with _dns_ghbyname() and
77 * friends.
78 */
79
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -070080#include <fcntl.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080081#include <sys/cdefs.h>
82#include <sys/types.h>
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -070083#include <sys/stat.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084#include <sys/param.h>
85#include <sys/socket.h>
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -070086#include <sys/un.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080087#include <net/if.h>
88#include <netinet/in.h>
89#include <arpa/inet.h>
90#include "arpa_nameser.h"
91#include <assert.h>
92#include <ctype.h>
93#include <errno.h>
94#include <netdb.h>
95#include "resolv_private.h"
96#include <stddef.h>
97#include <stdio.h>
98#include <stdlib.h>
99#include <string.h>
100#include <unistd.h>
101
102#include <syslog.h>
103#include <stdarg.h>
104#include "nsswitch.h"
105
Brad Fitzpatrick78585642010-10-28 13:22:20 -0700106#ifdef ANDROID_CHANGES
107#include <sys/system_properties.h>
108#endif /* ANDROID_CHANGES */
109
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -0700110typedef union sockaddr_union {
111 struct sockaddr generic;
112 struct sockaddr_in in;
113 struct sockaddr_in6 in6;
114} sockaddr_union;
115
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800116#define SUCCESS 0
117#define ANY 0
118#define YES 1
119#define NO 0
120
121static const char in_addrany[] = { 0, 0, 0, 0 };
122static const char in_loopback[] = { 127, 0, 0, 1 };
123#ifdef INET6
124static const char in6_addrany[] = {
125 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
126};
127static const char in6_loopback[] = {
128 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
129};
130#endif
131
132static const struct afd {
133 int a_af;
134 int a_addrlen;
135 int a_socklen;
136 int a_off;
137 const char *a_addrany;
138 const char *a_loopback;
139 int a_scoped;
140} afdl [] = {
141#ifdef INET6
142 {PF_INET6, sizeof(struct in6_addr),
143 sizeof(struct sockaddr_in6),
144 offsetof(struct sockaddr_in6, sin6_addr),
145 in6_addrany, in6_loopback, 1},
146#endif
147 {PF_INET, sizeof(struct in_addr),
148 sizeof(struct sockaddr_in),
149 offsetof(struct sockaddr_in, sin_addr),
150 in_addrany, in_loopback, 0},
151 {0, 0, 0, 0, NULL, NULL, 0},
152};
153
154struct explore {
155 int e_af;
156 int e_socktype;
157 int e_protocol;
158 const char *e_protostr;
159 int e_wild;
160#define WILD_AF(ex) ((ex)->e_wild & 0x01)
161#define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
162#define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
163};
164
165static const struct explore explore[] = {
166#if 0
167 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
168#endif
169#ifdef INET6
170 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
171 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
172 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
173#endif
174 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
175 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
176 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
177 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
178 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
179 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
180 { -1, 0, 0, NULL, 0 },
181};
182
183#ifdef INET6
184#define PTON_MAX 16
185#else
186#define PTON_MAX 4
187#endif
188
189static const ns_src default_dns_files[] = {
190 { NSSRC_FILES, NS_SUCCESS },
191 { NSSRC_DNS, NS_SUCCESS },
192 { 0, 0 }
193};
194
195#define MAXPACKET (64*1024)
196
197typedef union {
198 HEADER hdr;
199 u_char buf[MAXPACKET];
200} querybuf;
201
202struct res_target {
203 struct res_target *next;
204 const char *name; /* domain name */
205 int qclass, qtype; /* class and type of query */
206 u_char *answer; /* buffer to put answer */
207 int anslen; /* size of answer buffer */
208 int n; /* result length */
209};
210
211static int str2number(const char *);
212static int explore_fqdn(const struct addrinfo *, const char *,
213 const char *, struct addrinfo **);
214static int explore_null(const struct addrinfo *,
215 const char *, struct addrinfo **);
216static int explore_numeric(const struct addrinfo *, const char *,
217 const char *, struct addrinfo **, const char *);
218static int explore_numeric_scope(const struct addrinfo *, const char *,
219 const char *, struct addrinfo **);
220static int get_canonname(const struct addrinfo *,
221 struct addrinfo *, const char *);
222static struct addrinfo *get_ai(const struct addrinfo *,
223 const struct afd *, const char *);
224static int get_portmatch(const struct addrinfo *, const char *);
225static int get_port(const struct addrinfo *, const char *, int);
226static const struct afd *find_afd(int);
227#ifdef INET6
228static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
229#endif
230
231static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
232 const struct addrinfo *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800233static int _dns_getaddrinfo(void *, void *, va_list);
234static void _sethtent(FILE **);
235static void _endhtent(FILE **);
236static struct addrinfo *_gethtent(FILE **, const char *,
237 const struct addrinfo *);
238static int _files_getaddrinfo(void *, void *, va_list);
239
240static int res_queryN(const char *, struct res_target *, res_state);
241static int res_searchN(const char *, struct res_target *, res_state);
242static int res_querydomainN(const char *, const char *,
243 struct res_target *, res_state);
244
245static const char * const ai_errlist[] = {
246 "Success",
247 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
248 "Temporary failure in name resolution", /* EAI_AGAIN */
249 "Invalid value for ai_flags", /* EAI_BADFLAGS */
250 "Non-recoverable failure in name resolution", /* EAI_FAIL */
251 "ai_family not supported", /* EAI_FAMILY */
252 "Memory allocation failure", /* EAI_MEMORY */
253 "No address associated with hostname", /* EAI_NODATA */
254 "hostname nor servname provided, or not known", /* EAI_NONAME */
255 "servname not supported for ai_socktype", /* EAI_SERVICE */
256 "ai_socktype not supported", /* EAI_SOCKTYPE */
257 "System error returned in errno", /* EAI_SYSTEM */
258 "Invalid value for hints", /* EAI_BADHINTS */
259 "Resolved protocol is unknown", /* EAI_PROTOCOL */
260 "Argument buffer overflow", /* EAI_OVERFLOW */
261 "Unknown error", /* EAI_MAX */
262};
263
264/* XXX macros that make external reference is BAD. */
265
266#define GET_AI(ai, afd, addr) \
267do { \
268 /* external reference: pai, error, and label free */ \
269 (ai) = get_ai(pai, (afd), (addr)); \
270 if ((ai) == NULL) { \
271 error = EAI_MEMORY; \
272 goto free; \
273 } \
274} while (/*CONSTCOND*/0)
275
276#define GET_PORT(ai, serv) \
277do { \
278 /* external reference: error and label free */ \
279 error = get_port((ai), (serv), 0); \
280 if (error != 0) \
281 goto free; \
282} while (/*CONSTCOND*/0)
283
284#define GET_CANONNAME(ai, str) \
285do { \
286 /* external reference: pai, error and label free */ \
287 error = get_canonname(pai, (ai), (str)); \
288 if (error != 0) \
289 goto free; \
290} while (/*CONSTCOND*/0)
291
292#define ERR(err) \
293do { \
294 /* external reference: error, and label bad */ \
295 error = (err); \
296 goto bad; \
297 /*NOTREACHED*/ \
298} while (/*CONSTCOND*/0)
299
300#define MATCH_FAMILY(x, y, w) \
301 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || \
302 (y) == PF_UNSPEC)))
303#define MATCH(x, y, w) \
304 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
305
306const char *
307gai_strerror(int ecode)
308{
309 if (ecode < 0 || ecode > EAI_MAX)
310 ecode = EAI_MAX;
311 return ai_errlist[ecode];
312}
313
314void
315freeaddrinfo(struct addrinfo *ai)
316{
317 struct addrinfo *next;
318
319 assert(ai != NULL);
320
321 do {
322 next = ai->ai_next;
323 if (ai->ai_canonname)
324 free(ai->ai_canonname);
325 /* no need to free(ai->ai_addr) */
326 free(ai);
327 ai = next;
328 } while (ai);
329}
330
331static int
332str2number(const char *p)
333{
334 char *ep;
335 unsigned long v;
336
337 assert(p != NULL);
338
339 if (*p == '\0')
340 return -1;
341 ep = NULL;
342 errno = 0;
343 v = strtoul(p, &ep, 10);
344 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
345 return v;
346 else
347 return -1;
348}
349
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800350/*
351 * Connect a UDP socket to a given unicast address. This will cause no network
352 * traffic, but will fail fast if the system has no or limited reachability to
353 * the destination (e.g., no IPv4 address, no IPv6 default route, ...).
354 */
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700355static int
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800356_test_connect(int pf, struct sockaddr *addr, size_t addrlen) {
357 int s = socket(pf, SOCK_DGRAM, IPPROTO_UDP);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700358 if (s < 0)
359 return 0;
360 int ret;
361 do {
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800362 ret = connect(s, addr, addrlen);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700363 } while (ret < 0 && errno == EINTR);
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800364 int success = (ret == 0);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700365 do {
366 ret = close(s);
367 } while (ret < 0 && errno == EINTR);
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800368 return success;
369}
370
371/*
372 * The following functions determine whether IPv4 or IPv6 connectivity is
373 * available in order to implement AI_ADDRCONFIG.
374 *
375 * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
376 * available, but whether addresses of the specified family are "configured
377 * on the local system". However, bionic doesn't currently support getifaddrs,
378 * so checking for connectivity is the next best thing.
379 */
380static int
381_have_ipv6() {
382 static const struct sockaddr_in6 sin6_test = {
383 .sin6_family = AF_INET6,
384 .sin6_addr.s6_addr = { // 2000::
385 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
386 };
387 sockaddr_union addr = { .in6 = sin6_test };
388 return _test_connect(PF_INET6, &addr.generic, sizeof(addr.in6));
389}
390
391static int
392_have_ipv4() {
393 static const struct sockaddr_in sin_test = {
394 .sin_family = AF_INET,
395 .sin_addr.s_addr = __constant_htonl(0x08080808L) // 8.8.8.8
396 };
397 sockaddr_union addr = { .in = sin_test };
398 return _test_connect(PF_INET, &addr.generic, sizeof(addr.in));
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700399}
400
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700401// Returns 0 on success, else returns non-zero on error (in which case
402// getaddrinfo should continue as normal)
403static int
404android_getaddrinfo_proxy(
405 const char *hostname, const char *servname,
406 const struct addrinfo *hints, struct addrinfo **res)
407{
408 int sock;
409 const int one = 1;
410 struct sockaddr_un proxy_addr;
411 const char* cache_mode = getenv("ANDROID_DNS_MODE");
412 FILE* proxy = NULL;
413 int success = 0;
414
415 // Clear this at start, as we use its non-NULLness later (in the
416 // error path) to decide if we have to free up any memory we
417 // allocated in the process (before failing).
418 *res = NULL;
419
420 if (cache_mode != NULL && strcmp(cache_mode, "local") == 0) {
421 // Don't use the proxy in local mode. This is used by the
422 // proxy itself.
423 return -1;
424 }
425
Brad Fitzpatrick78585642010-10-28 13:22:20 -0700426 // Temporary cautious hack to disable the DNS proxy for processes
427 // requesting special treatment. Ideally the DNS proxy should
428 // accomodate these apps, though.
429 char propname[PROP_NAME_MAX];
430 char propvalue[PROP_VALUE_MAX];
431 snprintf(propname, sizeof(propname), "net.dns1.%d", getpid());
432 if (__system_property_get(propname, propvalue) > 0) {
433 return -1;
434 }
435
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700436 // Bogus things we can't serialize. Don't use the proxy.
437 if ((hostname != NULL &&
438 strcspn(hostname, " \n\r\t^'\"") != strlen(hostname)) ||
439 (servname != NULL &&
440 strcspn(servname, " \n\r\t^'\"") != strlen(servname))) {
441 return -1;
442 }
443
444 sock = socket(AF_UNIX, SOCK_STREAM, 0);
445 if (sock < 0) {
446 return -1;
447 }
448
449 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
450 memset(&proxy_addr, 0, sizeof(proxy_addr));
451 proxy_addr.sun_family = AF_UNIX;
452 strlcpy(proxy_addr.sun_path, "/dev/socket/dnsproxyd",
453 sizeof(proxy_addr.sun_path));
454 if (TEMP_FAILURE_RETRY(connect(sock,
455 (const struct sockaddr*) &proxy_addr,
456 sizeof(proxy_addr))) != 0) {
457 close(sock);
458 return -1;
459 }
460
461 // Send the request.
462 proxy = fdopen(sock, "r+");
463 if (fprintf(proxy, "getaddrinfo %s %s %d %d %d %d",
464 hostname == NULL ? "^" : hostname,
465 servname == NULL ? "^" : servname,
466 hints == NULL ? -1 : hints->ai_flags,
467 hints == NULL ? -1 : hints->ai_family,
468 hints == NULL ? -1 : hints->ai_socktype,
469 hints == NULL ? -1 : hints->ai_protocol) < 0) {
470 goto exit;
471 }
472 // literal NULL byte at end, required by FrameworkListener
473 if (fputc(0, proxy) == EOF ||
474 fflush(proxy) != 0) {
475 goto exit;
476 }
477
478 int remote_rv;
479 if (fread(&remote_rv, sizeof(int), 1, proxy) != 1) {
480 goto exit;
481 }
482
483 if (remote_rv != 0) {
484 goto exit;
485 }
486
487 struct addrinfo* ai = NULL;
488 struct addrinfo** nextres = res;
489 while (1) {
490 uint32_t addrinfo_len;
491 if (fread(&addrinfo_len, sizeof(addrinfo_len),
492 1, proxy) != 1) {
493 break;
494 }
495 addrinfo_len = ntohl(addrinfo_len);
496 if (addrinfo_len == 0) {
497 success = 1;
498 break;
499 }
500
501 if (addrinfo_len < sizeof(struct addrinfo)) {
502 break;
503 }
504 struct addrinfo* ai = calloc(1, addrinfo_len +
505 sizeof(struct sockaddr_storage));
506 if (ai == NULL) {
507 break;
508 }
509
510 if (fread(ai, addrinfo_len, 1, proxy) != 1) {
511 // Error; fall through.
512 break;
513 }
514
515 // Zero out the pointer fields we copied which aren't
516 // valid in this address space.
517 ai->ai_addr = NULL;
518 ai->ai_canonname = NULL;
519 ai->ai_next = NULL;
520
521 // struct sockaddr
522 uint32_t addr_len;
523 if (fread(&addr_len, sizeof(addr_len), 1, proxy) != 1) {
524 break;
525 }
526 addr_len = ntohl(addr_len);
527 if (addr_len != 0) {
528 if (addr_len > sizeof(struct sockaddr_storage)) {
529 // Bogus; too big.
530 break;
531 }
532 struct sockaddr* addr = (struct sockaddr*)(ai + 1);
533 if (fread(addr, addr_len, 1, proxy) != 1) {
534 break;
535 }
536 ai->ai_addr = addr;
537 }
538
539 // cannonname
540 uint32_t name_len;
541 if (fread(&name_len, sizeof(name_len), 1, proxy) != 1) {
542 break;
543 }
Mattias Falk0ee092f2011-02-15 08:44:20 +0100544 name_len = ntohl(name_len);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700545 if (name_len != 0) {
546 ai->ai_canonname = (char*) malloc(name_len);
547 if (fread(ai->ai_canonname, name_len, 1, proxy) != 1) {
548 break;
549 }
550 if (ai->ai_canonname[name_len - 1] != '\0') {
551 // The proxy should be returning this
552 // NULL-terminated.
553 break;
554 }
555 }
556
557 *nextres = ai;
558 nextres = &ai->ai_next;
559 ai = NULL;
560 }
561
562 if (ai != NULL) {
563 // Clean up partially-built addrinfo that we never ended up
564 // attaching to the response.
565 freeaddrinfo(ai);
566 }
567exit:
568 if (proxy != NULL) {
569 fclose(proxy);
570 }
571
572 if (success) {
573 return 0;
574 }
575
576 // Proxy failed; fall through to local
577 // resolver case. But first clean up any
578 // memory we might've allocated.
579 if (*res) {
580 freeaddrinfo(*res);
581 *res = NULL;
582 }
583 return -1;
584}
585
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800586int
587getaddrinfo(const char *hostname, const char *servname,
588 const struct addrinfo *hints, struct addrinfo **res)
589{
590 struct addrinfo sentinel;
591 struct addrinfo *cur;
592 int error = 0;
593 struct addrinfo ai;
594 struct addrinfo ai0;
595 struct addrinfo *pai;
596 const struct explore *ex;
597
598 /* hostname is allowed to be NULL */
599 /* servname is allowed to be NULL */
600 /* hints is allowed to be NULL */
601 assert(res != NULL);
602
603 memset(&sentinel, 0, sizeof(sentinel));
604 cur = &sentinel;
605 pai = &ai;
606 pai->ai_flags = 0;
607 pai->ai_family = PF_UNSPEC;
608 pai->ai_socktype = ANY;
609 pai->ai_protocol = ANY;
610 pai->ai_addrlen = 0;
611 pai->ai_canonname = NULL;
612 pai->ai_addr = NULL;
613 pai->ai_next = NULL;
614
615 if (hostname == NULL && servname == NULL)
616 return EAI_NONAME;
617 if (hints) {
618 /* error check for hints */
619 if (hints->ai_addrlen || hints->ai_canonname ||
620 hints->ai_addr || hints->ai_next)
621 ERR(EAI_BADHINTS); /* xxx */
622 if (hints->ai_flags & ~AI_MASK)
623 ERR(EAI_BADFLAGS);
624 switch (hints->ai_family) {
625 case PF_UNSPEC:
626 case PF_INET:
627#ifdef INET6
628 case PF_INET6:
629#endif
630 break;
631 default:
632 ERR(EAI_FAMILY);
633 }
634 memcpy(pai, hints, sizeof(*pai));
635
636 /*
637 * if both socktype/protocol are specified, check if they
638 * are meaningful combination.
639 */
640 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
641 for (ex = explore; ex->e_af >= 0; ex++) {
642 if (pai->ai_family != ex->e_af)
643 continue;
644 if (ex->e_socktype == ANY)
645 continue;
646 if (ex->e_protocol == ANY)
647 continue;
648 if (pai->ai_socktype == ex->e_socktype
649 && pai->ai_protocol != ex->e_protocol) {
650 ERR(EAI_BADHINTS);
651 }
652 }
653 }
654 }
655
656 /*
657 * check for special cases. (1) numeric servname is disallowed if
658 * socktype/protocol are left unspecified. (2) servname is disallowed
659 * for raw and other inet{,6} sockets.
660 */
661 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
662#ifdef PF_INET6
663 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
664#endif
665 ) {
666 ai0 = *pai; /* backup *pai */
667
668 if (pai->ai_family == PF_UNSPEC) {
669#ifdef PF_INET6
670 pai->ai_family = PF_INET6;
671#else
672 pai->ai_family = PF_INET;
673#endif
674 }
675 error = get_portmatch(pai, servname);
676 if (error)
677 ERR(error);
678
679 *pai = ai0;
680 }
681
682 ai0 = *pai;
683
684 /* NULL hostname, or numeric hostname */
685 for (ex = explore; ex->e_af >= 0; ex++) {
686 *pai = ai0;
687
688 /* PF_UNSPEC entries are prepared for DNS queries only */
689 if (ex->e_af == PF_UNSPEC)
690 continue;
691
692 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
693 continue;
694 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
695 continue;
696 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
697 continue;
698
699 if (pai->ai_family == PF_UNSPEC)
700 pai->ai_family = ex->e_af;
701 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
702 pai->ai_socktype = ex->e_socktype;
703 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
704 pai->ai_protocol = ex->e_protocol;
705
706 if (hostname == NULL)
707 error = explore_null(pai, servname, &cur->ai_next);
708 else
709 error = explore_numeric_scope(pai, hostname, servname,
710 &cur->ai_next);
711
712 if (error)
713 goto free;
714
715 while (cur->ai_next)
716 cur = cur->ai_next;
717 }
718
719 /*
720 * XXX
721 * If numeric representation of AF1 can be interpreted as FQDN
722 * representation of AF2, we need to think again about the code below.
723 */
724 if (sentinel.ai_next)
725 goto good;
726
727 if (hostname == NULL)
728 ERR(EAI_NODATA);
729 if (pai->ai_flags & AI_NUMERICHOST)
730 ERR(EAI_NONAME);
731
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700732 /*
733 * BEGIN ANDROID CHANGES; proxying to the cache
734 */
735 if (android_getaddrinfo_proxy(hostname, servname, hints, res) == 0) {
736 return 0;
737 }
738
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800739 /*
740 * hostname as alphabetical name.
741 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
742 * outer loop by AFs.
743 */
744 for (ex = explore; ex->e_af >= 0; ex++) {
745 *pai = ai0;
746
747 /* require exact match for family field */
748 if (pai->ai_family != ex->e_af)
749 continue;
750
751 if (!MATCH(pai->ai_socktype, ex->e_socktype,
752 WILD_SOCKTYPE(ex))) {
753 continue;
754 }
755 if (!MATCH(pai->ai_protocol, ex->e_protocol,
756 WILD_PROTOCOL(ex))) {
757 continue;
758 }
759
760 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
761 pai->ai_socktype = ex->e_socktype;
762 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
763 pai->ai_protocol = ex->e_protocol;
764
765 error = explore_fqdn(pai, hostname, servname,
766 &cur->ai_next);
767
768 while (cur && cur->ai_next)
769 cur = cur->ai_next;
770 }
771
772 /* XXX */
773 if (sentinel.ai_next)
774 error = 0;
775
776 if (error)
777 goto free;
778 if (error == 0) {
779 if (sentinel.ai_next) {
780 good:
781 *res = sentinel.ai_next;
782 return SUCCESS;
783 } else
784 error = EAI_FAIL;
785 }
786 free:
787 bad:
788 if (sentinel.ai_next)
789 freeaddrinfo(sentinel.ai_next);
790 *res = NULL;
791 return error;
792}
793
794/*
795 * FQDN hostname, DNS lookup
796 */
797static int
798explore_fqdn(const struct addrinfo *pai, const char *hostname,
799 const char *servname, struct addrinfo **res)
800{
801 struct addrinfo *result;
802 struct addrinfo *cur;
803 int error = 0;
804 static const ns_dtab dtab[] = {
805 NS_FILES_CB(_files_getaddrinfo, NULL)
806 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
807 NS_NIS_CB(_yp_getaddrinfo, NULL)
808 { 0, 0, 0 }
809 };
810
811 assert(pai != NULL);
812 /* hostname may be NULL */
813 /* servname may be NULL */
814 assert(res != NULL);
815
816 result = NULL;
817
818 /*
819 * if the servname does not match socktype/protocol, ignore it.
820 */
821 if (get_portmatch(pai, servname) != 0)
822 return 0;
823
824 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
825 default_dns_files, hostname, pai)) {
826 case NS_TRYAGAIN:
827 error = EAI_AGAIN;
828 goto free;
829 case NS_UNAVAIL:
830 error = EAI_FAIL;
831 goto free;
832 case NS_NOTFOUND:
833 error = EAI_NODATA;
834 goto free;
835 case NS_SUCCESS:
836 error = 0;
837 for (cur = result; cur; cur = cur->ai_next) {
838 GET_PORT(cur, servname);
839 /* canonname should be filled already */
840 }
841 break;
842 }
843
844 *res = result;
845
846 return 0;
847
848free:
849 if (result)
850 freeaddrinfo(result);
851 return error;
852}
853
854/*
855 * hostname == NULL.
856 * passive socket -> anyaddr (0.0.0.0 or ::)
857 * non-passive socket -> localhost (127.0.0.1 or ::1)
858 */
859static int
860explore_null(const struct addrinfo *pai, const char *servname,
861 struct addrinfo **res)
862{
863 int s;
864 const struct afd *afd;
865 struct addrinfo *cur;
866 struct addrinfo sentinel;
867 int error;
868
869 assert(pai != NULL);
870 /* servname may be NULL */
871 assert(res != NULL);
872
873 *res = NULL;
874 sentinel.ai_next = NULL;
875 cur = &sentinel;
876
877 /*
878 * filter out AFs that are not supported by the kernel
879 * XXX errno?
880 */
881 s = socket(pai->ai_family, SOCK_DGRAM, 0);
882 if (s < 0) {
883 if (errno != EMFILE)
884 return 0;
885 } else
886 close(s);
887
888 /*
889 * if the servname does not match socktype/protocol, ignore it.
890 */
891 if (get_portmatch(pai, servname) != 0)
892 return 0;
893
894 afd = find_afd(pai->ai_family);
895 if (afd == NULL)
896 return 0;
897
898 if (pai->ai_flags & AI_PASSIVE) {
899 GET_AI(cur->ai_next, afd, afd->a_addrany);
900 /* xxx meaningless?
901 * GET_CANONNAME(cur->ai_next, "anyaddr");
902 */
903 GET_PORT(cur->ai_next, servname);
904 } else {
905 GET_AI(cur->ai_next, afd, afd->a_loopback);
906 /* xxx meaningless?
907 * GET_CANONNAME(cur->ai_next, "localhost");
908 */
909 GET_PORT(cur->ai_next, servname);
910 }
911 cur = cur->ai_next;
912
913 *res = sentinel.ai_next;
914 return 0;
915
916free:
917 if (sentinel.ai_next)
918 freeaddrinfo(sentinel.ai_next);
919 return error;
920}
921
922/*
923 * numeric hostname
924 */
925static int
926explore_numeric(const struct addrinfo *pai, const char *hostname,
927 const char *servname, struct addrinfo **res, const char *canonname)
928{
929 const struct afd *afd;
930 struct addrinfo *cur;
931 struct addrinfo sentinel;
932 int error;
933 char pton[PTON_MAX];
934
935 assert(pai != NULL);
936 /* hostname may be NULL */
937 /* servname may be NULL */
938 assert(res != NULL);
939
940 *res = NULL;
941 sentinel.ai_next = NULL;
942 cur = &sentinel;
943
944 /*
945 * if the servname does not match socktype/protocol, ignore it.
946 */
947 if (get_portmatch(pai, servname) != 0)
948 return 0;
949
950 afd = find_afd(pai->ai_family);
951 if (afd == NULL)
952 return 0;
953
954 switch (afd->a_af) {
955#if 0 /*X/Open spec*/
956 case AF_INET:
957 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
958 if (pai->ai_family == afd->a_af ||
959 pai->ai_family == PF_UNSPEC /*?*/) {
960 GET_AI(cur->ai_next, afd, pton);
961 GET_PORT(cur->ai_next, servname);
962 if ((pai->ai_flags & AI_CANONNAME)) {
963 /*
964 * Set the numeric address itself as
965 * the canonical name, based on a
966 * clarification in rfc2553bis-03.
967 */
968 GET_CANONNAME(cur->ai_next, canonname);
969 }
970 while (cur && cur->ai_next)
971 cur = cur->ai_next;
972 } else
973 ERR(EAI_FAMILY); /*xxx*/
974 }
975 break;
976#endif
977 default:
978 if (inet_pton(afd->a_af, hostname, pton) == 1) {
979 if (pai->ai_family == afd->a_af ||
980 pai->ai_family == PF_UNSPEC /*?*/) {
981 GET_AI(cur->ai_next, afd, pton);
982 GET_PORT(cur->ai_next, servname);
983 if ((pai->ai_flags & AI_CANONNAME)) {
984 /*
985 * Set the numeric address itself as
986 * the canonical name, based on a
987 * clarification in rfc2553bis-03.
988 */
989 GET_CANONNAME(cur->ai_next, canonname);
990 }
991 while (cur->ai_next)
992 cur = cur->ai_next;
993 } else
994 ERR(EAI_FAMILY); /*xxx*/
995 }
996 break;
997 }
998
999 *res = sentinel.ai_next;
1000 return 0;
1001
1002free:
1003bad:
1004 if (sentinel.ai_next)
1005 freeaddrinfo(sentinel.ai_next);
1006 return error;
1007}
1008
1009/*
1010 * numeric hostname with scope
1011 */
1012static int
1013explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1014 const char *servname, struct addrinfo **res)
1015{
1016#if !defined(SCOPE_DELIMITER) || !defined(INET6)
1017 return explore_numeric(pai, hostname, servname, res, hostname);
1018#else
1019 const struct afd *afd;
1020 struct addrinfo *cur;
1021 int error;
1022 char *cp, *hostname2 = NULL, *scope, *addr;
1023 struct sockaddr_in6 *sin6;
1024
1025 assert(pai != NULL);
1026 /* hostname may be NULL */
1027 /* servname may be NULL */
1028 assert(res != NULL);
1029
1030 /*
1031 * if the servname does not match socktype/protocol, ignore it.
1032 */
1033 if (get_portmatch(pai, servname) != 0)
1034 return 0;
1035
1036 afd = find_afd(pai->ai_family);
1037 if (afd == NULL)
1038 return 0;
1039
1040 if (!afd->a_scoped)
1041 return explore_numeric(pai, hostname, servname, res, hostname);
1042
1043 cp = strchr(hostname, SCOPE_DELIMITER);
1044 if (cp == NULL)
1045 return explore_numeric(pai, hostname, servname, res, hostname);
1046
1047 /*
1048 * Handle special case of <scoped_address><delimiter><scope id>
1049 */
1050 hostname2 = strdup(hostname);
1051 if (hostname2 == NULL)
1052 return EAI_MEMORY;
1053 /* terminate at the delimiter */
1054 hostname2[cp - hostname] = '\0';
1055 addr = hostname2;
1056 scope = cp + 1;
1057
1058 error = explore_numeric(pai, addr, servname, res, hostname);
1059 if (error == 0) {
1060 u_int32_t scopeid;
1061
1062 for (cur = *res; cur; cur = cur->ai_next) {
1063 if (cur->ai_family != AF_INET6)
1064 continue;
1065 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1066 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1067 free(hostname2);
1068 return(EAI_NODATA); /* XXX: is return OK? */
1069 }
1070 sin6->sin6_scope_id = scopeid;
1071 }
1072 }
1073
1074 free(hostname2);
1075
1076 return error;
1077#endif
1078}
1079
1080static int
1081get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1082{
1083
1084 assert(pai != NULL);
1085 assert(ai != NULL);
1086 assert(str != NULL);
1087
1088 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1089 ai->ai_canonname = strdup(str);
1090 if (ai->ai_canonname == NULL)
1091 return EAI_MEMORY;
1092 }
1093 return 0;
1094}
1095
1096static struct addrinfo *
1097get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1098{
1099 char *p;
1100 struct addrinfo *ai;
1101
1102 assert(pai != NULL);
1103 assert(afd != NULL);
1104 assert(addr != NULL);
1105
1106 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1107 + (afd->a_socklen));
1108 if (ai == NULL)
1109 return NULL;
1110
1111 memcpy(ai, pai, sizeof(struct addrinfo));
1112 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1113 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1114
1115#ifdef HAVE_SA_LEN
1116 ai->ai_addr->sa_len = afd->a_socklen;
1117#endif
1118
1119 ai->ai_addrlen = afd->a_socklen;
1120#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
1121 ai->__ai_pad0 = 0;
1122#endif
1123 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1124 p = (char *)(void *)(ai->ai_addr);
1125 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1126 return ai;
1127}
1128
1129static int
1130get_portmatch(const struct addrinfo *ai, const char *servname)
1131{
1132
1133 assert(ai != NULL);
1134 /* servname may be NULL */
1135
1136 return get_port(ai, servname, 1);
1137}
1138
1139static int
1140get_port(const struct addrinfo *ai, const char *servname, int matchonly)
1141{
1142 const char *proto;
1143 struct servent *sp;
1144 int port;
1145 int allownumeric;
1146
1147 assert(ai != NULL);
1148 /* servname may be NULL */
1149
1150 if (servname == NULL)
1151 return 0;
1152 switch (ai->ai_family) {
1153 case AF_INET:
1154#ifdef AF_INET6
1155 case AF_INET6:
1156#endif
1157 break;
1158 default:
1159 return 0;
1160 }
1161
1162 switch (ai->ai_socktype) {
1163 case SOCK_RAW:
1164 return EAI_SERVICE;
1165 case SOCK_DGRAM:
1166 case SOCK_STREAM:
1167 allownumeric = 1;
1168 break;
1169 case ANY:
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001170#if 1 /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001171 allownumeric = 1;
1172#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001173 allownumeric = 0;
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001174#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001175 break;
1176 default:
1177 return EAI_SOCKTYPE;
1178 }
1179
1180 port = str2number(servname);
1181 if (port >= 0) {
1182 if (!allownumeric)
1183 return EAI_SERVICE;
1184 if (port < 0 || port > 65535)
1185 return EAI_SERVICE;
1186 port = htons(port);
1187 } else {
1188 if (ai->ai_flags & AI_NUMERICSERV)
1189 return EAI_NONAME;
1190
1191 switch (ai->ai_socktype) {
1192 case SOCK_DGRAM:
1193 proto = "udp";
1194 break;
1195 case SOCK_STREAM:
1196 proto = "tcp";
1197 break;
1198 default:
1199 proto = NULL;
1200 break;
1201 }
1202
1203 if ((sp = getservbyname(servname, proto)) == NULL)
1204 return EAI_SERVICE;
1205 port = sp->s_port;
1206 }
1207
1208 if (!matchonly) {
1209 switch (ai->ai_family) {
1210 case AF_INET:
1211 ((struct sockaddr_in *)(void *)
1212 ai->ai_addr)->sin_port = port;
1213 break;
1214#ifdef INET6
1215 case AF_INET6:
1216 ((struct sockaddr_in6 *)(void *)
1217 ai->ai_addr)->sin6_port = port;
1218 break;
1219#endif
1220 }
1221 }
1222
1223 return 0;
1224}
1225
1226static const struct afd *
1227find_afd(int af)
1228{
1229 const struct afd *afd;
1230
1231 if (af == PF_UNSPEC)
1232 return NULL;
1233 for (afd = afdl; afd->a_af; afd++) {
1234 if (afd->a_af == af)
1235 return afd;
1236 }
1237 return NULL;
1238}
1239
1240#ifdef INET6
1241/* convert a string to a scope identifier. XXX: IPv6 specific */
1242static int
1243ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1244{
1245 u_long lscopeid;
1246 struct in6_addr *a6;
1247 char *ep;
1248
1249 assert(scope != NULL);
1250 assert(sin6 != NULL);
1251 assert(scopeid != NULL);
1252
1253 a6 = &sin6->sin6_addr;
1254
1255 /* empty scopeid portion is invalid */
1256 if (*scope == '\0')
1257 return -1;
1258
1259 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1260 /*
1261 * We currently assume a one-to-one mapping between links
1262 * and interfaces, so we simply use interface indices for
1263 * like-local scopes.
1264 */
1265 *scopeid = if_nametoindex(scope);
1266 if (*scopeid == 0)
1267 goto trynumeric;
1268 return 0;
1269 }
1270
1271 /* still unclear about literal, allow numeric only - placeholder */
1272 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1273 goto trynumeric;
1274 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1275 goto trynumeric;
1276 else
1277 goto trynumeric; /* global */
1278
1279 /* try to convert to a numeric id as a last resort */
1280 trynumeric:
1281 errno = 0;
1282 lscopeid = strtoul(scope, &ep, 10);
1283 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1284 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1285 return 0;
1286 else
1287 return -1;
1288}
1289#endif
1290
1291/* code duplicate with gethnamaddr.c */
1292
1293static const char AskedForGot[] =
1294 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1295
1296static struct addrinfo *
1297getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1298 const struct addrinfo *pai)
1299{
1300 struct addrinfo sentinel, *cur;
1301 struct addrinfo ai;
1302 const struct afd *afd;
1303 char *canonname;
1304 const HEADER *hp;
1305 const u_char *cp;
1306 int n;
1307 const u_char *eom;
1308 char *bp, *ep;
1309 int type, class, ancount, qdcount;
1310 int haveanswer, had_error;
1311 char tbuf[MAXDNAME];
1312 int (*name_ok) (const char *);
1313 char hostbuf[8*1024];
1314
1315 assert(answer != NULL);
1316 assert(qname != NULL);
1317 assert(pai != NULL);
1318
1319 memset(&sentinel, 0, sizeof(sentinel));
1320 cur = &sentinel;
1321
1322 canonname = NULL;
1323 eom = answer->buf + anslen;
1324 switch (qtype) {
1325 case T_A:
1326 case T_AAAA:
1327 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1328 name_ok = res_hnok;
1329 break;
1330 default:
1331 return NULL; /* XXX should be abort(); */
1332 }
1333 /*
1334 * find first satisfactory answer
1335 */
1336 hp = &answer->hdr;
1337 ancount = ntohs(hp->ancount);
1338 qdcount = ntohs(hp->qdcount);
1339 bp = hostbuf;
1340 ep = hostbuf + sizeof hostbuf;
1341 cp = answer->buf + HFIXEDSZ;
1342 if (qdcount != 1) {
1343 h_errno = NO_RECOVERY;
1344 return (NULL);
1345 }
1346 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1347 if ((n < 0) || !(*name_ok)(bp)) {
1348 h_errno = NO_RECOVERY;
1349 return (NULL);
1350 }
1351 cp += n + QFIXEDSZ;
1352 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1353 /* res_send() has already verified that the query name is the
1354 * same as the one we sent; this just gets the expanded name
1355 * (i.e., with the succeeding search-domain tacked on).
1356 */
1357 n = strlen(bp) + 1; /* for the \0 */
1358 if (n >= MAXHOSTNAMELEN) {
1359 h_errno = NO_RECOVERY;
1360 return (NULL);
1361 }
1362 canonname = bp;
1363 bp += n;
1364 /* The qname can be abbreviated, but h_name is now absolute. */
1365 qname = canonname;
1366 }
1367 haveanswer = 0;
1368 had_error = 0;
1369 while (ancount-- > 0 && cp < eom && !had_error) {
1370 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1371 if ((n < 0) || !(*name_ok)(bp)) {
1372 had_error++;
1373 continue;
1374 }
1375 cp += n; /* name */
1376 type = _getshort(cp);
1377 cp += INT16SZ; /* type */
1378 class = _getshort(cp);
1379 cp += INT16SZ + INT32SZ; /* class, TTL */
1380 n = _getshort(cp);
1381 cp += INT16SZ; /* len */
1382 if (class != C_IN) {
1383 /* XXX - debug? syslog? */
1384 cp += n;
1385 continue; /* XXX - had_error++ ? */
1386 }
1387 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1388 type == T_CNAME) {
1389 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1390 if ((n < 0) || !(*name_ok)(tbuf)) {
1391 had_error++;
1392 continue;
1393 }
1394 cp += n;
1395 /* Get canonical name. */
1396 n = strlen(tbuf) + 1; /* for the \0 */
1397 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1398 had_error++;
1399 continue;
1400 }
1401 strlcpy(bp, tbuf, (size_t)(ep - bp));
1402 canonname = bp;
1403 bp += n;
1404 continue;
1405 }
1406 if (qtype == T_ANY) {
1407 if (!(type == T_A || type == T_AAAA)) {
1408 cp += n;
1409 continue;
1410 }
1411 } else if (type != qtype) {
1412 if (type != T_KEY && type != T_SIG)
1413 syslog(LOG_NOTICE|LOG_AUTH,
1414 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1415 qname, p_class(C_IN), p_type(qtype),
1416 p_type(type));
1417 cp += n;
1418 continue; /* XXX - had_error++ ? */
1419 }
1420 switch (type) {
1421 case T_A:
1422 case T_AAAA:
1423 if (strcasecmp(canonname, bp) != 0) {
1424 syslog(LOG_NOTICE|LOG_AUTH,
1425 AskedForGot, canonname, bp);
1426 cp += n;
1427 continue; /* XXX - had_error++ ? */
1428 }
1429 if (type == T_A && n != INADDRSZ) {
1430 cp += n;
1431 continue;
1432 }
1433 if (type == T_AAAA && n != IN6ADDRSZ) {
1434 cp += n;
1435 continue;
1436 }
1437 if (type == T_AAAA) {
1438 struct in6_addr in6;
1439 memcpy(&in6, cp, IN6ADDRSZ);
1440 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1441 cp += n;
1442 continue;
1443 }
1444 }
1445 if (!haveanswer) {
1446 int nn;
1447
1448 canonname = bp;
1449 nn = strlen(bp) + 1; /* for the \0 */
1450 bp += nn;
1451 }
1452
1453 /* don't overwrite pai */
1454 ai = *pai;
1455 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1456 afd = find_afd(ai.ai_family);
1457 if (afd == NULL) {
1458 cp += n;
1459 continue;
1460 }
1461 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1462 if (cur->ai_next == NULL)
1463 had_error++;
1464 while (cur && cur->ai_next)
1465 cur = cur->ai_next;
1466 cp += n;
1467 break;
1468 default:
1469 abort();
1470 }
1471 if (!had_error)
1472 haveanswer++;
1473 }
1474 if (haveanswer) {
1475 if (!canonname)
1476 (void)get_canonname(pai, sentinel.ai_next, qname);
1477 else
1478 (void)get_canonname(pai, sentinel.ai_next, canonname);
1479 h_errno = NETDB_SUCCESS;
1480 return sentinel.ai_next;
1481 }
1482
1483 h_errno = NO_RECOVERY;
1484 return NULL;
1485}
1486
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001487struct addrinfo_sort_elem {
1488 struct addrinfo *ai;
1489 int has_src_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001490 sockaddr_union src_addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001491 int original_order;
1492};
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001493
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001494/*ARGSUSED*/
1495static int
1496_get_scope(const struct sockaddr *addr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001497{
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001498 if (addr->sa_family == AF_INET6) {
1499 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1500 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1501 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1502 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1503 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1504 /*
1505 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1506 * link-local scope.
1507 */
1508 return IPV6_ADDR_SCOPE_LINKLOCAL;
1509 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1510 return IPV6_ADDR_SCOPE_SITELOCAL;
1511 } else {
1512 return IPV6_ADDR_SCOPE_GLOBAL;
1513 }
1514 } else if (addr->sa_family == AF_INET) {
1515 const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1516 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001517
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001518 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1519 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1520 return IPV6_ADDR_SCOPE_LINKLOCAL;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001521 } else {
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001522 /*
1523 * According to draft-ietf-6man-rfc3484-revise-01 section 2.3,
1524 * it is best not to treat the private IPv4 ranges
1525 * (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16) as being
1526 * in a special scope, so we don't.
1527 */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001528 return IPV6_ADDR_SCOPE_GLOBAL;
1529 }
1530 } else {
1531 /*
1532 * This should never happen.
1533 * Return a scope with low priority as a last resort.
1534 */
1535 return IPV6_ADDR_SCOPE_NODELOCAL;
1536 }
1537}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001538
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001539/* These macros are modelled after the ones in <netinet/in6.h>. */
1540
1541/* RFC 4380, section 2.6 */
1542#define IN6_IS_ADDR_TEREDO(a) \
1543 ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1544
1545/* RFC 3056, section 2. */
1546#define IN6_IS_ADDR_6TO4(a) \
1547 (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1548
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001549/* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1550#define IN6_IS_ADDR_6BONE(a) \
1551 (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1552
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001553/*
1554 * Get the label for a given IPv4/IPv6 address.
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001555 * RFC 3484, section 2.1, plus changes from draft-ietf-6man-rfc3484-revise-01.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001556 */
1557
1558/*ARGSUSED*/
1559static int
1560_get_label(const struct sockaddr *addr)
1561{
1562 if (addr->sa_family == AF_INET) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001563 return 3;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001564 } else if (addr->sa_family == AF_INET6) {
1565 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1566 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1567 return 0;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001568 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1569 return 1;
1570 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001571 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001572 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1573 return 4;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001574 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1575 return 5;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001576 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1577 return 10;
1578 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1579 return 11;
1580 } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1581 return 12;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001582 } else {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001583 return 2;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001584 }
1585 } else {
1586 /*
1587 * This should never happen.
1588 * Return a semi-random label as a last resort.
1589 */
1590 return 1;
1591 }
1592}
1593
1594/*
1595 * Get the precedence for a given IPv4/IPv6 address.
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001596 * RFC 3484, section 2.1, plus changes from draft-ietf-6man-rfc3484-revise-01.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001597 */
1598
1599/*ARGSUSED*/
1600static int
1601_get_precedence(const struct sockaddr *addr)
1602{
1603 if (addr->sa_family == AF_INET) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001604 return 30;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001605 } else if (addr->sa_family == AF_INET6) {
1606 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1607 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001608 return 60;
1609 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001610 return 50;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001611 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1612 return 30;
1613 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001614 return 20;
1615 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001616 return 10;
1617 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
1618 IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1619 IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1620 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001621 } else {
1622 return 40;
1623 }
1624 } else {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001625 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001626 }
1627}
1628
1629/*
1630 * Find number of matching initial bits between the two addresses a1 and a2.
1631 */
1632
1633/*ARGSUSED*/
1634static int
1635_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1636{
1637 const char *p1 = (const char *)a1;
1638 const char *p2 = (const char *)a2;
1639 unsigned i;
1640
1641 for (i = 0; i < sizeof(*a1); ++i) {
1642 int x, j;
1643
1644 if (p1[i] == p2[i]) {
1645 continue;
1646 }
1647 x = p1[i] ^ p2[i];
1648 for (j = 0; j < CHAR_BIT; ++j) {
1649 if (x & (1 << (CHAR_BIT - 1))) {
1650 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001651 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001652 x <<= 1;
1653 }
1654 }
1655 return sizeof(*a1) * CHAR_BIT;
1656}
1657
1658/*
1659 * Compare two source/destination address pairs.
1660 * RFC 3484, section 6.
1661 */
1662
1663/*ARGSUSED*/
1664static int
1665_rfc3484_compare(const void *ptr1, const void* ptr2)
1666{
1667 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1668 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1669 int scope_src1, scope_dst1, scope_match1;
1670 int scope_src2, scope_dst2, scope_match2;
1671 int label_src1, label_dst1, label_match1;
1672 int label_src2, label_dst2, label_match2;
1673 int precedence1, precedence2;
1674 int prefixlen1, prefixlen2;
1675
1676 /* Rule 1: Avoid unusable destinations. */
1677 if (a1->has_src_addr != a2->has_src_addr) {
1678 return a2->has_src_addr - a1->has_src_addr;
1679 }
1680
1681 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001682 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001683 scope_dst1 = _get_scope(a1->ai->ai_addr);
1684 scope_match1 = (scope_src1 == scope_dst1);
1685
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001686 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001687 scope_dst2 = _get_scope(a2->ai->ai_addr);
1688 scope_match2 = (scope_src2 == scope_dst2);
1689
1690 if (scope_match1 != scope_match2) {
1691 return scope_match2 - scope_match1;
1692 }
1693
1694 /*
1695 * Rule 3: Avoid deprecated addresses.
1696 * TODO(sesse): We don't currently have a good way of finding this.
1697 */
1698
1699 /*
1700 * Rule 4: Prefer home addresses.
1701 * TODO(sesse): We don't currently have a good way of finding this.
1702 */
1703
1704 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001705 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001706 label_dst1 = _get_label(a1->ai->ai_addr);
1707 label_match1 = (label_src1 == label_dst1);
1708
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001709 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001710 label_dst2 = _get_label(a2->ai->ai_addr);
1711 label_match2 = (label_src2 == label_dst2);
1712
1713 if (label_match1 != label_match2) {
1714 return label_match2 - label_match1;
1715 }
1716
1717 /* Rule 6: Prefer higher precedence. */
1718 precedence1 = _get_precedence(a1->ai->ai_addr);
1719 precedence2 = _get_precedence(a2->ai->ai_addr);
1720 if (precedence1 != precedence2) {
1721 return precedence2 - precedence1;
1722 }
1723
1724 /*
1725 * Rule 7: Prefer native transport.
1726 * TODO(sesse): We don't currently have a good way of finding this.
1727 */
1728
1729 /* Rule 8: Prefer smaller scope. */
1730 if (scope_dst1 != scope_dst2) {
1731 return scope_dst1 - scope_dst2;
1732 }
1733
1734 /*
1735 * Rule 9: Use longest matching prefix.
1736 * We implement this for IPv6 only, as the rules in RFC 3484 don't seem
1737 * to work very well directly applied to IPv4. (glibc uses information from
1738 * the routing table for a custom IPv4 implementation here.)
1739 */
1740 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1741 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001742 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001743 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001744 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001745 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1746 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001747 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001748 if (prefixlen1 != prefixlen2) {
1749 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001750 }
1751 }
1752
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001753 /*
1754 * Rule 10: Leave the order unchanged.
1755 * We need this since qsort() is not necessarily stable.
1756 */
1757 return a1->original_order - a2->original_order;
1758}
1759
1760/*
1761 * Find the source address that will be used if trying to connect to the given
1762 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1763 *
1764 * Returns 1 if a source address was found, 0 if the address is unreachable,
1765 * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
1766 * undefined.
1767 */
1768
1769/*ARGSUSED*/
1770static int
1771_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr)
1772{
1773 int sock;
1774 int ret;
1775 socklen_t len;
1776
1777 switch (addr->sa_family) {
1778 case AF_INET:
1779 len = sizeof(struct sockaddr_in);
1780 break;
1781 case AF_INET6:
1782 len = sizeof(struct sockaddr_in6);
1783 break;
1784 default:
1785 /* No known usable source address for non-INET families. */
1786 return 0;
1787 }
1788
1789 sock = socket(addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
1790 if (sock == -1) {
1791 if (errno == EAFNOSUPPORT) {
1792 return 0;
1793 } else {
1794 return -1;
1795 }
1796 }
1797
1798 do {
1799 ret = connect(sock, addr, len);
1800 } while (ret == -1 && errno == EINTR);
1801
1802 if (ret == -1) {
1803 close(sock);
1804 return 0;
1805 }
1806
1807 if (getsockname(sock, src_addr, &len) == -1) {
1808 close(sock);
1809 return -1;
1810 }
1811 close(sock);
1812 return 1;
1813}
1814
1815/*
1816 * Sort the linked list starting at sentinel->ai_next in RFC3484 order.
1817 * Will leave the list unchanged if an error occurs.
1818 */
1819
1820/*ARGSUSED*/
1821static void
1822_rfc3484_sort(struct addrinfo *list_sentinel)
1823{
1824 struct addrinfo *cur;
1825 int nelem = 0, i;
1826 struct addrinfo_sort_elem *elems;
1827
1828 cur = list_sentinel->ai_next;
1829 while (cur) {
1830 ++nelem;
1831 cur = cur->ai_next;
1832 }
1833
1834 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1835 if (elems == NULL) {
1836 goto error;
1837 }
1838
1839 /*
1840 * Convert the linked list to an array that also contains the candidate
1841 * source address for each destination address.
1842 */
1843 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1844 int has_src_addr;
1845 assert(cur != NULL);
1846 elems[i].ai = cur;
1847 elems[i].original_order = i;
1848
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001849 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001850 if (has_src_addr == -1) {
1851 goto error;
1852 }
1853 elems[i].has_src_addr = has_src_addr;
1854 }
1855
1856 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1857 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc3484_compare);
1858
1859 list_sentinel->ai_next = elems[0].ai;
1860 for (i = 0; i < nelem - 1; ++i) {
1861 elems[i].ai->ai_next = elems[i + 1].ai;
1862 }
1863 elems[nelem - 1].ai->ai_next = NULL;
1864
1865error:
1866 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001867}
1868
1869/*ARGSUSED*/
1870static int
1871_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1872{
1873 struct addrinfo *ai;
1874 querybuf *buf, *buf2;
1875 const char *name;
1876 const struct addrinfo *pai;
1877 struct addrinfo sentinel, *cur;
1878 struct res_target q, q2;
1879 res_state res;
1880
1881 name = va_arg(ap, char *);
1882 pai = va_arg(ap, const struct addrinfo *);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001883 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001884
1885 memset(&q, 0, sizeof(q));
1886 memset(&q2, 0, sizeof(q2));
1887 memset(&sentinel, 0, sizeof(sentinel));
1888 cur = &sentinel;
1889
1890 buf = malloc(sizeof(*buf));
1891 if (buf == NULL) {
1892 h_errno = NETDB_INTERNAL;
1893 return NS_NOTFOUND;
1894 }
1895 buf2 = malloc(sizeof(*buf2));
1896 if (buf2 == NULL) {
1897 free(buf);
1898 h_errno = NETDB_INTERNAL;
1899 return NS_NOTFOUND;
1900 }
1901
1902 switch (pai->ai_family) {
1903 case AF_UNSPEC:
1904 /* prefer IPv6 */
1905 q.name = name;
1906 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001907 q.answer = buf->buf;
1908 q.anslen = sizeof(buf->buf);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001909 int query_ipv6 = 1, query_ipv4 = 1;
1910 if (pai->ai_flags & AI_ADDRCONFIG) {
1911 query_ipv6 = _have_ipv6();
1912 query_ipv4 = _have_ipv4();
1913 }
1914 if (query_ipv6) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001915 q.qtype = T_AAAA;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001916 if (query_ipv4) {
1917 q.next = &q2;
1918 q2.name = name;
1919 q2.qclass = C_IN;
1920 q2.qtype = T_A;
1921 q2.answer = buf2->buf;
1922 q2.anslen = sizeof(buf2->buf);
1923 }
1924 } else if (query_ipv4) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001925 q.qtype = T_A;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001926 } else {
1927 free(buf);
1928 free(buf2);
1929 return NS_NOTFOUND;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001930 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001931 break;
1932 case AF_INET:
1933 q.name = name;
1934 q.qclass = C_IN;
1935 q.qtype = T_A;
1936 q.answer = buf->buf;
1937 q.anslen = sizeof(buf->buf);
1938 break;
1939 case AF_INET6:
1940 q.name = name;
1941 q.qclass = C_IN;
1942 q.qtype = T_AAAA;
1943 q.answer = buf->buf;
1944 q.anslen = sizeof(buf->buf);
1945 break;
1946 default:
1947 free(buf);
1948 free(buf2);
1949 return NS_UNAVAIL;
1950 }
1951
1952 res = __res_get_state();
1953 if (res == NULL) {
1954 free(buf);
1955 free(buf2);
1956 return NS_NOTFOUND;
1957 }
1958
1959 if (res_searchN(name, &q, res) < 0) {
1960 __res_put_state(res);
1961 free(buf);
1962 free(buf2);
1963 return NS_NOTFOUND;
1964 }
1965 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1966 if (ai) {
1967 cur->ai_next = ai;
1968 while (cur && cur->ai_next)
1969 cur = cur->ai_next;
1970 }
1971 if (q.next) {
1972 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1973 if (ai)
1974 cur->ai_next = ai;
1975 }
1976 free(buf);
1977 free(buf2);
1978 if (sentinel.ai_next == NULL) {
1979 __res_put_state(res);
1980 switch (h_errno) {
1981 case HOST_NOT_FOUND:
1982 return NS_NOTFOUND;
1983 case TRY_AGAIN:
1984 return NS_TRYAGAIN;
1985 default:
1986 return NS_UNAVAIL;
1987 }
1988 }
1989
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001990 _rfc3484_sort(&sentinel);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001991
1992 __res_put_state(res);
1993
1994 *((struct addrinfo **)rv) = sentinel.ai_next;
1995 return NS_SUCCESS;
1996}
1997
1998static void
1999_sethtent(FILE **hostf)
2000{
2001
2002 if (!*hostf)
2003 *hostf = fopen(_PATH_HOSTS, "r" );
2004 else
2005 rewind(*hostf);
2006}
2007
2008static void
2009_endhtent(FILE **hostf)
2010{
2011
2012 if (*hostf) {
2013 (void) fclose(*hostf);
2014 *hostf = NULL;
2015 }
2016}
2017
2018static struct addrinfo *
2019_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2020{
2021 char *p;
2022 char *cp, *tname, *cname;
2023 struct addrinfo hints, *res0, *res;
2024 int error;
2025 const char *addr;
2026 char hostbuf[8*1024];
2027
2028// fprintf(stderr, "_gethtent() name = '%s'\n", name);
2029 assert(name != NULL);
2030 assert(pai != NULL);
2031
2032 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
2033 return (NULL);
2034 again:
2035 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2036 return (NULL);
2037 if (*p == '#')
2038 goto again;
2039 if (!(cp = strpbrk(p, "#\n")))
2040 goto again;
2041 *cp = '\0';
2042 if (!(cp = strpbrk(p, " \t")))
2043 goto again;
2044 *cp++ = '\0';
2045 addr = p;
2046 /* if this is not something we're looking for, skip it. */
2047 cname = NULL;
2048 while (cp && *cp) {
2049 if (*cp == ' ' || *cp == '\t') {
2050 cp++;
2051 continue;
2052 }
2053 if (!cname)
2054 cname = cp;
2055 tname = cp;
2056 if ((cp = strpbrk(cp, " \t")) != NULL)
2057 *cp++ = '\0';
2058// fprintf(stderr, "\ttname = '%s'", tname);
2059 if (strcasecmp(name, tname) == 0)
2060 goto found;
2061 }
2062 goto again;
2063
2064found:
2065 hints = *pai;
2066 hints.ai_flags = AI_NUMERICHOST;
2067 error = getaddrinfo(addr, NULL, &hints, &res0);
2068 if (error)
2069 goto again;
2070 for (res = res0; res; res = res->ai_next) {
2071 /* cover it up */
2072 res->ai_flags = pai->ai_flags;
2073
2074 if (pai->ai_flags & AI_CANONNAME) {
2075 if (get_canonname(pai, res, cname) != 0) {
2076 freeaddrinfo(res0);
2077 goto again;
2078 }
2079 }
2080 }
2081 return res0;
2082}
2083
2084/*ARGSUSED*/
2085static int
2086_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2087{
2088 const char *name;
2089 const struct addrinfo *pai;
2090 struct addrinfo sentinel, *cur;
2091 struct addrinfo *p;
2092 FILE *hostf = NULL;
2093
2094 name = va_arg(ap, char *);
2095 pai = va_arg(ap, struct addrinfo *);
2096
2097// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
2098 memset(&sentinel, 0, sizeof(sentinel));
2099 cur = &sentinel;
2100
2101 _sethtent(&hostf);
2102 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2103 cur->ai_next = p;
2104 while (cur && cur->ai_next)
2105 cur = cur->ai_next;
2106 }
2107 _endhtent(&hostf);
2108
2109 *((struct addrinfo **)rv) = sentinel.ai_next;
2110 if (sentinel.ai_next == NULL)
2111 return NS_NOTFOUND;
2112 return NS_SUCCESS;
2113}
2114
2115/* resolver logic */
2116
2117/*
2118 * Formulate a normal query, send, and await answer.
2119 * Returned answer is placed in supplied buffer "answer".
2120 * Perform preliminary check of answer, returning success only
2121 * if no error is indicated and the answer count is nonzero.
2122 * Return the size of the response on success, -1 on error.
2123 * Error number is left in h_errno.
2124 *
2125 * Caller must parse answer and determine whether it answers the question.
2126 */
2127static int
2128res_queryN(const char *name, /* domain name */ struct res_target *target,
2129 res_state res)
2130{
2131 u_char buf[MAXPACKET];
2132 HEADER *hp;
2133 int n;
2134 struct res_target *t;
2135 int rcode;
2136 int ancount;
2137
2138 assert(name != NULL);
2139 /* XXX: target may be NULL??? */
2140
2141 rcode = NOERROR;
2142 ancount = 0;
2143
2144 for (t = target; t; t = t->next) {
2145 int class, type;
2146 u_char *answer;
2147 int anslen;
2148
2149 hp = (HEADER *)(void *)t->answer;
2150 hp->rcode = NOERROR; /* default */
2151
2152 /* make it easier... */
2153 class = t->qclass;
2154 type = t->qtype;
2155 answer = t->answer;
2156 anslen = t->anslen;
2157#ifdef DEBUG
2158 if (res->options & RES_DEBUG)
2159 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
2160#endif
2161
2162 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2163 buf, sizeof(buf));
2164#ifdef RES_USE_EDNS0
2165 if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
2166 n = res_nopt(res, n, buf, sizeof(buf), anslen);
2167#endif
2168 if (n <= 0) {
2169#ifdef DEBUG
2170 if (res->options & RES_DEBUG)
2171 printf(";; res_nquery: mkquery failed\n");
2172#endif
2173 h_errno = NO_RECOVERY;
2174 return n;
2175 }
2176 n = res_nsend(res, buf, n, answer, anslen);
2177#if 0
2178 if (n < 0) {
2179#ifdef DEBUG
2180 if (res->options & RES_DEBUG)
2181 printf(";; res_query: send error\n");
2182#endif
2183 h_errno = TRY_AGAIN;
2184 return n;
2185 }
2186#endif
2187
2188 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2189 rcode = hp->rcode; /* record most recent error */
2190#ifdef DEBUG
2191 if (res->options & RES_DEBUG)
2192 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2193 ntohs(hp->ancount));
2194#endif
2195 continue;
2196 }
2197
2198 ancount += ntohs(hp->ancount);
2199
2200 t->n = n;
2201 }
2202
2203 if (ancount == 0) {
2204 switch (rcode) {
2205 case NXDOMAIN:
2206 h_errno = HOST_NOT_FOUND;
2207 break;
2208 case SERVFAIL:
2209 h_errno = TRY_AGAIN;
2210 break;
2211 case NOERROR:
2212 h_errno = NO_DATA;
2213 break;
2214 case FORMERR:
2215 case NOTIMP:
2216 case REFUSED:
2217 default:
2218 h_errno = NO_RECOVERY;
2219 break;
2220 }
2221 return -1;
2222 }
2223 return ancount;
2224}
2225
2226/*
2227 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2228 * Return the size of the response on success, -1 on error.
2229 * If enabled, implement search rules until answer or unrecoverable failure
2230 * is detected. Error code, if any, is left in h_errno.
2231 */
2232static int
2233res_searchN(const char *name, struct res_target *target, res_state res)
2234{
2235 const char *cp, * const *domain;
2236 HEADER *hp;
2237 u_int dots;
2238 int trailing_dot, ret, saved_herrno;
2239 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2240
2241 assert(name != NULL);
2242 assert(target != NULL);
2243
2244 hp = (HEADER *)(void *)target->answer; /*XXX*/
2245
2246 errno = 0;
2247 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2248 dots = 0;
2249 for (cp = name; *cp; cp++)
2250 dots += (*cp == '.');
2251 trailing_dot = 0;
2252 if (cp > name && *--cp == '.')
2253 trailing_dot++;
2254
2255
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002256 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002257
2258 /*
2259 * if there aren't any dots, it could be a user-level alias
2260 */
2261 if (!dots && (cp = __hostalias(name)) != NULL) {
2262 ret = res_queryN(cp, target, res);
2263 return ret;
2264 }
2265
2266 /*
2267 * If there are dots in the name already, let's just give it a try
2268 * 'as is'. The threshold can be set with the "ndots" option.
2269 */
2270 saved_herrno = -1;
2271 if (dots >= res->ndots) {
2272 ret = res_querydomainN(name, NULL, target, res);
2273 if (ret > 0)
2274 return (ret);
2275 saved_herrno = h_errno;
2276 tried_as_is++;
2277 }
2278
2279 /*
2280 * We do at least one level of search if
2281 * - there is no dot and RES_DEFNAME is set, or
2282 * - there is at least one dot, there is no trailing dot,
2283 * and RES_DNSRCH is set.
2284 */
2285 if ((!dots && (res->options & RES_DEFNAMES)) ||
2286 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2287 int done = 0;
2288
2289 for (domain = (const char * const *)res->dnsrch;
2290 *domain && !done;
2291 domain++) {
2292
2293 ret = res_querydomainN(name, *domain, target, res);
2294 if (ret > 0)
2295 return ret;
2296
2297 /*
2298 * If no server present, give up.
2299 * If name isn't found in this domain,
2300 * keep trying higher domains in the search list
2301 * (if that's enabled).
2302 * On a NO_DATA error, keep trying, otherwise
2303 * a wildcard entry of another type could keep us
2304 * from finding this entry higher in the domain.
2305 * If we get some other error (negative answer or
2306 * server failure), then stop searching up,
2307 * but try the input name below in case it's
2308 * fully-qualified.
2309 */
2310 if (errno == ECONNREFUSED) {
2311 h_errno = TRY_AGAIN;
2312 return -1;
2313 }
2314
2315 switch (h_errno) {
2316 case NO_DATA:
2317 got_nodata++;
2318 /* FALLTHROUGH */
2319 case HOST_NOT_FOUND:
2320 /* keep trying */
2321 break;
2322 case TRY_AGAIN:
2323 if (hp->rcode == SERVFAIL) {
2324 /* try next search element, if any */
2325 got_servfail++;
2326 break;
2327 }
2328 /* FALLTHROUGH */
2329 default:
2330 /* anything else implies that we're done */
2331 done++;
2332 }
2333 /*
2334 * if we got here for some reason other than DNSRCH,
2335 * we only wanted one iteration of the loop, so stop.
2336 */
2337 if (!(res->options & RES_DNSRCH))
2338 done++;
2339 }
2340 }
2341
2342 /*
2343 * if we have not already tried the name "as is", do that now.
2344 * note that we do this regardless of how many dots were in the
2345 * name or whether it ends with a dot.
2346 */
2347 if (!tried_as_is) {
2348 ret = res_querydomainN(name, NULL, target, res);
2349 if (ret > 0)
2350 return ret;
2351 }
2352
2353 /*
2354 * if we got here, we didn't satisfy the search.
2355 * if we did an initial full query, return that query's h_errno
2356 * (note that we wouldn't be here if that query had succeeded).
2357 * else if we ever got a nodata, send that back as the reason.
2358 * else send back meaningless h_errno, that being the one from
2359 * the last DNSRCH we did.
2360 */
2361 if (saved_herrno != -1)
2362 h_errno = saved_herrno;
2363 else if (got_nodata)
2364 h_errno = NO_DATA;
2365 else if (got_servfail)
2366 h_errno = TRY_AGAIN;
2367 return -1;
2368}
2369
2370/*
2371 * Perform a call on res_query on the concatenation of name and domain,
2372 * removing a trailing dot from name if domain is NULL.
2373 */
2374static int
2375res_querydomainN(const char *name, const char *domain,
2376 struct res_target *target, res_state res)
2377{
2378 char nbuf[MAXDNAME];
2379 const char *longname = nbuf;
2380 size_t n, d;
2381
2382 assert(name != NULL);
2383 /* XXX: target may be NULL??? */
2384
2385#ifdef DEBUG
2386 if (res->options & RES_DEBUG)
2387 printf(";; res_querydomain(%s, %s)\n",
2388 name, domain?domain:"<Nil>");
2389#endif
2390 if (domain == NULL) {
2391 /*
2392 * Check for trailing '.';
2393 * copy without '.' if present.
2394 */
2395 n = strlen(name);
2396 if (n + 1 > sizeof(nbuf)) {
2397 h_errno = NO_RECOVERY;
2398 return -1;
2399 }
2400 if (n > 0 && name[--n] == '.') {
2401 strncpy(nbuf, name, n);
2402 nbuf[n] = '\0';
2403 } else
2404 longname = name;
2405 } else {
2406 n = strlen(name);
2407 d = strlen(domain);
2408 if (n + 1 + d + 1 > sizeof(nbuf)) {
2409 h_errno = NO_RECOVERY;
2410 return -1;
2411 }
2412 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2413 }
2414 return res_queryN(longname, target, res);
2415}