blob: 895662ed0302cc67149d32f4c68cc256ede45d63 [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
80#include <sys/cdefs.h>
81#include <sys/types.h>
82#include <sys/param.h>
83#include <sys/socket.h>
84#include <net/if.h>
85#include <netinet/in.h>
86#include <arpa/inet.h>
87#include "arpa_nameser.h"
88#include <assert.h>
89#include <ctype.h>
90#include <errno.h>
91#include <netdb.h>
92#include "resolv_private.h"
93#include <stddef.h>
94#include <stdio.h>
95#include <stdlib.h>
96#include <string.h>
97#include <unistd.h>
98
99#include <syslog.h>
100#include <stdarg.h>
101#include "nsswitch.h"
102
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -0700103typedef union sockaddr_union {
104 struct sockaddr generic;
105 struct sockaddr_in in;
106 struct sockaddr_in6 in6;
107} sockaddr_union;
108
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800109#define SUCCESS 0
110#define ANY 0
111#define YES 1
112#define NO 0
113
114static const char in_addrany[] = { 0, 0, 0, 0 };
115static const char in_loopback[] = { 127, 0, 0, 1 };
116#ifdef INET6
117static const char in6_addrany[] = {
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
119};
120static const char in6_loopback[] = {
121 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
122};
123#endif
124
125static const struct afd {
126 int a_af;
127 int a_addrlen;
128 int a_socklen;
129 int a_off;
130 const char *a_addrany;
131 const char *a_loopback;
132 int a_scoped;
133} afdl [] = {
134#ifdef INET6
135 {PF_INET6, sizeof(struct in6_addr),
136 sizeof(struct sockaddr_in6),
137 offsetof(struct sockaddr_in6, sin6_addr),
138 in6_addrany, in6_loopback, 1},
139#endif
140 {PF_INET, sizeof(struct in_addr),
141 sizeof(struct sockaddr_in),
142 offsetof(struct sockaddr_in, sin_addr),
143 in_addrany, in_loopback, 0},
144 {0, 0, 0, 0, NULL, NULL, 0},
145};
146
147struct explore {
148 int e_af;
149 int e_socktype;
150 int e_protocol;
151 const char *e_protostr;
152 int e_wild;
153#define WILD_AF(ex) ((ex)->e_wild & 0x01)
154#define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
155#define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
156};
157
158static const struct explore explore[] = {
159#if 0
160 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
161#endif
162#ifdef INET6
163 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
164 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
165 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
166#endif
167 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
168 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
169 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
170 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
171 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
172 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
173 { -1, 0, 0, NULL, 0 },
174};
175
176#ifdef INET6
177#define PTON_MAX 16
178#else
179#define PTON_MAX 4
180#endif
181
182static const ns_src default_dns_files[] = {
183 { NSSRC_FILES, NS_SUCCESS },
184 { NSSRC_DNS, NS_SUCCESS },
185 { 0, 0 }
186};
187
188#define MAXPACKET (64*1024)
189
190typedef union {
191 HEADER hdr;
192 u_char buf[MAXPACKET];
193} querybuf;
194
195struct res_target {
196 struct res_target *next;
197 const char *name; /* domain name */
198 int qclass, qtype; /* class and type of query */
199 u_char *answer; /* buffer to put answer */
200 int anslen; /* size of answer buffer */
201 int n; /* result length */
202};
203
204static int str2number(const char *);
205static int explore_fqdn(const struct addrinfo *, const char *,
206 const char *, struct addrinfo **);
207static int explore_null(const struct addrinfo *,
208 const char *, struct addrinfo **);
209static int explore_numeric(const struct addrinfo *, const char *,
210 const char *, struct addrinfo **, const char *);
211static int explore_numeric_scope(const struct addrinfo *, const char *,
212 const char *, struct addrinfo **);
213static int get_canonname(const struct addrinfo *,
214 struct addrinfo *, const char *);
215static struct addrinfo *get_ai(const struct addrinfo *,
216 const struct afd *, const char *);
217static int get_portmatch(const struct addrinfo *, const char *);
218static int get_port(const struct addrinfo *, const char *, int);
219static const struct afd *find_afd(int);
220#ifdef INET6
221static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
222#endif
223
224static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
225 const struct addrinfo *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800226static int _dns_getaddrinfo(void *, void *, va_list);
227static void _sethtent(FILE **);
228static void _endhtent(FILE **);
229static struct addrinfo *_gethtent(FILE **, const char *,
230 const struct addrinfo *);
231static int _files_getaddrinfo(void *, void *, va_list);
232
233static int res_queryN(const char *, struct res_target *, res_state);
234static int res_searchN(const char *, struct res_target *, res_state);
235static int res_querydomainN(const char *, const char *,
236 struct res_target *, res_state);
237
238static const char * const ai_errlist[] = {
239 "Success",
240 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
241 "Temporary failure in name resolution", /* EAI_AGAIN */
242 "Invalid value for ai_flags", /* EAI_BADFLAGS */
243 "Non-recoverable failure in name resolution", /* EAI_FAIL */
244 "ai_family not supported", /* EAI_FAMILY */
245 "Memory allocation failure", /* EAI_MEMORY */
246 "No address associated with hostname", /* EAI_NODATA */
247 "hostname nor servname provided, or not known", /* EAI_NONAME */
248 "servname not supported for ai_socktype", /* EAI_SERVICE */
249 "ai_socktype not supported", /* EAI_SOCKTYPE */
250 "System error returned in errno", /* EAI_SYSTEM */
251 "Invalid value for hints", /* EAI_BADHINTS */
252 "Resolved protocol is unknown", /* EAI_PROTOCOL */
253 "Argument buffer overflow", /* EAI_OVERFLOW */
254 "Unknown error", /* EAI_MAX */
255};
256
257/* XXX macros that make external reference is BAD. */
258
259#define GET_AI(ai, afd, addr) \
260do { \
261 /* external reference: pai, error, and label free */ \
262 (ai) = get_ai(pai, (afd), (addr)); \
263 if ((ai) == NULL) { \
264 error = EAI_MEMORY; \
265 goto free; \
266 } \
267} while (/*CONSTCOND*/0)
268
269#define GET_PORT(ai, serv) \
270do { \
271 /* external reference: error and label free */ \
272 error = get_port((ai), (serv), 0); \
273 if (error != 0) \
274 goto free; \
275} while (/*CONSTCOND*/0)
276
277#define GET_CANONNAME(ai, str) \
278do { \
279 /* external reference: pai, error and label free */ \
280 error = get_canonname(pai, (ai), (str)); \
281 if (error != 0) \
282 goto free; \
283} while (/*CONSTCOND*/0)
284
285#define ERR(err) \
286do { \
287 /* external reference: error, and label bad */ \
288 error = (err); \
289 goto bad; \
290 /*NOTREACHED*/ \
291} while (/*CONSTCOND*/0)
292
293#define MATCH_FAMILY(x, y, w) \
294 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || \
295 (y) == PF_UNSPEC)))
296#define MATCH(x, y, w) \
297 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
298
299const char *
300gai_strerror(int ecode)
301{
302 if (ecode < 0 || ecode > EAI_MAX)
303 ecode = EAI_MAX;
304 return ai_errlist[ecode];
305}
306
307void
308freeaddrinfo(struct addrinfo *ai)
309{
310 struct addrinfo *next;
311
312 assert(ai != NULL);
313
314 do {
315 next = ai->ai_next;
316 if (ai->ai_canonname)
317 free(ai->ai_canonname);
318 /* no need to free(ai->ai_addr) */
319 free(ai);
320 ai = next;
321 } while (ai);
322}
323
324static int
325str2number(const char *p)
326{
327 char *ep;
328 unsigned long v;
329
330 assert(p != NULL);
331
332 if (*p == '\0')
333 return -1;
334 ep = NULL;
335 errno = 0;
336 v = strtoul(p, &ep, 10);
337 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
338 return v;
339 else
340 return -1;
341}
342
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800343/*
344 * Connect a UDP socket to a given unicast address. This will cause no network
345 * traffic, but will fail fast if the system has no or limited reachability to
346 * the destination (e.g., no IPv4 address, no IPv6 default route, ...).
347 */
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700348static int
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800349_test_connect(int pf, struct sockaddr *addr, size_t addrlen) {
350 int s = socket(pf, SOCK_DGRAM, IPPROTO_UDP);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700351 if (s < 0)
352 return 0;
353 int ret;
354 do {
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800355 ret = connect(s, addr, addrlen);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700356 } while (ret < 0 && errno == EINTR);
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800357 int success = (ret == 0);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700358 do {
359 ret = close(s);
360 } while (ret < 0 && errno == EINTR);
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800361 return success;
362}
363
364/*
365 * The following functions determine whether IPv4 or IPv6 connectivity is
366 * available in order to implement AI_ADDRCONFIG.
367 *
368 * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
369 * available, but whether addresses of the specified family are "configured
370 * on the local system". However, bionic doesn't currently support getifaddrs,
371 * so checking for connectivity is the next best thing.
372 */
373static int
374_have_ipv6() {
375 static const struct sockaddr_in6 sin6_test = {
376 .sin6_family = AF_INET6,
377 .sin6_addr.s6_addr = { // 2000::
378 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
379 };
380 sockaddr_union addr = { .in6 = sin6_test };
381 return _test_connect(PF_INET6, &addr.generic, sizeof(addr.in6));
382}
383
384static int
385_have_ipv4() {
386 static const struct sockaddr_in sin_test = {
387 .sin_family = AF_INET,
388 .sin_addr.s_addr = __constant_htonl(0x08080808L) // 8.8.8.8
389 };
390 sockaddr_union addr = { .in = sin_test };
391 return _test_connect(PF_INET, &addr.generic, sizeof(addr.in));
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700392}
393
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800394int
395getaddrinfo(const char *hostname, const char *servname,
396 const struct addrinfo *hints, struct addrinfo **res)
397{
398 struct addrinfo sentinel;
399 struct addrinfo *cur;
400 int error = 0;
401 struct addrinfo ai;
402 struct addrinfo ai0;
403 struct addrinfo *pai;
404 const struct explore *ex;
405
406 /* hostname is allowed to be NULL */
407 /* servname is allowed to be NULL */
408 /* hints is allowed to be NULL */
409 assert(res != NULL);
410
411 memset(&sentinel, 0, sizeof(sentinel));
412 cur = &sentinel;
413 pai = &ai;
414 pai->ai_flags = 0;
415 pai->ai_family = PF_UNSPEC;
416 pai->ai_socktype = ANY;
417 pai->ai_protocol = ANY;
418 pai->ai_addrlen = 0;
419 pai->ai_canonname = NULL;
420 pai->ai_addr = NULL;
421 pai->ai_next = NULL;
422
423 if (hostname == NULL && servname == NULL)
424 return EAI_NONAME;
425 if (hints) {
426 /* error check for hints */
427 if (hints->ai_addrlen || hints->ai_canonname ||
428 hints->ai_addr || hints->ai_next)
429 ERR(EAI_BADHINTS); /* xxx */
430 if (hints->ai_flags & ~AI_MASK)
431 ERR(EAI_BADFLAGS);
432 switch (hints->ai_family) {
433 case PF_UNSPEC:
434 case PF_INET:
435#ifdef INET6
436 case PF_INET6:
437#endif
438 break;
439 default:
440 ERR(EAI_FAMILY);
441 }
442 memcpy(pai, hints, sizeof(*pai));
443
444 /*
445 * if both socktype/protocol are specified, check if they
446 * are meaningful combination.
447 */
448 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
449 for (ex = explore; ex->e_af >= 0; ex++) {
450 if (pai->ai_family != ex->e_af)
451 continue;
452 if (ex->e_socktype == ANY)
453 continue;
454 if (ex->e_protocol == ANY)
455 continue;
456 if (pai->ai_socktype == ex->e_socktype
457 && pai->ai_protocol != ex->e_protocol) {
458 ERR(EAI_BADHINTS);
459 }
460 }
461 }
462 }
463
464 /*
465 * check for special cases. (1) numeric servname is disallowed if
466 * socktype/protocol are left unspecified. (2) servname is disallowed
467 * for raw and other inet{,6} sockets.
468 */
469 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
470#ifdef PF_INET6
471 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
472#endif
473 ) {
474 ai0 = *pai; /* backup *pai */
475
476 if (pai->ai_family == PF_UNSPEC) {
477#ifdef PF_INET6
478 pai->ai_family = PF_INET6;
479#else
480 pai->ai_family = PF_INET;
481#endif
482 }
483 error = get_portmatch(pai, servname);
484 if (error)
485 ERR(error);
486
487 *pai = ai0;
488 }
489
490 ai0 = *pai;
491
492 /* NULL hostname, or numeric hostname */
493 for (ex = explore; ex->e_af >= 0; ex++) {
494 *pai = ai0;
495
496 /* PF_UNSPEC entries are prepared for DNS queries only */
497 if (ex->e_af == PF_UNSPEC)
498 continue;
499
500 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
501 continue;
502 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
503 continue;
504 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
505 continue;
506
507 if (pai->ai_family == PF_UNSPEC)
508 pai->ai_family = ex->e_af;
509 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
510 pai->ai_socktype = ex->e_socktype;
511 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
512 pai->ai_protocol = ex->e_protocol;
513
514 if (hostname == NULL)
515 error = explore_null(pai, servname, &cur->ai_next);
516 else
517 error = explore_numeric_scope(pai, hostname, servname,
518 &cur->ai_next);
519
520 if (error)
521 goto free;
522
523 while (cur->ai_next)
524 cur = cur->ai_next;
525 }
526
527 /*
528 * XXX
529 * If numeric representation of AF1 can be interpreted as FQDN
530 * representation of AF2, we need to think again about the code below.
531 */
532 if (sentinel.ai_next)
533 goto good;
534
535 if (hostname == NULL)
536 ERR(EAI_NODATA);
537 if (pai->ai_flags & AI_NUMERICHOST)
538 ERR(EAI_NONAME);
539
540 /*
541 * hostname as alphabetical name.
542 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
543 * outer loop by AFs.
544 */
545 for (ex = explore; ex->e_af >= 0; ex++) {
546 *pai = ai0;
547
548 /* require exact match for family field */
549 if (pai->ai_family != ex->e_af)
550 continue;
551
552 if (!MATCH(pai->ai_socktype, ex->e_socktype,
553 WILD_SOCKTYPE(ex))) {
554 continue;
555 }
556 if (!MATCH(pai->ai_protocol, ex->e_protocol,
557 WILD_PROTOCOL(ex))) {
558 continue;
559 }
560
561 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
562 pai->ai_socktype = ex->e_socktype;
563 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
564 pai->ai_protocol = ex->e_protocol;
565
566 error = explore_fqdn(pai, hostname, servname,
567 &cur->ai_next);
568
569 while (cur && cur->ai_next)
570 cur = cur->ai_next;
571 }
572
573 /* XXX */
574 if (sentinel.ai_next)
575 error = 0;
576
577 if (error)
578 goto free;
579 if (error == 0) {
580 if (sentinel.ai_next) {
581 good:
582 *res = sentinel.ai_next;
583 return SUCCESS;
584 } else
585 error = EAI_FAIL;
586 }
587 free:
588 bad:
589 if (sentinel.ai_next)
590 freeaddrinfo(sentinel.ai_next);
591 *res = NULL;
592 return error;
593}
594
595/*
596 * FQDN hostname, DNS lookup
597 */
598static int
599explore_fqdn(const struct addrinfo *pai, const char *hostname,
600 const char *servname, struct addrinfo **res)
601{
602 struct addrinfo *result;
603 struct addrinfo *cur;
604 int error = 0;
605 static const ns_dtab dtab[] = {
606 NS_FILES_CB(_files_getaddrinfo, NULL)
607 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
608 NS_NIS_CB(_yp_getaddrinfo, NULL)
609 { 0, 0, 0 }
610 };
611
612 assert(pai != NULL);
613 /* hostname may be NULL */
614 /* servname may be NULL */
615 assert(res != NULL);
616
617 result = NULL;
618
619 /*
620 * if the servname does not match socktype/protocol, ignore it.
621 */
622 if (get_portmatch(pai, servname) != 0)
623 return 0;
624
625 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
626 default_dns_files, hostname, pai)) {
627 case NS_TRYAGAIN:
628 error = EAI_AGAIN;
629 goto free;
630 case NS_UNAVAIL:
631 error = EAI_FAIL;
632 goto free;
633 case NS_NOTFOUND:
634 error = EAI_NODATA;
635 goto free;
636 case NS_SUCCESS:
637 error = 0;
638 for (cur = result; cur; cur = cur->ai_next) {
639 GET_PORT(cur, servname);
640 /* canonname should be filled already */
641 }
642 break;
643 }
644
645 *res = result;
646
647 return 0;
648
649free:
650 if (result)
651 freeaddrinfo(result);
652 return error;
653}
654
655/*
656 * hostname == NULL.
657 * passive socket -> anyaddr (0.0.0.0 or ::)
658 * non-passive socket -> localhost (127.0.0.1 or ::1)
659 */
660static int
661explore_null(const struct addrinfo *pai, const char *servname,
662 struct addrinfo **res)
663{
664 int s;
665 const struct afd *afd;
666 struct addrinfo *cur;
667 struct addrinfo sentinel;
668 int error;
669
670 assert(pai != NULL);
671 /* servname may be NULL */
672 assert(res != NULL);
673
674 *res = NULL;
675 sentinel.ai_next = NULL;
676 cur = &sentinel;
677
678 /*
679 * filter out AFs that are not supported by the kernel
680 * XXX errno?
681 */
682 s = socket(pai->ai_family, SOCK_DGRAM, 0);
683 if (s < 0) {
684 if (errno != EMFILE)
685 return 0;
686 } else
687 close(s);
688
689 /*
690 * if the servname does not match socktype/protocol, ignore it.
691 */
692 if (get_portmatch(pai, servname) != 0)
693 return 0;
694
695 afd = find_afd(pai->ai_family);
696 if (afd == NULL)
697 return 0;
698
699 if (pai->ai_flags & AI_PASSIVE) {
700 GET_AI(cur->ai_next, afd, afd->a_addrany);
701 /* xxx meaningless?
702 * GET_CANONNAME(cur->ai_next, "anyaddr");
703 */
704 GET_PORT(cur->ai_next, servname);
705 } else {
706 GET_AI(cur->ai_next, afd, afd->a_loopback);
707 /* xxx meaningless?
708 * GET_CANONNAME(cur->ai_next, "localhost");
709 */
710 GET_PORT(cur->ai_next, servname);
711 }
712 cur = cur->ai_next;
713
714 *res = sentinel.ai_next;
715 return 0;
716
717free:
718 if (sentinel.ai_next)
719 freeaddrinfo(sentinel.ai_next);
720 return error;
721}
722
723/*
724 * numeric hostname
725 */
726static int
727explore_numeric(const struct addrinfo *pai, const char *hostname,
728 const char *servname, struct addrinfo **res, const char *canonname)
729{
730 const struct afd *afd;
731 struct addrinfo *cur;
732 struct addrinfo sentinel;
733 int error;
734 char pton[PTON_MAX];
735
736 assert(pai != NULL);
737 /* hostname may be NULL */
738 /* servname may be NULL */
739 assert(res != NULL);
740
741 *res = NULL;
742 sentinel.ai_next = NULL;
743 cur = &sentinel;
744
745 /*
746 * if the servname does not match socktype/protocol, ignore it.
747 */
748 if (get_portmatch(pai, servname) != 0)
749 return 0;
750
751 afd = find_afd(pai->ai_family);
752 if (afd == NULL)
753 return 0;
754
755 switch (afd->a_af) {
756#if 0 /*X/Open spec*/
757 case AF_INET:
758 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
759 if (pai->ai_family == afd->a_af ||
760 pai->ai_family == PF_UNSPEC /*?*/) {
761 GET_AI(cur->ai_next, afd, pton);
762 GET_PORT(cur->ai_next, servname);
763 if ((pai->ai_flags & AI_CANONNAME)) {
764 /*
765 * Set the numeric address itself as
766 * the canonical name, based on a
767 * clarification in rfc2553bis-03.
768 */
769 GET_CANONNAME(cur->ai_next, canonname);
770 }
771 while (cur && cur->ai_next)
772 cur = cur->ai_next;
773 } else
774 ERR(EAI_FAMILY); /*xxx*/
775 }
776 break;
777#endif
778 default:
779 if (inet_pton(afd->a_af, hostname, pton) == 1) {
780 if (pai->ai_family == afd->a_af ||
781 pai->ai_family == PF_UNSPEC /*?*/) {
782 GET_AI(cur->ai_next, afd, pton);
783 GET_PORT(cur->ai_next, servname);
784 if ((pai->ai_flags & AI_CANONNAME)) {
785 /*
786 * Set the numeric address itself as
787 * the canonical name, based on a
788 * clarification in rfc2553bis-03.
789 */
790 GET_CANONNAME(cur->ai_next, canonname);
791 }
792 while (cur->ai_next)
793 cur = cur->ai_next;
794 } else
795 ERR(EAI_FAMILY); /*xxx*/
796 }
797 break;
798 }
799
800 *res = sentinel.ai_next;
801 return 0;
802
803free:
804bad:
805 if (sentinel.ai_next)
806 freeaddrinfo(sentinel.ai_next);
807 return error;
808}
809
810/*
811 * numeric hostname with scope
812 */
813static int
814explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
815 const char *servname, struct addrinfo **res)
816{
817#if !defined(SCOPE_DELIMITER) || !defined(INET6)
818 return explore_numeric(pai, hostname, servname, res, hostname);
819#else
820 const struct afd *afd;
821 struct addrinfo *cur;
822 int error;
823 char *cp, *hostname2 = NULL, *scope, *addr;
824 struct sockaddr_in6 *sin6;
825
826 assert(pai != NULL);
827 /* hostname may be NULL */
828 /* servname may be NULL */
829 assert(res != NULL);
830
831 /*
832 * if the servname does not match socktype/protocol, ignore it.
833 */
834 if (get_portmatch(pai, servname) != 0)
835 return 0;
836
837 afd = find_afd(pai->ai_family);
838 if (afd == NULL)
839 return 0;
840
841 if (!afd->a_scoped)
842 return explore_numeric(pai, hostname, servname, res, hostname);
843
844 cp = strchr(hostname, SCOPE_DELIMITER);
845 if (cp == NULL)
846 return explore_numeric(pai, hostname, servname, res, hostname);
847
848 /*
849 * Handle special case of <scoped_address><delimiter><scope id>
850 */
851 hostname2 = strdup(hostname);
852 if (hostname2 == NULL)
853 return EAI_MEMORY;
854 /* terminate at the delimiter */
855 hostname2[cp - hostname] = '\0';
856 addr = hostname2;
857 scope = cp + 1;
858
859 error = explore_numeric(pai, addr, servname, res, hostname);
860 if (error == 0) {
861 u_int32_t scopeid;
862
863 for (cur = *res; cur; cur = cur->ai_next) {
864 if (cur->ai_family != AF_INET6)
865 continue;
866 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
867 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
868 free(hostname2);
869 return(EAI_NODATA); /* XXX: is return OK? */
870 }
871 sin6->sin6_scope_id = scopeid;
872 }
873 }
874
875 free(hostname2);
876
877 return error;
878#endif
879}
880
881static int
882get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
883{
884
885 assert(pai != NULL);
886 assert(ai != NULL);
887 assert(str != NULL);
888
889 if ((pai->ai_flags & AI_CANONNAME) != 0) {
890 ai->ai_canonname = strdup(str);
891 if (ai->ai_canonname == NULL)
892 return EAI_MEMORY;
893 }
894 return 0;
895}
896
897static struct addrinfo *
898get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
899{
900 char *p;
901 struct addrinfo *ai;
902
903 assert(pai != NULL);
904 assert(afd != NULL);
905 assert(addr != NULL);
906
907 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
908 + (afd->a_socklen));
909 if (ai == NULL)
910 return NULL;
911
912 memcpy(ai, pai, sizeof(struct addrinfo));
913 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
914 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
915
916#ifdef HAVE_SA_LEN
917 ai->ai_addr->sa_len = afd->a_socklen;
918#endif
919
920 ai->ai_addrlen = afd->a_socklen;
921#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
922 ai->__ai_pad0 = 0;
923#endif
924 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
925 p = (char *)(void *)(ai->ai_addr);
926 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
927 return ai;
928}
929
930static int
931get_portmatch(const struct addrinfo *ai, const char *servname)
932{
933
934 assert(ai != NULL);
935 /* servname may be NULL */
936
937 return get_port(ai, servname, 1);
938}
939
940static int
941get_port(const struct addrinfo *ai, const char *servname, int matchonly)
942{
943 const char *proto;
944 struct servent *sp;
945 int port;
946 int allownumeric;
947
948 assert(ai != NULL);
949 /* servname may be NULL */
950
951 if (servname == NULL)
952 return 0;
953 switch (ai->ai_family) {
954 case AF_INET:
955#ifdef AF_INET6
956 case AF_INET6:
957#endif
958 break;
959 default:
960 return 0;
961 }
962
963 switch (ai->ai_socktype) {
964 case SOCK_RAW:
965 return EAI_SERVICE;
966 case SOCK_DGRAM:
967 case SOCK_STREAM:
968 allownumeric = 1;
969 break;
970 case ANY:
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +0100971#if 1 /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
David 'Digit' Turner5e563702009-05-05 15:50:24 +0200972 allownumeric = 1;
973#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800974 allownumeric = 0;
David 'Digit' Turner5e563702009-05-05 15:50:24 +0200975#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800976 break;
977 default:
978 return EAI_SOCKTYPE;
979 }
980
981 port = str2number(servname);
982 if (port >= 0) {
983 if (!allownumeric)
984 return EAI_SERVICE;
985 if (port < 0 || port > 65535)
986 return EAI_SERVICE;
987 port = htons(port);
988 } else {
989 if (ai->ai_flags & AI_NUMERICSERV)
990 return EAI_NONAME;
991
992 switch (ai->ai_socktype) {
993 case SOCK_DGRAM:
994 proto = "udp";
995 break;
996 case SOCK_STREAM:
997 proto = "tcp";
998 break;
999 default:
1000 proto = NULL;
1001 break;
1002 }
1003
1004 if ((sp = getservbyname(servname, proto)) == NULL)
1005 return EAI_SERVICE;
1006 port = sp->s_port;
1007 }
1008
1009 if (!matchonly) {
1010 switch (ai->ai_family) {
1011 case AF_INET:
1012 ((struct sockaddr_in *)(void *)
1013 ai->ai_addr)->sin_port = port;
1014 break;
1015#ifdef INET6
1016 case AF_INET6:
1017 ((struct sockaddr_in6 *)(void *)
1018 ai->ai_addr)->sin6_port = port;
1019 break;
1020#endif
1021 }
1022 }
1023
1024 return 0;
1025}
1026
1027static const struct afd *
1028find_afd(int af)
1029{
1030 const struct afd *afd;
1031
1032 if (af == PF_UNSPEC)
1033 return NULL;
1034 for (afd = afdl; afd->a_af; afd++) {
1035 if (afd->a_af == af)
1036 return afd;
1037 }
1038 return NULL;
1039}
1040
1041#ifdef INET6
1042/* convert a string to a scope identifier. XXX: IPv6 specific */
1043static int
1044ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1045{
1046 u_long lscopeid;
1047 struct in6_addr *a6;
1048 char *ep;
1049
1050 assert(scope != NULL);
1051 assert(sin6 != NULL);
1052 assert(scopeid != NULL);
1053
1054 a6 = &sin6->sin6_addr;
1055
1056 /* empty scopeid portion is invalid */
1057 if (*scope == '\0')
1058 return -1;
1059
1060 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1061 /*
1062 * We currently assume a one-to-one mapping between links
1063 * and interfaces, so we simply use interface indices for
1064 * like-local scopes.
1065 */
1066 *scopeid = if_nametoindex(scope);
1067 if (*scopeid == 0)
1068 goto trynumeric;
1069 return 0;
1070 }
1071
1072 /* still unclear about literal, allow numeric only - placeholder */
1073 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1074 goto trynumeric;
1075 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1076 goto trynumeric;
1077 else
1078 goto trynumeric; /* global */
1079
1080 /* try to convert to a numeric id as a last resort */
1081 trynumeric:
1082 errno = 0;
1083 lscopeid = strtoul(scope, &ep, 10);
1084 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1085 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1086 return 0;
1087 else
1088 return -1;
1089}
1090#endif
1091
1092/* code duplicate with gethnamaddr.c */
1093
1094static const char AskedForGot[] =
1095 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1096
1097static struct addrinfo *
1098getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1099 const struct addrinfo *pai)
1100{
1101 struct addrinfo sentinel, *cur;
1102 struct addrinfo ai;
1103 const struct afd *afd;
1104 char *canonname;
1105 const HEADER *hp;
1106 const u_char *cp;
1107 int n;
1108 const u_char *eom;
1109 char *bp, *ep;
1110 int type, class, ancount, qdcount;
1111 int haveanswer, had_error;
1112 char tbuf[MAXDNAME];
1113 int (*name_ok) (const char *);
1114 char hostbuf[8*1024];
1115
1116 assert(answer != NULL);
1117 assert(qname != NULL);
1118 assert(pai != NULL);
1119
1120 memset(&sentinel, 0, sizeof(sentinel));
1121 cur = &sentinel;
1122
1123 canonname = NULL;
1124 eom = answer->buf + anslen;
1125 switch (qtype) {
1126 case T_A:
1127 case T_AAAA:
1128 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1129 name_ok = res_hnok;
1130 break;
1131 default:
1132 return NULL; /* XXX should be abort(); */
1133 }
1134 /*
1135 * find first satisfactory answer
1136 */
1137 hp = &answer->hdr;
1138 ancount = ntohs(hp->ancount);
1139 qdcount = ntohs(hp->qdcount);
1140 bp = hostbuf;
1141 ep = hostbuf + sizeof hostbuf;
1142 cp = answer->buf + HFIXEDSZ;
1143 if (qdcount != 1) {
1144 h_errno = NO_RECOVERY;
1145 return (NULL);
1146 }
1147 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1148 if ((n < 0) || !(*name_ok)(bp)) {
1149 h_errno = NO_RECOVERY;
1150 return (NULL);
1151 }
1152 cp += n + QFIXEDSZ;
1153 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1154 /* res_send() has already verified that the query name is the
1155 * same as the one we sent; this just gets the expanded name
1156 * (i.e., with the succeeding search-domain tacked on).
1157 */
1158 n = strlen(bp) + 1; /* for the \0 */
1159 if (n >= MAXHOSTNAMELEN) {
1160 h_errno = NO_RECOVERY;
1161 return (NULL);
1162 }
1163 canonname = bp;
1164 bp += n;
1165 /* The qname can be abbreviated, but h_name is now absolute. */
1166 qname = canonname;
1167 }
1168 haveanswer = 0;
1169 had_error = 0;
1170 while (ancount-- > 0 && cp < eom && !had_error) {
1171 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1172 if ((n < 0) || !(*name_ok)(bp)) {
1173 had_error++;
1174 continue;
1175 }
1176 cp += n; /* name */
1177 type = _getshort(cp);
1178 cp += INT16SZ; /* type */
1179 class = _getshort(cp);
1180 cp += INT16SZ + INT32SZ; /* class, TTL */
1181 n = _getshort(cp);
1182 cp += INT16SZ; /* len */
1183 if (class != C_IN) {
1184 /* XXX - debug? syslog? */
1185 cp += n;
1186 continue; /* XXX - had_error++ ? */
1187 }
1188 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1189 type == T_CNAME) {
1190 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1191 if ((n < 0) || !(*name_ok)(tbuf)) {
1192 had_error++;
1193 continue;
1194 }
1195 cp += n;
1196 /* Get canonical name. */
1197 n = strlen(tbuf) + 1; /* for the \0 */
1198 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1199 had_error++;
1200 continue;
1201 }
1202 strlcpy(bp, tbuf, (size_t)(ep - bp));
1203 canonname = bp;
1204 bp += n;
1205 continue;
1206 }
1207 if (qtype == T_ANY) {
1208 if (!(type == T_A || type == T_AAAA)) {
1209 cp += n;
1210 continue;
1211 }
1212 } else if (type != qtype) {
1213 if (type != T_KEY && type != T_SIG)
1214 syslog(LOG_NOTICE|LOG_AUTH,
1215 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1216 qname, p_class(C_IN), p_type(qtype),
1217 p_type(type));
1218 cp += n;
1219 continue; /* XXX - had_error++ ? */
1220 }
1221 switch (type) {
1222 case T_A:
1223 case T_AAAA:
1224 if (strcasecmp(canonname, bp) != 0) {
1225 syslog(LOG_NOTICE|LOG_AUTH,
1226 AskedForGot, canonname, bp);
1227 cp += n;
1228 continue; /* XXX - had_error++ ? */
1229 }
1230 if (type == T_A && n != INADDRSZ) {
1231 cp += n;
1232 continue;
1233 }
1234 if (type == T_AAAA && n != IN6ADDRSZ) {
1235 cp += n;
1236 continue;
1237 }
1238 if (type == T_AAAA) {
1239 struct in6_addr in6;
1240 memcpy(&in6, cp, IN6ADDRSZ);
1241 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1242 cp += n;
1243 continue;
1244 }
1245 }
1246 if (!haveanswer) {
1247 int nn;
1248
1249 canonname = bp;
1250 nn = strlen(bp) + 1; /* for the \0 */
1251 bp += nn;
1252 }
1253
1254 /* don't overwrite pai */
1255 ai = *pai;
1256 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1257 afd = find_afd(ai.ai_family);
1258 if (afd == NULL) {
1259 cp += n;
1260 continue;
1261 }
1262 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1263 if (cur->ai_next == NULL)
1264 had_error++;
1265 while (cur && cur->ai_next)
1266 cur = cur->ai_next;
1267 cp += n;
1268 break;
1269 default:
1270 abort();
1271 }
1272 if (!had_error)
1273 haveanswer++;
1274 }
1275 if (haveanswer) {
1276 if (!canonname)
1277 (void)get_canonname(pai, sentinel.ai_next, qname);
1278 else
1279 (void)get_canonname(pai, sentinel.ai_next, canonname);
1280 h_errno = NETDB_SUCCESS;
1281 return sentinel.ai_next;
1282 }
1283
1284 h_errno = NO_RECOVERY;
1285 return NULL;
1286}
1287
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001288struct addrinfo_sort_elem {
1289 struct addrinfo *ai;
1290 int has_src_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001291 sockaddr_union src_addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001292 int original_order;
1293};
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001294
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001295/*ARGSUSED*/
1296static int
1297_get_scope(const struct sockaddr *addr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001298{
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001299 if (addr->sa_family == AF_INET6) {
1300 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1301 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1302 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1303 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1304 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1305 /*
1306 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1307 * link-local scope.
1308 */
1309 return IPV6_ADDR_SCOPE_LINKLOCAL;
1310 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1311 return IPV6_ADDR_SCOPE_SITELOCAL;
1312 } else {
1313 return IPV6_ADDR_SCOPE_GLOBAL;
1314 }
1315 } else if (addr->sa_family == AF_INET) {
1316 const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1317 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001318
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001319 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1320 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1321 return IPV6_ADDR_SCOPE_LINKLOCAL;
1322 } else if ((na & 0xff000000) == 0x0a000000 || /* 10.0.0.0/8 */
1323 (na & 0xfff00000) == 0xac100000 || /* 172.16.0.0/12 */
1324 (na & 0xffff0000) == 0xc0a80000) { /* 192.168.0.0/16 */
1325 return IPV6_ADDR_SCOPE_SITELOCAL;
1326 } else {
1327 return IPV6_ADDR_SCOPE_GLOBAL;
1328 }
1329 } else {
1330 /*
1331 * This should never happen.
1332 * Return a scope with low priority as a last resort.
1333 */
1334 return IPV6_ADDR_SCOPE_NODELOCAL;
1335 }
1336}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001337
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001338/* These macros are modelled after the ones in <netinet/in6.h>. */
1339
1340/* RFC 4380, section 2.6 */
1341#define IN6_IS_ADDR_TEREDO(a) \
1342 ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1343
1344/* RFC 3056, section 2. */
1345#define IN6_IS_ADDR_6TO4(a) \
1346 (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1347
1348/*
1349 * Get the label for a given IPv4/IPv6 address.
1350 * RFC 3484, section 2.1, plus Teredo added in with label 5.
1351 */
1352
1353/*ARGSUSED*/
1354static int
1355_get_label(const struct sockaddr *addr)
1356{
1357 if (addr->sa_family == AF_INET) {
1358 return 4;
1359 } else if (addr->sa_family == AF_INET6) {
1360 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1361 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1362 return 0;
1363 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1364 return 3;
1365 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1366 return 5;
1367 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1368 return 2;
1369 } else {
1370 return 1;
1371 }
1372 } else {
1373 /*
1374 * This should never happen.
1375 * Return a semi-random label as a last resort.
1376 */
1377 return 1;
1378 }
1379}
1380
1381/*
1382 * Get the precedence for a given IPv4/IPv6 address.
1383 * RFC 3484, section 2.1, plus Teredo added in with precedence 25.
1384 */
1385
1386/*ARGSUSED*/
1387static int
1388_get_precedence(const struct sockaddr *addr)
1389{
1390 if (addr->sa_family == AF_INET) {
1391 return 10;
1392 } else if (addr->sa_family == AF_INET6) {
1393 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1394 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1395 return 50;
1396 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1397 return 20;
1398 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1399 return 25;
1400 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1401 return 30;
1402 } else {
1403 return 40;
1404 }
1405 } else {
1406 return 5;
1407 }
1408}
1409
1410/*
1411 * Find number of matching initial bits between the two addresses a1 and a2.
1412 */
1413
1414/*ARGSUSED*/
1415static int
1416_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1417{
1418 const char *p1 = (const char *)a1;
1419 const char *p2 = (const char *)a2;
1420 unsigned i;
1421
1422 for (i = 0; i < sizeof(*a1); ++i) {
1423 int x, j;
1424
1425 if (p1[i] == p2[i]) {
1426 continue;
1427 }
1428 x = p1[i] ^ p2[i];
1429 for (j = 0; j < CHAR_BIT; ++j) {
1430 if (x & (1 << (CHAR_BIT - 1))) {
1431 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001432 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001433 x <<= 1;
1434 }
1435 }
1436 return sizeof(*a1) * CHAR_BIT;
1437}
1438
1439/*
1440 * Compare two source/destination address pairs.
1441 * RFC 3484, section 6.
1442 */
1443
1444/*ARGSUSED*/
1445static int
1446_rfc3484_compare(const void *ptr1, const void* ptr2)
1447{
1448 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1449 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1450 int scope_src1, scope_dst1, scope_match1;
1451 int scope_src2, scope_dst2, scope_match2;
1452 int label_src1, label_dst1, label_match1;
1453 int label_src2, label_dst2, label_match2;
1454 int precedence1, precedence2;
1455 int prefixlen1, prefixlen2;
1456
1457 /* Rule 1: Avoid unusable destinations. */
1458 if (a1->has_src_addr != a2->has_src_addr) {
1459 return a2->has_src_addr - a1->has_src_addr;
1460 }
1461
1462 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001463 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001464 scope_dst1 = _get_scope(a1->ai->ai_addr);
1465 scope_match1 = (scope_src1 == scope_dst1);
1466
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001467 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001468 scope_dst2 = _get_scope(a2->ai->ai_addr);
1469 scope_match2 = (scope_src2 == scope_dst2);
1470
1471 if (scope_match1 != scope_match2) {
1472 return scope_match2 - scope_match1;
1473 }
1474
1475 /*
1476 * Rule 3: Avoid deprecated addresses.
1477 * TODO(sesse): We don't currently have a good way of finding this.
1478 */
1479
1480 /*
1481 * Rule 4: Prefer home addresses.
1482 * TODO(sesse): We don't currently have a good way of finding this.
1483 */
1484
1485 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001486 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001487 label_dst1 = _get_label(a1->ai->ai_addr);
1488 label_match1 = (label_src1 == label_dst1);
1489
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001490 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001491 label_dst2 = _get_label(a2->ai->ai_addr);
1492 label_match2 = (label_src2 == label_dst2);
1493
1494 if (label_match1 != label_match2) {
1495 return label_match2 - label_match1;
1496 }
1497
1498 /* Rule 6: Prefer higher precedence. */
1499 precedence1 = _get_precedence(a1->ai->ai_addr);
1500 precedence2 = _get_precedence(a2->ai->ai_addr);
1501 if (precedence1 != precedence2) {
1502 return precedence2 - precedence1;
1503 }
1504
1505 /*
1506 * Rule 7: Prefer native transport.
1507 * TODO(sesse): We don't currently have a good way of finding this.
1508 */
1509
1510 /* Rule 8: Prefer smaller scope. */
1511 if (scope_dst1 != scope_dst2) {
1512 return scope_dst1 - scope_dst2;
1513 }
1514
1515 /*
1516 * Rule 9: Use longest matching prefix.
1517 * We implement this for IPv6 only, as the rules in RFC 3484 don't seem
1518 * to work very well directly applied to IPv4. (glibc uses information from
1519 * the routing table for a custom IPv4 implementation here.)
1520 */
1521 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1522 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001523 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001524 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001525 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001526 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1527 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001528 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001529 if (prefixlen1 != prefixlen2) {
1530 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001531 }
1532 }
1533
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001534 /*
1535 * Rule 10: Leave the order unchanged.
1536 * We need this since qsort() is not necessarily stable.
1537 */
1538 return a1->original_order - a2->original_order;
1539}
1540
1541/*
1542 * Find the source address that will be used if trying to connect to the given
1543 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1544 *
1545 * Returns 1 if a source address was found, 0 if the address is unreachable,
1546 * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
1547 * undefined.
1548 */
1549
1550/*ARGSUSED*/
1551static int
1552_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr)
1553{
1554 int sock;
1555 int ret;
1556 socklen_t len;
1557
1558 switch (addr->sa_family) {
1559 case AF_INET:
1560 len = sizeof(struct sockaddr_in);
1561 break;
1562 case AF_INET6:
1563 len = sizeof(struct sockaddr_in6);
1564 break;
1565 default:
1566 /* No known usable source address for non-INET families. */
1567 return 0;
1568 }
1569
1570 sock = socket(addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
1571 if (sock == -1) {
1572 if (errno == EAFNOSUPPORT) {
1573 return 0;
1574 } else {
1575 return -1;
1576 }
1577 }
1578
1579 do {
1580 ret = connect(sock, addr, len);
1581 } while (ret == -1 && errno == EINTR);
1582
1583 if (ret == -1) {
1584 close(sock);
1585 return 0;
1586 }
1587
1588 if (getsockname(sock, src_addr, &len) == -1) {
1589 close(sock);
1590 return -1;
1591 }
1592 close(sock);
1593 return 1;
1594}
1595
1596/*
1597 * Sort the linked list starting at sentinel->ai_next in RFC3484 order.
1598 * Will leave the list unchanged if an error occurs.
1599 */
1600
1601/*ARGSUSED*/
1602static void
1603_rfc3484_sort(struct addrinfo *list_sentinel)
1604{
1605 struct addrinfo *cur;
1606 int nelem = 0, i;
1607 struct addrinfo_sort_elem *elems;
1608
1609 cur = list_sentinel->ai_next;
1610 while (cur) {
1611 ++nelem;
1612 cur = cur->ai_next;
1613 }
1614
1615 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1616 if (elems == NULL) {
1617 goto error;
1618 }
1619
1620 /*
1621 * Convert the linked list to an array that also contains the candidate
1622 * source address for each destination address.
1623 */
1624 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1625 int has_src_addr;
1626 assert(cur != NULL);
1627 elems[i].ai = cur;
1628 elems[i].original_order = i;
1629
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001630 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001631 if (has_src_addr == -1) {
1632 goto error;
1633 }
1634 elems[i].has_src_addr = has_src_addr;
1635 }
1636
1637 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1638 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc3484_compare);
1639
1640 list_sentinel->ai_next = elems[0].ai;
1641 for (i = 0; i < nelem - 1; ++i) {
1642 elems[i].ai->ai_next = elems[i + 1].ai;
1643 }
1644 elems[nelem - 1].ai->ai_next = NULL;
1645
1646error:
1647 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001648}
1649
1650/*ARGSUSED*/
1651static int
1652_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1653{
1654 struct addrinfo *ai;
1655 querybuf *buf, *buf2;
1656 const char *name;
1657 const struct addrinfo *pai;
1658 struct addrinfo sentinel, *cur;
1659 struct res_target q, q2;
1660 res_state res;
1661
1662 name = va_arg(ap, char *);
1663 pai = va_arg(ap, const struct addrinfo *);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001664 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001665
1666 memset(&q, 0, sizeof(q));
1667 memset(&q2, 0, sizeof(q2));
1668 memset(&sentinel, 0, sizeof(sentinel));
1669 cur = &sentinel;
1670
1671 buf = malloc(sizeof(*buf));
1672 if (buf == NULL) {
1673 h_errno = NETDB_INTERNAL;
1674 return NS_NOTFOUND;
1675 }
1676 buf2 = malloc(sizeof(*buf2));
1677 if (buf2 == NULL) {
1678 free(buf);
1679 h_errno = NETDB_INTERNAL;
1680 return NS_NOTFOUND;
1681 }
1682
1683 switch (pai->ai_family) {
1684 case AF_UNSPEC:
1685 /* prefer IPv6 */
1686 q.name = name;
1687 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001688 q.answer = buf->buf;
1689 q.anslen = sizeof(buf->buf);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001690 int query_ipv6 = 1, query_ipv4 = 1;
1691 if (pai->ai_flags & AI_ADDRCONFIG) {
1692 query_ipv6 = _have_ipv6();
1693 query_ipv4 = _have_ipv4();
1694 }
1695 if (query_ipv6) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001696 q.qtype = T_AAAA;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001697 if (query_ipv4) {
1698 q.next = &q2;
1699 q2.name = name;
1700 q2.qclass = C_IN;
1701 q2.qtype = T_A;
1702 q2.answer = buf2->buf;
1703 q2.anslen = sizeof(buf2->buf);
1704 }
1705 } else if (query_ipv4) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001706 q.qtype = T_A;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001707 } else {
1708 free(buf);
1709 free(buf2);
1710 return NS_NOTFOUND;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001711 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001712 break;
1713 case AF_INET:
1714 q.name = name;
1715 q.qclass = C_IN;
1716 q.qtype = T_A;
1717 q.answer = buf->buf;
1718 q.anslen = sizeof(buf->buf);
1719 break;
1720 case AF_INET6:
1721 q.name = name;
1722 q.qclass = C_IN;
1723 q.qtype = T_AAAA;
1724 q.answer = buf->buf;
1725 q.anslen = sizeof(buf->buf);
1726 break;
1727 default:
1728 free(buf);
1729 free(buf2);
1730 return NS_UNAVAIL;
1731 }
1732
1733 res = __res_get_state();
1734 if (res == NULL) {
1735 free(buf);
1736 free(buf2);
1737 return NS_NOTFOUND;
1738 }
1739
1740 if (res_searchN(name, &q, res) < 0) {
1741 __res_put_state(res);
1742 free(buf);
1743 free(buf2);
1744 return NS_NOTFOUND;
1745 }
1746 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1747 if (ai) {
1748 cur->ai_next = ai;
1749 while (cur && cur->ai_next)
1750 cur = cur->ai_next;
1751 }
1752 if (q.next) {
1753 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1754 if (ai)
1755 cur->ai_next = ai;
1756 }
1757 free(buf);
1758 free(buf2);
1759 if (sentinel.ai_next == NULL) {
1760 __res_put_state(res);
1761 switch (h_errno) {
1762 case HOST_NOT_FOUND:
1763 return NS_NOTFOUND;
1764 case TRY_AGAIN:
1765 return NS_TRYAGAIN;
1766 default:
1767 return NS_UNAVAIL;
1768 }
1769 }
1770
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001771 _rfc3484_sort(&sentinel);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001772
1773 __res_put_state(res);
1774
1775 *((struct addrinfo **)rv) = sentinel.ai_next;
1776 return NS_SUCCESS;
1777}
1778
1779static void
1780_sethtent(FILE **hostf)
1781{
1782
1783 if (!*hostf)
1784 *hostf = fopen(_PATH_HOSTS, "r" );
1785 else
1786 rewind(*hostf);
1787}
1788
1789static void
1790_endhtent(FILE **hostf)
1791{
1792
1793 if (*hostf) {
1794 (void) fclose(*hostf);
1795 *hostf = NULL;
1796 }
1797}
1798
1799static struct addrinfo *
1800_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
1801{
1802 char *p;
1803 char *cp, *tname, *cname;
1804 struct addrinfo hints, *res0, *res;
1805 int error;
1806 const char *addr;
1807 char hostbuf[8*1024];
1808
1809// fprintf(stderr, "_gethtent() name = '%s'\n", name);
1810 assert(name != NULL);
1811 assert(pai != NULL);
1812
1813 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
1814 return (NULL);
1815 again:
1816 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
1817 return (NULL);
1818 if (*p == '#')
1819 goto again;
1820 if (!(cp = strpbrk(p, "#\n")))
1821 goto again;
1822 *cp = '\0';
1823 if (!(cp = strpbrk(p, " \t")))
1824 goto again;
1825 *cp++ = '\0';
1826 addr = p;
1827 /* if this is not something we're looking for, skip it. */
1828 cname = NULL;
1829 while (cp && *cp) {
1830 if (*cp == ' ' || *cp == '\t') {
1831 cp++;
1832 continue;
1833 }
1834 if (!cname)
1835 cname = cp;
1836 tname = cp;
1837 if ((cp = strpbrk(cp, " \t")) != NULL)
1838 *cp++ = '\0';
1839// fprintf(stderr, "\ttname = '%s'", tname);
1840 if (strcasecmp(name, tname) == 0)
1841 goto found;
1842 }
1843 goto again;
1844
1845found:
1846 hints = *pai;
1847 hints.ai_flags = AI_NUMERICHOST;
1848 error = getaddrinfo(addr, NULL, &hints, &res0);
1849 if (error)
1850 goto again;
1851 for (res = res0; res; res = res->ai_next) {
1852 /* cover it up */
1853 res->ai_flags = pai->ai_flags;
1854
1855 if (pai->ai_flags & AI_CANONNAME) {
1856 if (get_canonname(pai, res, cname) != 0) {
1857 freeaddrinfo(res0);
1858 goto again;
1859 }
1860 }
1861 }
1862 return res0;
1863}
1864
1865/*ARGSUSED*/
1866static int
1867_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
1868{
1869 const char *name;
1870 const struct addrinfo *pai;
1871 struct addrinfo sentinel, *cur;
1872 struct addrinfo *p;
1873 FILE *hostf = NULL;
1874
1875 name = va_arg(ap, char *);
1876 pai = va_arg(ap, struct addrinfo *);
1877
1878// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
1879 memset(&sentinel, 0, sizeof(sentinel));
1880 cur = &sentinel;
1881
1882 _sethtent(&hostf);
1883 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
1884 cur->ai_next = p;
1885 while (cur && cur->ai_next)
1886 cur = cur->ai_next;
1887 }
1888 _endhtent(&hostf);
1889
1890 *((struct addrinfo **)rv) = sentinel.ai_next;
1891 if (sentinel.ai_next == NULL)
1892 return NS_NOTFOUND;
1893 return NS_SUCCESS;
1894}
1895
1896/* resolver logic */
1897
1898/*
1899 * Formulate a normal query, send, and await answer.
1900 * Returned answer is placed in supplied buffer "answer".
1901 * Perform preliminary check of answer, returning success only
1902 * if no error is indicated and the answer count is nonzero.
1903 * Return the size of the response on success, -1 on error.
1904 * Error number is left in h_errno.
1905 *
1906 * Caller must parse answer and determine whether it answers the question.
1907 */
1908static int
1909res_queryN(const char *name, /* domain name */ struct res_target *target,
1910 res_state res)
1911{
1912 u_char buf[MAXPACKET];
1913 HEADER *hp;
1914 int n;
1915 struct res_target *t;
1916 int rcode;
1917 int ancount;
1918
1919 assert(name != NULL);
1920 /* XXX: target may be NULL??? */
1921
1922 rcode = NOERROR;
1923 ancount = 0;
1924
1925 for (t = target; t; t = t->next) {
1926 int class, type;
1927 u_char *answer;
1928 int anslen;
1929
1930 hp = (HEADER *)(void *)t->answer;
1931 hp->rcode = NOERROR; /* default */
1932
1933 /* make it easier... */
1934 class = t->qclass;
1935 type = t->qtype;
1936 answer = t->answer;
1937 anslen = t->anslen;
1938#ifdef DEBUG
1939 if (res->options & RES_DEBUG)
1940 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
1941#endif
1942
1943 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
1944 buf, sizeof(buf));
1945#ifdef RES_USE_EDNS0
1946 if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
1947 n = res_nopt(res, n, buf, sizeof(buf), anslen);
1948#endif
1949 if (n <= 0) {
1950#ifdef DEBUG
1951 if (res->options & RES_DEBUG)
1952 printf(";; res_nquery: mkquery failed\n");
1953#endif
1954 h_errno = NO_RECOVERY;
1955 return n;
1956 }
1957 n = res_nsend(res, buf, n, answer, anslen);
1958#if 0
1959 if (n < 0) {
1960#ifdef DEBUG
1961 if (res->options & RES_DEBUG)
1962 printf(";; res_query: send error\n");
1963#endif
1964 h_errno = TRY_AGAIN;
1965 return n;
1966 }
1967#endif
1968
1969 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1970 rcode = hp->rcode; /* record most recent error */
1971#ifdef DEBUG
1972 if (res->options & RES_DEBUG)
1973 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
1974 ntohs(hp->ancount));
1975#endif
1976 continue;
1977 }
1978
1979 ancount += ntohs(hp->ancount);
1980
1981 t->n = n;
1982 }
1983
1984 if (ancount == 0) {
1985 switch (rcode) {
1986 case NXDOMAIN:
1987 h_errno = HOST_NOT_FOUND;
1988 break;
1989 case SERVFAIL:
1990 h_errno = TRY_AGAIN;
1991 break;
1992 case NOERROR:
1993 h_errno = NO_DATA;
1994 break;
1995 case FORMERR:
1996 case NOTIMP:
1997 case REFUSED:
1998 default:
1999 h_errno = NO_RECOVERY;
2000 break;
2001 }
2002 return -1;
2003 }
2004 return ancount;
2005}
2006
2007/*
2008 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2009 * Return the size of the response on success, -1 on error.
2010 * If enabled, implement search rules until answer or unrecoverable failure
2011 * is detected. Error code, if any, is left in h_errno.
2012 */
2013static int
2014res_searchN(const char *name, struct res_target *target, res_state res)
2015{
2016 const char *cp, * const *domain;
2017 HEADER *hp;
2018 u_int dots;
2019 int trailing_dot, ret, saved_herrno;
2020 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2021
2022 assert(name != NULL);
2023 assert(target != NULL);
2024
2025 hp = (HEADER *)(void *)target->answer; /*XXX*/
2026
2027 errno = 0;
2028 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2029 dots = 0;
2030 for (cp = name; *cp; cp++)
2031 dots += (*cp == '.');
2032 trailing_dot = 0;
2033 if (cp > name && *--cp == '.')
2034 trailing_dot++;
2035
2036
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002037 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002038
2039 /*
2040 * if there aren't any dots, it could be a user-level alias
2041 */
2042 if (!dots && (cp = __hostalias(name)) != NULL) {
2043 ret = res_queryN(cp, target, res);
2044 return ret;
2045 }
2046
2047 /*
2048 * If there are dots in the name already, let's just give it a try
2049 * 'as is'. The threshold can be set with the "ndots" option.
2050 */
2051 saved_herrno = -1;
2052 if (dots >= res->ndots) {
2053 ret = res_querydomainN(name, NULL, target, res);
2054 if (ret > 0)
2055 return (ret);
2056 saved_herrno = h_errno;
2057 tried_as_is++;
2058 }
2059
2060 /*
2061 * We do at least one level of search if
2062 * - there is no dot and RES_DEFNAME is set, or
2063 * - there is at least one dot, there is no trailing dot,
2064 * and RES_DNSRCH is set.
2065 */
2066 if ((!dots && (res->options & RES_DEFNAMES)) ||
2067 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2068 int done = 0;
2069
2070 for (domain = (const char * const *)res->dnsrch;
2071 *domain && !done;
2072 domain++) {
2073
2074 ret = res_querydomainN(name, *domain, target, res);
2075 if (ret > 0)
2076 return ret;
2077
2078 /*
2079 * If no server present, give up.
2080 * If name isn't found in this domain,
2081 * keep trying higher domains in the search list
2082 * (if that's enabled).
2083 * On a NO_DATA error, keep trying, otherwise
2084 * a wildcard entry of another type could keep us
2085 * from finding this entry higher in the domain.
2086 * If we get some other error (negative answer or
2087 * server failure), then stop searching up,
2088 * but try the input name below in case it's
2089 * fully-qualified.
2090 */
2091 if (errno == ECONNREFUSED) {
2092 h_errno = TRY_AGAIN;
2093 return -1;
2094 }
2095
2096 switch (h_errno) {
2097 case NO_DATA:
2098 got_nodata++;
2099 /* FALLTHROUGH */
2100 case HOST_NOT_FOUND:
2101 /* keep trying */
2102 break;
2103 case TRY_AGAIN:
2104 if (hp->rcode == SERVFAIL) {
2105 /* try next search element, if any */
2106 got_servfail++;
2107 break;
2108 }
2109 /* FALLTHROUGH */
2110 default:
2111 /* anything else implies that we're done */
2112 done++;
2113 }
2114 /*
2115 * if we got here for some reason other than DNSRCH,
2116 * we only wanted one iteration of the loop, so stop.
2117 */
2118 if (!(res->options & RES_DNSRCH))
2119 done++;
2120 }
2121 }
2122
2123 /*
2124 * if we have not already tried the name "as is", do that now.
2125 * note that we do this regardless of how many dots were in the
2126 * name or whether it ends with a dot.
2127 */
2128 if (!tried_as_is) {
2129 ret = res_querydomainN(name, NULL, target, res);
2130 if (ret > 0)
2131 return ret;
2132 }
2133
2134 /*
2135 * if we got here, we didn't satisfy the search.
2136 * if we did an initial full query, return that query's h_errno
2137 * (note that we wouldn't be here if that query had succeeded).
2138 * else if we ever got a nodata, send that back as the reason.
2139 * else send back meaningless h_errno, that being the one from
2140 * the last DNSRCH we did.
2141 */
2142 if (saved_herrno != -1)
2143 h_errno = saved_herrno;
2144 else if (got_nodata)
2145 h_errno = NO_DATA;
2146 else if (got_servfail)
2147 h_errno = TRY_AGAIN;
2148 return -1;
2149}
2150
2151/*
2152 * Perform a call on res_query on the concatenation of name and domain,
2153 * removing a trailing dot from name if domain is NULL.
2154 */
2155static int
2156res_querydomainN(const char *name, const char *domain,
2157 struct res_target *target, res_state res)
2158{
2159 char nbuf[MAXDNAME];
2160 const char *longname = nbuf;
2161 size_t n, d;
2162
2163 assert(name != NULL);
2164 /* XXX: target may be NULL??? */
2165
2166#ifdef DEBUG
2167 if (res->options & RES_DEBUG)
2168 printf(";; res_querydomain(%s, %s)\n",
2169 name, domain?domain:"<Nil>");
2170#endif
2171 if (domain == NULL) {
2172 /*
2173 * Check for trailing '.';
2174 * copy without '.' if present.
2175 */
2176 n = strlen(name);
2177 if (n + 1 > sizeof(nbuf)) {
2178 h_errno = NO_RECOVERY;
2179 return -1;
2180 }
2181 if (n > 0 && name[--n] == '.') {
2182 strncpy(nbuf, name, n);
2183 nbuf[n] = '\0';
2184 } else
2185 longname = name;
2186 } else {
2187 n = strlen(name);
2188 d = strlen(domain);
2189 if (n + 1 + d + 1 > sizeof(nbuf)) {
2190 h_errno = NO_RECOVERY;
2191 return -1;
2192 }
2193 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2194 }
2195 return res_queryN(longname, target, res);
2196}