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