summaryrefslogtreecommitdiff
path: root/src/lib/libc/net/getaddrinfo.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/libc/net/getaddrinfo.c')
-rw-r--r--src/lib/libc/net/getaddrinfo.c1748
1 files changed, 1748 insertions, 0 deletions
diff --git a/src/lib/libc/net/getaddrinfo.c b/src/lib/libc/net/getaddrinfo.c
new file mode 100644
index 0000000000..0f3b6319f4
--- /dev/null
+++ b/src/lib/libc/net/getaddrinfo.c
@@ -0,0 +1,1748 @@
1/* $OpenBSD: getaddrinfo.c,v 1.67 2007/05/20 03:54:52 ray Exp $ */
2/* $KAME: getaddrinfo.c,v 1.31 2000/08/31 17:36:43 itojun Exp $ */
3
4/*
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * Issues to be discussed:
35 * - Thread safe-ness must be checked.
36 * - Return values. There are nonstandard return values defined and used
37 * in the source code. This is because RFC2553 is silent about which error
38 * code must be returned for which situation.
39 * - IPv4 classful (shortened) form. RFC2553 is silent about it. XNET 5.2
40 * says to use inet_aton() to convert IPv4 numeric to binary (allows
41 * classful form as a result).
42 * current code - disallow classful form for IPv4 (due to use of inet_pton).
43 * - freeaddrinfo(NULL). RFC2553 is silent about it. XNET 5.2 says it is
44 * invalid.
45 * current code - SEGV on freeaddrinfo(NULL)
46 * Note:
47 * - We use getipnodebyname() just for thread-safeness. There's no intent
48 * to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
49 * getipnodebyname().
50 * - The code filters out AFs that are not supported by the kernel,
51 * when globbing NULL hostname (to loopback, or wildcard). Is it the right
52 * thing to do? What is the relationship with post-RFC2553 AI_ADDRCONFIG
53 * in ai_flags?
54 * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
55 * (1) what should we do against numeric hostname (2) what should we do
56 * against NULL hostname (3) what is AI_ADDRCONFIG itself. AF not ready?
57 * non-loopback address configured? global address configured?
58 * - To avoid search order issue, we have a big amount of code duplicate
59 * from gethnamaddr.c and some other places. The issues that there's no
60 * lower layer function to lookup "IPv4 or IPv6" record. Calling
61 * gethostbyname2 from getaddrinfo will end up in wrong search order, as
62 * follows:
63 * - The code makes use of following calls when asked to resolver with
64 * ai_family = PF_UNSPEC:
65 * getipnodebyname(host, AF_INET6);
66 * getipnodebyname(host, AF_INET);
67 * This will result in the following queries if the node is configure to
68 * prefer /etc/hosts than DNS:
69 * lookup /etc/hosts for IPv6 address
70 * lookup DNS for IPv6 address
71 * lookup /etc/hosts for IPv4 address
72 * lookup DNS for IPv4 address
73 * which may not meet people's requirement.
74 * The right thing to happen is to have underlying layer which does
75 * PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
76 * This would result in a bit of code duplicate with _dns_ghbyname() and
77 * friends.
78 */
79
80#ifndef INET6
81#define INET6
82#endif
83
84#include <sys/types.h>
85#include <sys/param.h>
86#include <sys/socket.h>
87#include <net/if.h>
88#include <netinet/in.h>
89#include <arpa/inet.h>
90#include <arpa/nameser.h>
91#include <netdb.h>
92#include <resolv.h>
93#include <string.h>
94#include <stdint.h>
95#include <stdlib.h>
96#include <stddef.h>
97#include <ctype.h>
98#include <unistd.h>
99#include <stdio.h>
100#include <errno.h>
101
102#include <syslog.h>
103#include <stdarg.h>
104
105#ifdef YP
106#include <rpc/rpc.h>
107#include <rpcsvc/yp.h>
108#include <rpcsvc/ypclnt.h>
109#include "ypinternal.h"
110#endif
111
112#include "thread_private.h"
113
114#define SUCCESS 0
115#define ANY 0
116#define YES 1
117#define NO 0
118
119static const char in_addrany[] = { 0, 0, 0, 0 };
120static const char in6_addrany[] = {
121 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
122};
123static const char in_loopback[] = { 127, 0, 0, 1 };
124static const char in6_loopback[] = {
125 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
126};
127
128static 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
150struct 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
161static 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#define MAXPACKET (64*1024)
186
187typedef union {
188 HEADER hdr;
189 u_char buf[MAXPACKET];
190} querybuf;
191
192struct res_target {
193 struct res_target *next;
194 const char *name; /* domain name */
195 int qclass, qtype; /* class and type of query */
196 u_char *answer; /* buffer to put answer */
197 int anslen; /* size of answer buffer */
198 int n; /* result length */
199};
200
201static int explore_fqdn(const struct addrinfo *, const char *,
202 const char *, struct addrinfo **);
203static int explore_null(const struct addrinfo *,
204 const char *, struct addrinfo **);
205static int explore_numeric(const struct addrinfo *, const char *,
206 const char *, struct addrinfo **, const char *);
207static int explore_numeric_scope(const struct addrinfo *, const char *,
208 const char *, struct addrinfo **);
209static int get_canonname(const struct addrinfo *,
210 struct addrinfo *, const char *);
211static struct addrinfo *get_ai(const struct addrinfo *,
212 const struct afd *, const char *);
213static int get_portmatch(const struct addrinfo *, const char *);
214static int get_port(struct addrinfo *, const char *, int);
215static const struct afd *find_afd(int);
216#ifdef INET6
217static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
218#endif
219
220static struct addrinfo * _gethtent(const char *, const struct addrinfo *,
221 FILE *);
222static struct addrinfo *_files_getaddrinfo(const char *,
223 const struct addrinfo *);
224
225#ifdef YP
226static struct addrinfo *_yphostent(char *, const struct addrinfo *);
227static struct addrinfo *_yp_getaddrinfo(const char *,
228 const struct addrinfo *);
229#endif
230
231static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
232 const struct addrinfo *);
233static int res_queryN(const char *, struct res_target *);
234static int res_searchN(const char *, struct res_target *);
235static int res_querydomainN(const char *, const char *, struct res_target *);
236static struct addrinfo *_dns_getaddrinfo(const char *, const struct addrinfo *);
237
238
239/* XXX macros that make external reference is BAD. */
240
241#define GET_AI(ai, afd, addr) \
242do { \
243 /* external reference: pai, error, and label free */ \
244 (ai) = get_ai(pai, (afd), (addr)); \
245 if ((ai) == NULL) { \
246 error = EAI_MEMORY; \
247 goto free; \
248 } \
249} while (/*CONSTCOND*/0)
250
251#define GET_PORT(ai, serv) \
252do { \
253 /* external reference: error and label free */ \
254 error = get_port((ai), (serv), 0); \
255 if (error != 0) \
256 goto free; \
257} while (/*CONSTCOND*/0)
258
259#define GET_CANONNAME(ai, str) \
260do { \
261 /* external reference: pai, error and label free */ \
262 error = get_canonname(pai, (ai), (str)); \
263 if (error != 0) \
264 goto free; \
265} while (/*CONSTCOND*/0)
266
267#define ERR(err) \
268do { \
269 /* external reference: error, and label bad */ \
270 error = (err); \
271 goto bad; \
272 /*NOTREACHED*/ \
273} while (/*CONSTCOND*/0)
274
275#define MATCH_FAMILY(x, y, w) \
276 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
277#define MATCH(x, y, w) \
278 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
279
280int
281getaddrinfo(const char *hostname, const char *servname,
282 const struct addrinfo *hints, struct addrinfo **res)
283{
284 struct addrinfo sentinel;
285 struct addrinfo *cur;
286 int error = 0;
287 struct addrinfo ai;
288 struct addrinfo ai0;
289 struct addrinfo *pai;
290 const struct explore *ex;
291
292 memset(&sentinel, 0, sizeof(sentinel));
293 cur = &sentinel;
294 pai = &ai;
295 pai->ai_flags = 0;
296 pai->ai_family = PF_UNSPEC;
297 pai->ai_socktype = ANY;
298 pai->ai_protocol = ANY;
299 pai->ai_addrlen = 0;
300 pai->ai_canonname = NULL;
301 pai->ai_addr = NULL;
302 pai->ai_next = NULL;
303
304 if (hostname == NULL && servname == NULL)
305 return EAI_NONAME;
306 if (hints) {
307 /* error check for hints */
308 if (hints->ai_addrlen || hints->ai_canonname ||
309 hints->ai_addr || hints->ai_next)
310 ERR(EAI_BADHINTS); /* xxx */
311 if (hints->ai_flags & ~AI_MASK)
312 ERR(EAI_BADFLAGS);
313 switch (hints->ai_family) {
314 case PF_UNSPEC:
315 case PF_INET:
316#ifdef INET6
317 case PF_INET6:
318#endif
319 break;
320 default:
321 ERR(EAI_FAMILY);
322 }
323 memcpy(pai, hints, sizeof(*pai));
324
325 /*
326 * if both socktype/protocol are specified, check if they
327 * are meaningful combination.
328 */
329 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
330 for (ex = explore; ex->e_af >= 0; ex++) {
331 if (pai->ai_family != ex->e_af)
332 continue;
333 if (ex->e_socktype == ANY)
334 continue;
335 if (ex->e_protocol == ANY)
336 continue;
337 if (pai->ai_socktype == ex->e_socktype
338 && pai->ai_protocol != ex->e_protocol) {
339 ERR(EAI_BADHINTS);
340 }
341 }
342 }
343 }
344
345 /*
346 * check for special cases. (1) numeric servname is disallowed if
347 * socktype/protocol are left unspecified. (2) servname is disallowed
348 * for raw and other inet{,6} sockets.
349 */
350 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
351#ifdef PF_INET6
352 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
353#endif
354 ) {
355 ai0 = *pai; /* backup *pai */
356
357 if (pai->ai_family == PF_UNSPEC) {
358#ifdef PF_INET6
359 pai->ai_family = PF_INET6;
360#else
361 pai->ai_family = PF_INET;
362#endif
363 }
364 error = get_portmatch(pai, servname);
365 if (error)
366 ERR(error);
367
368 *pai = ai0;
369 }
370
371 ai0 = *pai;
372
373 /* NULL hostname, or numeric hostname */
374 for (ex = explore; ex->e_af >= 0; ex++) {
375 *pai = ai0;
376
377 /* PF_UNSPEC entries are prepared for DNS queries only */
378 if (ex->e_af == PF_UNSPEC)
379 continue;
380
381 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
382 continue;
383 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
384 continue;
385 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
386 continue;
387
388 if (pai->ai_family == PF_UNSPEC)
389 pai->ai_family = ex->e_af;
390 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
391 pai->ai_socktype = ex->e_socktype;
392 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
393 pai->ai_protocol = ex->e_protocol;
394
395 if (hostname == NULL)
396 error = explore_null(pai, servname, &cur->ai_next);
397 else
398 error = explore_numeric_scope(pai, hostname, servname,
399 &cur->ai_next);
400
401 if (error)
402 goto free;
403
404 while (cur && cur->ai_next)
405 cur = cur->ai_next;
406 }
407
408 /*
409 * XXX
410 * If numeric representation of AF1 can be interpreted as FQDN
411 * representation of AF2, we need to think again about the code below.
412 */
413 if (sentinel.ai_next)
414 goto good;
415
416 if (hostname == NULL)
417 ERR(EAI_NODATA);
418 if (pai->ai_flags & AI_NUMERICHOST)
419 ERR(EAI_NONAME);
420
421 /*
422 * hostname as alphabetical name.
423 * we would like to prefer AF_INET6 than AF_INET, so we'll make an
424 * outer loop by AFs.
425 */
426 for (ex = explore; ex->e_af >= 0; ex++) {
427 *pai = ai0;
428
429 /* require exact match for family field */
430 if (pai->ai_family != ex->e_af)
431 continue;
432
433 if (!MATCH(pai->ai_socktype, ex->e_socktype,
434 WILD_SOCKTYPE(ex))) {
435 continue;
436 }
437 if (!MATCH(pai->ai_protocol, ex->e_protocol,
438 WILD_PROTOCOL(ex))) {
439 continue;
440 }
441
442 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
443 pai->ai_socktype = ex->e_socktype;
444 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
445 pai->ai_protocol = ex->e_protocol;
446
447 error = explore_fqdn(pai, hostname, servname,
448 &cur->ai_next);
449
450 while (cur && cur->ai_next)
451 cur = cur->ai_next;
452 }
453
454 /* XXX */
455 if (sentinel.ai_next)
456 error = 0;
457
458 if (error == 0) {
459 if (sentinel.ai_next) {
460 good:
461 *res = sentinel.ai_next;
462 return SUCCESS;
463 } else
464 error = EAI_FAIL;
465 }
466 free:
467 bad:
468 if (sentinel.ai_next)
469 freeaddrinfo(sentinel.ai_next);
470 *res = NULL;
471 return error;
472}
473
474/*
475 * FQDN hostname, DNS lookup
476 */
477
478static int
479explore_fqdn(const struct addrinfo *pai, const char *hostname,
480 const char *servname, struct addrinfo **res)
481{
482 struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
483 struct addrinfo *result;
484 struct addrinfo *cur;
485 int error = 0;
486 char lookups[MAXDNSLUS];
487 int i;
488 _THREAD_PRIVATE_MUTEX(_explore_mutex);
489
490 result = NULL;
491
492 /*
493 * if the servname does not match socktype/protocol, ignore it.
494 */
495 if (get_portmatch(pai, servname) != 0) {
496 return 0;
497 }
498
499 if (_res_init(0) == -1)
500 strlcpy(lookups, "f", sizeof lookups);
501 else {
502 bcopy(_resp->lookups, lookups, sizeof lookups);
503 if (lookups[0] == '\0')
504 strlcpy(lookups, "bf", sizeof lookups);
505 }
506
507 /*
508 * The yp/dns/files getaddrinfo functions are not thread safe.
509 * Protect them with a mutex.
510 */
511 _THREAD_PRIVATE_MUTEX_LOCK(_explore_mutex);
512 for (i = 0; i < MAXDNSLUS && result == NULL && lookups[i]; i++) {
513 switch (lookups[i]) {
514#ifdef YP
515 case 'y':
516 result = _yp_getaddrinfo(hostname, pai);
517 break;
518#endif
519 case 'b':
520 result = _dns_getaddrinfo(hostname, pai);
521 break;
522 case 'f':
523 result = _files_getaddrinfo(hostname, pai);
524 break;
525 }
526 }
527 _THREAD_PRIVATE_MUTEX_UNLOCK(_explore_mutex);
528 if (result) {
529 for (cur = result; cur; cur = cur->ai_next) {
530 GET_PORT(cur, servname);
531 /* canonname should be filled already */
532 }
533 *res = result;
534 return 0;
535 } else {
536 /* translate error code */
537 switch (h_errno) {
538 case NETDB_SUCCESS:
539 error = EAI_FAIL; /*XXX strange */
540 break;
541 case HOST_NOT_FOUND:
542 error = EAI_NODATA;
543 break;
544 case TRY_AGAIN:
545 error = EAI_AGAIN;
546 break;
547 case NO_RECOVERY:
548 error = EAI_FAIL;
549 break;
550 case NO_DATA:
551#if NO_ADDRESS != NO_DATA
552 case NO_ADDRESS:
553#endif
554 error = EAI_NODATA;
555 break;
556 default: /* unknown ones */
557 error = EAI_FAIL;
558 break;
559 }
560 }
561
562free:
563 if (result)
564 freeaddrinfo(result);
565 return error;
566}
567
568/*
569 * hostname == NULL.
570 * passive socket -> anyaddr (0.0.0.0 or ::)
571 * non-passive socket -> localhost (127.0.0.1 or ::1)
572 */
573static int
574explore_null(const struct addrinfo *pai, const char *servname,
575 struct addrinfo **res)
576{
577 int s;
578 const struct afd *afd;
579 struct addrinfo *cur;
580 struct addrinfo sentinel;
581 int error;
582
583 *res = NULL;
584 sentinel.ai_next = NULL;
585 cur = &sentinel;
586
587 /*
588 * filter out AFs that are not supported by the kernel
589 * XXX errno?
590 */
591 s = socket(pai->ai_family, SOCK_DGRAM, 0);
592 if (s < 0) {
593 if (errno != EMFILE)
594 return 0;
595 } else
596 close(s);
597
598 /*
599 * if the servname does not match socktype/protocol, ignore it.
600 */
601 if (get_portmatch(pai, servname) != 0)
602 return 0;
603
604 afd = find_afd(pai->ai_family);
605 if (afd == NULL)
606 return 0;
607
608 if (pai->ai_flags & AI_PASSIVE) {
609 GET_AI(cur->ai_next, afd, afd->a_addrany);
610 /* xxx meaningless?
611 * GET_CANONNAME(cur->ai_next, "anyaddr");
612 */
613 } else {
614 GET_AI(cur->ai_next, afd, afd->a_loopback);
615 /* xxx meaningless?
616 * GET_CANONNAME(cur->ai_next, "localhost");
617 */
618 }
619 GET_PORT(cur->ai_next, servname);
620 cur = cur->ai_next;
621
622 *res = sentinel.ai_next;
623 return 0;
624
625free:
626 if (sentinel.ai_next)
627 freeaddrinfo(sentinel.ai_next);
628 return error;
629}
630
631/*
632 * numeric hostname
633 */
634static int
635explore_numeric(const struct addrinfo *pai, const char *hostname,
636 const char *servname, struct addrinfo **res, const char *canonname)
637{
638 const struct afd *afd;
639 struct addrinfo *cur;
640 struct addrinfo sentinel;
641 int error;
642 char pton[PTON_MAX];
643
644 *res = NULL;
645 sentinel.ai_next = NULL;
646 cur = &sentinel;
647
648 /*
649 * if the servname does not match socktype/protocol, ignore it.
650 */
651 if (get_portmatch(pai, servname) != 0)
652 return 0;
653
654 afd = find_afd(pai->ai_family);
655 if (afd == NULL)
656 return 0;
657
658 switch (afd->a_af) {
659#if 0 /*X/Open spec*/
660 case AF_INET:
661 error = inet_aton(hostname, (struct in_addr *)pton);
662 break;
663#endif
664 default:
665 error = inet_pton(afd->a_af, hostname, pton);
666 break;
667 }
668 if (error == 1) {
669 if (pai->ai_family == afd->a_af ||
670 pai->ai_family == PF_UNSPEC /*?*/) {
671 GET_AI(cur->ai_next, afd, pton);
672 GET_PORT(cur->ai_next, servname);
673 if ((pai->ai_flags & AI_CANONNAME)) {
674 /*
675 * Set the numeric address itself as
676 * the canonical name, based on a
677 * clarification in rfc2553bis-03.
678 */
679 GET_CANONNAME(cur->ai_next, canonname);
680 }
681 while (cur && cur->ai_next)
682 cur = cur->ai_next;
683 } else
684 ERR(EAI_FAMILY); /*xxx*/
685 }
686
687 *res = sentinel.ai_next;
688 return 0;
689
690free:
691bad:
692 if (sentinel.ai_next)
693 freeaddrinfo(sentinel.ai_next);
694 return error;
695}
696
697/*
698 * numeric hostname with scope
699 */
700static int
701explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
702 const char *servname, struct addrinfo **res)
703{
704#if !defined(SCOPE_DELIMITER) || !defined(INET6)
705 return explore_numeric(pai, hostname, servname, res, hostname);
706#else
707 const struct afd *afd;
708 struct addrinfo *cur;
709 int error;
710 char *cp, *hostname2 = NULL, *scope, *addr;
711 struct sockaddr_in6 *sin6;
712
713 /*
714 * if the servname does not match socktype/protocol, ignore it.
715 */
716 if (get_portmatch(pai, servname) != 0)
717 return 0;
718
719 afd = find_afd(pai->ai_family);
720 if (afd == NULL)
721 return 0;
722
723 if (!afd->a_scoped)
724 return explore_numeric(pai, hostname, servname, res, hostname);
725
726 cp = strchr(hostname, SCOPE_DELIMITER);
727 if (cp == NULL)
728 return explore_numeric(pai, hostname, servname, res, hostname);
729
730 /*
731 * Handle special case of <scoped_address><delimiter><scope id>
732 */
733 hostname2 = strdup(hostname);
734 if (hostname2 == NULL)
735 return EAI_MEMORY;
736 /* terminate at the delimiter */
737 hostname2[cp - hostname] = '\0';
738 addr = hostname2;
739 scope = cp + 1;
740
741 error = explore_numeric(pai, addr, servname, res, hostname);
742 if (error == 0) {
743 u_int32_t scopeid;
744
745 for (cur = *res; cur; cur = cur->ai_next) {
746 if (cur->ai_family != AF_INET6)
747 continue;
748 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
749 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
750 free(hostname2);
751 return(EAI_NODATA); /* XXX: is return OK? */
752 }
753 sin6->sin6_scope_id = scopeid;
754 }
755 }
756
757 free(hostname2);
758
759 return error;
760#endif
761}
762
763static int
764get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
765{
766 if ((pai->ai_flags & AI_CANONNAME) != 0) {
767 ai->ai_canonname = strdup(str);
768 if (ai->ai_canonname == NULL)
769 return EAI_MEMORY;
770 }
771 return 0;
772}
773
774static struct addrinfo *
775get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
776{
777 char *p;
778 struct addrinfo *ai;
779
780 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
781 + (afd->a_socklen));
782 if (ai == NULL)
783 return NULL;
784
785 memcpy(ai, pai, sizeof(struct addrinfo));
786 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
787 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
788 ai->ai_addr->sa_len = afd->a_socklen;
789 ai->ai_addrlen = afd->a_socklen;
790 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
791 p = (char *)(void *)(ai->ai_addr);
792 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
793 return ai;
794}
795
796static int
797get_portmatch(const struct addrinfo *ai, const char *servname)
798{
799
800 /* get_port does not touch first argument. when matchonly == 1. */
801 /* LINTED const cast */
802 return get_port((struct addrinfo *)ai, servname, 1);
803}
804
805static int
806get_port(struct addrinfo *ai, const char *servname, int matchonly)
807{
808 const char *errstr, *proto;
809 int port;
810 int allownumeric;
811
812 if (servname == NULL)
813 return 0;
814 switch (ai->ai_family) {
815 case AF_INET:
816#ifdef AF_INET6
817 case AF_INET6:
818#endif
819 break;
820 default:
821 return 0;
822 }
823
824 switch (ai->ai_socktype) {
825 case SOCK_RAW:
826 return EAI_SERVICE;
827 case SOCK_DGRAM:
828 case SOCK_STREAM:
829 allownumeric = 1;
830 break;
831 case ANY:
832 allownumeric = 0;
833 break;
834 default:
835 return EAI_SOCKTYPE;
836 }
837
838 port = (int)strtonum(servname, 0, USHRT_MAX, &errstr);
839 if (!errstr) {
840 if (!allownumeric)
841 return EAI_SERVICE;
842 port = htons(port);
843 } else {
844 struct servent sp;
845 struct servent_data sd;
846
847 if (errno == ERANGE)
848 return EAI_SERVICE;
849 if (ai->ai_flags & AI_NUMERICSERV)
850 return EAI_NONAME;
851
852 switch (ai->ai_socktype) {
853 case SOCK_DGRAM:
854 proto = "udp";
855 break;
856 case SOCK_STREAM:
857 proto = "tcp";
858 break;
859 default:
860 proto = NULL;
861 break;
862 }
863
864 (void)memset(&sd, 0, sizeof(sd));
865 if (getservbyname_r(servname, proto, &sp, &sd) == -1)
866 return EAI_SERVICE;
867 port = sp.s_port;
868 endservent_r(&sd);
869 }
870
871 if (!matchonly) {
872 switch (ai->ai_family) {
873 case AF_INET:
874 ((struct sockaddr_in *)(void *)
875 ai->ai_addr)->sin_port = port;
876 break;
877#ifdef INET6
878 case AF_INET6:
879 ((struct sockaddr_in6 *)(void *)
880 ai->ai_addr)->sin6_port = port;
881 break;
882#endif
883 }
884 }
885
886 return 0;
887}
888
889static const struct afd *
890find_afd(int af)
891{
892 const struct afd *afd;
893
894 if (af == PF_UNSPEC)
895 return NULL;
896 for (afd = afdl; afd->a_af; afd++) {
897 if (afd->a_af == af)
898 return afd;
899 }
900 return NULL;
901}
902
903#ifdef INET6
904/* convert a string to a scope identifier. XXX: IPv6 specific */
905static int
906ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
907{
908 struct in6_addr *a6 = &sin6->sin6_addr;
909 const char *errstr;
910
911 /* empty scopeid portion is invalid */
912 if (*scope == '\0')
913 return -1;
914
915 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) ||
916 IN6_IS_ADDR_MC_INTFACELOCAL(a6)) {
917 /*
918 * We currently assume a one-to-one mapping between links
919 * and interfaces, so we simply use interface indices for
920 * like-local scopes.
921 */
922 *scopeid = if_nametoindex(scope);
923 if (*scopeid == 0)
924 goto trynumeric;
925 return 0;
926 }
927
928 /* still unclear about literal, allow numeric only - placeholder */
929 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
930 goto trynumeric;
931 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
932 goto trynumeric;
933 else
934 goto trynumeric; /* global */
935
936 /* try to convert to a numeric id as a last resort */
937 trynumeric:
938 *scopeid = (u_int32_t)strtonum(scope, 0, UINT32_MAX, &errstr);
939 if (errstr)
940 return (-1);
941 return (0);
942}
943#endif
944
945/* code duplicate with gethnamaddr.c */
946
947static const char AskedForGot[] =
948 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
949
950static struct addrinfo *
951getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
952 const struct addrinfo *pai)
953{
954 struct addrinfo sentinel, *cur;
955 struct addrinfo ai;
956 const struct afd *afd;
957 char *canonname;
958 const HEADER *hp;
959 const u_char *cp;
960 int n;
961 const u_char *eom;
962 char *bp, *ep;
963 int type, class, ancount, qdcount;
964 int haveanswer, had_error;
965 char tbuf[MAXDNAME];
966 int (*name_ok)(const char *);
967 char hostbuf[8*1024];
968
969 memset(&sentinel, 0, sizeof(sentinel));
970 cur = &sentinel;
971
972 canonname = NULL;
973 eom = answer->buf + anslen;
974 switch (qtype) {
975 case T_A:
976 case T_AAAA:
977 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
978 name_ok = res_hnok;
979 break;
980 default:
981 return (NULL); /* XXX should be abort() -- but that is illegal */
982 }
983 /*
984 * find first satisfactory answer
985 */
986 hp = &answer->hdr;
987 ancount = ntohs(hp->ancount);
988 qdcount = ntohs(hp->qdcount);
989 bp = hostbuf;
990 ep = hostbuf + sizeof hostbuf;
991 cp = answer->buf + HFIXEDSZ;
992 if (qdcount != 1) {
993 h_errno = NO_RECOVERY;
994 return (NULL);
995 }
996 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
997 if ((n < 0) || !(*name_ok)(bp)) {
998 h_errno = NO_RECOVERY;
999 return (NULL);
1000 }
1001 cp += n + QFIXEDSZ;
1002 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1003 size_t len;
1004
1005 /* res_send() has already verified that the query name is the
1006 * same as the one we sent; this just gets the expanded name
1007 * (i.e., with the succeeding search-domain tacked on).
1008 */
1009 len = strlen(bp) + 1; /* for the \0 */
1010 if (len >= MAXHOSTNAMELEN) {
1011 h_errno = NO_RECOVERY;
1012 return (NULL);
1013 }
1014 canonname = bp;
1015 bp += len;
1016 /* The qname can be abbreviated, but h_name is now absolute. */
1017 qname = canonname;
1018 }
1019 haveanswer = 0;
1020 had_error = 0;
1021 while (ancount-- > 0 && cp < eom && !had_error) {
1022 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1023 if ((n < 0) || !(*name_ok)(bp)) {
1024 had_error++;
1025 continue;
1026 }
1027 cp += n; /* name */
1028 type = _getshort(cp);
1029 cp += INT16SZ; /* type */
1030 class = _getshort(cp);
1031 cp += INT16SZ + INT32SZ; /* class, TTL */
1032 n = _getshort(cp);
1033 cp += INT16SZ; /* len */
1034 if (class != C_IN) {
1035 /* XXX - debug? syslog? */
1036 cp += n;
1037 continue; /* XXX - had_error++ ? */
1038 }
1039 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1040 type == T_CNAME) {
1041 size_t len;
1042
1043 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1044 if ((n < 0) || !(*name_ok)(tbuf)) {
1045 had_error++;
1046 continue;
1047 }
1048 cp += n;
1049 /* Get canonical name. */
1050 len = strlen(tbuf) + 1; /* for the \0 */
1051 if (len > ep - bp || len >= MAXHOSTNAMELEN) {
1052 had_error++;
1053 continue;
1054 }
1055 strlcpy(bp, tbuf, ep - bp);
1056 canonname = bp;
1057 bp += len;
1058 continue;
1059 }
1060 if (qtype == T_ANY) {
1061 if (!(type == T_A || type == T_AAAA)) {
1062 cp += n;
1063 continue;
1064 }
1065 } else if (type != qtype) {
1066 if (type != T_KEY && type != T_SIG) {
1067 struct syslog_data sdata = SYSLOG_DATA_INIT;
1068
1069 syslog_r(LOG_NOTICE|LOG_AUTH, &sdata,
1070 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1071 qname, p_class(C_IN), p_type(qtype),
1072 p_type(type));
1073 }
1074 cp += n;
1075 continue; /* XXX - had_error++ ? */
1076 }
1077 switch (type) {
1078 case T_A:
1079 case T_AAAA:
1080 if (strcasecmp(canonname, bp) != 0) {
1081 struct syslog_data sdata = SYSLOG_DATA_INIT;
1082
1083 syslog_r(LOG_NOTICE|LOG_AUTH, &sdata,
1084 AskedForGot, canonname, bp);
1085 cp += n;
1086 continue; /* XXX - had_error++ ? */
1087 }
1088 if (type == T_A && n != INADDRSZ) {
1089 cp += n;
1090 continue;
1091 }
1092 if (type == T_AAAA && n != IN6ADDRSZ) {
1093 cp += n;
1094 continue;
1095 }
1096 if (type == T_AAAA) {
1097 struct in6_addr in6;
1098 memcpy(&in6, cp, IN6ADDRSZ);
1099 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1100 cp += n;
1101 continue;
1102 }
1103 }
1104 if (!haveanswer) {
1105 canonname = bp;
1106 bp += strlen(bp) + 1; /* for the \0 */
1107 }
1108
1109 /* don't overwrite pai */
1110 ai = *pai;
1111 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1112 afd = find_afd(ai.ai_family);
1113 if (afd == NULL) {
1114 cp += n;
1115 continue;
1116 }
1117 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1118 if (cur->ai_next == NULL)
1119 had_error++;
1120 while (cur && cur->ai_next)
1121 cur = cur->ai_next;
1122 cp += n;
1123 break;
1124 default:
1125 abort(); /* XXX abort illegal in library */
1126 }
1127 if (!had_error)
1128 haveanswer++;
1129 }
1130 if (haveanswer) {
1131 if (!canonname)
1132 (void)get_canonname(pai, sentinel.ai_next, qname);
1133 else
1134 (void)get_canonname(pai, sentinel.ai_next, canonname);
1135 h_errno = NETDB_SUCCESS;
1136 return sentinel.ai_next;
1137 }
1138
1139 h_errno = NO_RECOVERY;
1140 return NULL;
1141}
1142
1143/*ARGSUSED*/
1144static struct addrinfo *
1145_dns_getaddrinfo(const char *name, const struct addrinfo *pai)
1146{
1147 struct addrinfo *ai;
1148 querybuf *buf, *buf2;
1149 struct addrinfo sentinel, *cur;
1150 struct res_target q, q2;
1151
1152 memset(&q, 0, sizeof(q));
1153 memset(&q2, 0, sizeof(q2));
1154 memset(&sentinel, 0, sizeof(sentinel));
1155 cur = &sentinel;
1156
1157 buf = malloc(sizeof(*buf));
1158 if (buf == NULL) {
1159 h_errno = NETDB_INTERNAL;
1160 return NULL;
1161 }
1162 buf2 = malloc(sizeof(*buf2));
1163 if (buf2 == NULL) {
1164 free(buf);
1165 h_errno = NETDB_INTERNAL;
1166 return NULL;
1167 }
1168
1169 switch (pai->ai_family) {
1170 case AF_UNSPEC:
1171 /* prefer IPv6 */
1172 q.qclass = C_IN;
1173 q.qtype = T_AAAA;
1174 q.answer = buf->buf;
1175 q.anslen = sizeof(buf->buf);
1176 q.next = &q2;
1177 q2.qclass = C_IN;
1178 q2.qtype = T_A;
1179 q2.answer = buf2->buf;
1180 q2.anslen = sizeof(buf2->buf);
1181 break;
1182 case AF_INET:
1183 q.qclass = C_IN;
1184 q.qtype = T_A;
1185 q.answer = buf->buf;
1186 q.anslen = sizeof(buf->buf);
1187 break;
1188 case AF_INET6:
1189 q.qclass = C_IN;
1190 q.qtype = T_AAAA;
1191 q.answer = buf->buf;
1192 q.anslen = sizeof(buf->buf);
1193 break;
1194 default:
1195 free(buf);
1196 free(buf2);
1197 return NULL;
1198 }
1199 if (res_searchN(name, &q) < 0) {
1200 free(buf);
1201 free(buf2);
1202 return NULL;
1203 }
1204 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1205 if (ai) {
1206 cur->ai_next = ai;
1207 while (cur && cur->ai_next)
1208 cur = cur->ai_next;
1209 }
1210 if (q.next) {
1211 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1212 if (ai)
1213 cur->ai_next = ai;
1214 }
1215 free(buf);
1216 free(buf2);
1217 return sentinel.ai_next;
1218}
1219
1220static struct addrinfo *
1221_gethtent(const char *name, const struct addrinfo *pai, FILE *hostf)
1222{
1223 char *p;
1224 char *cp, *tname, *cname;
1225 struct addrinfo hints, *res0, *res;
1226 int error;
1227 const char *addr;
1228 char hostbuf[8*1024];
1229
1230 again:
1231 if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
1232 return (NULL);
1233 if (*p == '#')
1234 goto again;
1235 if (!(cp = strpbrk(p, "#\n")))
1236 goto again;
1237 *cp = '\0';
1238 if (!(cp = strpbrk(p, " \t")))
1239 goto again;
1240 *cp++ = '\0';
1241 addr = p;
1242 /* if this is not something we're looking for, skip it. */
1243 cname = NULL;
1244 while (cp && *cp) {
1245 if (*cp == ' ' || *cp == '\t') {
1246 cp++;
1247 continue;
1248 }
1249 if (!cname)
1250 cname = cp;
1251 tname = cp;
1252 if ((cp = strpbrk(cp, " \t")) != NULL)
1253 *cp++ = '\0';
1254 if (strcasecmp(name, tname) == 0)
1255 goto found;
1256 }
1257 goto again;
1258
1259found:
1260 hints = *pai;
1261 hints.ai_flags = AI_NUMERICHOST;
1262 error = getaddrinfo(addr, NULL, &hints, &res0);
1263 if (error)
1264 goto again;
1265 for (res = res0; res; res = res->ai_next) {
1266 /* cover it up */
1267 res->ai_flags = pai->ai_flags;
1268
1269 if (pai->ai_flags & AI_CANONNAME) {
1270 if (get_canonname(pai, res, cname) != 0) {
1271 freeaddrinfo(res0);
1272 goto again;
1273 }
1274 }
1275 }
1276 return res0;
1277}
1278
1279/*ARGSUSED*/
1280static struct addrinfo *
1281_files_getaddrinfo(const char *name, const struct addrinfo *pai)
1282{
1283 struct addrinfo sentinel, *cur;
1284 struct addrinfo *p;
1285 FILE *hostf;
1286
1287 hostf = fopen(_PATH_HOSTS, "r");
1288 if (hostf == NULL)
1289 return NULL;
1290
1291 memset(&sentinel, 0, sizeof(sentinel));
1292 cur = &sentinel;
1293
1294 while ((p = _gethtent(name, pai, hostf)) != NULL) {
1295 cur->ai_next = p;
1296 while (cur && cur->ai_next)
1297 cur = cur->ai_next;
1298 }
1299 fclose(hostf);
1300
1301 return sentinel.ai_next;
1302}
1303
1304#ifdef YP
1305static char *__ypdomain;
1306
1307/*ARGSUSED*/
1308static struct addrinfo *
1309_yphostent(char *line, const struct addrinfo *pai)
1310{
1311 struct addrinfo sentinel, *cur;
1312 struct addrinfo hints, *res, *res0;
1313 int error;
1314 char *p = line;
1315 const char *addr, *canonname;
1316 char *nextline;
1317 char *cp;
1318
1319 addr = canonname = NULL;
1320
1321 memset(&sentinel, 0, sizeof(sentinel));
1322 cur = &sentinel;
1323
1324nextline:
1325 /* terminate line */
1326 cp = strchr(p, '\n');
1327 if (cp) {
1328 *cp++ = '\0';
1329 nextline = cp;
1330 } else
1331 nextline = NULL;
1332
1333 cp = strpbrk(p, " \t");
1334 if (cp == NULL) {
1335 if (canonname == NULL)
1336 return (NULL);
1337 else
1338 goto done;
1339 }
1340 *cp++ = '\0';
1341
1342 addr = p;
1343
1344 while (cp && *cp) {
1345 if (*cp == ' ' || *cp == '\t') {
1346 cp++;
1347 continue;
1348 }
1349 if (!canonname)
1350 canonname = cp;
1351 if ((cp = strpbrk(cp, " \t")) != NULL)
1352 *cp++ = '\0';
1353 }
1354
1355 hints = *pai;
1356 hints.ai_flags = AI_NUMERICHOST;
1357 error = getaddrinfo(addr, NULL, &hints, &res0);
1358 if (error == 0) {
1359 for (res = res0; res; res = res->ai_next) {
1360 /* cover it up */
1361 res->ai_flags = pai->ai_flags;
1362
1363 if (pai->ai_flags & AI_CANONNAME)
1364 (void)get_canonname(pai, res, canonname);
1365 }
1366 } else
1367 res0 = NULL;
1368 if (res0) {
1369 cur->ai_next = res0;
1370 while (cur && cur->ai_next)
1371 cur = cur->ai_next;
1372 }
1373
1374 if (nextline) {
1375 p = nextline;
1376 goto nextline;
1377 }
1378
1379done:
1380 return sentinel.ai_next;
1381}
1382
1383/*ARGSUSED*/
1384static struct addrinfo *
1385_yp_getaddrinfo(const char *name, const struct addrinfo *pai)
1386{
1387 struct addrinfo sentinel, *cur;
1388 struct addrinfo *ai = NULL;
1389 static char *__ypcurrent;
1390 int __ypcurrentlen, r;
1391
1392 memset(&sentinel, 0, sizeof(sentinel));
1393 cur = &sentinel;
1394
1395 if (!__ypdomain) {
1396 if (_yp_check(&__ypdomain) == 0)
1397 return NULL;
1398 }
1399 if (__ypcurrent)
1400 free(__ypcurrent);
1401 __ypcurrent = NULL;
1402
1403 /* hosts.byname is only for IPv4 (Solaris8) */
1404 if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
1405 r = yp_match(__ypdomain, "hosts.byname", name,
1406 (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1407 if (r == 0) {
1408 struct addrinfo ai4;
1409
1410 ai4 = *pai;
1411 ai4.ai_family = AF_INET;
1412 ai = _yphostent(__ypcurrent, &ai4);
1413 if (ai) {
1414 cur->ai_next = ai;
1415 while (cur && cur->ai_next)
1416 cur = cur->ai_next;
1417 }
1418 }
1419 }
1420
1421 /* ipnodes.byname can hold both IPv4/v6 */
1422 r = yp_match(__ypdomain, "ipnodes.byname", name,
1423 (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1424 if (r == 0) {
1425 ai = _yphostent(__ypcurrent, pai);
1426 if (ai) {
1427 cur->ai_next = ai;
1428 while (cur && cur->ai_next)
1429 cur = cur->ai_next;
1430 }
1431 }
1432
1433 return sentinel.ai_next;
1434}
1435#endif
1436
1437
1438/* resolver logic */
1439
1440extern const char *__hostalias(const char *);
1441extern int h_errno;
1442extern int res_opt(int, u_char *, int, int);
1443
1444/*
1445 * Formulate a normal query, send, and await answer.
1446 * Returned answer is placed in supplied buffer "answer".
1447 * Perform preliminary check of answer, returning success only
1448 * if no error is indicated and the answer count is nonzero.
1449 * Return the size of the response on success, -1 on error.
1450 * Error number is left in h_errno.
1451 *
1452 * Caller must parse answer and determine whether it answers the question.
1453 */
1454static int
1455res_queryN(const char *name, struct res_target *target)
1456{
1457 struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
1458 u_char *buf;
1459 HEADER *hp;
1460 int n;
1461 struct res_target *t;
1462 int rcode;
1463 int ancount;
1464
1465 buf = malloc(MAXPACKET);
1466 if (buf == NULL) {
1467 h_errno = NETDB_INTERNAL;
1468 return (-1);
1469 }
1470
1471 rcode = NOERROR;
1472 ancount = 0;
1473
1474 if (_res_init(0) == -1) {
1475 h_errno = NETDB_INTERNAL;
1476 free(buf);
1477 return (-1);
1478 }
1479
1480 for (t = target; t; t = t->next) {
1481 int class, type;
1482 u_char *answer;
1483 int anslen;
1484
1485 hp = (HEADER *)(void *)t->answer;
1486 hp->rcode = NOERROR; /* default */
1487
1488 /* make it easier... */
1489 class = t->qclass;
1490 type = t->qtype;
1491 answer = t->answer;
1492 anslen = t->anslen;
1493#ifdef DEBUG
1494 if (_resp->options & RES_DEBUG)
1495 printf(";; res_query(%s, %d, %d)\n", name, class, type);
1496#endif
1497
1498 n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
1499 buf, MAXPACKET);
1500 if (n > 0 && (_resp->options & RES_USE_EDNS0) != 0)
1501 n = res_opt(n, buf, MAXPACKET, anslen);
1502 if (n <= 0) {
1503#ifdef DEBUG
1504 if (_resp->options & RES_DEBUG)
1505 printf(";; res_query: mkquery failed\n");
1506#endif
1507 h_errno = NO_RECOVERY;
1508 free(buf);
1509 return (n);
1510 }
1511 n = res_send(buf, n, answer, anslen);
1512#if 0
1513 if (n < 0) {
1514#ifdef DEBUG
1515 if (_resp->options & RES_DEBUG)
1516 printf(";; res_query: send error\n");
1517#endif
1518 h_errno = TRY_AGAIN;
1519 free(buf);
1520 return (n);
1521 }
1522#endif
1523
1524 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1525 rcode = hp->rcode; /* record most recent error */
1526#ifdef DEBUG
1527 if (_resp->options & RES_DEBUG)
1528 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
1529 ntohs(hp->ancount));
1530#endif
1531 continue;
1532 }
1533
1534 ancount += ntohs(hp->ancount);
1535
1536 t->n = n;
1537 }
1538
1539 if (ancount == 0) {
1540 switch (rcode) {
1541 case NXDOMAIN:
1542 h_errno = HOST_NOT_FOUND;
1543 break;
1544 case SERVFAIL:
1545 h_errno = TRY_AGAIN;
1546 break;
1547 case NOERROR:
1548 h_errno = NO_DATA;
1549 break;
1550 case FORMERR:
1551 case NOTIMP:
1552 case REFUSED:
1553 default:
1554 h_errno = NO_RECOVERY;
1555 break;
1556 }
1557 free(buf);
1558 return (-1);
1559 }
1560 free(buf);
1561 return (ancount);
1562}
1563
1564/*
1565 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1566 * Return the size of the response on success, -1 on error.
1567 * If enabled, implement search rules until answer or unrecoverable failure
1568 * is detected. Error code, if any, is left in h_errno.
1569 */
1570static int
1571res_searchN(const char *name, struct res_target *target)
1572{
1573 struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
1574 const char *cp, * const *domain;
1575 HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/
1576 u_int dots;
1577 int trailing_dot, ret, saved_herrno;
1578 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1579
1580 if (_res_init(0) == -1) {
1581 h_errno = NETDB_INTERNAL;
1582 return (-1);
1583 }
1584
1585 errno = 0;
1586 h_errno = HOST_NOT_FOUND; /* default, if we never query */
1587 dots = 0;
1588 for (cp = name; *cp; cp++)
1589 dots += (*cp == '.');
1590 trailing_dot = 0;
1591 if (cp > name && *--cp == '.')
1592 trailing_dot++;
1593
1594 /*
1595 * if there aren't any dots, it could be a user-level alias
1596 */
1597 if (!dots && (cp = __hostalias(name)) != NULL)
1598 return (res_queryN(cp, target));
1599
1600 /*
1601 * If there are dots in the name already, let's just give it a try
1602 * 'as is'. The threshold can be set with the "ndots" option.
1603 */
1604 saved_herrno = -1;
1605 if (dots >= _resp->ndots) {
1606 ret = res_querydomainN(name, NULL, target);
1607 if (ret > 0)
1608 return (ret);
1609 saved_herrno = h_errno;
1610 tried_as_is++;
1611 }
1612
1613 /*
1614 * We do at least one level of search if
1615 * - there is no dot and RES_DEFNAME is set, or
1616 * - there is at least one dot, there is no trailing dot,
1617 * and RES_DNSRCH is set.
1618 */
1619 if ((!dots && (_resp->options & RES_DEFNAMES)) ||
1620 (dots && !trailing_dot && (_resp->options & RES_DNSRCH))) {
1621 int done = 0;
1622
1623 for (domain = (const char * const *)_resp->dnsrch;
1624 *domain && !done;
1625 domain++) {
1626
1627 ret = res_querydomainN(name, *domain, target);
1628 if (ret > 0)
1629 return (ret);
1630
1631 /*
1632 * If no server present, give up.
1633 * If name isn't found in this domain,
1634 * keep trying higher domains in the search list
1635 * (if that's enabled).
1636 * On a NO_DATA error, keep trying, otherwise
1637 * a wildcard entry of another type could keep us
1638 * from finding this entry higher in the domain.
1639 * If we get some other error (negative answer or
1640 * server failure), then stop searching up,
1641 * but try the input name below in case it's
1642 * fully-qualified.
1643 */
1644 if (errno == ECONNREFUSED) {
1645 h_errno = TRY_AGAIN;
1646 return (-1);
1647 }
1648
1649 switch (h_errno) {
1650 case NO_DATA:
1651 got_nodata++;
1652 /* FALLTHROUGH */
1653 case HOST_NOT_FOUND:
1654 /* keep trying */
1655 break;
1656 case TRY_AGAIN:
1657 if (hp->rcode == SERVFAIL) {
1658 /* try next search element, if any */
1659 got_servfail++;
1660 break;
1661 }
1662 /* FALLTHROUGH */
1663 default:
1664 /* anything else implies that we're done */
1665 done++;
1666 }
1667 /*
1668 * if we got here for some reason other than DNSRCH,
1669 * we only wanted one iteration of the loop, so stop.
1670 */
1671 if (!(_resp->options & RES_DNSRCH))
1672 done++;
1673 }
1674 }
1675
1676 /*
1677 * if we have not already tried the name "as is", do that now.
1678 * note that we do this regardless of how many dots were in the
1679 * name or whether it ends with a dot.
1680 */
1681 if (!tried_as_is) {
1682 ret = res_querydomainN(name, NULL, target);
1683 if (ret > 0)
1684 return (ret);
1685 }
1686
1687 /*
1688 * if we got here, we didn't satisfy the search.
1689 * if we did an initial full query, return that query's h_errno
1690 * (note that we wouldn't be here if that query had succeeded).
1691 * else if we ever got a nodata, send that back as the reason.
1692 * else send back meaningless h_errno, that being the one from
1693 * the last DNSRCH we did.
1694 */
1695 if (saved_herrno != -1)
1696 h_errno = saved_herrno;
1697 else if (got_nodata)
1698 h_errno = NO_DATA;
1699 else if (got_servfail)
1700 h_errno = TRY_AGAIN;
1701 return (-1);
1702}
1703
1704/*
1705 * Perform a call on res_query on the concatenation of name and domain,
1706 * removing a trailing dot from name if domain is NULL.
1707 */
1708static int
1709res_querydomainN(const char *name, const char *domain,
1710 struct res_target *target)
1711{
1712 struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
1713 char nbuf[MAXDNAME];
1714 const char *longname = nbuf;
1715 size_t len;
1716
1717 if (_res_init(0) == -1) {
1718 h_errno = NETDB_INTERNAL;
1719 return (-1);
1720 }
1721#ifdef DEBUG
1722 if (_resp->options & RES_DEBUG)
1723 printf(";; res_querydomain(%s, %s)\n",
1724 name, domain?domain:"<Nil>");
1725#endif
1726 if (domain == NULL) {
1727 /*
1728 * Check for trailing '.';
1729 * copy without '.' if present.
1730 */
1731 len = strlcpy(nbuf, name, sizeof(nbuf));
1732 if (len >= sizeof(nbuf)) {
1733 h_errno = NO_RECOVERY;
1734 return (-1);
1735 }
1736 if (len > 0 && nbuf[len - 1] == '.')
1737 nbuf[len - 1] = '\0';
1738 } else {
1739 int i;
1740
1741 i = snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1742 if (i < 0 || i >= sizeof(nbuf)) {
1743 h_errno = NO_RECOVERY;
1744 return (-1);
1745 }
1746 }
1747 return (res_queryN(longname, target));
1748}