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