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