blob: 2dd3d971eb105d98beecd08aed6adad56db9dfc6 [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
103#define SUCCESS 0
104#define ANY 0
105#define YES 1
106#define NO 0
107
108static const char in_addrany[] = { 0, 0, 0, 0 };
109static const char in_loopback[] = { 127, 0, 0, 1 };
110#ifdef INET6
111static const char in6_addrany[] = {
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
113};
114static const char in6_loopback[] = {
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
116};
117#endif
118
119static const struct afd {
120 int a_af;
121 int a_addrlen;
122 int a_socklen;
123 int a_off;
124 const char *a_addrany;
125 const char *a_loopback;
126 int a_scoped;
127} afdl [] = {
128#ifdef INET6
129 {PF_INET6, sizeof(struct in6_addr),
130 sizeof(struct sockaddr_in6),
131 offsetof(struct sockaddr_in6, sin6_addr),
132 in6_addrany, in6_loopback, 1},
133#endif
134 {PF_INET, sizeof(struct in_addr),
135 sizeof(struct sockaddr_in),
136 offsetof(struct sockaddr_in, sin_addr),
137 in_addrany, in_loopback, 0},
138 {0, 0, 0, 0, NULL, NULL, 0},
139};
140
141struct explore {
142 int e_af;
143 int e_socktype;
144 int e_protocol;
145 const char *e_protostr;
146 int e_wild;
147#define WILD_AF(ex) ((ex)->e_wild & 0x01)
148#define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
149#define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
150};
151
152static const struct explore explore[] = {
153#if 0
154 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
155#endif
156#ifdef INET6
157 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
158 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
159 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
160#endif
161 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
162 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
163 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
164 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
165 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
166 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
167 { -1, 0, 0, NULL, 0 },
168};
169
170#ifdef INET6
171#define PTON_MAX 16
172#else
173#define PTON_MAX 4
174#endif
175
176static const ns_src default_dns_files[] = {
177 { NSSRC_FILES, NS_SUCCESS },
178 { NSSRC_DNS, NS_SUCCESS },
179 { 0, 0 }
180};
181
182#define MAXPACKET (64*1024)
183
184typedef union {
185 HEADER hdr;
186 u_char buf[MAXPACKET];
187} querybuf;
188
189struct res_target {
190 struct res_target *next;
191 const char *name; /* domain name */
192 int qclass, qtype; /* class and type of query */
193 u_char *answer; /* buffer to put answer */
194 int anslen; /* size of answer buffer */
195 int n; /* result length */
196};
197
198static int str2number(const char *);
199static int explore_fqdn(const struct addrinfo *, const char *,
200 const char *, struct addrinfo **);
201static int explore_null(const struct addrinfo *,
202 const char *, struct addrinfo **);
203static int explore_numeric(const struct addrinfo *, const char *,
204 const char *, struct addrinfo **, const char *);
205static int explore_numeric_scope(const struct addrinfo *, const char *,
206 const char *, struct addrinfo **);
207static int get_canonname(const struct addrinfo *,
208 struct addrinfo *, const char *);
209static struct addrinfo *get_ai(const struct addrinfo *,
210 const struct afd *, const char *);
211static int get_portmatch(const struct addrinfo *, const char *);
212static int get_port(const struct addrinfo *, const char *, int);
213static const struct afd *find_afd(int);
214#ifdef INET6
215static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
216#endif
217
218static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
219 const struct addrinfo *);
220static void aisort(struct addrinfo *s, res_state res);
221static int _dns_getaddrinfo(void *, void *, va_list);
222static void _sethtent(FILE **);
223static void _endhtent(FILE **);
224static struct addrinfo *_gethtent(FILE **, const char *,
225 const struct addrinfo *);
226static int _files_getaddrinfo(void *, void *, va_list);
227
228static int res_queryN(const char *, struct res_target *, res_state);
229static int res_searchN(const char *, struct res_target *, res_state);
230static int res_querydomainN(const char *, const char *,
231 struct res_target *, res_state);
232
233static const char * const ai_errlist[] = {
234 "Success",
235 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
236 "Temporary failure in name resolution", /* EAI_AGAIN */
237 "Invalid value for ai_flags", /* EAI_BADFLAGS */
238 "Non-recoverable failure in name resolution", /* EAI_FAIL */
239 "ai_family not supported", /* EAI_FAMILY */
240 "Memory allocation failure", /* EAI_MEMORY */
241 "No address associated with hostname", /* EAI_NODATA */
242 "hostname nor servname provided, or not known", /* EAI_NONAME */
243 "servname not supported for ai_socktype", /* EAI_SERVICE */
244 "ai_socktype not supported", /* EAI_SOCKTYPE */
245 "System error returned in errno", /* EAI_SYSTEM */
246 "Invalid value for hints", /* EAI_BADHINTS */
247 "Resolved protocol is unknown", /* EAI_PROTOCOL */
248 "Argument buffer overflow", /* EAI_OVERFLOW */
249 "Unknown error", /* EAI_MAX */
250};
251
252/* XXX macros that make external reference is BAD. */
253
254#define GET_AI(ai, afd, addr) \
255do { \
256 /* external reference: pai, error, and label free */ \
257 (ai) = get_ai(pai, (afd), (addr)); \
258 if ((ai) == NULL) { \
259 error = EAI_MEMORY; \
260 goto free; \
261 } \
262} while (/*CONSTCOND*/0)
263
264#define GET_PORT(ai, serv) \
265do { \
266 /* external reference: error and label free */ \
267 error = get_port((ai), (serv), 0); \
268 if (error != 0) \
269 goto free; \
270} while (/*CONSTCOND*/0)
271
272#define GET_CANONNAME(ai, str) \
273do { \
274 /* external reference: pai, error and label free */ \
275 error = get_canonname(pai, (ai), (str)); \
276 if (error != 0) \
277 goto free; \
278} while (/*CONSTCOND*/0)
279
280#define ERR(err) \
281do { \
282 /* external reference: error, and label bad */ \
283 error = (err); \
284 goto bad; \
285 /*NOTREACHED*/ \
286} while (/*CONSTCOND*/0)
287
288#define MATCH_FAMILY(x, y, w) \
289 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || \
290 (y) == PF_UNSPEC)))
291#define MATCH(x, y, w) \
292 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
293
294const char *
295gai_strerror(int ecode)
296{
297 if (ecode < 0 || ecode > EAI_MAX)
298 ecode = EAI_MAX;
299 return ai_errlist[ecode];
300}
301
302void
303freeaddrinfo(struct addrinfo *ai)
304{
305 struct addrinfo *next;
306
307 assert(ai != NULL);
308
309 do {
310 next = ai->ai_next;
311 if (ai->ai_canonname)
312 free(ai->ai_canonname);
313 /* no need to free(ai->ai_addr) */
314 free(ai);
315 ai = next;
316 } while (ai);
317}
318
319static int
320str2number(const char *p)
321{
322 char *ep;
323 unsigned long v;
324
325 assert(p != NULL);
326
327 if (*p == '\0')
328 return -1;
329 ep = NULL;
330 errno = 0;
331 v = strtoul(p, &ep, 10);
332 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
333 return v;
334 else
335 return -1;
336}
337
338int
339getaddrinfo(const char *hostname, const char *servname,
340 const struct addrinfo *hints, struct addrinfo **res)
341{
342 struct addrinfo sentinel;
343 struct addrinfo *cur;
344 int error = 0;
345 struct addrinfo ai;
346 struct addrinfo ai0;
347 struct addrinfo *pai;
348 const struct explore *ex;
349
350 /* hostname is allowed to be NULL */
351 /* servname is allowed to be NULL */
352 /* hints is allowed to be NULL */
353 assert(res != NULL);
354
355 memset(&sentinel, 0, sizeof(sentinel));
356 cur = &sentinel;
357 pai = &ai;
358 pai->ai_flags = 0;
359 pai->ai_family = PF_UNSPEC;
360 pai->ai_socktype = ANY;
361 pai->ai_protocol = ANY;
362 pai->ai_addrlen = 0;
363 pai->ai_canonname = NULL;
364 pai->ai_addr = NULL;
365 pai->ai_next = NULL;
366
367 if (hostname == NULL && servname == NULL)
368 return EAI_NONAME;
369 if (hints) {
370 /* error check for hints */
371 if (hints->ai_addrlen || hints->ai_canonname ||
372 hints->ai_addr || hints->ai_next)
373 ERR(EAI_BADHINTS); /* xxx */
374 if (hints->ai_flags & ~AI_MASK)
375 ERR(EAI_BADFLAGS);
376 switch (hints->ai_family) {
377 case PF_UNSPEC:
378 case PF_INET:
379#ifdef INET6
380 case PF_INET6:
381#endif
382 break;
383 default:
384 ERR(EAI_FAMILY);
385 }
386 memcpy(pai, hints, sizeof(*pai));
387
388 /*
389 * if both socktype/protocol are specified, check if they
390 * are meaningful combination.
391 */
392 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
393 for (ex = explore; ex->e_af >= 0; ex++) {
394 if (pai->ai_family != ex->e_af)
395 continue;
396 if (ex->e_socktype == ANY)
397 continue;
398 if (ex->e_protocol == ANY)
399 continue;
400 if (pai->ai_socktype == ex->e_socktype
401 && pai->ai_protocol != ex->e_protocol) {
402 ERR(EAI_BADHINTS);
403 }
404 }
405 }
406 }
407
408 /*
409 * check for special cases. (1) numeric servname is disallowed if
410 * socktype/protocol are left unspecified. (2) servname is disallowed
411 * for raw and other inet{,6} sockets.
412 */
413 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
414#ifdef PF_INET6
415 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
416#endif
417 ) {
418 ai0 = *pai; /* backup *pai */
419
420 if (pai->ai_family == PF_UNSPEC) {
421#ifdef PF_INET6
422 pai->ai_family = PF_INET6;
423#else
424 pai->ai_family = PF_INET;
425#endif
426 }
427 error = get_portmatch(pai, servname);
428 if (error)
429 ERR(error);
430
431 *pai = ai0;
432 }
433
434 ai0 = *pai;
435
436 /* NULL hostname, or numeric hostname */
437 for (ex = explore; ex->e_af >= 0; ex++) {
438 *pai = ai0;
439
440 /* PF_UNSPEC entries are prepared for DNS queries only */
441 if (ex->e_af == PF_UNSPEC)
442 continue;
443
444 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
445 continue;
446 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
447 continue;
448 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
449 continue;
450
451 if (pai->ai_family == PF_UNSPEC)
452 pai->ai_family = ex->e_af;
453 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
454 pai->ai_socktype = ex->e_socktype;
455 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
456 pai->ai_protocol = ex->e_protocol;
457
458 if (hostname == NULL)
459 error = explore_null(pai, servname, &cur->ai_next);
460 else
461 error = explore_numeric_scope(pai, hostname, servname,
462 &cur->ai_next);
463
464 if (error)
465 goto free;
466
467 while (cur->ai_next)
468 cur = cur->ai_next;
469 }
470
471 /*
472 * XXX
473 * If numeric representation of AF1 can be interpreted as FQDN
474 * representation of AF2, we need to think again about the code below.
475 */
476 if (sentinel.ai_next)
477 goto good;
478
479 if (hostname == NULL)
480 ERR(EAI_NODATA);
481 if (pai->ai_flags & AI_NUMERICHOST)
482 ERR(EAI_NONAME);
483
484 /*
485 * hostname as alphabetical name.
486 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
487 * outer loop by AFs.
488 */
489 for (ex = explore; ex->e_af >= 0; ex++) {
490 *pai = ai0;
491
492 /* require exact match for family field */
493 if (pai->ai_family != ex->e_af)
494 continue;
495
496 if (!MATCH(pai->ai_socktype, ex->e_socktype,
497 WILD_SOCKTYPE(ex))) {
498 continue;
499 }
500 if (!MATCH(pai->ai_protocol, ex->e_protocol,
501 WILD_PROTOCOL(ex))) {
502 continue;
503 }
504
505 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
506 pai->ai_socktype = ex->e_socktype;
507 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
508 pai->ai_protocol = ex->e_protocol;
509
510 error = explore_fqdn(pai, hostname, servname,
511 &cur->ai_next);
512
513 while (cur && cur->ai_next)
514 cur = cur->ai_next;
515 }
516
517 /* XXX */
518 if (sentinel.ai_next)
519 error = 0;
520
521 if (error)
522 goto free;
523 if (error == 0) {
524 if (sentinel.ai_next) {
525 good:
526 *res = sentinel.ai_next;
527 return SUCCESS;
528 } else
529 error = EAI_FAIL;
530 }
531 free:
532 bad:
533 if (sentinel.ai_next)
534 freeaddrinfo(sentinel.ai_next);
535 *res = NULL;
536 return error;
537}
538
539/*
540 * FQDN hostname, DNS lookup
541 */
542static int
543explore_fqdn(const struct addrinfo *pai, const char *hostname,
544 const char *servname, struct addrinfo **res)
545{
546 struct addrinfo *result;
547 struct addrinfo *cur;
548 int error = 0;
549 static const ns_dtab dtab[] = {
550 NS_FILES_CB(_files_getaddrinfo, NULL)
551 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
552 NS_NIS_CB(_yp_getaddrinfo, NULL)
553 { 0, 0, 0 }
554 };
555
556 assert(pai != NULL);
557 /* hostname may be NULL */
558 /* servname may be NULL */
559 assert(res != NULL);
560
561 result = NULL;
562
563 /*
564 * if the servname does not match socktype/protocol, ignore it.
565 */
566 if (get_portmatch(pai, servname) != 0)
567 return 0;
568
569 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
570 default_dns_files, hostname, pai)) {
571 case NS_TRYAGAIN:
572 error = EAI_AGAIN;
573 goto free;
574 case NS_UNAVAIL:
575 error = EAI_FAIL;
576 goto free;
577 case NS_NOTFOUND:
578 error = EAI_NODATA;
579 goto free;
580 case NS_SUCCESS:
581 error = 0;
582 for (cur = result; cur; cur = cur->ai_next) {
583 GET_PORT(cur, servname);
584 /* canonname should be filled already */
585 }
586 break;
587 }
588
589 *res = result;
590
591 return 0;
592
593free:
594 if (result)
595 freeaddrinfo(result);
596 return error;
597}
598
599/*
600 * hostname == NULL.
601 * passive socket -> anyaddr (0.0.0.0 or ::)
602 * non-passive socket -> localhost (127.0.0.1 or ::1)
603 */
604static int
605explore_null(const struct addrinfo *pai, const char *servname,
606 struct addrinfo **res)
607{
608 int s;
609 const struct afd *afd;
610 struct addrinfo *cur;
611 struct addrinfo sentinel;
612 int error;
613
614 assert(pai != NULL);
615 /* servname may be NULL */
616 assert(res != NULL);
617
618 *res = NULL;
619 sentinel.ai_next = NULL;
620 cur = &sentinel;
621
622 /*
623 * filter out AFs that are not supported by the kernel
624 * XXX errno?
625 */
626 s = socket(pai->ai_family, SOCK_DGRAM, 0);
627 if (s < 0) {
628 if (errno != EMFILE)
629 return 0;
630 } else
631 close(s);
632
633 /*
634 * if the servname does not match socktype/protocol, ignore it.
635 */
636 if (get_portmatch(pai, servname) != 0)
637 return 0;
638
639 afd = find_afd(pai->ai_family);
640 if (afd == NULL)
641 return 0;
642
643 if (pai->ai_flags & AI_PASSIVE) {
644 GET_AI(cur->ai_next, afd, afd->a_addrany);
645 /* xxx meaningless?
646 * GET_CANONNAME(cur->ai_next, "anyaddr");
647 */
648 GET_PORT(cur->ai_next, servname);
649 } else {
650 GET_AI(cur->ai_next, afd, afd->a_loopback);
651 /* xxx meaningless?
652 * GET_CANONNAME(cur->ai_next, "localhost");
653 */
654 GET_PORT(cur->ai_next, servname);
655 }
656 cur = cur->ai_next;
657
658 *res = sentinel.ai_next;
659 return 0;
660
661free:
662 if (sentinel.ai_next)
663 freeaddrinfo(sentinel.ai_next);
664 return error;
665}
666
667/*
668 * numeric hostname
669 */
670static int
671explore_numeric(const struct addrinfo *pai, const char *hostname,
672 const char *servname, struct addrinfo **res, const char *canonname)
673{
674 const struct afd *afd;
675 struct addrinfo *cur;
676 struct addrinfo sentinel;
677 int error;
678 char pton[PTON_MAX];
679
680 assert(pai != NULL);
681 /* hostname may be NULL */
682 /* servname may be NULL */
683 assert(res != NULL);
684
685 *res = NULL;
686 sentinel.ai_next = NULL;
687 cur = &sentinel;
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 switch (afd->a_af) {
700#if 0 /*X/Open spec*/
701 case AF_INET:
702 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
703 if (pai->ai_family == afd->a_af ||
704 pai->ai_family == PF_UNSPEC /*?*/) {
705 GET_AI(cur->ai_next, afd, pton);
706 GET_PORT(cur->ai_next, servname);
707 if ((pai->ai_flags & AI_CANONNAME)) {
708 /*
709 * Set the numeric address itself as
710 * the canonical name, based on a
711 * clarification in rfc2553bis-03.
712 */
713 GET_CANONNAME(cur->ai_next, canonname);
714 }
715 while (cur && cur->ai_next)
716 cur = cur->ai_next;
717 } else
718 ERR(EAI_FAMILY); /*xxx*/
719 }
720 break;
721#endif
722 default:
723 if (inet_pton(afd->a_af, hostname, pton) == 1) {
724 if (pai->ai_family == afd->a_af ||
725 pai->ai_family == PF_UNSPEC /*?*/) {
726 GET_AI(cur->ai_next, afd, pton);
727 GET_PORT(cur->ai_next, servname);
728 if ((pai->ai_flags & AI_CANONNAME)) {
729 /*
730 * Set the numeric address itself as
731 * the canonical name, based on a
732 * clarification in rfc2553bis-03.
733 */
734 GET_CANONNAME(cur->ai_next, canonname);
735 }
736 while (cur->ai_next)
737 cur = cur->ai_next;
738 } else
739 ERR(EAI_FAMILY); /*xxx*/
740 }
741 break;
742 }
743
744 *res = sentinel.ai_next;
745 return 0;
746
747free:
748bad:
749 if (sentinel.ai_next)
750 freeaddrinfo(sentinel.ai_next);
751 return error;
752}
753
754/*
755 * numeric hostname with scope
756 */
757static int
758explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
759 const char *servname, struct addrinfo **res)
760{
761#if !defined(SCOPE_DELIMITER) || !defined(INET6)
762 return explore_numeric(pai, hostname, servname, res, hostname);
763#else
764 const struct afd *afd;
765 struct addrinfo *cur;
766 int error;
767 char *cp, *hostname2 = NULL, *scope, *addr;
768 struct sockaddr_in6 *sin6;
769
770 assert(pai != NULL);
771 /* hostname may be NULL */
772 /* servname may be NULL */
773 assert(res != NULL);
774
775 /*
776 * if the servname does not match socktype/protocol, ignore it.
777 */
778 if (get_portmatch(pai, servname) != 0)
779 return 0;
780
781 afd = find_afd(pai->ai_family);
782 if (afd == NULL)
783 return 0;
784
785 if (!afd->a_scoped)
786 return explore_numeric(pai, hostname, servname, res, hostname);
787
788 cp = strchr(hostname, SCOPE_DELIMITER);
789 if (cp == NULL)
790 return explore_numeric(pai, hostname, servname, res, hostname);
791
792 /*
793 * Handle special case of <scoped_address><delimiter><scope id>
794 */
795 hostname2 = strdup(hostname);
796 if (hostname2 == NULL)
797 return EAI_MEMORY;
798 /* terminate at the delimiter */
799 hostname2[cp - hostname] = '\0';
800 addr = hostname2;
801 scope = cp + 1;
802
803 error = explore_numeric(pai, addr, servname, res, hostname);
804 if (error == 0) {
805 u_int32_t scopeid;
806
807 for (cur = *res; cur; cur = cur->ai_next) {
808 if (cur->ai_family != AF_INET6)
809 continue;
810 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
811 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
812 free(hostname2);
813 return(EAI_NODATA); /* XXX: is return OK? */
814 }
815 sin6->sin6_scope_id = scopeid;
816 }
817 }
818
819 free(hostname2);
820
821 return error;
822#endif
823}
824
825static int
826get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
827{
828
829 assert(pai != NULL);
830 assert(ai != NULL);
831 assert(str != NULL);
832
833 if ((pai->ai_flags & AI_CANONNAME) != 0) {
834 ai->ai_canonname = strdup(str);
835 if (ai->ai_canonname == NULL)
836 return EAI_MEMORY;
837 }
838 return 0;
839}
840
841static struct addrinfo *
842get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
843{
844 char *p;
845 struct addrinfo *ai;
846
847 assert(pai != NULL);
848 assert(afd != NULL);
849 assert(addr != NULL);
850
851 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
852 + (afd->a_socklen));
853 if (ai == NULL)
854 return NULL;
855
856 memcpy(ai, pai, sizeof(struct addrinfo));
857 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
858 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
859
860#ifdef HAVE_SA_LEN
861 ai->ai_addr->sa_len = afd->a_socklen;
862#endif
863
864 ai->ai_addrlen = afd->a_socklen;
865#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
866 ai->__ai_pad0 = 0;
867#endif
868 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
869 p = (char *)(void *)(ai->ai_addr);
870 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
871 return ai;
872}
873
874static int
875get_portmatch(const struct addrinfo *ai, const char *servname)
876{
877
878 assert(ai != NULL);
879 /* servname may be NULL */
880
881 return get_port(ai, servname, 1);
882}
883
884static int
885get_port(const struct addrinfo *ai, const char *servname, int matchonly)
886{
887 const char *proto;
888 struct servent *sp;
889 int port;
890 int allownumeric;
891
892 assert(ai != NULL);
893 /* servname may be NULL */
894
895 if (servname == NULL)
896 return 0;
897 switch (ai->ai_family) {
898 case AF_INET:
899#ifdef AF_INET6
900 case AF_INET6:
901#endif
902 break;
903 default:
904 return 0;
905 }
906
907 switch (ai->ai_socktype) {
908 case SOCK_RAW:
909 return EAI_SERVICE;
910 case SOCK_DGRAM:
911 case SOCK_STREAM:
912 allownumeric = 1;
913 break;
914 case ANY:
915 allownumeric = 0;
916 break;
917 default:
918 return EAI_SOCKTYPE;
919 }
920
921 port = str2number(servname);
922 if (port >= 0) {
923 if (!allownumeric)
924 return EAI_SERVICE;
925 if (port < 0 || port > 65535)
926 return EAI_SERVICE;
927 port = htons(port);
928 } else {
929 if (ai->ai_flags & AI_NUMERICSERV)
930 return EAI_NONAME;
931
932 switch (ai->ai_socktype) {
933 case SOCK_DGRAM:
934 proto = "udp";
935 break;
936 case SOCK_STREAM:
937 proto = "tcp";
938 break;
939 default:
940 proto = NULL;
941 break;
942 }
943
944 if ((sp = getservbyname(servname, proto)) == NULL)
945 return EAI_SERVICE;
946 port = sp->s_port;
947 }
948
949 if (!matchonly) {
950 switch (ai->ai_family) {
951 case AF_INET:
952 ((struct sockaddr_in *)(void *)
953 ai->ai_addr)->sin_port = port;
954 break;
955#ifdef INET6
956 case AF_INET6:
957 ((struct sockaddr_in6 *)(void *)
958 ai->ai_addr)->sin6_port = port;
959 break;
960#endif
961 }
962 }
963
964 return 0;
965}
966
967static const struct afd *
968find_afd(int af)
969{
970 const struct afd *afd;
971
972 if (af == PF_UNSPEC)
973 return NULL;
974 for (afd = afdl; afd->a_af; afd++) {
975 if (afd->a_af == af)
976 return afd;
977 }
978 return NULL;
979}
980
981#ifdef INET6
982/* convert a string to a scope identifier. XXX: IPv6 specific */
983static int
984ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
985{
986 u_long lscopeid;
987 struct in6_addr *a6;
988 char *ep;
989
990 assert(scope != NULL);
991 assert(sin6 != NULL);
992 assert(scopeid != NULL);
993
994 a6 = &sin6->sin6_addr;
995
996 /* empty scopeid portion is invalid */
997 if (*scope == '\0')
998 return -1;
999
1000 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1001 /*
1002 * We currently assume a one-to-one mapping between links
1003 * and interfaces, so we simply use interface indices for
1004 * like-local scopes.
1005 */
1006 *scopeid = if_nametoindex(scope);
1007 if (*scopeid == 0)
1008 goto trynumeric;
1009 return 0;
1010 }
1011
1012 /* still unclear about literal, allow numeric only - placeholder */
1013 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1014 goto trynumeric;
1015 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1016 goto trynumeric;
1017 else
1018 goto trynumeric; /* global */
1019
1020 /* try to convert to a numeric id as a last resort */
1021 trynumeric:
1022 errno = 0;
1023 lscopeid = strtoul(scope, &ep, 10);
1024 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1025 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1026 return 0;
1027 else
1028 return -1;
1029}
1030#endif
1031
1032/* code duplicate with gethnamaddr.c */
1033
1034static const char AskedForGot[] =
1035 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1036
1037static struct addrinfo *
1038getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1039 const struct addrinfo *pai)
1040{
1041 struct addrinfo sentinel, *cur;
1042 struct addrinfo ai;
1043 const struct afd *afd;
1044 char *canonname;
1045 const HEADER *hp;
1046 const u_char *cp;
1047 int n;
1048 const u_char *eom;
1049 char *bp, *ep;
1050 int type, class, ancount, qdcount;
1051 int haveanswer, had_error;
1052 char tbuf[MAXDNAME];
1053 int (*name_ok) (const char *);
1054 char hostbuf[8*1024];
1055
1056 assert(answer != NULL);
1057 assert(qname != NULL);
1058 assert(pai != NULL);
1059
1060 memset(&sentinel, 0, sizeof(sentinel));
1061 cur = &sentinel;
1062
1063 canonname = NULL;
1064 eom = answer->buf + anslen;
1065 switch (qtype) {
1066 case T_A:
1067 case T_AAAA:
1068 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1069 name_ok = res_hnok;
1070 break;
1071 default:
1072 return NULL; /* XXX should be abort(); */
1073 }
1074 /*
1075 * find first satisfactory answer
1076 */
1077 hp = &answer->hdr;
1078 ancount = ntohs(hp->ancount);
1079 qdcount = ntohs(hp->qdcount);
1080 bp = hostbuf;
1081 ep = hostbuf + sizeof hostbuf;
1082 cp = answer->buf + HFIXEDSZ;
1083 if (qdcount != 1) {
1084 h_errno = NO_RECOVERY;
1085 return (NULL);
1086 }
1087 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1088 if ((n < 0) || !(*name_ok)(bp)) {
1089 h_errno = NO_RECOVERY;
1090 return (NULL);
1091 }
1092 cp += n + QFIXEDSZ;
1093 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1094 /* res_send() has already verified that the query name is the
1095 * same as the one we sent; this just gets the expanded name
1096 * (i.e., with the succeeding search-domain tacked on).
1097 */
1098 n = strlen(bp) + 1; /* for the \0 */
1099 if (n >= MAXHOSTNAMELEN) {
1100 h_errno = NO_RECOVERY;
1101 return (NULL);
1102 }
1103 canonname = bp;
1104 bp += n;
1105 /* The qname can be abbreviated, but h_name is now absolute. */
1106 qname = canonname;
1107 }
1108 haveanswer = 0;
1109 had_error = 0;
1110 while (ancount-- > 0 && cp < eom && !had_error) {
1111 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1112 if ((n < 0) || !(*name_ok)(bp)) {
1113 had_error++;
1114 continue;
1115 }
1116 cp += n; /* name */
1117 type = _getshort(cp);
1118 cp += INT16SZ; /* type */
1119 class = _getshort(cp);
1120 cp += INT16SZ + INT32SZ; /* class, TTL */
1121 n = _getshort(cp);
1122 cp += INT16SZ; /* len */
1123 if (class != C_IN) {
1124 /* XXX - debug? syslog? */
1125 cp += n;
1126 continue; /* XXX - had_error++ ? */
1127 }
1128 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1129 type == T_CNAME) {
1130 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1131 if ((n < 0) || !(*name_ok)(tbuf)) {
1132 had_error++;
1133 continue;
1134 }
1135 cp += n;
1136 /* Get canonical name. */
1137 n = strlen(tbuf) + 1; /* for the \0 */
1138 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1139 had_error++;
1140 continue;
1141 }
1142 strlcpy(bp, tbuf, (size_t)(ep - bp));
1143 canonname = bp;
1144 bp += n;
1145 continue;
1146 }
1147 if (qtype == T_ANY) {
1148 if (!(type == T_A || type == T_AAAA)) {
1149 cp += n;
1150 continue;
1151 }
1152 } else if (type != qtype) {
1153 if (type != T_KEY && type != T_SIG)
1154 syslog(LOG_NOTICE|LOG_AUTH,
1155 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1156 qname, p_class(C_IN), p_type(qtype),
1157 p_type(type));
1158 cp += n;
1159 continue; /* XXX - had_error++ ? */
1160 }
1161 switch (type) {
1162 case T_A:
1163 case T_AAAA:
1164 if (strcasecmp(canonname, bp) != 0) {
1165 syslog(LOG_NOTICE|LOG_AUTH,
1166 AskedForGot, canonname, bp);
1167 cp += n;
1168 continue; /* XXX - had_error++ ? */
1169 }
1170 if (type == T_A && n != INADDRSZ) {
1171 cp += n;
1172 continue;
1173 }
1174 if (type == T_AAAA && n != IN6ADDRSZ) {
1175 cp += n;
1176 continue;
1177 }
1178 if (type == T_AAAA) {
1179 struct in6_addr in6;
1180 memcpy(&in6, cp, IN6ADDRSZ);
1181 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1182 cp += n;
1183 continue;
1184 }
1185 }
1186 if (!haveanswer) {
1187 int nn;
1188
1189 canonname = bp;
1190 nn = strlen(bp) + 1; /* for the \0 */
1191 bp += nn;
1192 }
1193
1194 /* don't overwrite pai */
1195 ai = *pai;
1196 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1197 afd = find_afd(ai.ai_family);
1198 if (afd == NULL) {
1199 cp += n;
1200 continue;
1201 }
1202 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1203 if (cur->ai_next == NULL)
1204 had_error++;
1205 while (cur && cur->ai_next)
1206 cur = cur->ai_next;
1207 cp += n;
1208 break;
1209 default:
1210 abort();
1211 }
1212 if (!had_error)
1213 haveanswer++;
1214 }
1215 if (haveanswer) {
1216 if (!canonname)
1217 (void)get_canonname(pai, sentinel.ai_next, qname);
1218 else
1219 (void)get_canonname(pai, sentinel.ai_next, canonname);
1220 h_errno = NETDB_SUCCESS;
1221 return sentinel.ai_next;
1222 }
1223
1224 h_errno = NO_RECOVERY;
1225 return NULL;
1226}
1227
1228#define SORTEDADDR(p) (((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
1229#define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
1230
1231static void
1232aisort(struct addrinfo *s, res_state res)
1233{
1234 struct addrinfo head, *t, *p;
1235 int i;
1236
1237 head.ai_next = NULL;
1238 t = &head;
1239
1240 for (i = 0; i < res->nsort; i++) {
1241 p = s;
1242 while (p->ai_next) {
1243 if ((p->ai_next->ai_family != AF_INET)
1244 || SORTMATCH(p, res->sort_list[i])) {
1245 t->ai_next = p->ai_next;
1246 t = t->ai_next;
1247 p->ai_next = p->ai_next->ai_next;
1248 } else {
1249 p = p->ai_next;
1250 }
1251 }
1252 }
1253
1254 /* add rest of list and reset s to the new list*/
1255 t->ai_next = s->ai_next;
1256 s->ai_next = head.ai_next;
1257}
1258
1259/*ARGSUSED*/
1260static int
1261_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1262{
1263 struct addrinfo *ai;
1264 querybuf *buf, *buf2;
1265 const char *name;
1266 const struct addrinfo *pai;
1267 struct addrinfo sentinel, *cur;
1268 struct res_target q, q2;
1269 res_state res;
1270
1271 name = va_arg(ap, char *);
1272 pai = va_arg(ap, const struct addrinfo *);
1273
1274 fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
1275
1276 memset(&q, 0, sizeof(q));
1277 memset(&q2, 0, sizeof(q2));
1278 memset(&sentinel, 0, sizeof(sentinel));
1279 cur = &sentinel;
1280
1281 buf = malloc(sizeof(*buf));
1282 if (buf == NULL) {
1283 h_errno = NETDB_INTERNAL;
1284 return NS_NOTFOUND;
1285 }
1286 buf2 = malloc(sizeof(*buf2));
1287 if (buf2 == NULL) {
1288 free(buf);
1289 h_errno = NETDB_INTERNAL;
1290 return NS_NOTFOUND;
1291 }
1292
1293 switch (pai->ai_family) {
1294 case AF_UNSPEC:
1295 /* prefer IPv6 */
1296 q.name = name;
1297 q.qclass = C_IN;
1298 q.qtype = T_AAAA;
1299 q.answer = buf->buf;
1300 q.anslen = sizeof(buf->buf);
1301 q.next = &q2;
1302 q2.name = name;
1303 q2.qclass = C_IN;
1304 q2.qtype = T_A;
1305 q2.answer = buf2->buf;
1306 q2.anslen = sizeof(buf2->buf);
1307 break;
1308 case AF_INET:
1309 q.name = name;
1310 q.qclass = C_IN;
1311 q.qtype = T_A;
1312 q.answer = buf->buf;
1313 q.anslen = sizeof(buf->buf);
1314 break;
1315 case AF_INET6:
1316 q.name = name;
1317 q.qclass = C_IN;
1318 q.qtype = T_AAAA;
1319 q.answer = buf->buf;
1320 q.anslen = sizeof(buf->buf);
1321 break;
1322 default:
1323 free(buf);
1324 free(buf2);
1325 return NS_UNAVAIL;
1326 }
1327
1328 res = __res_get_state();
1329 if (res == NULL) {
1330 free(buf);
1331 free(buf2);
1332 return NS_NOTFOUND;
1333 }
1334
1335 if (res_searchN(name, &q, res) < 0) {
1336 __res_put_state(res);
1337 free(buf);
1338 free(buf2);
1339 return NS_NOTFOUND;
1340 }
1341 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1342 if (ai) {
1343 cur->ai_next = ai;
1344 while (cur && cur->ai_next)
1345 cur = cur->ai_next;
1346 }
1347 if (q.next) {
1348 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1349 if (ai)
1350 cur->ai_next = ai;
1351 }
1352 free(buf);
1353 free(buf2);
1354 if (sentinel.ai_next == NULL) {
1355 __res_put_state(res);
1356 switch (h_errno) {
1357 case HOST_NOT_FOUND:
1358 return NS_NOTFOUND;
1359 case TRY_AGAIN:
1360 return NS_TRYAGAIN;
1361 default:
1362 return NS_UNAVAIL;
1363 }
1364 }
1365
1366 if (res->nsort)
1367 aisort(&sentinel, res);
1368
1369 __res_put_state(res);
1370
1371 *((struct addrinfo **)rv) = sentinel.ai_next;
1372 return NS_SUCCESS;
1373}
1374
1375static void
1376_sethtent(FILE **hostf)
1377{
1378
1379 if (!*hostf)
1380 *hostf = fopen(_PATH_HOSTS, "r" );
1381 else
1382 rewind(*hostf);
1383}
1384
1385static void
1386_endhtent(FILE **hostf)
1387{
1388
1389 if (*hostf) {
1390 (void) fclose(*hostf);
1391 *hostf = NULL;
1392 }
1393}
1394
1395static struct addrinfo *
1396_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
1397{
1398 char *p;
1399 char *cp, *tname, *cname;
1400 struct addrinfo hints, *res0, *res;
1401 int error;
1402 const char *addr;
1403 char hostbuf[8*1024];
1404
1405// fprintf(stderr, "_gethtent() name = '%s'\n", name);
1406 assert(name != NULL);
1407 assert(pai != NULL);
1408
1409 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
1410 return (NULL);
1411 again:
1412 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
1413 return (NULL);
1414 if (*p == '#')
1415 goto again;
1416 if (!(cp = strpbrk(p, "#\n")))
1417 goto again;
1418 *cp = '\0';
1419 if (!(cp = strpbrk(p, " \t")))
1420 goto again;
1421 *cp++ = '\0';
1422 addr = p;
1423 /* if this is not something we're looking for, skip it. */
1424 cname = NULL;
1425 while (cp && *cp) {
1426 if (*cp == ' ' || *cp == '\t') {
1427 cp++;
1428 continue;
1429 }
1430 if (!cname)
1431 cname = cp;
1432 tname = cp;
1433 if ((cp = strpbrk(cp, " \t")) != NULL)
1434 *cp++ = '\0';
1435// fprintf(stderr, "\ttname = '%s'", tname);
1436 if (strcasecmp(name, tname) == 0)
1437 goto found;
1438 }
1439 goto again;
1440
1441found:
1442 hints = *pai;
1443 hints.ai_flags = AI_NUMERICHOST;
1444 error = getaddrinfo(addr, NULL, &hints, &res0);
1445 if (error)
1446 goto again;
1447 for (res = res0; res; res = res->ai_next) {
1448 /* cover it up */
1449 res->ai_flags = pai->ai_flags;
1450
1451 if (pai->ai_flags & AI_CANONNAME) {
1452 if (get_canonname(pai, res, cname) != 0) {
1453 freeaddrinfo(res0);
1454 goto again;
1455 }
1456 }
1457 }
1458 return res0;
1459}
1460
1461/*ARGSUSED*/
1462static int
1463_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
1464{
1465 const char *name;
1466 const struct addrinfo *pai;
1467 struct addrinfo sentinel, *cur;
1468 struct addrinfo *p;
1469 FILE *hostf = NULL;
1470
1471 name = va_arg(ap, char *);
1472 pai = va_arg(ap, struct addrinfo *);
1473
1474// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
1475 memset(&sentinel, 0, sizeof(sentinel));
1476 cur = &sentinel;
1477
1478 _sethtent(&hostf);
1479 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
1480 cur->ai_next = p;
1481 while (cur && cur->ai_next)
1482 cur = cur->ai_next;
1483 }
1484 _endhtent(&hostf);
1485
1486 *((struct addrinfo **)rv) = sentinel.ai_next;
1487 if (sentinel.ai_next == NULL)
1488 return NS_NOTFOUND;
1489 return NS_SUCCESS;
1490}
1491
1492/* resolver logic */
1493
1494/*
1495 * Formulate a normal query, send, and await answer.
1496 * Returned answer is placed in supplied buffer "answer".
1497 * Perform preliminary check of answer, returning success only
1498 * if no error is indicated and the answer count is nonzero.
1499 * Return the size of the response on success, -1 on error.
1500 * Error number is left in h_errno.
1501 *
1502 * Caller must parse answer and determine whether it answers the question.
1503 */
1504static int
1505res_queryN(const char *name, /* domain name */ struct res_target *target,
1506 res_state res)
1507{
1508 u_char buf[MAXPACKET];
1509 HEADER *hp;
1510 int n;
1511 struct res_target *t;
1512 int rcode;
1513 int ancount;
1514
1515 assert(name != NULL);
1516 /* XXX: target may be NULL??? */
1517
1518 rcode = NOERROR;
1519 ancount = 0;
1520
1521 for (t = target; t; t = t->next) {
1522 int class, type;
1523 u_char *answer;
1524 int anslen;
1525
1526 hp = (HEADER *)(void *)t->answer;
1527 hp->rcode = NOERROR; /* default */
1528
1529 /* make it easier... */
1530 class = t->qclass;
1531 type = t->qtype;
1532 answer = t->answer;
1533 anslen = t->anslen;
1534#ifdef DEBUG
1535 if (res->options & RES_DEBUG)
1536 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
1537#endif
1538
1539 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
1540 buf, sizeof(buf));
1541#ifdef RES_USE_EDNS0
1542 if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
1543 n = res_nopt(res, n, buf, sizeof(buf), anslen);
1544#endif
1545 if (n <= 0) {
1546#ifdef DEBUG
1547 if (res->options & RES_DEBUG)
1548 printf(";; res_nquery: mkquery failed\n");
1549#endif
1550 h_errno = NO_RECOVERY;
1551 return n;
1552 }
1553 n = res_nsend(res, buf, n, answer, anslen);
1554#if 0
1555 if (n < 0) {
1556#ifdef DEBUG
1557 if (res->options & RES_DEBUG)
1558 printf(";; res_query: send error\n");
1559#endif
1560 h_errno = TRY_AGAIN;
1561 return n;
1562 }
1563#endif
1564
1565 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1566 rcode = hp->rcode; /* record most recent error */
1567#ifdef DEBUG
1568 if (res->options & RES_DEBUG)
1569 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
1570 ntohs(hp->ancount));
1571#endif
1572 continue;
1573 }
1574
1575 ancount += ntohs(hp->ancount);
1576
1577 t->n = n;
1578 }
1579
1580 if (ancount == 0) {
1581 switch (rcode) {
1582 case NXDOMAIN:
1583 h_errno = HOST_NOT_FOUND;
1584 break;
1585 case SERVFAIL:
1586 h_errno = TRY_AGAIN;
1587 break;
1588 case NOERROR:
1589 h_errno = NO_DATA;
1590 break;
1591 case FORMERR:
1592 case NOTIMP:
1593 case REFUSED:
1594 default:
1595 h_errno = NO_RECOVERY;
1596 break;
1597 }
1598 return -1;
1599 }
1600 return ancount;
1601}
1602
1603/*
1604 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1605 * Return the size of the response on success, -1 on error.
1606 * If enabled, implement search rules until answer or unrecoverable failure
1607 * is detected. Error code, if any, is left in h_errno.
1608 */
1609static int
1610res_searchN(const char *name, struct res_target *target, res_state res)
1611{
1612 const char *cp, * const *domain;
1613 HEADER *hp;
1614 u_int dots;
1615 int trailing_dot, ret, saved_herrno;
1616 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1617
1618 assert(name != NULL);
1619 assert(target != NULL);
1620
1621 hp = (HEADER *)(void *)target->answer; /*XXX*/
1622
1623 errno = 0;
1624 h_errno = HOST_NOT_FOUND; /* default, if we never query */
1625 dots = 0;
1626 for (cp = name; *cp; cp++)
1627 dots += (*cp == '.');
1628 trailing_dot = 0;
1629 if (cp > name && *--cp == '.')
1630 trailing_dot++;
1631
1632
1633fprintf(stderr, "res_searchN() name = '%s'\n", name);
1634
1635 /*
1636 * if there aren't any dots, it could be a user-level alias
1637 */
1638 if (!dots && (cp = __hostalias(name)) != NULL) {
1639 ret = res_queryN(cp, target, res);
1640 return ret;
1641 }
1642
1643 /*
1644 * If there are dots in the name already, let's just give it a try
1645 * 'as is'. The threshold can be set with the "ndots" option.
1646 */
1647 saved_herrno = -1;
1648 if (dots >= res->ndots) {
1649 ret = res_querydomainN(name, NULL, target, res);
1650 if (ret > 0)
1651 return (ret);
1652 saved_herrno = h_errno;
1653 tried_as_is++;
1654 }
1655
1656 /*
1657 * We do at least one level of search if
1658 * - there is no dot and RES_DEFNAME is set, or
1659 * - there is at least one dot, there is no trailing dot,
1660 * and RES_DNSRCH is set.
1661 */
1662 if ((!dots && (res->options & RES_DEFNAMES)) ||
1663 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
1664 int done = 0;
1665
1666 for (domain = (const char * const *)res->dnsrch;
1667 *domain && !done;
1668 domain++) {
1669
1670 ret = res_querydomainN(name, *domain, target, res);
1671 if (ret > 0)
1672 return ret;
1673
1674 /*
1675 * If no server present, give up.
1676 * If name isn't found in this domain,
1677 * keep trying higher domains in the search list
1678 * (if that's enabled).
1679 * On a NO_DATA error, keep trying, otherwise
1680 * a wildcard entry of another type could keep us
1681 * from finding this entry higher in the domain.
1682 * If we get some other error (negative answer or
1683 * server failure), then stop searching up,
1684 * but try the input name below in case it's
1685 * fully-qualified.
1686 */
1687 if (errno == ECONNREFUSED) {
1688 h_errno = TRY_AGAIN;
1689 return -1;
1690 }
1691
1692 switch (h_errno) {
1693 case NO_DATA:
1694 got_nodata++;
1695 /* FALLTHROUGH */
1696 case HOST_NOT_FOUND:
1697 /* keep trying */
1698 break;
1699 case TRY_AGAIN:
1700 if (hp->rcode == SERVFAIL) {
1701 /* try next search element, if any */
1702 got_servfail++;
1703 break;
1704 }
1705 /* FALLTHROUGH */
1706 default:
1707 /* anything else implies that we're done */
1708 done++;
1709 }
1710 /*
1711 * if we got here for some reason other than DNSRCH,
1712 * we only wanted one iteration of the loop, so stop.
1713 */
1714 if (!(res->options & RES_DNSRCH))
1715 done++;
1716 }
1717 }
1718
1719 /*
1720 * if we have not already tried the name "as is", do that now.
1721 * note that we do this regardless of how many dots were in the
1722 * name or whether it ends with a dot.
1723 */
1724 if (!tried_as_is) {
1725 ret = res_querydomainN(name, NULL, target, res);
1726 if (ret > 0)
1727 return ret;
1728 }
1729
1730 /*
1731 * if we got here, we didn't satisfy the search.
1732 * if we did an initial full query, return that query's h_errno
1733 * (note that we wouldn't be here if that query had succeeded).
1734 * else if we ever got a nodata, send that back as the reason.
1735 * else send back meaningless h_errno, that being the one from
1736 * the last DNSRCH we did.
1737 */
1738 if (saved_herrno != -1)
1739 h_errno = saved_herrno;
1740 else if (got_nodata)
1741 h_errno = NO_DATA;
1742 else if (got_servfail)
1743 h_errno = TRY_AGAIN;
1744 return -1;
1745}
1746
1747/*
1748 * Perform a call on res_query on the concatenation of name and domain,
1749 * removing a trailing dot from name if domain is NULL.
1750 */
1751static int
1752res_querydomainN(const char *name, const char *domain,
1753 struct res_target *target, res_state res)
1754{
1755 char nbuf[MAXDNAME];
1756 const char *longname = nbuf;
1757 size_t n, d;
1758
1759 assert(name != NULL);
1760 /* XXX: target may be NULL??? */
1761
1762#ifdef DEBUG
1763 if (res->options & RES_DEBUG)
1764 printf(";; res_querydomain(%s, %s)\n",
1765 name, domain?domain:"<Nil>");
1766#endif
1767 if (domain == NULL) {
1768 /*
1769 * Check for trailing '.';
1770 * copy without '.' if present.
1771 */
1772 n = strlen(name);
1773 if (n + 1 > sizeof(nbuf)) {
1774 h_errno = NO_RECOVERY;
1775 return -1;
1776 }
1777 if (n > 0 && name[--n] == '.') {
1778 strncpy(nbuf, name, n);
1779 nbuf[n] = '\0';
1780 } else
1781 longname = name;
1782 } else {
1783 n = strlen(name);
1784 d = strlen(domain);
1785 if (n + 1 + d + 1 > sizeof(nbuf)) {
1786 h_errno = NO_RECOVERY;
1787 return -1;
1788 }
1789 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1790 }
1791 return res_queryN(longname, target, res);
1792}