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