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