blob: 778f44c21022d9ee8fc2d8ae048a6cd48211a8d7 [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
1528/*
1529 * Get the label for a given IPv4/IPv6 address.
1530 * RFC 3484, section 2.1, plus Teredo added in with label 5.
1531 */
1532
1533/*ARGSUSED*/
1534static int
1535_get_label(const struct sockaddr *addr)
1536{
1537 if (addr->sa_family == AF_INET) {
1538 return 4;
1539 } else if (addr->sa_family == AF_INET6) {
1540 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1541 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1542 return 0;
1543 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1544 return 3;
1545 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1546 return 5;
1547 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1548 return 2;
1549 } else {
1550 return 1;
1551 }
1552 } else {
1553 /*
1554 * This should never happen.
1555 * Return a semi-random label as a last resort.
1556 */
1557 return 1;
1558 }
1559}
1560
1561/*
1562 * Get the precedence for a given IPv4/IPv6 address.
1563 * RFC 3484, section 2.1, plus Teredo added in with precedence 25.
1564 */
1565
1566/*ARGSUSED*/
1567static int
1568_get_precedence(const struct sockaddr *addr)
1569{
1570 if (addr->sa_family == AF_INET) {
1571 return 10;
1572 } else if (addr->sa_family == AF_INET6) {
1573 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1574 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1575 return 50;
1576 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1577 return 20;
1578 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1579 return 25;
1580 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1581 return 30;
1582 } else {
1583 return 40;
1584 }
1585 } else {
1586 return 5;
1587 }
1588}
1589
1590/*
1591 * Find number of matching initial bits between the two addresses a1 and a2.
1592 */
1593
1594/*ARGSUSED*/
1595static int
1596_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1597{
1598 const char *p1 = (const char *)a1;
1599 const char *p2 = (const char *)a2;
1600 unsigned i;
1601
1602 for (i = 0; i < sizeof(*a1); ++i) {
1603 int x, j;
1604
1605 if (p1[i] == p2[i]) {
1606 continue;
1607 }
1608 x = p1[i] ^ p2[i];
1609 for (j = 0; j < CHAR_BIT; ++j) {
1610 if (x & (1 << (CHAR_BIT - 1))) {
1611 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001612 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001613 x <<= 1;
1614 }
1615 }
1616 return sizeof(*a1) * CHAR_BIT;
1617}
1618
1619/*
1620 * Compare two source/destination address pairs.
1621 * RFC 3484, section 6.
1622 */
1623
1624/*ARGSUSED*/
1625static int
1626_rfc3484_compare(const void *ptr1, const void* ptr2)
1627{
1628 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1629 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1630 int scope_src1, scope_dst1, scope_match1;
1631 int scope_src2, scope_dst2, scope_match2;
1632 int label_src1, label_dst1, label_match1;
1633 int label_src2, label_dst2, label_match2;
1634 int precedence1, precedence2;
1635 int prefixlen1, prefixlen2;
1636
1637 /* Rule 1: Avoid unusable destinations. */
1638 if (a1->has_src_addr != a2->has_src_addr) {
1639 return a2->has_src_addr - a1->has_src_addr;
1640 }
1641
1642 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001643 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001644 scope_dst1 = _get_scope(a1->ai->ai_addr);
1645 scope_match1 = (scope_src1 == scope_dst1);
1646
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001647 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001648 scope_dst2 = _get_scope(a2->ai->ai_addr);
1649 scope_match2 = (scope_src2 == scope_dst2);
1650
1651 if (scope_match1 != scope_match2) {
1652 return scope_match2 - scope_match1;
1653 }
1654
1655 /*
1656 * Rule 3: Avoid deprecated addresses.
1657 * TODO(sesse): We don't currently have a good way of finding this.
1658 */
1659
1660 /*
1661 * Rule 4: Prefer home addresses.
1662 * TODO(sesse): We don't currently have a good way of finding this.
1663 */
1664
1665 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001666 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001667 label_dst1 = _get_label(a1->ai->ai_addr);
1668 label_match1 = (label_src1 == label_dst1);
1669
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001670 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001671 label_dst2 = _get_label(a2->ai->ai_addr);
1672 label_match2 = (label_src2 == label_dst2);
1673
1674 if (label_match1 != label_match2) {
1675 return label_match2 - label_match1;
1676 }
1677
1678 /* Rule 6: Prefer higher precedence. */
1679 precedence1 = _get_precedence(a1->ai->ai_addr);
1680 precedence2 = _get_precedence(a2->ai->ai_addr);
1681 if (precedence1 != precedence2) {
1682 return precedence2 - precedence1;
1683 }
1684
1685 /*
1686 * Rule 7: Prefer native transport.
1687 * TODO(sesse): We don't currently have a good way of finding this.
1688 */
1689
1690 /* Rule 8: Prefer smaller scope. */
1691 if (scope_dst1 != scope_dst2) {
1692 return scope_dst1 - scope_dst2;
1693 }
1694
1695 /*
1696 * Rule 9: Use longest matching prefix.
1697 * We implement this for IPv6 only, as the rules in RFC 3484 don't seem
1698 * to work very well directly applied to IPv4. (glibc uses information from
1699 * the routing table for a custom IPv4 implementation here.)
1700 */
1701 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1702 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001703 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001704 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001705 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001706 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1707 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001708 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001709 if (prefixlen1 != prefixlen2) {
1710 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001711 }
1712 }
1713
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001714 /*
1715 * Rule 10: Leave the order unchanged.
1716 * We need this since qsort() is not necessarily stable.
1717 */
1718 return a1->original_order - a2->original_order;
1719}
1720
1721/*
1722 * Find the source address that will be used if trying to connect to the given
1723 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1724 *
1725 * Returns 1 if a source address was found, 0 if the address is unreachable,
1726 * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
1727 * undefined.
1728 */
1729
1730/*ARGSUSED*/
1731static int
1732_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr)
1733{
1734 int sock;
1735 int ret;
1736 socklen_t len;
1737
1738 switch (addr->sa_family) {
1739 case AF_INET:
1740 len = sizeof(struct sockaddr_in);
1741 break;
1742 case AF_INET6:
1743 len = sizeof(struct sockaddr_in6);
1744 break;
1745 default:
1746 /* No known usable source address for non-INET families. */
1747 return 0;
1748 }
1749
1750 sock = socket(addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
1751 if (sock == -1) {
1752 if (errno == EAFNOSUPPORT) {
1753 return 0;
1754 } else {
1755 return -1;
1756 }
1757 }
1758
1759 do {
1760 ret = connect(sock, addr, len);
1761 } while (ret == -1 && errno == EINTR);
1762
1763 if (ret == -1) {
1764 close(sock);
1765 return 0;
1766 }
1767
1768 if (getsockname(sock, src_addr, &len) == -1) {
1769 close(sock);
1770 return -1;
1771 }
1772 close(sock);
1773 return 1;
1774}
1775
1776/*
1777 * Sort the linked list starting at sentinel->ai_next in RFC3484 order.
1778 * Will leave the list unchanged if an error occurs.
1779 */
1780
1781/*ARGSUSED*/
1782static void
1783_rfc3484_sort(struct addrinfo *list_sentinel)
1784{
1785 struct addrinfo *cur;
1786 int nelem = 0, i;
1787 struct addrinfo_sort_elem *elems;
1788
1789 cur = list_sentinel->ai_next;
1790 while (cur) {
1791 ++nelem;
1792 cur = cur->ai_next;
1793 }
1794
1795 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1796 if (elems == NULL) {
1797 goto error;
1798 }
1799
1800 /*
1801 * Convert the linked list to an array that also contains the candidate
1802 * source address for each destination address.
1803 */
1804 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1805 int has_src_addr;
1806 assert(cur != NULL);
1807 elems[i].ai = cur;
1808 elems[i].original_order = i;
1809
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001810 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001811 if (has_src_addr == -1) {
1812 goto error;
1813 }
1814 elems[i].has_src_addr = has_src_addr;
1815 }
1816
1817 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1818 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc3484_compare);
1819
1820 list_sentinel->ai_next = elems[0].ai;
1821 for (i = 0; i < nelem - 1; ++i) {
1822 elems[i].ai->ai_next = elems[i + 1].ai;
1823 }
1824 elems[nelem - 1].ai->ai_next = NULL;
1825
1826error:
1827 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001828}
1829
1830/*ARGSUSED*/
1831static int
1832_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1833{
1834 struct addrinfo *ai;
1835 querybuf *buf, *buf2;
1836 const char *name;
1837 const struct addrinfo *pai;
1838 struct addrinfo sentinel, *cur;
1839 struct res_target q, q2;
1840 res_state res;
1841
1842 name = va_arg(ap, char *);
1843 pai = va_arg(ap, const struct addrinfo *);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001844 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001845
1846 memset(&q, 0, sizeof(q));
1847 memset(&q2, 0, sizeof(q2));
1848 memset(&sentinel, 0, sizeof(sentinel));
1849 cur = &sentinel;
1850
1851 buf = malloc(sizeof(*buf));
1852 if (buf == NULL) {
1853 h_errno = NETDB_INTERNAL;
1854 return NS_NOTFOUND;
1855 }
1856 buf2 = malloc(sizeof(*buf2));
1857 if (buf2 == NULL) {
1858 free(buf);
1859 h_errno = NETDB_INTERNAL;
1860 return NS_NOTFOUND;
1861 }
1862
1863 switch (pai->ai_family) {
1864 case AF_UNSPEC:
1865 /* prefer IPv6 */
1866 q.name = name;
1867 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001868 q.answer = buf->buf;
1869 q.anslen = sizeof(buf->buf);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001870 /* If AI_ADDRCONFIG, lookup IPv6 only if we have connectivity */
1871 if (!(pai->ai_flags & AI_ADDRCONFIG) || _have_ipv6()) {
1872 q.qtype = T_AAAA;
1873 q.next = &q2;
1874 q2.name = name;
1875 q2.qclass = C_IN;
1876 q2.qtype = T_A;
1877 q2.answer = buf2->buf;
1878 q2.anslen = sizeof(buf2->buf);
1879 } else {
1880 q.qtype = T_A;
1881 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001882 break;
1883 case AF_INET:
1884 q.name = name;
1885 q.qclass = C_IN;
1886 q.qtype = T_A;
1887 q.answer = buf->buf;
1888 q.anslen = sizeof(buf->buf);
1889 break;
1890 case AF_INET6:
1891 q.name = name;
1892 q.qclass = C_IN;
1893 q.qtype = T_AAAA;
1894 q.answer = buf->buf;
1895 q.anslen = sizeof(buf->buf);
1896 break;
1897 default:
1898 free(buf);
1899 free(buf2);
1900 return NS_UNAVAIL;
1901 }
1902
1903 res = __res_get_state();
1904 if (res == NULL) {
1905 free(buf);
1906 free(buf2);
1907 return NS_NOTFOUND;
1908 }
1909
1910 if (res_searchN(name, &q, res) < 0) {
1911 __res_put_state(res);
1912 free(buf);
1913 free(buf2);
1914 return NS_NOTFOUND;
1915 }
1916 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1917 if (ai) {
1918 cur->ai_next = ai;
1919 while (cur && cur->ai_next)
1920 cur = cur->ai_next;
1921 }
1922 if (q.next) {
1923 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1924 if (ai)
1925 cur->ai_next = ai;
1926 }
1927 free(buf);
1928 free(buf2);
1929 if (sentinel.ai_next == NULL) {
1930 __res_put_state(res);
1931 switch (h_errno) {
1932 case HOST_NOT_FOUND:
1933 return NS_NOTFOUND;
1934 case TRY_AGAIN:
1935 return NS_TRYAGAIN;
1936 default:
1937 return NS_UNAVAIL;
1938 }
1939 }
1940
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001941 _rfc3484_sort(&sentinel);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001942
1943 __res_put_state(res);
1944
1945 *((struct addrinfo **)rv) = sentinel.ai_next;
1946 return NS_SUCCESS;
1947}
1948
1949static void
1950_sethtent(FILE **hostf)
1951{
1952
1953 if (!*hostf)
1954 *hostf = fopen(_PATH_HOSTS, "r" );
1955 else
1956 rewind(*hostf);
1957}
1958
1959static void
1960_endhtent(FILE **hostf)
1961{
1962
1963 if (*hostf) {
1964 (void) fclose(*hostf);
1965 *hostf = NULL;
1966 }
1967}
1968
1969static struct addrinfo *
1970_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
1971{
1972 char *p;
1973 char *cp, *tname, *cname;
1974 struct addrinfo hints, *res0, *res;
1975 int error;
1976 const char *addr;
1977 char hostbuf[8*1024];
1978
1979// fprintf(stderr, "_gethtent() name = '%s'\n", name);
1980 assert(name != NULL);
1981 assert(pai != NULL);
1982
1983 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
1984 return (NULL);
1985 again:
1986 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
1987 return (NULL);
1988 if (*p == '#')
1989 goto again;
1990 if (!(cp = strpbrk(p, "#\n")))
1991 goto again;
1992 *cp = '\0';
1993 if (!(cp = strpbrk(p, " \t")))
1994 goto again;
1995 *cp++ = '\0';
1996 addr = p;
1997 /* if this is not something we're looking for, skip it. */
1998 cname = NULL;
1999 while (cp && *cp) {
2000 if (*cp == ' ' || *cp == '\t') {
2001 cp++;
2002 continue;
2003 }
2004 if (!cname)
2005 cname = cp;
2006 tname = cp;
2007 if ((cp = strpbrk(cp, " \t")) != NULL)
2008 *cp++ = '\0';
2009// fprintf(stderr, "\ttname = '%s'", tname);
2010 if (strcasecmp(name, tname) == 0)
2011 goto found;
2012 }
2013 goto again;
2014
2015found:
2016 hints = *pai;
2017 hints.ai_flags = AI_NUMERICHOST;
2018 error = getaddrinfo(addr, NULL, &hints, &res0);
2019 if (error)
2020 goto again;
2021 for (res = res0; res; res = res->ai_next) {
2022 /* cover it up */
2023 res->ai_flags = pai->ai_flags;
2024
2025 if (pai->ai_flags & AI_CANONNAME) {
2026 if (get_canonname(pai, res, cname) != 0) {
2027 freeaddrinfo(res0);
2028 goto again;
2029 }
2030 }
2031 }
2032 return res0;
2033}
2034
2035/*ARGSUSED*/
2036static int
2037_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2038{
2039 const char *name;
2040 const struct addrinfo *pai;
2041 struct addrinfo sentinel, *cur;
2042 struct addrinfo *p;
2043 FILE *hostf = NULL;
2044
2045 name = va_arg(ap, char *);
2046 pai = va_arg(ap, struct addrinfo *);
2047
2048// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
2049 memset(&sentinel, 0, sizeof(sentinel));
2050 cur = &sentinel;
2051
2052 _sethtent(&hostf);
2053 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2054 cur->ai_next = p;
2055 while (cur && cur->ai_next)
2056 cur = cur->ai_next;
2057 }
2058 _endhtent(&hostf);
2059
2060 *((struct addrinfo **)rv) = sentinel.ai_next;
2061 if (sentinel.ai_next == NULL)
2062 return NS_NOTFOUND;
2063 return NS_SUCCESS;
2064}
2065
2066/* resolver logic */
2067
2068/*
2069 * Formulate a normal query, send, and await answer.
2070 * Returned answer is placed in supplied buffer "answer".
2071 * Perform preliminary check of answer, returning success only
2072 * if no error is indicated and the answer count is nonzero.
2073 * Return the size of the response on success, -1 on error.
2074 * Error number is left in h_errno.
2075 *
2076 * Caller must parse answer and determine whether it answers the question.
2077 */
2078static int
2079res_queryN(const char *name, /* domain name */ struct res_target *target,
2080 res_state res)
2081{
2082 u_char buf[MAXPACKET];
2083 HEADER *hp;
2084 int n;
2085 struct res_target *t;
2086 int rcode;
2087 int ancount;
2088
2089 assert(name != NULL);
2090 /* XXX: target may be NULL??? */
2091
2092 rcode = NOERROR;
2093 ancount = 0;
2094
2095 for (t = target; t; t = t->next) {
2096 int class, type;
2097 u_char *answer;
2098 int anslen;
2099
2100 hp = (HEADER *)(void *)t->answer;
2101 hp->rcode = NOERROR; /* default */
2102
2103 /* make it easier... */
2104 class = t->qclass;
2105 type = t->qtype;
2106 answer = t->answer;
2107 anslen = t->anslen;
2108#ifdef DEBUG
2109 if (res->options & RES_DEBUG)
2110 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
2111#endif
2112
2113 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2114 buf, sizeof(buf));
2115#ifdef RES_USE_EDNS0
2116 if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
2117 n = res_nopt(res, n, buf, sizeof(buf), anslen);
2118#endif
2119 if (n <= 0) {
2120#ifdef DEBUG
2121 if (res->options & RES_DEBUG)
2122 printf(";; res_nquery: mkquery failed\n");
2123#endif
2124 h_errno = NO_RECOVERY;
2125 return n;
2126 }
2127 n = res_nsend(res, buf, n, answer, anslen);
2128#if 0
2129 if (n < 0) {
2130#ifdef DEBUG
2131 if (res->options & RES_DEBUG)
2132 printf(";; res_query: send error\n");
2133#endif
2134 h_errno = TRY_AGAIN;
2135 return n;
2136 }
2137#endif
2138
2139 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2140 rcode = hp->rcode; /* record most recent error */
2141#ifdef DEBUG
2142 if (res->options & RES_DEBUG)
2143 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2144 ntohs(hp->ancount));
2145#endif
2146 continue;
2147 }
2148
2149 ancount += ntohs(hp->ancount);
2150
2151 t->n = n;
2152 }
2153
2154 if (ancount == 0) {
2155 switch (rcode) {
2156 case NXDOMAIN:
2157 h_errno = HOST_NOT_FOUND;
2158 break;
2159 case SERVFAIL:
2160 h_errno = TRY_AGAIN;
2161 break;
2162 case NOERROR:
2163 h_errno = NO_DATA;
2164 break;
2165 case FORMERR:
2166 case NOTIMP:
2167 case REFUSED:
2168 default:
2169 h_errno = NO_RECOVERY;
2170 break;
2171 }
2172 return -1;
2173 }
2174 return ancount;
2175}
2176
2177/*
2178 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2179 * Return the size of the response on success, -1 on error.
2180 * If enabled, implement search rules until answer or unrecoverable failure
2181 * is detected. Error code, if any, is left in h_errno.
2182 */
2183static int
2184res_searchN(const char *name, struct res_target *target, res_state res)
2185{
2186 const char *cp, * const *domain;
2187 HEADER *hp;
2188 u_int dots;
2189 int trailing_dot, ret, saved_herrno;
2190 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2191
2192 assert(name != NULL);
2193 assert(target != NULL);
2194
2195 hp = (HEADER *)(void *)target->answer; /*XXX*/
2196
2197 errno = 0;
2198 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2199 dots = 0;
2200 for (cp = name; *cp; cp++)
2201 dots += (*cp == '.');
2202 trailing_dot = 0;
2203 if (cp > name && *--cp == '.')
2204 trailing_dot++;
2205
2206
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002207 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002208
2209 /*
2210 * if there aren't any dots, it could be a user-level alias
2211 */
2212 if (!dots && (cp = __hostalias(name)) != NULL) {
2213 ret = res_queryN(cp, target, res);
2214 return ret;
2215 }
2216
2217 /*
2218 * If there are dots in the name already, let's just give it a try
2219 * 'as is'. The threshold can be set with the "ndots" option.
2220 */
2221 saved_herrno = -1;
2222 if (dots >= res->ndots) {
2223 ret = res_querydomainN(name, NULL, target, res);
2224 if (ret > 0)
2225 return (ret);
2226 saved_herrno = h_errno;
2227 tried_as_is++;
2228 }
2229
2230 /*
2231 * We do at least one level of search if
2232 * - there is no dot and RES_DEFNAME is set, or
2233 * - there is at least one dot, there is no trailing dot,
2234 * and RES_DNSRCH is set.
2235 */
2236 if ((!dots && (res->options & RES_DEFNAMES)) ||
2237 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2238 int done = 0;
2239
2240 for (domain = (const char * const *)res->dnsrch;
2241 *domain && !done;
2242 domain++) {
2243
2244 ret = res_querydomainN(name, *domain, target, res);
2245 if (ret > 0)
2246 return ret;
2247
2248 /*
2249 * If no server present, give up.
2250 * If name isn't found in this domain,
2251 * keep trying higher domains in the search list
2252 * (if that's enabled).
2253 * On a NO_DATA error, keep trying, otherwise
2254 * a wildcard entry of another type could keep us
2255 * from finding this entry higher in the domain.
2256 * If we get some other error (negative answer or
2257 * server failure), then stop searching up,
2258 * but try the input name below in case it's
2259 * fully-qualified.
2260 */
2261 if (errno == ECONNREFUSED) {
2262 h_errno = TRY_AGAIN;
2263 return -1;
2264 }
2265
2266 switch (h_errno) {
2267 case NO_DATA:
2268 got_nodata++;
2269 /* FALLTHROUGH */
2270 case HOST_NOT_FOUND:
2271 /* keep trying */
2272 break;
2273 case TRY_AGAIN:
2274 if (hp->rcode == SERVFAIL) {
2275 /* try next search element, if any */
2276 got_servfail++;
2277 break;
2278 }
2279 /* FALLTHROUGH */
2280 default:
2281 /* anything else implies that we're done */
2282 done++;
2283 }
2284 /*
2285 * if we got here for some reason other than DNSRCH,
2286 * we only wanted one iteration of the loop, so stop.
2287 */
2288 if (!(res->options & RES_DNSRCH))
2289 done++;
2290 }
2291 }
2292
2293 /*
2294 * if we have not already tried the name "as is", do that now.
2295 * note that we do this regardless of how many dots were in the
2296 * name or whether it ends with a dot.
2297 */
2298 if (!tried_as_is) {
2299 ret = res_querydomainN(name, NULL, target, res);
2300 if (ret > 0)
2301 return ret;
2302 }
2303
2304 /*
2305 * if we got here, we didn't satisfy the search.
2306 * if we did an initial full query, return that query's h_errno
2307 * (note that we wouldn't be here if that query had succeeded).
2308 * else if we ever got a nodata, send that back as the reason.
2309 * else send back meaningless h_errno, that being the one from
2310 * the last DNSRCH we did.
2311 */
2312 if (saved_herrno != -1)
2313 h_errno = saved_herrno;
2314 else if (got_nodata)
2315 h_errno = NO_DATA;
2316 else if (got_servfail)
2317 h_errno = TRY_AGAIN;
2318 return -1;
2319}
2320
2321/*
2322 * Perform a call on res_query on the concatenation of name and domain,
2323 * removing a trailing dot from name if domain is NULL.
2324 */
2325static int
2326res_querydomainN(const char *name, const char *domain,
2327 struct res_target *target, res_state res)
2328{
2329 char nbuf[MAXDNAME];
2330 const char *longname = nbuf;
2331 size_t n, d;
2332
2333 assert(name != NULL);
2334 /* XXX: target may be NULL??? */
2335
2336#ifdef DEBUG
2337 if (res->options & RES_DEBUG)
2338 printf(";; res_querydomain(%s, %s)\n",
2339 name, domain?domain:"<Nil>");
2340#endif
2341 if (domain == NULL) {
2342 /*
2343 * Check for trailing '.';
2344 * copy without '.' if present.
2345 */
2346 n = strlen(name);
2347 if (n + 1 > sizeof(nbuf)) {
2348 h_errno = NO_RECOVERY;
2349 return -1;
2350 }
2351 if (n > 0 && name[--n] == '.') {
2352 strncpy(nbuf, name, n);
2353 nbuf[n] = '\0';
2354 } else
2355 longname = name;
2356 } else {
2357 n = strlen(name);
2358 d = strlen(domain);
2359 if (n + 1 + d + 1 > sizeof(nbuf)) {
2360 h_errno = NO_RECOVERY;
2361 return -1;
2362 }
2363 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2364 }
2365 return res_queryN(longname, target, res);
2366}