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