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