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