blob: 993c934cb22f877af70602c98ddd9b32df87f19e [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 Colitti3d8f4ad2009-08-03 22:36:31 -0700350/* Determine whether IPv6 connectivity is available. */
351static int
352_have_ipv6() {
353 /*
354 * Connect a UDP socket to an global unicast IPv6 address. This will
355 * cause no network traffic, but will fail fast if the system has no or
356 * limited IPv6 connectivity (e.g., only a link-local address).
357 */
358 static const struct sockaddr_in6 sin6_test = {
359 /* family, port, flow label */
360 AF_INET6, 0, 0,
361 /* 2000:: */
362 {{{ 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }}},
363 /* scope ID */
364 0};
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -0700365 sockaddr_union addr_test;
366 addr_test.in6 = sin6_test;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700367 int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
368 if (s < 0)
369 return 0;
370 int ret;
371 do {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -0700372 ret = connect(s, &addr_test.generic, sizeof(addr_test.in6));
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700373 } while (ret < 0 && errno == EINTR);
374 int have_ipv6 = (ret == 0);
375 do {
376 ret = close(s);
377 } while (ret < 0 && errno == EINTR);
378 return have_ipv6;
379}
380
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700381// Returns 0 on success, else returns non-zero on error (in which case
382// getaddrinfo should continue as normal)
383static int
384android_getaddrinfo_proxy(
385 const char *hostname, const char *servname,
386 const struct addrinfo *hints, struct addrinfo **res)
387{
388 int sock;
389 const int one = 1;
390 struct sockaddr_un proxy_addr;
391 const char* cache_mode = getenv("ANDROID_DNS_MODE");
392 FILE* proxy = NULL;
393 int success = 0;
394
395 // Clear this at start, as we use its non-NULLness later (in the
396 // error path) to decide if we have to free up any memory we
397 // allocated in the process (before failing).
398 *res = NULL;
399
400 if (cache_mode != NULL && strcmp(cache_mode, "local") == 0) {
401 // Don't use the proxy in local mode. This is used by the
402 // proxy itself.
403 return -1;
404 }
405
Brad Fitzpatrick78585642010-10-28 13:22:20 -0700406 // Temporary cautious hack to disable the DNS proxy for processes
407 // requesting special treatment. Ideally the DNS proxy should
408 // accomodate these apps, though.
409 char propname[PROP_NAME_MAX];
410 char propvalue[PROP_VALUE_MAX];
411 snprintf(propname, sizeof(propname), "net.dns1.%d", getpid());
412 if (__system_property_get(propname, propvalue) > 0) {
413 return -1;
414 }
415
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700416 // Bogus things we can't serialize. Don't use the proxy.
417 if ((hostname != NULL &&
418 strcspn(hostname, " \n\r\t^'\"") != strlen(hostname)) ||
419 (servname != NULL &&
420 strcspn(servname, " \n\r\t^'\"") != strlen(servname))) {
421 return -1;
422 }
423
424 sock = socket(AF_UNIX, SOCK_STREAM, 0);
425 if (sock < 0) {
426 return -1;
427 }
428
429 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
430 memset(&proxy_addr, 0, sizeof(proxy_addr));
431 proxy_addr.sun_family = AF_UNIX;
432 strlcpy(proxy_addr.sun_path, "/dev/socket/dnsproxyd",
433 sizeof(proxy_addr.sun_path));
434 if (TEMP_FAILURE_RETRY(connect(sock,
435 (const struct sockaddr*) &proxy_addr,
436 sizeof(proxy_addr))) != 0) {
437 close(sock);
438 return -1;
439 }
440
441 // Send the request.
442 proxy = fdopen(sock, "r+");
443 if (fprintf(proxy, "getaddrinfo %s %s %d %d %d %d",
444 hostname == NULL ? "^" : hostname,
445 servname == NULL ? "^" : servname,
446 hints == NULL ? -1 : hints->ai_flags,
447 hints == NULL ? -1 : hints->ai_family,
448 hints == NULL ? -1 : hints->ai_socktype,
449 hints == NULL ? -1 : hints->ai_protocol) < 0) {
450 goto exit;
451 }
452 // literal NULL byte at end, required by FrameworkListener
453 if (fputc(0, proxy) == EOF ||
454 fflush(proxy) != 0) {
455 goto exit;
456 }
457
458 int remote_rv;
459 if (fread(&remote_rv, sizeof(int), 1, proxy) != 1) {
460 goto exit;
461 }
462
463 if (remote_rv != 0) {
464 goto exit;
465 }
466
467 struct addrinfo* ai = NULL;
468 struct addrinfo** nextres = res;
469 while (1) {
470 uint32_t addrinfo_len;
471 if (fread(&addrinfo_len, sizeof(addrinfo_len),
472 1, proxy) != 1) {
473 break;
474 }
475 addrinfo_len = ntohl(addrinfo_len);
476 if (addrinfo_len == 0) {
477 success = 1;
478 break;
479 }
480
481 if (addrinfo_len < sizeof(struct addrinfo)) {
482 break;
483 }
484 struct addrinfo* ai = calloc(1, addrinfo_len +
485 sizeof(struct sockaddr_storage));
486 if (ai == NULL) {
487 break;
488 }
489
490 if (fread(ai, addrinfo_len, 1, proxy) != 1) {
491 // Error; fall through.
492 break;
493 }
494
495 // Zero out the pointer fields we copied which aren't
496 // valid in this address space.
497 ai->ai_addr = NULL;
498 ai->ai_canonname = NULL;
499 ai->ai_next = NULL;
500
501 // struct sockaddr
502 uint32_t addr_len;
503 if (fread(&addr_len, sizeof(addr_len), 1, proxy) != 1) {
504 break;
505 }
506 addr_len = ntohl(addr_len);
507 if (addr_len != 0) {
508 if (addr_len > sizeof(struct sockaddr_storage)) {
509 // Bogus; too big.
510 break;
511 }
512 struct sockaddr* addr = (struct sockaddr*)(ai + 1);
513 if (fread(addr, addr_len, 1, proxy) != 1) {
514 break;
515 }
516 ai->ai_addr = addr;
517 }
518
519 // cannonname
520 uint32_t name_len;
521 if (fread(&name_len, sizeof(name_len), 1, proxy) != 1) {
522 break;
523 }
524 if (name_len != 0) {
525 ai->ai_canonname = (char*) malloc(name_len);
526 if (fread(ai->ai_canonname, name_len, 1, proxy) != 1) {
527 break;
528 }
529 if (ai->ai_canonname[name_len - 1] != '\0') {
530 // The proxy should be returning this
531 // NULL-terminated.
532 break;
533 }
534 }
535
536 *nextres = ai;
537 nextres = &ai->ai_next;
538 ai = NULL;
539 }
540
541 if (ai != NULL) {
542 // Clean up partially-built addrinfo that we never ended up
543 // attaching to the response.
544 freeaddrinfo(ai);
545 }
546exit:
547 if (proxy != NULL) {
548 fclose(proxy);
549 }
550
551 if (success) {
552 return 0;
553 }
554
555 // Proxy failed; fall through to local
556 // resolver case. But first clean up any
557 // memory we might've allocated.
558 if (*res) {
559 freeaddrinfo(*res);
560 *res = NULL;
561 }
562 return -1;
563}
564
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800565int
566getaddrinfo(const char *hostname, const char *servname,
567 const struct addrinfo *hints, struct addrinfo **res)
568{
569 struct addrinfo sentinel;
570 struct addrinfo *cur;
571 int error = 0;
572 struct addrinfo ai;
573 struct addrinfo ai0;
574 struct addrinfo *pai;
575 const struct explore *ex;
576
577 /* hostname is allowed to be NULL */
578 /* servname is allowed to be NULL */
579 /* hints is allowed to be NULL */
580 assert(res != NULL);
581
582 memset(&sentinel, 0, sizeof(sentinel));
583 cur = &sentinel;
584 pai = &ai;
585 pai->ai_flags = 0;
586 pai->ai_family = PF_UNSPEC;
587 pai->ai_socktype = ANY;
588 pai->ai_protocol = ANY;
589 pai->ai_addrlen = 0;
590 pai->ai_canonname = NULL;
591 pai->ai_addr = NULL;
592 pai->ai_next = NULL;
593
594 if (hostname == NULL && servname == NULL)
595 return EAI_NONAME;
596 if (hints) {
597 /* error check for hints */
598 if (hints->ai_addrlen || hints->ai_canonname ||
599 hints->ai_addr || hints->ai_next)
600 ERR(EAI_BADHINTS); /* xxx */
601 if (hints->ai_flags & ~AI_MASK)
602 ERR(EAI_BADFLAGS);
603 switch (hints->ai_family) {
604 case PF_UNSPEC:
605 case PF_INET:
606#ifdef INET6
607 case PF_INET6:
608#endif
609 break;
610 default:
611 ERR(EAI_FAMILY);
612 }
613 memcpy(pai, hints, sizeof(*pai));
614
615 /*
616 * if both socktype/protocol are specified, check if they
617 * are meaningful combination.
618 */
619 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
620 for (ex = explore; ex->e_af >= 0; ex++) {
621 if (pai->ai_family != ex->e_af)
622 continue;
623 if (ex->e_socktype == ANY)
624 continue;
625 if (ex->e_protocol == ANY)
626 continue;
627 if (pai->ai_socktype == ex->e_socktype
628 && pai->ai_protocol != ex->e_protocol) {
629 ERR(EAI_BADHINTS);
630 }
631 }
632 }
633 }
634
635 /*
636 * check for special cases. (1) numeric servname is disallowed if
637 * socktype/protocol are left unspecified. (2) servname is disallowed
638 * for raw and other inet{,6} sockets.
639 */
640 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
641#ifdef PF_INET6
642 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
643#endif
644 ) {
645 ai0 = *pai; /* backup *pai */
646
647 if (pai->ai_family == PF_UNSPEC) {
648#ifdef PF_INET6
649 pai->ai_family = PF_INET6;
650#else
651 pai->ai_family = PF_INET;
652#endif
653 }
654 error = get_portmatch(pai, servname);
655 if (error)
656 ERR(error);
657
658 *pai = ai0;
659 }
660
661 ai0 = *pai;
662
663 /* NULL hostname, or numeric hostname */
664 for (ex = explore; ex->e_af >= 0; ex++) {
665 *pai = ai0;
666
667 /* PF_UNSPEC entries are prepared for DNS queries only */
668 if (ex->e_af == PF_UNSPEC)
669 continue;
670
671 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
672 continue;
673 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
674 continue;
675 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
676 continue;
677
678 if (pai->ai_family == PF_UNSPEC)
679 pai->ai_family = ex->e_af;
680 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
681 pai->ai_socktype = ex->e_socktype;
682 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
683 pai->ai_protocol = ex->e_protocol;
684
685 if (hostname == NULL)
686 error = explore_null(pai, servname, &cur->ai_next);
687 else
688 error = explore_numeric_scope(pai, hostname, servname,
689 &cur->ai_next);
690
691 if (error)
692 goto free;
693
694 while (cur->ai_next)
695 cur = cur->ai_next;
696 }
697
698 /*
699 * XXX
700 * If numeric representation of AF1 can be interpreted as FQDN
701 * representation of AF2, we need to think again about the code below.
702 */
703 if (sentinel.ai_next)
704 goto good;
705
706 if (hostname == NULL)
707 ERR(EAI_NODATA);
708 if (pai->ai_flags & AI_NUMERICHOST)
709 ERR(EAI_NONAME);
710
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700711 /*
712 * BEGIN ANDROID CHANGES; proxying to the cache
713 */
714 if (android_getaddrinfo_proxy(hostname, servname, hints, res) == 0) {
715 return 0;
716 }
717
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800718 /*
719 * hostname as alphabetical name.
720 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
721 * outer loop by AFs.
722 */
723 for (ex = explore; ex->e_af >= 0; ex++) {
724 *pai = ai0;
725
726 /* require exact match for family field */
727 if (pai->ai_family != ex->e_af)
728 continue;
729
730 if (!MATCH(pai->ai_socktype, ex->e_socktype,
731 WILD_SOCKTYPE(ex))) {
732 continue;
733 }
734 if (!MATCH(pai->ai_protocol, ex->e_protocol,
735 WILD_PROTOCOL(ex))) {
736 continue;
737 }
738
739 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
740 pai->ai_socktype = ex->e_socktype;
741 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
742 pai->ai_protocol = ex->e_protocol;
743
744 error = explore_fqdn(pai, hostname, servname,
745 &cur->ai_next);
746
747 while (cur && cur->ai_next)
748 cur = cur->ai_next;
749 }
750
751 /* XXX */
752 if (sentinel.ai_next)
753 error = 0;
754
755 if (error)
756 goto free;
757 if (error == 0) {
758 if (sentinel.ai_next) {
759 good:
760 *res = sentinel.ai_next;
761 return SUCCESS;
762 } else
763 error = EAI_FAIL;
764 }
765 free:
766 bad:
767 if (sentinel.ai_next)
768 freeaddrinfo(sentinel.ai_next);
769 *res = NULL;
770 return error;
771}
772
773/*
774 * FQDN hostname, DNS lookup
775 */
776static int
777explore_fqdn(const struct addrinfo *pai, const char *hostname,
778 const char *servname, struct addrinfo **res)
779{
780 struct addrinfo *result;
781 struct addrinfo *cur;
782 int error = 0;
783 static const ns_dtab dtab[] = {
784 NS_FILES_CB(_files_getaddrinfo, NULL)
785 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
786 NS_NIS_CB(_yp_getaddrinfo, NULL)
787 { 0, 0, 0 }
788 };
789
790 assert(pai != NULL);
791 /* hostname may be NULL */
792 /* servname may be NULL */
793 assert(res != NULL);
794
795 result = NULL;
796
797 /*
798 * if the servname does not match socktype/protocol, ignore it.
799 */
800 if (get_portmatch(pai, servname) != 0)
801 return 0;
802
803 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
804 default_dns_files, hostname, pai)) {
805 case NS_TRYAGAIN:
806 error = EAI_AGAIN;
807 goto free;
808 case NS_UNAVAIL:
809 error = EAI_FAIL;
810 goto free;
811 case NS_NOTFOUND:
812 error = EAI_NODATA;
813 goto free;
814 case NS_SUCCESS:
815 error = 0;
816 for (cur = result; cur; cur = cur->ai_next) {
817 GET_PORT(cur, servname);
818 /* canonname should be filled already */
819 }
820 break;
821 }
822
823 *res = result;
824
825 return 0;
826
827free:
828 if (result)
829 freeaddrinfo(result);
830 return error;
831}
832
833/*
834 * hostname == NULL.
835 * passive socket -> anyaddr (0.0.0.0 or ::)
836 * non-passive socket -> localhost (127.0.0.1 or ::1)
837 */
838static int
839explore_null(const struct addrinfo *pai, const char *servname,
840 struct addrinfo **res)
841{
842 int s;
843 const struct afd *afd;
844 struct addrinfo *cur;
845 struct addrinfo sentinel;
846 int error;
847
848 assert(pai != NULL);
849 /* servname may be NULL */
850 assert(res != NULL);
851
852 *res = NULL;
853 sentinel.ai_next = NULL;
854 cur = &sentinel;
855
856 /*
857 * filter out AFs that are not supported by the kernel
858 * XXX errno?
859 */
860 s = socket(pai->ai_family, SOCK_DGRAM, 0);
861 if (s < 0) {
862 if (errno != EMFILE)
863 return 0;
864 } else
865 close(s);
866
867 /*
868 * if the servname does not match socktype/protocol, ignore it.
869 */
870 if (get_portmatch(pai, servname) != 0)
871 return 0;
872
873 afd = find_afd(pai->ai_family);
874 if (afd == NULL)
875 return 0;
876
877 if (pai->ai_flags & AI_PASSIVE) {
878 GET_AI(cur->ai_next, afd, afd->a_addrany);
879 /* xxx meaningless?
880 * GET_CANONNAME(cur->ai_next, "anyaddr");
881 */
882 GET_PORT(cur->ai_next, servname);
883 } else {
884 GET_AI(cur->ai_next, afd, afd->a_loopback);
885 /* xxx meaningless?
886 * GET_CANONNAME(cur->ai_next, "localhost");
887 */
888 GET_PORT(cur->ai_next, servname);
889 }
890 cur = cur->ai_next;
891
892 *res = sentinel.ai_next;
893 return 0;
894
895free:
896 if (sentinel.ai_next)
897 freeaddrinfo(sentinel.ai_next);
898 return error;
899}
900
901/*
902 * numeric hostname
903 */
904static int
905explore_numeric(const struct addrinfo *pai, const char *hostname,
906 const char *servname, struct addrinfo **res, const char *canonname)
907{
908 const struct afd *afd;
909 struct addrinfo *cur;
910 struct addrinfo sentinel;
911 int error;
912 char pton[PTON_MAX];
913
914 assert(pai != NULL);
915 /* hostname may be NULL */
916 /* servname may be NULL */
917 assert(res != NULL);
918
919 *res = NULL;
920 sentinel.ai_next = NULL;
921 cur = &sentinel;
922
923 /*
924 * if the servname does not match socktype/protocol, ignore it.
925 */
926 if (get_portmatch(pai, servname) != 0)
927 return 0;
928
929 afd = find_afd(pai->ai_family);
930 if (afd == NULL)
931 return 0;
932
933 switch (afd->a_af) {
934#if 0 /*X/Open spec*/
935 case AF_INET:
936 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
937 if (pai->ai_family == afd->a_af ||
938 pai->ai_family == PF_UNSPEC /*?*/) {
939 GET_AI(cur->ai_next, afd, pton);
940 GET_PORT(cur->ai_next, servname);
941 if ((pai->ai_flags & AI_CANONNAME)) {
942 /*
943 * Set the numeric address itself as
944 * the canonical name, based on a
945 * clarification in rfc2553bis-03.
946 */
947 GET_CANONNAME(cur->ai_next, canonname);
948 }
949 while (cur && cur->ai_next)
950 cur = cur->ai_next;
951 } else
952 ERR(EAI_FAMILY); /*xxx*/
953 }
954 break;
955#endif
956 default:
957 if (inet_pton(afd->a_af, hostname, 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->ai_next)
971 cur = cur->ai_next;
972 } else
973 ERR(EAI_FAMILY); /*xxx*/
974 }
975 break;
976 }
977
978 *res = sentinel.ai_next;
979 return 0;
980
981free:
982bad:
983 if (sentinel.ai_next)
984 freeaddrinfo(sentinel.ai_next);
985 return error;
986}
987
988/*
989 * numeric hostname with scope
990 */
991static int
992explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
993 const char *servname, struct addrinfo **res)
994{
995#if !defined(SCOPE_DELIMITER) || !defined(INET6)
996 return explore_numeric(pai, hostname, servname, res, hostname);
997#else
998 const struct afd *afd;
999 struct addrinfo *cur;
1000 int error;
1001 char *cp, *hostname2 = NULL, *scope, *addr;
1002 struct sockaddr_in6 *sin6;
1003
1004 assert(pai != NULL);
1005 /* hostname may be NULL */
1006 /* servname may be NULL */
1007 assert(res != NULL);
1008
1009 /*
1010 * if the servname does not match socktype/protocol, ignore it.
1011 */
1012 if (get_portmatch(pai, servname) != 0)
1013 return 0;
1014
1015 afd = find_afd(pai->ai_family);
1016 if (afd == NULL)
1017 return 0;
1018
1019 if (!afd->a_scoped)
1020 return explore_numeric(pai, hostname, servname, res, hostname);
1021
1022 cp = strchr(hostname, SCOPE_DELIMITER);
1023 if (cp == NULL)
1024 return explore_numeric(pai, hostname, servname, res, hostname);
1025
1026 /*
1027 * Handle special case of <scoped_address><delimiter><scope id>
1028 */
1029 hostname2 = strdup(hostname);
1030 if (hostname2 == NULL)
1031 return EAI_MEMORY;
1032 /* terminate at the delimiter */
1033 hostname2[cp - hostname] = '\0';
1034 addr = hostname2;
1035 scope = cp + 1;
1036
1037 error = explore_numeric(pai, addr, servname, res, hostname);
1038 if (error == 0) {
1039 u_int32_t scopeid;
1040
1041 for (cur = *res; cur; cur = cur->ai_next) {
1042 if (cur->ai_family != AF_INET6)
1043 continue;
1044 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1045 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1046 free(hostname2);
1047 return(EAI_NODATA); /* XXX: is return OK? */
1048 }
1049 sin6->sin6_scope_id = scopeid;
1050 }
1051 }
1052
1053 free(hostname2);
1054
1055 return error;
1056#endif
1057}
1058
1059static int
1060get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1061{
1062
1063 assert(pai != NULL);
1064 assert(ai != NULL);
1065 assert(str != NULL);
1066
1067 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1068 ai->ai_canonname = strdup(str);
1069 if (ai->ai_canonname == NULL)
1070 return EAI_MEMORY;
1071 }
1072 return 0;
1073}
1074
1075static struct addrinfo *
1076get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1077{
1078 char *p;
1079 struct addrinfo *ai;
1080
1081 assert(pai != NULL);
1082 assert(afd != NULL);
1083 assert(addr != NULL);
1084
1085 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1086 + (afd->a_socklen));
1087 if (ai == NULL)
1088 return NULL;
1089
1090 memcpy(ai, pai, sizeof(struct addrinfo));
1091 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1092 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1093
1094#ifdef HAVE_SA_LEN
1095 ai->ai_addr->sa_len = afd->a_socklen;
1096#endif
1097
1098 ai->ai_addrlen = afd->a_socklen;
1099#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
1100 ai->__ai_pad0 = 0;
1101#endif
1102 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1103 p = (char *)(void *)(ai->ai_addr);
1104 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1105 return ai;
1106}
1107
1108static int
1109get_portmatch(const struct addrinfo *ai, const char *servname)
1110{
1111
1112 assert(ai != NULL);
1113 /* servname may be NULL */
1114
1115 return get_port(ai, servname, 1);
1116}
1117
1118static int
1119get_port(const struct addrinfo *ai, const char *servname, int matchonly)
1120{
1121 const char *proto;
1122 struct servent *sp;
1123 int port;
1124 int allownumeric;
1125
1126 assert(ai != NULL);
1127 /* servname may be NULL */
1128
1129 if (servname == NULL)
1130 return 0;
1131 switch (ai->ai_family) {
1132 case AF_INET:
1133#ifdef AF_INET6
1134 case AF_INET6:
1135#endif
1136 break;
1137 default:
1138 return 0;
1139 }
1140
1141 switch (ai->ai_socktype) {
1142 case SOCK_RAW:
1143 return EAI_SERVICE;
1144 case SOCK_DGRAM:
1145 case SOCK_STREAM:
1146 allownumeric = 1;
1147 break;
1148 case ANY:
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001149#if 1 /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001150 allownumeric = 1;
1151#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001152 allownumeric = 0;
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001153#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001154 break;
1155 default:
1156 return EAI_SOCKTYPE;
1157 }
1158
1159 port = str2number(servname);
1160 if (port >= 0) {
1161 if (!allownumeric)
1162 return EAI_SERVICE;
1163 if (port < 0 || port > 65535)
1164 return EAI_SERVICE;
1165 port = htons(port);
1166 } else {
1167 if (ai->ai_flags & AI_NUMERICSERV)
1168 return EAI_NONAME;
1169
1170 switch (ai->ai_socktype) {
1171 case SOCK_DGRAM:
1172 proto = "udp";
1173 break;
1174 case SOCK_STREAM:
1175 proto = "tcp";
1176 break;
1177 default:
1178 proto = NULL;
1179 break;
1180 }
1181
1182 if ((sp = getservbyname(servname, proto)) == NULL)
1183 return EAI_SERVICE;
1184 port = sp->s_port;
1185 }
1186
1187 if (!matchonly) {
1188 switch (ai->ai_family) {
1189 case AF_INET:
1190 ((struct sockaddr_in *)(void *)
1191 ai->ai_addr)->sin_port = port;
1192 break;
1193#ifdef INET6
1194 case AF_INET6:
1195 ((struct sockaddr_in6 *)(void *)
1196 ai->ai_addr)->sin6_port = port;
1197 break;
1198#endif
1199 }
1200 }
1201
1202 return 0;
1203}
1204
1205static const struct afd *
1206find_afd(int af)
1207{
1208 const struct afd *afd;
1209
1210 if (af == PF_UNSPEC)
1211 return NULL;
1212 for (afd = afdl; afd->a_af; afd++) {
1213 if (afd->a_af == af)
1214 return afd;
1215 }
1216 return NULL;
1217}
1218
1219#ifdef INET6
1220/* convert a string to a scope identifier. XXX: IPv6 specific */
1221static int
1222ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1223{
1224 u_long lscopeid;
1225 struct in6_addr *a6;
1226 char *ep;
1227
1228 assert(scope != NULL);
1229 assert(sin6 != NULL);
1230 assert(scopeid != NULL);
1231
1232 a6 = &sin6->sin6_addr;
1233
1234 /* empty scopeid portion is invalid */
1235 if (*scope == '\0')
1236 return -1;
1237
1238 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1239 /*
1240 * We currently assume a one-to-one mapping between links
1241 * and interfaces, so we simply use interface indices for
1242 * like-local scopes.
1243 */
1244 *scopeid = if_nametoindex(scope);
1245 if (*scopeid == 0)
1246 goto trynumeric;
1247 return 0;
1248 }
1249
1250 /* still unclear about literal, allow numeric only - placeholder */
1251 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1252 goto trynumeric;
1253 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1254 goto trynumeric;
1255 else
1256 goto trynumeric; /* global */
1257
1258 /* try to convert to a numeric id as a last resort */
1259 trynumeric:
1260 errno = 0;
1261 lscopeid = strtoul(scope, &ep, 10);
1262 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1263 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1264 return 0;
1265 else
1266 return -1;
1267}
1268#endif
1269
1270/* code duplicate with gethnamaddr.c */
1271
1272static const char AskedForGot[] =
1273 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1274
1275static struct addrinfo *
1276getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1277 const struct addrinfo *pai)
1278{
1279 struct addrinfo sentinel, *cur;
1280 struct addrinfo ai;
1281 const struct afd *afd;
1282 char *canonname;
1283 const HEADER *hp;
1284 const u_char *cp;
1285 int n;
1286 const u_char *eom;
1287 char *bp, *ep;
1288 int type, class, ancount, qdcount;
1289 int haveanswer, had_error;
1290 char tbuf[MAXDNAME];
1291 int (*name_ok) (const char *);
1292 char hostbuf[8*1024];
1293
1294 assert(answer != NULL);
1295 assert(qname != NULL);
1296 assert(pai != NULL);
1297
1298 memset(&sentinel, 0, sizeof(sentinel));
1299 cur = &sentinel;
1300
1301 canonname = NULL;
1302 eom = answer->buf + anslen;
1303 switch (qtype) {
1304 case T_A:
1305 case T_AAAA:
1306 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1307 name_ok = res_hnok;
1308 break;
1309 default:
1310 return NULL; /* XXX should be abort(); */
1311 }
1312 /*
1313 * find first satisfactory answer
1314 */
1315 hp = &answer->hdr;
1316 ancount = ntohs(hp->ancount);
1317 qdcount = ntohs(hp->qdcount);
1318 bp = hostbuf;
1319 ep = hostbuf + sizeof hostbuf;
1320 cp = answer->buf + HFIXEDSZ;
1321 if (qdcount != 1) {
1322 h_errno = NO_RECOVERY;
1323 return (NULL);
1324 }
1325 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1326 if ((n < 0) || !(*name_ok)(bp)) {
1327 h_errno = NO_RECOVERY;
1328 return (NULL);
1329 }
1330 cp += n + QFIXEDSZ;
1331 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1332 /* res_send() has already verified that the query name is the
1333 * same as the one we sent; this just gets the expanded name
1334 * (i.e., with the succeeding search-domain tacked on).
1335 */
1336 n = strlen(bp) + 1; /* for the \0 */
1337 if (n >= MAXHOSTNAMELEN) {
1338 h_errno = NO_RECOVERY;
1339 return (NULL);
1340 }
1341 canonname = bp;
1342 bp += n;
1343 /* The qname can be abbreviated, but h_name is now absolute. */
1344 qname = canonname;
1345 }
1346 haveanswer = 0;
1347 had_error = 0;
1348 while (ancount-- > 0 && cp < eom && !had_error) {
1349 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1350 if ((n < 0) || !(*name_ok)(bp)) {
1351 had_error++;
1352 continue;
1353 }
1354 cp += n; /* name */
1355 type = _getshort(cp);
1356 cp += INT16SZ; /* type */
1357 class = _getshort(cp);
1358 cp += INT16SZ + INT32SZ; /* class, TTL */
1359 n = _getshort(cp);
1360 cp += INT16SZ; /* len */
1361 if (class != C_IN) {
1362 /* XXX - debug? syslog? */
1363 cp += n;
1364 continue; /* XXX - had_error++ ? */
1365 }
1366 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1367 type == T_CNAME) {
1368 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1369 if ((n < 0) || !(*name_ok)(tbuf)) {
1370 had_error++;
1371 continue;
1372 }
1373 cp += n;
1374 /* Get canonical name. */
1375 n = strlen(tbuf) + 1; /* for the \0 */
1376 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1377 had_error++;
1378 continue;
1379 }
1380 strlcpy(bp, tbuf, (size_t)(ep - bp));
1381 canonname = bp;
1382 bp += n;
1383 continue;
1384 }
1385 if (qtype == T_ANY) {
1386 if (!(type == T_A || type == T_AAAA)) {
1387 cp += n;
1388 continue;
1389 }
1390 } else if (type != qtype) {
1391 if (type != T_KEY && type != T_SIG)
1392 syslog(LOG_NOTICE|LOG_AUTH,
1393 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1394 qname, p_class(C_IN), p_type(qtype),
1395 p_type(type));
1396 cp += n;
1397 continue; /* XXX - had_error++ ? */
1398 }
1399 switch (type) {
1400 case T_A:
1401 case T_AAAA:
1402 if (strcasecmp(canonname, bp) != 0) {
1403 syslog(LOG_NOTICE|LOG_AUTH,
1404 AskedForGot, canonname, bp);
1405 cp += n;
1406 continue; /* XXX - had_error++ ? */
1407 }
1408 if (type == T_A && n != INADDRSZ) {
1409 cp += n;
1410 continue;
1411 }
1412 if (type == T_AAAA && n != IN6ADDRSZ) {
1413 cp += n;
1414 continue;
1415 }
1416 if (type == T_AAAA) {
1417 struct in6_addr in6;
1418 memcpy(&in6, cp, IN6ADDRSZ);
1419 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1420 cp += n;
1421 continue;
1422 }
1423 }
1424 if (!haveanswer) {
1425 int nn;
1426
1427 canonname = bp;
1428 nn = strlen(bp) + 1; /* for the \0 */
1429 bp += nn;
1430 }
1431
1432 /* don't overwrite pai */
1433 ai = *pai;
1434 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1435 afd = find_afd(ai.ai_family);
1436 if (afd == NULL) {
1437 cp += n;
1438 continue;
1439 }
1440 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1441 if (cur->ai_next == NULL)
1442 had_error++;
1443 while (cur && cur->ai_next)
1444 cur = cur->ai_next;
1445 cp += n;
1446 break;
1447 default:
1448 abort();
1449 }
1450 if (!had_error)
1451 haveanswer++;
1452 }
1453 if (haveanswer) {
1454 if (!canonname)
1455 (void)get_canonname(pai, sentinel.ai_next, qname);
1456 else
1457 (void)get_canonname(pai, sentinel.ai_next, canonname);
1458 h_errno = NETDB_SUCCESS;
1459 return sentinel.ai_next;
1460 }
1461
1462 h_errno = NO_RECOVERY;
1463 return NULL;
1464}
1465
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001466struct addrinfo_sort_elem {
1467 struct addrinfo *ai;
1468 int has_src_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001469 sockaddr_union src_addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001470 int original_order;
1471};
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001472
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001473/*ARGSUSED*/
1474static int
1475_get_scope(const struct sockaddr *addr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001476{
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001477 if (addr->sa_family == AF_INET6) {
1478 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1479 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1480 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1481 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1482 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1483 /*
1484 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1485 * link-local scope.
1486 */
1487 return IPV6_ADDR_SCOPE_LINKLOCAL;
1488 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1489 return IPV6_ADDR_SCOPE_SITELOCAL;
1490 } else {
1491 return IPV6_ADDR_SCOPE_GLOBAL;
1492 }
1493 } else if (addr->sa_family == AF_INET) {
1494 const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1495 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001496
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001497 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1498 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1499 return IPV6_ADDR_SCOPE_LINKLOCAL;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001500 } else {
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001501 /*
1502 * According to draft-ietf-6man-rfc3484-revise-01 section 2.3,
1503 * it is best not to treat the private IPv4 ranges
1504 * (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16) as being
1505 * in a special scope, so we don't.
1506 */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001507 return IPV6_ADDR_SCOPE_GLOBAL;
1508 }
1509 } else {
1510 /*
1511 * This should never happen.
1512 * Return a scope with low priority as a last resort.
1513 */
1514 return IPV6_ADDR_SCOPE_NODELOCAL;
1515 }
1516}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001517
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001518/* These macros are modelled after the ones in <netinet/in6.h>. */
1519
1520/* RFC 4380, section 2.6 */
1521#define IN6_IS_ADDR_TEREDO(a) \
1522 ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1523
1524/* RFC 3056, section 2. */
1525#define IN6_IS_ADDR_6TO4(a) \
1526 (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1527
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001528/* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1529#define IN6_IS_ADDR_6BONE(a) \
1530 (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1531
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001532/*
1533 * Get the label for a given IPv4/IPv6 address.
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001534 * RFC 3484, section 2.1, plus changes from draft-ietf-6man-rfc3484-revise-01.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001535 */
1536
1537/*ARGSUSED*/
1538static int
1539_get_label(const struct sockaddr *addr)
1540{
1541 if (addr->sa_family == AF_INET) {
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001542 return 3;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001543 } else if (addr->sa_family == AF_INET6) {
1544 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1545 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1546 return 0;
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001547 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1548 return 1;
1549 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001550 return 3;
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001551 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1552 return 4;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001553 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1554 return 5;
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001555 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1556 return 10;
1557 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1558 return 11;
1559 } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1560 return 12;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001561 } else {
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001562 return 2;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001563 }
1564 } else {
1565 /*
1566 * This should never happen.
1567 * Return a semi-random label as a last resort.
1568 */
1569 return 1;
1570 }
1571}
1572
1573/*
1574 * Get the precedence for a given IPv4/IPv6 address.
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001575 * RFC 3484, section 2.1, plus changes from draft-ietf-6man-rfc3484-revise-01.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001576 */
1577
1578/*ARGSUSED*/
1579static int
1580_get_precedence(const struct sockaddr *addr)
1581{
1582 if (addr->sa_family == AF_INET) {
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001583 return 30;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001584 } else if (addr->sa_family == AF_INET6) {
1585 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1586 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001587 return 60;
1588 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001589 return 50;
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001590 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1591 return 30;
1592 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001593 return 20;
1594 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001595 return 10;
1596 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
1597 IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1598 IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1599 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001600 } else {
1601 return 40;
1602 }
1603 } else {
Steinar H. Gundersond3301902010-12-20 11:48:07 +01001604 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001605 }
1606}
1607
1608/*
1609 * Find number of matching initial bits between the two addresses a1 and a2.
1610 */
1611
1612/*ARGSUSED*/
1613static int
1614_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1615{
1616 const char *p1 = (const char *)a1;
1617 const char *p2 = (const char *)a2;
1618 unsigned i;
1619
1620 for (i = 0; i < sizeof(*a1); ++i) {
1621 int x, j;
1622
1623 if (p1[i] == p2[i]) {
1624 continue;
1625 }
1626 x = p1[i] ^ p2[i];
1627 for (j = 0; j < CHAR_BIT; ++j) {
1628 if (x & (1 << (CHAR_BIT - 1))) {
1629 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001630 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001631 x <<= 1;
1632 }
1633 }
1634 return sizeof(*a1) * CHAR_BIT;
1635}
1636
1637/*
1638 * Compare two source/destination address pairs.
1639 * RFC 3484, section 6.
1640 */
1641
1642/*ARGSUSED*/
1643static int
1644_rfc3484_compare(const void *ptr1, const void* ptr2)
1645{
1646 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1647 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1648 int scope_src1, scope_dst1, scope_match1;
1649 int scope_src2, scope_dst2, scope_match2;
1650 int label_src1, label_dst1, label_match1;
1651 int label_src2, label_dst2, label_match2;
1652 int precedence1, precedence2;
1653 int prefixlen1, prefixlen2;
1654
1655 /* Rule 1: Avoid unusable destinations. */
1656 if (a1->has_src_addr != a2->has_src_addr) {
1657 return a2->has_src_addr - a1->has_src_addr;
1658 }
1659
1660 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001661 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001662 scope_dst1 = _get_scope(a1->ai->ai_addr);
1663 scope_match1 = (scope_src1 == scope_dst1);
1664
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001665 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001666 scope_dst2 = _get_scope(a2->ai->ai_addr);
1667 scope_match2 = (scope_src2 == scope_dst2);
1668
1669 if (scope_match1 != scope_match2) {
1670 return scope_match2 - scope_match1;
1671 }
1672
1673 /*
1674 * Rule 3: Avoid deprecated addresses.
1675 * TODO(sesse): We don't currently have a good way of finding this.
1676 */
1677
1678 /*
1679 * Rule 4: Prefer home addresses.
1680 * TODO(sesse): We don't currently have a good way of finding this.
1681 */
1682
1683 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001684 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001685 label_dst1 = _get_label(a1->ai->ai_addr);
1686 label_match1 = (label_src1 == label_dst1);
1687
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001688 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001689 label_dst2 = _get_label(a2->ai->ai_addr);
1690 label_match2 = (label_src2 == label_dst2);
1691
1692 if (label_match1 != label_match2) {
1693 return label_match2 - label_match1;
1694 }
1695
1696 /* Rule 6: Prefer higher precedence. */
1697 precedence1 = _get_precedence(a1->ai->ai_addr);
1698 precedence2 = _get_precedence(a2->ai->ai_addr);
1699 if (precedence1 != precedence2) {
1700 return precedence2 - precedence1;
1701 }
1702
1703 /*
1704 * Rule 7: Prefer native transport.
1705 * TODO(sesse): We don't currently have a good way of finding this.
1706 */
1707
1708 /* Rule 8: Prefer smaller scope. */
1709 if (scope_dst1 != scope_dst2) {
1710 return scope_dst1 - scope_dst2;
1711 }
1712
1713 /*
1714 * Rule 9: Use longest matching prefix.
1715 * We implement this for IPv6 only, as the rules in RFC 3484 don't seem
1716 * to work very well directly applied to IPv4. (glibc uses information from
1717 * the routing table for a custom IPv4 implementation here.)
1718 */
1719 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1720 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001721 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001722 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001723 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001724 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1725 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001726 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001727 if (prefixlen1 != prefixlen2) {
1728 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001729 }
1730 }
1731
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001732 /*
1733 * Rule 10: Leave the order unchanged.
1734 * We need this since qsort() is not necessarily stable.
1735 */
1736 return a1->original_order - a2->original_order;
1737}
1738
1739/*
1740 * Find the source address that will be used if trying to connect to the given
1741 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1742 *
1743 * Returns 1 if a source address was found, 0 if the address is unreachable,
1744 * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
1745 * undefined.
1746 */
1747
1748/*ARGSUSED*/
1749static int
1750_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr)
1751{
1752 int sock;
1753 int ret;
1754 socklen_t len;
1755
1756 switch (addr->sa_family) {
1757 case AF_INET:
1758 len = sizeof(struct sockaddr_in);
1759 break;
1760 case AF_INET6:
1761 len = sizeof(struct sockaddr_in6);
1762 break;
1763 default:
1764 /* No known usable source address for non-INET families. */
1765 return 0;
1766 }
1767
1768 sock = socket(addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
1769 if (sock == -1) {
1770 if (errno == EAFNOSUPPORT) {
1771 return 0;
1772 } else {
1773 return -1;
1774 }
1775 }
1776
1777 do {
1778 ret = connect(sock, addr, len);
1779 } while (ret == -1 && errno == EINTR);
1780
1781 if (ret == -1) {
1782 close(sock);
1783 return 0;
1784 }
1785
1786 if (getsockname(sock, src_addr, &len) == -1) {
1787 close(sock);
1788 return -1;
1789 }
1790 close(sock);
1791 return 1;
1792}
1793
1794/*
1795 * Sort the linked list starting at sentinel->ai_next in RFC3484 order.
1796 * Will leave the list unchanged if an error occurs.
1797 */
1798
1799/*ARGSUSED*/
1800static void
1801_rfc3484_sort(struct addrinfo *list_sentinel)
1802{
1803 struct addrinfo *cur;
1804 int nelem = 0, i;
1805 struct addrinfo_sort_elem *elems;
1806
1807 cur = list_sentinel->ai_next;
1808 while (cur) {
1809 ++nelem;
1810 cur = cur->ai_next;
1811 }
1812
1813 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1814 if (elems == NULL) {
1815 goto error;
1816 }
1817
1818 /*
1819 * Convert the linked list to an array that also contains the candidate
1820 * source address for each destination address.
1821 */
1822 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1823 int has_src_addr;
1824 assert(cur != NULL);
1825 elems[i].ai = cur;
1826 elems[i].original_order = i;
1827
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001828 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001829 if (has_src_addr == -1) {
1830 goto error;
1831 }
1832 elems[i].has_src_addr = has_src_addr;
1833 }
1834
1835 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1836 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc3484_compare);
1837
1838 list_sentinel->ai_next = elems[0].ai;
1839 for (i = 0; i < nelem - 1; ++i) {
1840 elems[i].ai->ai_next = elems[i + 1].ai;
1841 }
1842 elems[nelem - 1].ai->ai_next = NULL;
1843
1844error:
1845 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001846}
1847
1848/*ARGSUSED*/
1849static int
1850_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1851{
1852 struct addrinfo *ai;
1853 querybuf *buf, *buf2;
1854 const char *name;
1855 const struct addrinfo *pai;
1856 struct addrinfo sentinel, *cur;
1857 struct res_target q, q2;
1858 res_state res;
1859
1860 name = va_arg(ap, char *);
1861 pai = va_arg(ap, const struct addrinfo *);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001862 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001863
1864 memset(&q, 0, sizeof(q));
1865 memset(&q2, 0, sizeof(q2));
1866 memset(&sentinel, 0, sizeof(sentinel));
1867 cur = &sentinel;
1868
1869 buf = malloc(sizeof(*buf));
1870 if (buf == NULL) {
1871 h_errno = NETDB_INTERNAL;
1872 return NS_NOTFOUND;
1873 }
1874 buf2 = malloc(sizeof(*buf2));
1875 if (buf2 == NULL) {
1876 free(buf);
1877 h_errno = NETDB_INTERNAL;
1878 return NS_NOTFOUND;
1879 }
1880
1881 switch (pai->ai_family) {
1882 case AF_UNSPEC:
1883 /* prefer IPv6 */
1884 q.name = name;
1885 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001886 q.answer = buf->buf;
1887 q.anslen = sizeof(buf->buf);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001888 /* If AI_ADDRCONFIG, lookup IPv6 only if we have connectivity */
1889 if (!(pai->ai_flags & AI_ADDRCONFIG) || _have_ipv6()) {
1890 q.qtype = T_AAAA;
1891 q.next = &q2;
1892 q2.name = name;
1893 q2.qclass = C_IN;
1894 q2.qtype = T_A;
1895 q2.answer = buf2->buf;
1896 q2.anslen = sizeof(buf2->buf);
1897 } else {
1898 q.qtype = T_A;
1899 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001900 break;
1901 case AF_INET:
1902 q.name = name;
1903 q.qclass = C_IN;
1904 q.qtype = T_A;
1905 q.answer = buf->buf;
1906 q.anslen = sizeof(buf->buf);
1907 break;
1908 case AF_INET6:
1909 q.name = name;
1910 q.qclass = C_IN;
1911 q.qtype = T_AAAA;
1912 q.answer = buf->buf;
1913 q.anslen = sizeof(buf->buf);
1914 break;
1915 default:
1916 free(buf);
1917 free(buf2);
1918 return NS_UNAVAIL;
1919 }
1920
1921 res = __res_get_state();
1922 if (res == NULL) {
1923 free(buf);
1924 free(buf2);
1925 return NS_NOTFOUND;
1926 }
1927
1928 if (res_searchN(name, &q, res) < 0) {
1929 __res_put_state(res);
1930 free(buf);
1931 free(buf2);
1932 return NS_NOTFOUND;
1933 }
1934 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1935 if (ai) {
1936 cur->ai_next = ai;
1937 while (cur && cur->ai_next)
1938 cur = cur->ai_next;
1939 }
1940 if (q.next) {
1941 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1942 if (ai)
1943 cur->ai_next = ai;
1944 }
1945 free(buf);
1946 free(buf2);
1947 if (sentinel.ai_next == NULL) {
1948 __res_put_state(res);
1949 switch (h_errno) {
1950 case HOST_NOT_FOUND:
1951 return NS_NOTFOUND;
1952 case TRY_AGAIN:
1953 return NS_TRYAGAIN;
1954 default:
1955 return NS_UNAVAIL;
1956 }
1957 }
1958
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001959 _rfc3484_sort(&sentinel);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001960
1961 __res_put_state(res);
1962
1963 *((struct addrinfo **)rv) = sentinel.ai_next;
1964 return NS_SUCCESS;
1965}
1966
1967static void
1968_sethtent(FILE **hostf)
1969{
1970
1971 if (!*hostf)
1972 *hostf = fopen(_PATH_HOSTS, "r" );
1973 else
1974 rewind(*hostf);
1975}
1976
1977static void
1978_endhtent(FILE **hostf)
1979{
1980
1981 if (*hostf) {
1982 (void) fclose(*hostf);
1983 *hostf = NULL;
1984 }
1985}
1986
1987static struct addrinfo *
1988_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
1989{
1990 char *p;
1991 char *cp, *tname, *cname;
1992 struct addrinfo hints, *res0, *res;
1993 int error;
1994 const char *addr;
1995 char hostbuf[8*1024];
1996
1997// fprintf(stderr, "_gethtent() name = '%s'\n", name);
1998 assert(name != NULL);
1999 assert(pai != NULL);
2000
2001 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
2002 return (NULL);
2003 again:
2004 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2005 return (NULL);
2006 if (*p == '#')
2007 goto again;
2008 if (!(cp = strpbrk(p, "#\n")))
2009 goto again;
2010 *cp = '\0';
2011 if (!(cp = strpbrk(p, " \t")))
2012 goto again;
2013 *cp++ = '\0';
2014 addr = p;
2015 /* if this is not something we're looking for, skip it. */
2016 cname = NULL;
2017 while (cp && *cp) {
2018 if (*cp == ' ' || *cp == '\t') {
2019 cp++;
2020 continue;
2021 }
2022 if (!cname)
2023 cname = cp;
2024 tname = cp;
2025 if ((cp = strpbrk(cp, " \t")) != NULL)
2026 *cp++ = '\0';
2027// fprintf(stderr, "\ttname = '%s'", tname);
2028 if (strcasecmp(name, tname) == 0)
2029 goto found;
2030 }
2031 goto again;
2032
2033found:
2034 hints = *pai;
2035 hints.ai_flags = AI_NUMERICHOST;
2036 error = getaddrinfo(addr, NULL, &hints, &res0);
2037 if (error)
2038 goto again;
2039 for (res = res0; res; res = res->ai_next) {
2040 /* cover it up */
2041 res->ai_flags = pai->ai_flags;
2042
2043 if (pai->ai_flags & AI_CANONNAME) {
2044 if (get_canonname(pai, res, cname) != 0) {
2045 freeaddrinfo(res0);
2046 goto again;
2047 }
2048 }
2049 }
2050 return res0;
2051}
2052
2053/*ARGSUSED*/
2054static int
2055_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2056{
2057 const char *name;
2058 const struct addrinfo *pai;
2059 struct addrinfo sentinel, *cur;
2060 struct addrinfo *p;
2061 FILE *hostf = NULL;
2062
2063 name = va_arg(ap, char *);
2064 pai = va_arg(ap, struct addrinfo *);
2065
2066// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
2067 memset(&sentinel, 0, sizeof(sentinel));
2068 cur = &sentinel;
2069
2070 _sethtent(&hostf);
2071 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2072 cur->ai_next = p;
2073 while (cur && cur->ai_next)
2074 cur = cur->ai_next;
2075 }
2076 _endhtent(&hostf);
2077
2078 *((struct addrinfo **)rv) = sentinel.ai_next;
2079 if (sentinel.ai_next == NULL)
2080 return NS_NOTFOUND;
2081 return NS_SUCCESS;
2082}
2083
2084/* resolver logic */
2085
2086/*
2087 * Formulate a normal query, send, and await answer.
2088 * Returned answer is placed in supplied buffer "answer".
2089 * Perform preliminary check of answer, returning success only
2090 * if no error is indicated and the answer count is nonzero.
2091 * Return the size of the response on success, -1 on error.
2092 * Error number is left in h_errno.
2093 *
2094 * Caller must parse answer and determine whether it answers the question.
2095 */
2096static int
2097res_queryN(const char *name, /* domain name */ struct res_target *target,
2098 res_state res)
2099{
2100 u_char buf[MAXPACKET];
2101 HEADER *hp;
2102 int n;
2103 struct res_target *t;
2104 int rcode;
2105 int ancount;
2106
2107 assert(name != NULL);
2108 /* XXX: target may be NULL??? */
2109
2110 rcode = NOERROR;
2111 ancount = 0;
2112
2113 for (t = target; t; t = t->next) {
2114 int class, type;
2115 u_char *answer;
2116 int anslen;
2117
2118 hp = (HEADER *)(void *)t->answer;
2119 hp->rcode = NOERROR; /* default */
2120
2121 /* make it easier... */
2122 class = t->qclass;
2123 type = t->qtype;
2124 answer = t->answer;
2125 anslen = t->anslen;
2126#ifdef DEBUG
2127 if (res->options & RES_DEBUG)
2128 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
2129#endif
2130
2131 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2132 buf, sizeof(buf));
2133#ifdef RES_USE_EDNS0
2134 if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
2135 n = res_nopt(res, n, buf, sizeof(buf), anslen);
2136#endif
2137 if (n <= 0) {
2138#ifdef DEBUG
2139 if (res->options & RES_DEBUG)
2140 printf(";; res_nquery: mkquery failed\n");
2141#endif
2142 h_errno = NO_RECOVERY;
2143 return n;
2144 }
2145 n = res_nsend(res, buf, n, answer, anslen);
2146#if 0
2147 if (n < 0) {
2148#ifdef DEBUG
2149 if (res->options & RES_DEBUG)
2150 printf(";; res_query: send error\n");
2151#endif
2152 h_errno = TRY_AGAIN;
2153 return n;
2154 }
2155#endif
2156
2157 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2158 rcode = hp->rcode; /* record most recent error */
2159#ifdef DEBUG
2160 if (res->options & RES_DEBUG)
2161 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2162 ntohs(hp->ancount));
2163#endif
2164 continue;
2165 }
2166
2167 ancount += ntohs(hp->ancount);
2168
2169 t->n = n;
2170 }
2171
2172 if (ancount == 0) {
2173 switch (rcode) {
2174 case NXDOMAIN:
2175 h_errno = HOST_NOT_FOUND;
2176 break;
2177 case SERVFAIL:
2178 h_errno = TRY_AGAIN;
2179 break;
2180 case NOERROR:
2181 h_errno = NO_DATA;
2182 break;
2183 case FORMERR:
2184 case NOTIMP:
2185 case REFUSED:
2186 default:
2187 h_errno = NO_RECOVERY;
2188 break;
2189 }
2190 return -1;
2191 }
2192 return ancount;
2193}
2194
2195/*
2196 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2197 * Return the size of the response on success, -1 on error.
2198 * If enabled, implement search rules until answer or unrecoverable failure
2199 * is detected. Error code, if any, is left in h_errno.
2200 */
2201static int
2202res_searchN(const char *name, struct res_target *target, res_state res)
2203{
2204 const char *cp, * const *domain;
2205 HEADER *hp;
2206 u_int dots;
2207 int trailing_dot, ret, saved_herrno;
2208 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2209
2210 assert(name != NULL);
2211 assert(target != NULL);
2212
2213 hp = (HEADER *)(void *)target->answer; /*XXX*/
2214
2215 errno = 0;
2216 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2217 dots = 0;
2218 for (cp = name; *cp; cp++)
2219 dots += (*cp == '.');
2220 trailing_dot = 0;
2221 if (cp > name && *--cp == '.')
2222 trailing_dot++;
2223
2224
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002225 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002226
2227 /*
2228 * if there aren't any dots, it could be a user-level alias
2229 */
2230 if (!dots && (cp = __hostalias(name)) != NULL) {
2231 ret = res_queryN(cp, target, res);
2232 return ret;
2233 }
2234
2235 /*
2236 * If there are dots in the name already, let's just give it a try
2237 * 'as is'. The threshold can be set with the "ndots" option.
2238 */
2239 saved_herrno = -1;
2240 if (dots >= res->ndots) {
2241 ret = res_querydomainN(name, NULL, target, res);
2242 if (ret > 0)
2243 return (ret);
2244 saved_herrno = h_errno;
2245 tried_as_is++;
2246 }
2247
2248 /*
2249 * We do at least one level of search if
2250 * - there is no dot and RES_DEFNAME is set, or
2251 * - there is at least one dot, there is no trailing dot,
2252 * and RES_DNSRCH is set.
2253 */
2254 if ((!dots && (res->options & RES_DEFNAMES)) ||
2255 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2256 int done = 0;
2257
2258 for (domain = (const char * const *)res->dnsrch;
2259 *domain && !done;
2260 domain++) {
2261
2262 ret = res_querydomainN(name, *domain, target, res);
2263 if (ret > 0)
2264 return ret;
2265
2266 /*
2267 * If no server present, give up.
2268 * If name isn't found in this domain,
2269 * keep trying higher domains in the search list
2270 * (if that's enabled).
2271 * On a NO_DATA error, keep trying, otherwise
2272 * a wildcard entry of another type could keep us
2273 * from finding this entry higher in the domain.
2274 * If we get some other error (negative answer or
2275 * server failure), then stop searching up,
2276 * but try the input name below in case it's
2277 * fully-qualified.
2278 */
2279 if (errno == ECONNREFUSED) {
2280 h_errno = TRY_AGAIN;
2281 return -1;
2282 }
2283
2284 switch (h_errno) {
2285 case NO_DATA:
2286 got_nodata++;
2287 /* FALLTHROUGH */
2288 case HOST_NOT_FOUND:
2289 /* keep trying */
2290 break;
2291 case TRY_AGAIN:
2292 if (hp->rcode == SERVFAIL) {
2293 /* try next search element, if any */
2294 got_servfail++;
2295 break;
2296 }
2297 /* FALLTHROUGH */
2298 default:
2299 /* anything else implies that we're done */
2300 done++;
2301 }
2302 /*
2303 * if we got here for some reason other than DNSRCH,
2304 * we only wanted one iteration of the loop, so stop.
2305 */
2306 if (!(res->options & RES_DNSRCH))
2307 done++;
2308 }
2309 }
2310
2311 /*
2312 * if we have not already tried the name "as is", do that now.
2313 * note that we do this regardless of how many dots were in the
2314 * name or whether it ends with a dot.
2315 */
2316 if (!tried_as_is) {
2317 ret = res_querydomainN(name, NULL, target, res);
2318 if (ret > 0)
2319 return ret;
2320 }
2321
2322 /*
2323 * if we got here, we didn't satisfy the search.
2324 * if we did an initial full query, return that query's h_errno
2325 * (note that we wouldn't be here if that query had succeeded).
2326 * else if we ever got a nodata, send that back as the reason.
2327 * else send back meaningless h_errno, that being the one from
2328 * the last DNSRCH we did.
2329 */
2330 if (saved_herrno != -1)
2331 h_errno = saved_herrno;
2332 else if (got_nodata)
2333 h_errno = NO_DATA;
2334 else if (got_servfail)
2335 h_errno = TRY_AGAIN;
2336 return -1;
2337}
2338
2339/*
2340 * Perform a call on res_query on the concatenation of name and domain,
2341 * removing a trailing dot from name if domain is NULL.
2342 */
2343static int
2344res_querydomainN(const char *name, const char *domain,
2345 struct res_target *target, res_state res)
2346{
2347 char nbuf[MAXDNAME];
2348 const char *longname = nbuf;
2349 size_t n, d;
2350
2351 assert(name != NULL);
2352 /* XXX: target may be NULL??? */
2353
2354#ifdef DEBUG
2355 if (res->options & RES_DEBUG)
2356 printf(";; res_querydomain(%s, %s)\n",
2357 name, domain?domain:"<Nil>");
2358#endif
2359 if (domain == NULL) {
2360 /*
2361 * Check for trailing '.';
2362 * copy without '.' if present.
2363 */
2364 n = strlen(name);
2365 if (n + 1 > sizeof(nbuf)) {
2366 h_errno = NO_RECOVERY;
2367 return -1;
2368 }
2369 if (n > 0 && name[--n] == '.') {
2370 strncpy(nbuf, name, n);
2371 nbuf[n] = '\0';
2372 } else
2373 longname = name;
2374 } else {
2375 n = strlen(name);
2376 d = strlen(domain);
2377 if (n + 1 + d + 1 > sizeof(nbuf)) {
2378 h_errno = NO_RECOVERY;
2379 return -1;
2380 }
2381 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2382 }
2383 return res_queryN(longname, target, res);
2384}