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