xref: /freebsd/lib/libc/net/getaddrinfo.c (revision 73d3c964be93034daf26a55ebac38c2152769f74)
1 /*	$KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Issues to be discussed:
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  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
40  *   invalid.  Current code accepts NULL to be compatible with other OSes.
41  *
42  * Note:
43  * - The code filters out AFs that are not supported by the kernel,
44  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
45  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
46  *   in ai_flags?
47  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
48  *   (1) what should we do against numeric hostname (2) what should we do
49  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
50  *   non-loopback address configured?  global address configured?
51  *
52  * OS specific notes for freebsd4:
53  * - FreeBSD supported $GAI.  The code does not.
54  */
55 
56 #include "namespace.h"
57 #include <sys/param.h>
58 #include <sys/socket.h>
59 #include <net/if.h>
60 #include <netinet/in.h>
61 #include <net/if_types.h>
62 #include <ifaddrs.h>
63 #include <sys/queue.h>
64 #ifdef INET6
65 #include <sys/sysctl.h>
66 #include <sys/ioctl.h>
67 #include <netinet6/in6_var.h>
68 #include <netinet6/nd6.h>
69 #endif
70 #include <arpa/inet.h>
71 #include <arpa/nameser.h>
72 #include <rpc/rpc.h>
73 #include <rpcsvc/yp_prot.h>
74 #include <rpcsvc/ypclnt.h>
75 #include <netdb.h>
76 #include <resolv.h>
77 #include <string.h>
78 #include <stdlib.h>
79 #include <stddef.h>
80 #include <ctype.h>
81 #include <unistd.h>
82 #include <stdio.h>
83 #include <errno.h>
84 
85 #include "res_config.h"
86 
87 #ifdef DEBUG
88 #include <syslog.h>
89 #endif
90 
91 #include <stdarg.h>
92 #include <nsswitch.h>
93 #include "un-namespace.h"
94 #include "netdb_private.h"
95 #include "libc_private.h"
96 #ifdef NS_CACHING
97 #include "nscache.h"
98 #endif
99 
100 #define ANY 0
101 #define YES 1
102 #define NO  0
103 
104 static const char in_addrany[] = { 0, 0, 0, 0 };
105 static const char in_loopback[] = { 127, 0, 0, 1 };
106 #ifdef INET6
107 static const char in6_addrany[] = {
108 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
109 };
110 static const char in6_loopback[] = {
111 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
112 };
113 #endif
114 
115 struct policyqueue {
116 	TAILQ_ENTRY(policyqueue) pc_entry;
117 #ifdef INET6
118 	struct in6_addrpolicy pc_policy;
119 #endif
120 };
121 TAILQ_HEAD(policyhead, policyqueue);
122 
123 static const struct afd {
124 	int a_af;
125 	int a_addrlen;
126 	socklen_t a_socklen;
127 	int a_off;
128 	const char *a_addrany;
129 	const char *a_loopback;
130 	int a_scoped;
131 } afdl [] = {
132 #ifdef INET6
133 #define	N_INET6 0
134 	{PF_INET6, sizeof(struct in6_addr),
135 	 sizeof(struct sockaddr_in6),
136 	 offsetof(struct sockaddr_in6, sin6_addr),
137 	 in6_addrany, in6_loopback, 1},
138 #define	N_INET 1
139 #define	N_LOCAL 2
140 #else
141 #define	N_INET 0
142 #define	N_LOCAL 1
143 #endif
144 	{PF_INET, sizeof(struct in_addr),
145 	 sizeof(struct sockaddr_in),
146 	 offsetof(struct sockaddr_in, sin_addr),
147 	 in_addrany, in_loopback, 0},
148 #define	sizeofmember(type, member)	(sizeof(((type *)0)->member))
149 	{PF_LOCAL, sizeofmember(struct sockaddr_un, sun_path),
150 	 sizeof(struct sockaddr_un),
151 	 offsetof(struct sockaddr_un, sun_path),
152 	 NULL, NULL, 0},
153 	{0, 0, 0, 0, NULL, NULL, 0},
154 };
155 
156 struct explore {
157 	int e_af;
158 	int e_socktype;
159 	int e_protocol;
160 	int e_wild;
161 #define	AF_ANY		0x01
162 #define	SOCKTYPE_ANY	0x02
163 #define	PROTOCOL_ANY	0x04
164 #define WILD_AF(ex)		((ex)->e_wild & AF_ANY)
165 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & SOCKTYPE_ANY)
166 #define WILD_PROTOCOL(ex)	((ex)->e_wild & PROTOCOL_ANY)
167 };
168 
169 static const struct explore explore[] = {
170 #ifdef INET6
171 	{ PF_INET6, SOCK_DGRAM,	 IPPROTO_UDP,
172 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
173 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP,
174 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
175 	{ PF_INET6, SOCK_STREAM, IPPROTO_SCTP,
176 	    AF_ANY | SOCKTYPE_ANY },
177 	{ PF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP,
178 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
179 	{ PF_INET6, SOCK_DGRAM,	IPPROTO_UDPLITE,
180 	    AF_ANY | SOCKTYPE_ANY },
181 	{ PF_INET6, SOCK_RAW, ANY,
182 	    AF_ANY | PROTOCOL_ANY },
183 #endif
184 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP,
185 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
186 	{ PF_INET, SOCK_STREAM,	IPPROTO_TCP,
187 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
188 	{ PF_INET, SOCK_STREAM, IPPROTO_SCTP,
189 	    AF_ANY | SOCKTYPE_ANY },
190 	{ PF_INET, SOCK_SEQPACKET, IPPROTO_SCTP,
191 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
192 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDPLITE,
193 	    AF_ANY | SOCKTYPE_ANY },
194 	{ PF_INET, SOCK_RAW, ANY,
195 	    AF_ANY | PROTOCOL_ANY },
196 	{ PF_LOCAL, SOCK_DGRAM,	ANY,
197 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
198 	{ PF_LOCAL, SOCK_STREAM, ANY,
199 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
200 	{ PF_LOCAL, SOCK_SEQPACKET, ANY,
201 	    AF_ANY | SOCKTYPE_ANY | PROTOCOL_ANY },
202 	{ -1, 0, 0, 0 },
203 };
204 
205 #ifdef INET6
206 #define PTON_MAX	16
207 #else
208 #define PTON_MAX	4
209 #endif
210 
211 #define AIO_SRCFLAG_DEPRECATED	0x1
212 
213 struct ai_order {
214 	union {
215 		struct sockaddr_storage aiou_ss;
216 		struct sockaddr aiou_sa;
217 	} aio_src_un;
218 #define aio_srcsa aio_src_un.aiou_sa
219 	u_int32_t aio_srcflag;
220 	int aio_srcscope;
221 	int aio_dstscope;
222 	struct policyqueue *aio_srcpolicy;
223 	struct policyqueue *aio_dstpolicy;
224 	struct addrinfo *aio_ai;
225 	int aio_matchlen;
226 	int aio_initial_sequence;
227 };
228 
229 static const ns_src default_dns_files[] = {
230 	{ NSSRC_FILES, 	NS_SUCCESS },
231 	{ NSSRC_DNS, 	NS_SUCCESS },
232 	{ 0 }
233 };
234 
235 struct res_target {
236 	struct res_target *next;
237 	const char *name;	/* domain name */
238 	int qclass, qtype;	/* class and type of query */
239 	u_char *answer;		/* buffer to put answer */
240 	int anslen;		/* size of answer buffer */
241 	int n;			/* result length */
242 };
243 
244 #define MAXPACKET	(64*1024)
245 
246 typedef union {
247 	HEADER hdr;
248 	u_char buf[MAXPACKET];
249 } querybuf;
250 
251 static int str2number(const char *, int *);
252 static int explore_copy(const struct addrinfo *, const struct addrinfo *,
253 	struct addrinfo **);
254 static int explore_null(const struct addrinfo *,
255 	const char *, struct addrinfo **);
256 static int explore_numeric(const struct addrinfo *, const char *,
257 	const char *, struct addrinfo **, const char *);
258 static int explore_numeric_scope(const struct addrinfo *, const char *,
259 	const char *, struct addrinfo **);
260 static int get_canonname(const struct addrinfo *,
261 	struct addrinfo *, const char *);
262 static struct addrinfo *get_ai(const struct addrinfo *,
263 	const struct afd *, const char *);
264 static struct addrinfo *copy_ai(const struct addrinfo *);
265 static int get_portmatch(const struct addrinfo *, const char *);
266 static int get_port(struct addrinfo *, const char *, int);
267 static const struct afd *find_afd(int);
268 static int addrconfig(struct addrinfo *);
269 #ifdef INET6
270 static int is_ifdisabled(char *);
271 #endif
272 static void set_source(struct ai_order *, struct policyhead *);
273 static int comp_dst(const void *, const void *);
274 #ifdef INET6
275 static int ip6_str2scopeid(const char *, struct sockaddr_in6 *, u_int32_t *);
276 #endif
277 static int gai_addr2scopetype(struct sockaddr *);
278 
279 static int explore_fqdn(const struct addrinfo *, const char *,
280 	const char *, struct addrinfo **);
281 
282 static int reorder(struct addrinfo *);
283 static int get_addrselectpolicy(struct policyhead *);
284 static void free_addrselectpolicy(struct policyhead *);
285 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
286 	struct policyhead *);
287 static int matchlen(struct sockaddr *, struct sockaddr *);
288 
289 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
290 	const struct addrinfo *, res_state);
291 #if defined(RESOLVSORT)
292 static int addr4sort(struct addrinfo *, res_state);
293 #endif
294 static int _dns_getaddrinfo(void *, void *, va_list);
295 static void _sethtent(FILE **);
296 static void _endhtent(FILE **);
297 static struct addrinfo *_gethtent(FILE **, const char *,
298 	const struct addrinfo *);
299 static int _files_getaddrinfo(void *, void *, va_list);
300 #ifdef YP
301 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
302 static int _yp_getaddrinfo(void *, void *, va_list);
303 #endif
304 #ifdef NS_CACHING
305 static int addrinfo_id_func(char *, size_t *, va_list, void *);
306 static int addrinfo_marshal_func(char *, size_t *, void *, va_list, void *);
307 static int addrinfo_unmarshal_func(char *, size_t, void *, va_list, void *);
308 #endif
309 
310 static int res_queryN(const char *, struct res_target *, res_state);
311 static int res_searchN(const char *, struct res_target *, res_state);
312 static int res_querydomainN(const char *, const char *,
313 	struct res_target *, res_state);
314 
315 /* XXX macros that make external reference is BAD. */
316 
317 #define GET_AI(ai, afd, addr) \
318 do { \
319 	/* external reference: pai, error, and label free */ \
320 	(ai) = get_ai(pai, (afd), (addr)); \
321 	if ((ai) == NULL) { \
322 		error = EAI_MEMORY; \
323 		goto free; \
324 	} \
325 } while (/*CONSTCOND*/0)
326 
327 #define GET_PORT(ai, serv) \
328 do { \
329 	/* external reference: error and label free */ \
330 	error = get_port((ai), (serv), 0); \
331 	if (error != 0) \
332 		goto free; \
333 } while (/*CONSTCOND*/0)
334 
335 #define GET_CANONNAME(ai, str) \
336 do { \
337 	/* external reference: pai, error and label free */ \
338 	error = get_canonname(pai, (ai), (str)); \
339 	if (error != 0) \
340 		goto free; \
341 } while (/*CONSTCOND*/0)
342 
343 #define ERR(err) \
344 do { \
345 	/* external reference: error, and label bad */ \
346 	error = (err); \
347 	goto bad; \
348 	/*NOTREACHED*/ \
349 } while (/*CONSTCOND*/0)
350 
351 #define MATCH_FAMILY(x, y, w) \
352 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
353 #define MATCH(x, y, w) \
354 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
355 
356 void
freeaddrinfo(struct addrinfo * ai)357 freeaddrinfo(struct addrinfo *ai)
358 {
359 	struct addrinfo *next;
360 
361 	while (ai != NULL) {
362 		next = ai->ai_next;
363 		free(ai->ai_canonname);
364 		/* no need to free(ai->ai_addr) */
365 		free(ai);
366 		ai = next;
367 	}
368 }
369 
370 static int
str2number(const char * p,int * portp)371 str2number(const char *p, int *portp)
372 {
373 	char *ep;
374 	unsigned long v;
375 
376 	if (*p == '\0')
377 		return -1;
378 	ep = NULL;
379 	errno = 0;
380 	v = strtoul(p, &ep, 10);
381 	if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX) {
382 		*portp = v;
383 		return 0;
384 	} else
385 		return -1;
386 }
387 
388 int
getaddrinfo(const char * hostname,const char * servname,const struct addrinfo * hints,struct addrinfo ** res)389 getaddrinfo(const char *hostname, const char *servname,
390     const struct addrinfo *hints, struct addrinfo **res)
391 {
392 	struct addrinfo sentinel;
393 	struct addrinfo *cur;
394 	int error = 0;
395 	struct addrinfo ai, ai0, *afai;
396 	struct addrinfo *pai;
397 	const struct afd *afd;
398 	const struct explore *ex;
399 	struct addrinfo *afailist[nitems(afdl)];
400 	struct addrinfo *afai_unspec;
401 	int found;
402 	int numeric = 0;
403 
404 	/* ensure we return NULL on errors */
405 	*res = NULL;
406 
407 	memset(&ai, 0, sizeof(ai));
408 
409 	memset(afailist, 0, sizeof(afailist));
410 	afai_unspec = NULL;
411 
412 	memset(&sentinel, 0, sizeof(sentinel));
413 	cur = &sentinel;
414 	pai = &ai;
415 	pai->ai_flags = 0;
416 	pai->ai_family = PF_UNSPEC;
417 	pai->ai_socktype = ANY;
418 	pai->ai_protocol = ANY;
419 	pai->ai_addrlen = 0;
420 	pai->ai_canonname = NULL;
421 	pai->ai_addr = NULL;
422 	pai->ai_next = NULL;
423 
424 	if (hostname == NULL && servname == NULL)
425 		return EAI_NONAME;
426 	if (hints) {
427 		/* error check for hints */
428 		if (hints->ai_addrlen || hints->ai_canonname ||
429 		    hints->ai_addr || hints->ai_next)
430 			ERR(EAI_BADHINTS); /* xxx */
431 		if (hints->ai_flags & ~AI_MASK)
432 			ERR(EAI_BADFLAGS);
433 		switch (hints->ai_family) {
434 		case PF_UNSPEC:
435 		case PF_LOCAL:
436 		case PF_INET:
437 #ifdef INET6
438 		case PF_INET6:
439 #endif
440 			break;
441 		default:
442 			ERR(EAI_FAMILY);
443 		}
444 		memcpy(pai, hints, sizeof(*pai));
445 
446 		/*
447 		 * if both socktype/protocol are specified, check if they
448 		 * are meaningful combination.
449 		 */
450 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
451 			for (ex = explore; ex->e_af >= 0; ex++) {
452 				if (!MATCH_FAMILY(pai->ai_family, ex->e_af,
453 				    WILD_AF(ex)))
454 					continue;
455 				if (!MATCH(pai->ai_socktype, ex->e_socktype,
456 				    WILD_SOCKTYPE(ex)))
457 					continue;
458 				if (!MATCH(pai->ai_protocol, ex->e_protocol,
459 				    WILD_PROTOCOL(ex)))
460 					continue;
461 
462 				/* matched */
463 				break;
464 			}
465 
466 			if (ex->e_af < 0)
467 				ERR(EAI_BADHINTS);
468 		}
469 	}
470 
471 	/*
472 	 * RFC 3493: AI_ALL and AI_V4MAPPED are effective only against
473 	 * AF_INET6 query.  They need to be ignored if specified in other
474 	 * occasions.
475 	 */
476 	switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
477 	case AI_V4MAPPED:
478 	case AI_ALL | AI_V4MAPPED:
479 #ifdef INET6
480 		if (pai->ai_family != AF_INET6)
481 			pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
482 		break;
483 #endif
484 	case AI_ALL:
485 		pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
486 		break;
487 	}
488 
489 	/*
490 	 * check for special cases.  (1) numeric servname is disallowed if
491 	 * socktype/protocol are left unspecified. (2) servname is disallowed
492 	 * for raw and other inet{,6} sockets.
493 	 */
494 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
495 #ifdef PF_INET6
496 	    || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
497 #endif
498 	    ) {
499 		ai0 = *pai;	/* backup *pai */
500 
501 		if (pai->ai_family == PF_UNSPEC) {
502 #ifdef PF_INET6
503 			pai->ai_family = PF_INET6;
504 #else
505 			pai->ai_family = PF_INET;
506 #endif
507 		}
508 		error = get_portmatch(pai, servname);
509 		if (error)
510 			goto bad;
511 
512 		*pai = ai0;
513 	}
514 
515 	ai0 = *pai;
516 
517 	/*
518 	 * NULL hostname, or numeric hostname.
519 	 * If numeric representation of AF1 can be interpreted as FQDN
520 	 * representation of AF2, we need to think again about the code below.
521 	 */
522 	found = 0;
523 	for (afd = afdl; afd->a_af; afd++) {
524 		*pai = ai0;
525 
526 		if (!MATCH_FAMILY(pai->ai_family, afd->a_af, 1))
527 			continue;
528 
529 		if (pai->ai_family == PF_UNSPEC)
530 			pai->ai_family = afd->a_af;
531 
532 		if (hostname == NULL) {
533 			error = explore_null(pai, servname,
534 			    &afailist[afd - afdl]);
535 
536 			/*
537 			 * Errors from explore_null should be unexpected and
538 			 * be caught to avoid returning an incomplete result.
539 			 */
540 			if (error != 0)
541 				goto bad;
542 		} else {
543 			error = explore_numeric_scope(pai, hostname, servname,
544 			    &afailist[afd - afdl]);
545 
546 			/*
547 			 * explore_numeric_scope returns an error for address
548 			 * families that do not match that of hostname.
549 			 * Thus we should not catch the error at this moment.
550 			 */
551 		}
552 
553 		if (!error && afailist[afd - afdl])
554 			found++;
555 	}
556 	if (found) {
557 		numeric = 1;
558 		goto globcopy;
559 	}
560 
561 	if (hostname == NULL)
562 		ERR(EAI_NONAME);	/* used to be EAI_NODATA */
563 	if (pai->ai_flags & AI_NUMERICHOST)
564 		ERR(EAI_NONAME);
565 
566 	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
567 		ERR(EAI_FAIL);
568 
569 	/*
570 	 * hostname as alphabetical name.
571 	 */
572 	*pai = ai0;
573 	error = explore_fqdn(pai, hostname, servname, &afai_unspec);
574 
575 globcopy:
576 	for (ex = explore; ex->e_af >= 0; ex++) {
577 		*pai = ai0;
578 
579 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
580 			continue;
581 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
582 		    WILD_SOCKTYPE(ex)))
583 			continue;
584 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
585 		    WILD_PROTOCOL(ex)))
586 			continue;
587 
588 		if (pai->ai_family == PF_UNSPEC)
589 			pai->ai_family = ex->e_af;
590 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
591 			pai->ai_socktype = ex->e_socktype;
592 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
593 			pai->ai_protocol = ex->e_protocol;
594 
595 		/*
596 		 * if the servname does not match socktype/protocol, ignore it.
597 		 */
598 		if (get_portmatch(pai, servname) != 0)
599 			continue;
600 
601 		if (afai_unspec)
602 			afai = afai_unspec;
603 		else {
604 			if ((afd = find_afd(pai->ai_family)) == NULL)
605 				continue;
606 			/* XXX assumes that afd points inside afdl[] */
607 			afai = afailist[afd - afdl];
608 		}
609 		if (!afai)
610 			continue;
611 
612 		error = explore_copy(pai, afai, &cur->ai_next);
613 		if (error != 0)
614 			goto bad;
615 
616 		while (cur && cur->ai_next)
617 			cur = cur->ai_next;
618 	}
619 
620 	/*
621 	 * ensure we return either:
622 	 * - error == 0, non-NULL *res
623 	 * - error != 0, NULL *res
624 	 */
625 	if (error == 0) {
626 		if (sentinel.ai_next) {
627 			/*
628 			 * If the returned entry is for an active connection,
629 			 * and the given name is not numeric, reorder the
630 			 * list, so that the application would try the list
631 			 * in the most efficient order.  Since the head entry
632 			 * of the original list may contain ai_canonname and
633 			 * that entry may be moved elsewhere in the new list,
634 			 * we keep the pointer and will  restore it in the new
635 			 * head entry.  (Note that RFC3493 requires the head
636 			 * entry store it when requested by the caller).
637 			 */
638 			if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
639 				if (!numeric) {
640 					char *canonname;
641 
642 					canonname =
643 					    sentinel.ai_next->ai_canonname;
644 					sentinel.ai_next->ai_canonname = NULL;
645 					(void)reorder(&sentinel);
646 					if (sentinel.ai_next->ai_canonname ==
647 					    NULL) {
648 						sentinel.ai_next->ai_canonname
649 						    = canonname;
650 					} else if (canonname != NULL)
651 						free(canonname);
652 				}
653 			}
654 			*res = sentinel.ai_next;
655 		} else
656 			error = EAI_FAIL;
657 	}
658 
659 bad:
660 	if (afai_unspec)
661 		freeaddrinfo(afai_unspec);
662 	for (afd = afdl; afd->a_af; afd++) {
663 		if (afailist[afd - afdl])
664 			freeaddrinfo(afailist[afd - afdl]);
665 	}
666 	if (!*res)
667 		if (sentinel.ai_next)
668 			freeaddrinfo(sentinel.ai_next);
669 
670 	return (error);
671 }
672 
673 static int
reorder(struct addrinfo * sentinel)674 reorder(struct addrinfo *sentinel)
675 {
676 	struct addrinfo *ai, **aip;
677 	struct ai_order *aio;
678 	int i, n;
679 	struct policyhead policyhead;
680 
681 	/* count the number of addrinfo elements for sorting. */
682 	for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
683 		;
684 
685 	/*
686 	 * If the number is small enough, we can skip the reordering process.
687 	 */
688 	if (n <= 1)
689 		return(n);
690 
691 	/* allocate a temporary array for sort and initialization of it. */
692 	if ((aio = calloc(n, sizeof(*aio))) == NULL)
693 		return(n);	/* give up reordering */
694 
695 	/* retrieve address selection policy from the kernel */
696 	TAILQ_INIT(&policyhead);
697 	if (!get_addrselectpolicy(&policyhead)) {
698 		/* no policy is installed into kernel, we don't sort. */
699 		free(aio);
700 		return (n);
701 	}
702 
703 	for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
704 		aio[i].aio_ai = ai;
705 		aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
706 		aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
707 							      &policyhead);
708 		set_source(&aio[i], &policyhead);
709 		aio[i].aio_initial_sequence = i;
710 	}
711 
712 	/* perform sorting. */
713 	qsort(aio, n, sizeof(*aio), comp_dst);
714 
715 	/* reorder the addrinfo chain. */
716 	for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
717 		*aip = aio[i].aio_ai;
718 		aip = &aio[i].aio_ai->ai_next;
719 	}
720 	*aip = NULL;
721 
722 	/* cleanup and return */
723 	free(aio);
724 	free_addrselectpolicy(&policyhead);
725 	return(n);
726 }
727 
728 static int
get_addrselectpolicy(struct policyhead * head)729 get_addrselectpolicy(struct policyhead *head)
730 {
731 #ifdef INET6
732 	int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
733 	size_t l;
734 	char *buf;
735 	struct in6_addrpolicy *pol, *ep;
736 
737 	if (sysctl(mib, nitems(mib), NULL, &l, NULL, 0) < 0)
738 		return (0);
739 	if (l == 0)
740 		return (0);
741 	if ((buf = malloc(l)) == NULL)
742 		return (0);
743 	if (sysctl(mib, nitems(mib), buf, &l, NULL, 0) < 0) {
744 		free(buf);
745 		return (0);
746 	}
747 
748 	ep = (struct in6_addrpolicy *)(buf + l);
749 	for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
750 		struct policyqueue *new;
751 
752 		if ((new = malloc(sizeof(*new))) == NULL) {
753 			free_addrselectpolicy(head); /* make the list empty */
754 			break;
755 		}
756 		new->pc_policy = *pol;
757 		TAILQ_INSERT_TAIL(head, new, pc_entry);
758 	}
759 
760 	free(buf);
761 	return (1);
762 #else
763 	return (0);
764 #endif
765 }
766 
767 static void
free_addrselectpolicy(struct policyhead * head)768 free_addrselectpolicy(struct policyhead *head)
769 {
770 	struct policyqueue *ent, *nent;
771 
772 	for (ent = TAILQ_FIRST(head); ent; ent = nent) {
773 		nent = TAILQ_NEXT(ent, pc_entry);
774 		TAILQ_REMOVE(head, ent, pc_entry);
775 		free(ent);
776 	}
777 }
778 
779 static struct policyqueue *
match_addrselectpolicy(struct sockaddr * addr,struct policyhead * head)780 match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
781 {
782 #ifdef INET6
783 	struct policyqueue *ent, *bestent = NULL;
784 	struct in6_addrpolicy *pol;
785 	int matchlen, bestmatchlen = -1;
786 	u_char *mp, *ep, *k, *p, m;
787 	struct sockaddr_in6 key;
788 
789 	switch(addr->sa_family) {
790 	case AF_INET6:
791 		key = *(struct sockaddr_in6 *)addr;
792 		break;
793 	case AF_INET:
794 		/* convert the address into IPv4-mapped IPv6 address. */
795 		memset(&key, 0, sizeof(key));
796 		key.sin6_family = AF_INET6;
797 		key.sin6_len = sizeof(key);
798 		_map_v4v6_address(
799 		    (char *)&((struct sockaddr_in *)addr)->sin_addr,
800 		    (char *)&key.sin6_addr);
801 		break;
802 	default:
803 		return(NULL);
804 	}
805 
806 	for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
807 		pol = &ent->pc_policy;
808 		matchlen = 0;
809 
810 		mp = (u_char *)&pol->addrmask.sin6_addr;
811 		ep = mp + 16;	/* XXX: scope field? */
812 		k = (u_char *)&key.sin6_addr;
813 		p = (u_char *)&pol->addr.sin6_addr;
814 		for (; mp < ep && *mp; mp++, k++, p++) {
815 			m = *mp;
816 			if ((*k & m) != *p)
817 				goto next; /* not match */
818 			if (m == 0xff) /* short cut for a typical case */
819 				matchlen += 8;
820 			else {
821 				while (m >= 0x80) {
822 					matchlen++;
823 					m <<= 1;
824 				}
825 			}
826 		}
827 
828 		/* matched.  check if this is better than the current best. */
829 		if (matchlen > bestmatchlen) {
830 			bestent = ent;
831 			bestmatchlen = matchlen;
832 		}
833 
834 	  next:
835 		continue;
836 	}
837 
838 	return(bestent);
839 #else
840 	return(NULL);
841 #endif
842 
843 }
844 
845 static void
set_source(struct ai_order * aio,struct policyhead * ph)846 set_source(struct ai_order *aio, struct policyhead *ph)
847 {
848 	struct addrinfo ai = *aio->aio_ai;
849 	struct sockaddr_storage ss;
850 	socklen_t srclen;
851 	int s;
852 
853 	/* set unspec ("no source is available"), just in case */
854 	aio->aio_srcsa.sa_family = AF_UNSPEC;
855 	aio->aio_srcscope = -1;
856 
857 	switch(ai.ai_family) {
858 	case AF_INET:
859 #ifdef INET6
860 	case AF_INET6:
861 #endif
862 		break;
863 	default:		/* ignore unsupported AFs explicitly */
864 		return;
865 	}
866 
867 	/* XXX: make a dummy addrinfo to call connect() */
868 	ai.ai_socktype = SOCK_DGRAM;
869 	ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
870 	ai.ai_next = NULL;
871 	memset(&ss, 0, sizeof(ss));
872 	memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
873 	ai.ai_addr = (struct sockaddr *)&ss;
874 	get_port(&ai, "1", 0);
875 
876 	/* open a socket to get the source address for the given dst */
877 	if ((s = _socket(ai.ai_family, ai.ai_socktype | SOCK_CLOEXEC,
878 	    ai.ai_protocol)) < 0)
879 		return;		/* give up */
880 #ifdef INET6
881 	if (ai.ai_family == AF_INET6) {
882 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ai.ai_addr;
883 		int off = 0;
884 
885 		if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
886 			(void)_setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
887 			    (char *)&off, sizeof(off));
888 	}
889 #endif
890 	if (_connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
891 		goto cleanup;
892 	srclen = ai.ai_addrlen;
893 	if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
894 		aio->aio_srcsa.sa_family = AF_UNSPEC;
895 		goto cleanup;
896 	}
897 	aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
898 	aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
899 	aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
900 #ifdef INET6
901 	if (ai.ai_family == AF_INET6) {
902 		struct in6_ifreq ifr6;
903 		u_int32_t flags6;
904 
905 		memset(&ifr6, 0, sizeof(ifr6));
906 		memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
907 		if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
908 			flags6 = ifr6.ifr_ifru.ifru_flags6;
909 			if ((flags6 & IN6_IFF_DEPRECATED))
910 				aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
911 		}
912 	}
913 #endif
914 
915   cleanup:
916 	_close(s);
917 	return;
918 }
919 
920 static int
matchlen(struct sockaddr * src,struct sockaddr * dst)921 matchlen(struct sockaddr *src, struct sockaddr *dst)
922 {
923 	int match = 0;
924 	u_char *s, *d;
925 	u_char *lim, r;
926 	int addrlen;
927 
928 	switch (src->sa_family) {
929 #ifdef INET6
930 	case AF_INET6:
931 		s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
932 		d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
933 		addrlen = sizeof(struct in6_addr);
934 		lim = s + addrlen;
935 		break;
936 #endif
937 	case AF_INET:
938 		s = (u_char *)&((struct sockaddr_in *)src)->sin_addr;
939 		d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr;
940 		addrlen = sizeof(struct in_addr);
941 		lim = s + addrlen;
942 		break;
943 	default:
944 		return(0);
945 	}
946 
947 	while (s < lim)
948 		if ((r = (*d++ ^ *s++)) != 0) {
949 			while ((r & 0x80) == 0) {
950 				match++;
951 				r <<= 1;
952 			}
953 			break;
954 		} else
955 			match += 8;
956 	return(match);
957 }
958 
959 static int
comp_dst(const void * arg1,const void * arg2)960 comp_dst(const void *arg1, const void *arg2)
961 {
962 	const struct ai_order *dst1 = arg1, *dst2 = arg2;
963 
964 	/*
965 	 * Rule 1: Avoid unusable destinations.
966 	 * XXX: we currently do not consider if an appropriate route exists.
967 	 */
968 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
969 	    dst2->aio_srcsa.sa_family == AF_UNSPEC) {
970 		return(-1);
971 	}
972 	if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
973 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
974 		return(1);
975 	}
976 
977 	/* Rule 2: Prefer matching scope. */
978 	if (dst1->aio_dstscope == dst1->aio_srcscope &&
979 	    dst2->aio_dstscope != dst2->aio_srcscope) {
980 		return(-1);
981 	}
982 	if (dst1->aio_dstscope != dst1->aio_srcscope &&
983 	    dst2->aio_dstscope == dst2->aio_srcscope) {
984 		return(1);
985 	}
986 
987 	/* Rule 3: Avoid deprecated addresses. */
988 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
989 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
990 		if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
991 		    (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
992 			return(-1);
993 		}
994 		if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
995 		    !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
996 			return(1);
997 		}
998 	}
999 
1000 	/* Rule 4: Prefer home addresses. */
1001 	/* XXX: not implemented yet */
1002 
1003 	/* Rule 5: Prefer matching label. */
1004 #ifdef INET6
1005 	if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
1006 	    dst1->aio_srcpolicy->pc_policy.label ==
1007 	    dst1->aio_dstpolicy->pc_policy.label &&
1008 	    (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
1009 	     dst2->aio_srcpolicy->pc_policy.label !=
1010 	     dst2->aio_dstpolicy->pc_policy.label)) {
1011 		return(-1);
1012 	}
1013 	if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
1014 	    dst2->aio_srcpolicy->pc_policy.label ==
1015 	    dst2->aio_dstpolicy->pc_policy.label &&
1016 	    (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
1017 	     dst1->aio_srcpolicy->pc_policy.label !=
1018 	     dst1->aio_dstpolicy->pc_policy.label)) {
1019 		return(1);
1020 	}
1021 #endif
1022 
1023 	/* Rule 6: Prefer higher precedence. */
1024 #ifdef INET6
1025 	if (dst1->aio_dstpolicy &&
1026 	    (dst2->aio_dstpolicy == NULL ||
1027 	     dst1->aio_dstpolicy->pc_policy.preced >
1028 	     dst2->aio_dstpolicy->pc_policy.preced)) {
1029 		return(-1);
1030 	}
1031 	if (dst2->aio_dstpolicy &&
1032 	    (dst1->aio_dstpolicy == NULL ||
1033 	     dst2->aio_dstpolicy->pc_policy.preced >
1034 	     dst1->aio_dstpolicy->pc_policy.preced)) {
1035 		return(1);
1036 	}
1037 #endif
1038 
1039 	/* Rule 7: Prefer native transport. */
1040 	/* XXX: not implemented yet */
1041 
1042 	/* Rule 8: Prefer smaller scope. */
1043 	if (dst1->aio_dstscope >= 0 &&
1044 	    dst1->aio_dstscope < dst2->aio_dstscope) {
1045 		return(-1);
1046 	}
1047 	if (dst2->aio_dstscope >= 0 &&
1048 	    dst2->aio_dstscope < dst1->aio_dstscope) {
1049 		return(1);
1050 	}
1051 
1052 	/*
1053 	 * Rule 9: Use longest matching prefix.
1054 	 * We compare the match length in a same AF only.
1055 	 */
1056 	if (dst1->aio_ai->ai_addr->sa_family ==
1057 	    dst2->aio_ai->ai_addr->sa_family &&
1058 	    dst1->aio_ai->ai_addr->sa_family != AF_INET) {
1059 		if (dst1->aio_matchlen > dst2->aio_matchlen) {
1060 			return(-1);
1061 		}
1062 		if (dst1->aio_matchlen < dst2->aio_matchlen) {
1063 			return(1);
1064 		}
1065 	}
1066 
1067 	/* Rule 10: Otherwise, leave the order unchanged. */
1068 
1069 	/*
1070 	 * Note that qsort is unstable; so, we can't return zero and
1071 	 * expect the order to be unchanged.
1072 	 * That also means we can't depend on the current position of
1073 	 * dst2 being after dst1.  We must enforce the initial order
1074 	 * with an explicit compare on the original position.
1075 	 * The qsort specification requires that "When the same objects
1076 	 * (consisting of width bytes, irrespective of their current
1077 	 * positions in the array) are passed more than once to the
1078 	 * comparison function, the results shall be consistent with one
1079 	 * another."
1080 	 * In other words, If A < B, then we must also return B > A.
1081 	 */
1082 	if (dst2->aio_initial_sequence < dst1->aio_initial_sequence)
1083 		return(1);
1084 
1085 	return(-1);
1086 }
1087 
1088 /*
1089  * Copy from scope.c.
1090  * XXX: we should standardize the functions and link them as standard
1091  * library.
1092  */
1093 static int
gai_addr2scopetype(struct sockaddr * sa)1094 gai_addr2scopetype(struct sockaddr *sa)
1095 {
1096 #ifdef INET6
1097 	struct sockaddr_in6 *sa6;
1098 #endif
1099 	struct sockaddr_in *sa4;
1100 
1101 	switch(sa->sa_family) {
1102 #ifdef INET6
1103 	case AF_INET6:
1104 		sa6 = (struct sockaddr_in6 *)sa;
1105 		if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1106 			/* just use the scope field of the multicast address */
1107 			return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1108 		}
1109 		/*
1110 		 * Unicast addresses: map scope type to corresponding scope
1111 		 * value defined for multcast addresses.
1112 		 * XXX: hardcoded scope type values are bad...
1113 		 */
1114 		if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1115 			return(1); /* node local scope */
1116 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1117 			return(2); /* link-local scope */
1118 		if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1119 			return(5); /* site-local scope */
1120 		return(14);	/* global scope */
1121 		break;
1122 #endif
1123 	case AF_INET:
1124 		/*
1125 		 * IPv4 pseudo scoping according to RFC 3484.
1126 		 */
1127 		sa4 = (struct sockaddr_in *)sa;
1128 		/* IPv4 autoconfiguration addresses have link-local scope. */
1129 		if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1130 		    ((u_char *)&sa4->sin_addr)[1] == 254)
1131 			return(2);
1132 		/* Private addresses have site-local scope. */
1133 		if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1134 		    (((u_char *)&sa4->sin_addr)[0] == 172 &&
1135 		     (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1136 		    (((u_char *)&sa4->sin_addr)[0] == 192 &&
1137 		     ((u_char *)&sa4->sin_addr)[1] == 168))
1138 			return(14);	/* XXX: It should be 5 unless NAT */
1139 		/* Loopback addresses have link-local scope. */
1140 		if (((u_char *)&sa4->sin_addr)[0] == 127)
1141 			return(2);
1142 		return(14);
1143 		break;
1144 	default:
1145 		errno = EAFNOSUPPORT; /* is this a good error? */
1146 		return(-1);
1147 	}
1148 }
1149 
1150 static int
explore_copy(const struct addrinfo * pai,const struct addrinfo * src0,struct addrinfo ** res)1151 explore_copy(const struct addrinfo *pai, const struct addrinfo *src0,
1152     struct addrinfo **res)
1153 {
1154 	int error;
1155 	struct addrinfo sentinel, *cur;
1156 	const struct addrinfo *src;
1157 
1158 	error = 0;
1159 	sentinel.ai_next = NULL;
1160 	cur = &sentinel;
1161 
1162 	for (src = src0; src != NULL; src = src->ai_next) {
1163 		if (src->ai_family != pai->ai_family)
1164 			continue;
1165 
1166 		cur->ai_next = copy_ai(src);
1167 		if (!cur->ai_next) {
1168 			error = EAI_MEMORY;
1169 			goto fail;
1170 		}
1171 
1172 		cur->ai_next->ai_socktype = pai->ai_socktype;
1173 		cur->ai_next->ai_protocol = pai->ai_protocol;
1174 		cur = cur->ai_next;
1175 	}
1176 
1177 	*res = sentinel.ai_next;
1178 	return 0;
1179 
1180 fail:
1181 	freeaddrinfo(sentinel.ai_next);
1182 	return error;
1183 }
1184 
1185 /*
1186  * hostname == NULL.
1187  * passive socket -> anyaddr (0.0.0.0 or ::)
1188  * non-passive socket -> localhost (127.0.0.1 or ::1)
1189  */
1190 static int
explore_null(const struct addrinfo * pai,const char * servname,struct addrinfo ** res)1191 explore_null(const struct addrinfo *pai, const char *servname,
1192     struct addrinfo **res)
1193 {
1194 	int s;
1195 	const struct afd *afd;
1196 	struct addrinfo *ai;
1197 	int error;
1198 
1199 	*res = NULL;
1200 	ai = NULL;
1201 
1202 	if (pai->ai_family == PF_LOCAL)
1203 		return (0);
1204 
1205 	/*
1206 	 * filter out AFs that are not supported by the kernel
1207 	 * XXX errno?
1208 	 */
1209 	s = _socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1210 	if (s < 0) {
1211 		if (errno != EMFILE)
1212 			return 0;
1213 	} else
1214 		_close(s);
1215 
1216 	afd = find_afd(pai->ai_family);
1217 	if (afd == NULL)
1218 		return 0;
1219 
1220 	if (pai->ai_flags & AI_PASSIVE) {
1221 		GET_AI(ai, afd, afd->a_addrany);
1222 		GET_PORT(ai, servname);
1223 	} else {
1224 		GET_AI(ai, afd, afd->a_loopback);
1225 		GET_PORT(ai, servname);
1226 	}
1227 
1228 	*res = ai;
1229 	return 0;
1230 
1231 free:
1232 	if (ai != NULL)
1233 		freeaddrinfo(ai);
1234 	return error;
1235 }
1236 
1237 /*
1238  * numeric hostname
1239  */
1240 static int
explore_numeric(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res,const char * canonname)1241 explore_numeric(const struct addrinfo *pai, const char *hostname,
1242     const char *servname, struct addrinfo **res, const char *canonname)
1243 {
1244 	const struct afd *afd;
1245 	struct addrinfo *ai, ai0;
1246 	int error;
1247 	char pton[PTON_MAX], path[PATH_MAX], *p;
1248 
1249 #ifdef CTASSERT
1250 	CTASSERT(sizeofmember(struct sockaddr_un, sun_path) <= PATH_MAX);
1251 #endif
1252 	*res = NULL;
1253 	ai = NULL;
1254 
1255 	afd = find_afd(pai->ai_family);
1256 	if (afd == NULL)
1257 		return 0;
1258 
1259 	switch (afd->a_af) {
1260 	case AF_LOCAL:
1261 		if (hostname[0] != '/')
1262 			ERR(EAI_NONAME);
1263 		if (strlen(hostname) > afd->a_addrlen)
1264 			ERR(EAI_MEMORY);
1265 		/* NUL-termination does not need to be guaranteed. */
1266 		strncpy(path, hostname, afd->a_addrlen);
1267 		p = &path[0];
1268 		break;
1269 	case AF_INET:
1270 		/*
1271 		 * RFC3493 requires getaddrinfo() to accept AF_INET formats
1272 		 * that are accepted by inet_addr() and its family.  The
1273 		 * accepted forms includes the "classful" one, which inet_pton
1274 		 * does not accept.  So we need to separate the case for
1275 		 * AF_INET.
1276 		 */
1277 		if (inet_aton(hostname, (struct in_addr *)pton) != 1 ||
1278 		    hostname[strspn(hostname, "0123456789.xabcdefXABCDEF")] != '\0')
1279 			return 0;
1280 		p = pton;
1281 		break;
1282 	default:
1283 		if (inet_pton(afd->a_af, hostname, pton) != 1) {
1284 			if (pai->ai_family != AF_INET6 ||
1285 			    (pai->ai_flags & AI_V4MAPPED) != AI_V4MAPPED)
1286 				return 0;
1287 			if (inet_aton(hostname, (struct in_addr *)pton) != 1)
1288 				return 0;
1289 			afd = &afdl[N_INET];
1290 			ai0 = *pai;
1291 			ai0.ai_family = AF_INET;
1292 			pai = &ai0;
1293 		}
1294 		p = pton;
1295 		break;
1296 	}
1297 
1298 	if (pai->ai_family == afd->a_af) {
1299 		GET_AI(ai, afd, p);
1300 		GET_PORT(ai, servname);
1301 		if ((pai->ai_family == AF_INET ||
1302 		     pai->ai_family == AF_INET6) &&
1303 		    (pai->ai_flags & AI_CANONNAME)) {
1304 			/*
1305 			 * Set the numeric address itself as the canonical
1306 			 * name, based on a clarification in RFC3493.
1307 			 */
1308 			GET_CANONNAME(ai, canonname);
1309 		}
1310 	} else {
1311 		/*
1312 		 * XXX: This should not happen since we already matched the AF
1313 		 * by find_afd.
1314 		 */
1315 		ERR(EAI_FAMILY);
1316 	}
1317 
1318 	*res = ai;
1319 	return 0;
1320 
1321 free:
1322 bad:
1323 	if (ai != NULL)
1324 		freeaddrinfo(ai);
1325 	return error;
1326 }
1327 
1328 /*
1329  * numeric hostname with scope
1330  */
1331 static int
explore_numeric_scope(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res)1332 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1333     const char *servname, struct addrinfo **res)
1334 {
1335 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
1336 	return explore_numeric(pai, hostname, servname, res, hostname);
1337 #else
1338 	const struct afd *afd;
1339 	struct addrinfo *cur;
1340 	int error;
1341 	char *hostname2 = NULL, *addr;
1342 	const char *cp, *scope;
1343 	struct sockaddr_in6 *sin6;
1344 
1345 	afd = find_afd(pai->ai_family);
1346 	if (afd == NULL)
1347 		return 0;
1348 
1349 	if (!afd->a_scoped)
1350 		return explore_numeric(pai, hostname, servname, res, hostname);
1351 
1352 	cp = strchr(hostname, SCOPE_DELIMITER);
1353 	if (cp == NULL)
1354 		return explore_numeric(pai, hostname, servname, res, hostname);
1355 
1356 	/*
1357 	 * Handle special case of <scoped_address><delimiter><scope id>
1358 	 */
1359 	hostname2 = strdup(hostname);
1360 	if (hostname2 == NULL)
1361 		return EAI_MEMORY;
1362 	/* terminate at the delimiter */
1363 	hostname2[cp - hostname] = '\0';
1364 	addr = hostname2;
1365 	scope = cp + 1;
1366 
1367 	error = explore_numeric(pai, addr, servname, res, hostname);
1368 	if (error == 0) {
1369 		u_int32_t scopeid;
1370 
1371 		for (cur = *res; cur; cur = cur->ai_next) {
1372 			if (cur->ai_family != AF_INET6)
1373 				continue;
1374 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1375 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1376 				free(hostname2);
1377 				freeaddrinfo(*res);
1378 				*res = NULL;
1379 				return(EAI_NONAME); /* XXX: is return OK? */
1380 			}
1381 			sin6->sin6_scope_id = scopeid;
1382 		}
1383 	}
1384 
1385 	free(hostname2);
1386 
1387 	if (error && *res) {
1388 		freeaddrinfo(*res);
1389 		*res = NULL;
1390 	}
1391 	return error;
1392 #endif
1393 }
1394 
1395 static int
get_canonname(const struct addrinfo * pai,struct addrinfo * ai,const char * str)1396 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1397 {
1398 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
1399 		ai->ai_canonname = strdup(str);
1400 		if (ai->ai_canonname == NULL)
1401 			return EAI_MEMORY;
1402 	}
1403 	return 0;
1404 }
1405 
1406 static struct addrinfo *
get_ai(const struct addrinfo * pai,const struct afd * afd,const char * addr)1407 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1408 {
1409 	char *p;
1410 	struct addrinfo *ai;
1411 #ifdef INET6
1412 	struct in6_addr mapaddr;
1413 
1414 	if (afd->a_af == AF_INET && (pai->ai_flags & AI_V4MAPPED) != 0) {
1415 		afd = &afdl[N_INET6];
1416 		_map_v4v6_address(addr, (char *)&mapaddr);
1417 		addr = (char *)&mapaddr;
1418 	}
1419 #endif
1420 
1421 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1422 		+ (afd->a_socklen));
1423 	if (ai == NULL)
1424 		return NULL;
1425 
1426 	memcpy(ai, pai, sizeof(struct addrinfo));
1427 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1428 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1429 	ai->ai_addr->sa_len = afd->a_socklen;
1430 	ai->ai_addrlen = afd->a_socklen;
1431 	if (ai->ai_family == PF_LOCAL) {
1432 		size_t n = strnlen(addr, afd->a_addrlen);
1433 
1434 		ai->ai_addrlen -= afd->a_addrlen - n;
1435 		ai->ai_addr->sa_len -= afd->a_addrlen - n;
1436 	}
1437 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1438 	p = (char *)(void *)(ai->ai_addr);
1439 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1440 	return ai;
1441 }
1442 
1443 /* XXX need to malloc() the same way we do from other functions! */
1444 static struct addrinfo *
copy_ai(const struct addrinfo * pai)1445 copy_ai(const struct addrinfo *pai)
1446 {
1447 	struct addrinfo *ai;
1448 	size_t l;
1449 
1450 	l = sizeof(*ai) + pai->ai_addrlen;
1451 	if ((ai = calloc(1, l)) == NULL)
1452 		return NULL;
1453 	memcpy(ai, pai, sizeof(*ai));
1454 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1455 	memcpy(ai->ai_addr, pai->ai_addr, pai->ai_addrlen);
1456 
1457 	if (pai->ai_canonname) {
1458 		l = strlen(pai->ai_canonname) + 1;
1459 		if ((ai->ai_canonname = malloc(l)) == NULL) {
1460 			free(ai);
1461 			return NULL;
1462 		}
1463 		strlcpy(ai->ai_canonname, pai->ai_canonname, l);
1464 	} else {
1465 		/* just to make sure */
1466 		ai->ai_canonname = NULL;
1467 	}
1468 
1469 	ai->ai_next = NULL;
1470 
1471 	return ai;
1472 }
1473 
1474 static int
get_portmatch(const struct addrinfo * ai,const char * servname)1475 get_portmatch(const struct addrinfo *ai, const char *servname)
1476 {
1477 
1478 	/* get_port does not touch first argument when matchonly == 1. */
1479 	/* LINTED const cast */
1480 	return get_port((struct addrinfo *)ai, servname, 1);
1481 }
1482 
1483 static int
get_port(struct addrinfo * ai,const char * servname,int matchonly)1484 get_port(struct addrinfo *ai, const char *servname, int matchonly)
1485 {
1486 	const char *proto;
1487 	struct servent *sp;
1488 	int port, error;
1489 	int allownumeric;
1490 
1491 	if (servname == NULL)
1492 		return 0;
1493 	switch (ai->ai_family) {
1494 	case AF_LOCAL:
1495 		/* AF_LOCAL ignores servname silently. */
1496 		return (0);
1497 	case AF_INET:
1498 #ifdef AF_INET6
1499 	case AF_INET6:
1500 #endif
1501 		break;
1502 	default:
1503 		return 0;
1504 	}
1505 
1506 	switch (ai->ai_socktype) {
1507 	case SOCK_RAW:
1508 		return EAI_SERVICE;
1509 	case SOCK_DGRAM:
1510 	case SOCK_STREAM:
1511 	case SOCK_SEQPACKET:
1512 		allownumeric = 1;
1513 		break;
1514 	case ANY:
1515 		switch (ai->ai_family) {
1516 		case AF_INET:
1517 #ifdef AF_INET6
1518 		case AF_INET6:
1519 #endif
1520 			allownumeric = 1;
1521 			break;
1522 		default:
1523 			allownumeric = 0;
1524 			break;
1525 		}
1526 		break;
1527 	default:
1528 		return EAI_SOCKTYPE;
1529 	}
1530 
1531 	error = str2number(servname, &port);
1532 	if (error == 0) {
1533 		if (!allownumeric)
1534 			return EAI_SERVICE;
1535 		if (port < 0 || port > 65535)
1536 			return EAI_SERVICE;
1537 		port = htons(port);
1538 	} else {
1539 		if (ai->ai_flags & AI_NUMERICSERV)
1540 			return EAI_NONAME;
1541 
1542 		switch (ai->ai_protocol) {
1543 		case IPPROTO_UDP:
1544 			proto = "udp";
1545 			break;
1546 		case IPPROTO_TCP:
1547 			proto = "tcp";
1548 			break;
1549 		case IPPROTO_SCTP:
1550 			proto = "sctp";
1551 			break;
1552 		case IPPROTO_UDPLITE:
1553 			proto = "udplite";
1554 			break;
1555 		default:
1556 			proto = NULL;
1557 			break;
1558 		}
1559 
1560 		if ((sp = getservbyname(servname, proto)) == NULL)
1561 			return EAI_SERVICE;
1562 		port = sp->s_port;
1563 	}
1564 
1565 	if (!matchonly) {
1566 		switch (ai->ai_family) {
1567 		case AF_INET:
1568 			((struct sockaddr_in *)(void *)
1569 			    ai->ai_addr)->sin_port = port;
1570 			break;
1571 #ifdef INET6
1572 		case AF_INET6:
1573 			((struct sockaddr_in6 *)(void *)
1574 			    ai->ai_addr)->sin6_port = port;
1575 			break;
1576 #endif
1577 		}
1578 	}
1579 
1580 	return 0;
1581 }
1582 
1583 static const struct afd *
find_afd(int af)1584 find_afd(int af)
1585 {
1586 	const struct afd *afd;
1587 
1588 	if (af == PF_UNSPEC)
1589 		return NULL;
1590 	for (afd = afdl; afd->a_af; afd++) {
1591 		if (afd->a_af == af)
1592 			return afd;
1593 	}
1594 	return NULL;
1595 }
1596 
1597 /*
1598  * RFC 3493: AI_ADDRCONFIG check.  Determines which address families are
1599  * configured on the local system and correlates with pai->ai_family value.
1600  * If an address family is not configured on the system, it will not be
1601  * queried for.  For this purpose, loopback addresses are not considered
1602  * configured addresses.
1603  *
1604  * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1605  * _dns_getaddrinfo.
1606  */
1607 static int
addrconfig(struct addrinfo * pai)1608 addrconfig(struct addrinfo *pai)
1609 {
1610 	struct ifaddrs *ifaddrs, *ifa;
1611 	struct sockaddr_in *sin;
1612 #ifdef INET6
1613 	struct sockaddr_in6 *sin6;
1614 #endif
1615 	int seen_inet = 0, seen_inet6 = 0;
1616 
1617 	if (getifaddrs(&ifaddrs) != 0)
1618 		return (0);
1619 
1620 	for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
1621 		if (ifa->ifa_addr == NULL || (ifa->ifa_flags & IFF_UP) == 0)
1622 			continue;
1623 		switch (ifa->ifa_addr->sa_family) {
1624 		case AF_INET:
1625 			if (seen_inet)
1626 				continue;
1627 			sin = (struct sockaddr_in *)(ifa->ifa_addr);
1628 			if (htonl(sin->sin_addr.s_addr) == INADDR_LOOPBACK)
1629 				continue;
1630 			seen_inet = 1;
1631 			break;
1632 #ifdef INET6
1633 		case AF_INET6:
1634 			if (seen_inet6)
1635 				continue;
1636 			sin6 = (struct sockaddr_in6 *)(ifa->ifa_addr);
1637 			if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
1638 				continue;
1639 			if ((ifa->ifa_flags & IFT_LOOP) != 0 &&
1640 			    IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
1641 				continue;
1642 			if (is_ifdisabled(ifa->ifa_name))
1643 				continue;
1644 			seen_inet6 = 1;
1645 			break;
1646 #endif
1647 		}
1648 	}
1649 	freeifaddrs(ifaddrs);
1650 
1651 	switch(pai->ai_family) {
1652 	case AF_INET6:
1653 		return (seen_inet6);
1654 	case AF_INET:
1655 		return (seen_inet);
1656 	case AF_UNSPEC:
1657 		if (seen_inet == seen_inet6)
1658 			return (seen_inet);
1659 		pai->ai_family = seen_inet ? AF_INET : AF_INET6;
1660 		return (1);
1661 	}
1662 	return (1);
1663 }
1664 
1665 #ifdef INET6
1666 static int
is_ifdisabled(char * name)1667 is_ifdisabled(char *name)
1668 {
1669 	struct in6_ndireq nd;
1670 	int fd;
1671 
1672 	if ((fd = _socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
1673 		return (-1);
1674 	memset(&nd, 0, sizeof(nd));
1675 	strlcpy(nd.ifname, name, sizeof(nd.ifname));
1676 	if (_ioctl(fd, SIOCGIFINFO_IN6, &nd) < 0) {
1677 		_close(fd);
1678 		return (-1);
1679 	}
1680 	_close(fd);
1681 	return ((nd.ndi.flags & ND6_IFF_IFDISABLED) != 0);
1682 }
1683 
1684 /* convert a string to a scope identifier. XXX: IPv6 specific */
1685 static int
ip6_str2scopeid(const char * scope,struct sockaddr_in6 * sin6,u_int32_t * scopeid)1686 ip6_str2scopeid(const char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1687 {
1688 	u_long lscopeid;
1689 	struct in6_addr *a6;
1690 	char *ep;
1691 
1692 	a6 = &sin6->sin6_addr;
1693 
1694 	/* empty scopeid portion is invalid */
1695 	if (*scope == '\0')
1696 		return -1;
1697 
1698 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) ||
1699 	    IN6_IS_ADDR_MC_NODELOCAL(a6)) {
1700 		/*
1701 		 * We currently assume a one-to-one mapping between links
1702 		 * and interfaces, so we simply use interface indices for
1703 		 * like-local scopes.
1704 		 */
1705 		*scopeid = if_nametoindex(scope);
1706 		if (*scopeid == 0)
1707 			goto trynumeric;
1708 		return 0;
1709 	}
1710 
1711 	/* still unclear about literal, allow numeric only - placeholder */
1712 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1713 		goto trynumeric;
1714 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1715 		goto trynumeric;
1716 	else
1717 		goto trynumeric;	/* global */
1718 
1719 	/* try to convert to a numeric id as a last resort */
1720   trynumeric:
1721 	errno = 0;
1722 	lscopeid = strtoul(scope, &ep, 10);
1723 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1724 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1725 		return 0;
1726 	else
1727 		return -1;
1728 }
1729 #endif
1730 
1731 
1732 #ifdef NS_CACHING
1733 static int
addrinfo_id_func(char * buffer,size_t * buffer_size,va_list ap,void * cache_mdata)1734 addrinfo_id_func(char *buffer, size_t *buffer_size, va_list ap,
1735     void *cache_mdata)
1736 {
1737 	res_state statp;
1738 	u_long res_options;
1739 
1740 	const int op_id = 0;	/* identifies the getaddrinfo for the cache */
1741 	char *hostname;
1742 	struct addrinfo *hints;
1743 
1744 	char *p;
1745 	int ai_flags, ai_family, ai_socktype, ai_protocol;
1746 	size_t desired_size, size;
1747 
1748 	statp = __res_state();
1749 	res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
1750 	    RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
1751 
1752 	hostname = va_arg(ap, char *);
1753 	hints = va_arg(ap, struct addrinfo *);
1754 
1755 	desired_size = sizeof(res_options) + sizeof(int) + sizeof(int) * 4;
1756 	if (hostname != NULL) {
1757 		size = strlen(hostname);
1758 		desired_size += size + 1;
1759 	} else
1760 		size = 0;
1761 
1762 	if (desired_size > *buffer_size) {
1763 		*buffer_size = desired_size;
1764 		return (NS_RETURN);
1765 	}
1766 
1767 	if (hints == NULL)
1768 		ai_flags = ai_family = ai_socktype = ai_protocol = 0;
1769 	else {
1770 		ai_flags = hints->ai_flags;
1771 		ai_family = hints->ai_family;
1772 		ai_socktype = hints->ai_socktype;
1773 		ai_protocol = hints->ai_protocol;
1774 	}
1775 
1776 	p = buffer;
1777 	memcpy(p, &res_options, sizeof(res_options));
1778 	p += sizeof(res_options);
1779 
1780 	memcpy(p, &op_id, sizeof(int));
1781 	p += sizeof(int);
1782 
1783 	memcpy(p, &ai_flags, sizeof(int));
1784 	p += sizeof(int);
1785 
1786 	memcpy(p, &ai_family, sizeof(int));
1787 	p += sizeof(int);
1788 
1789 	memcpy(p, &ai_socktype, sizeof(int));
1790 	p += sizeof(int);
1791 
1792 	memcpy(p, &ai_protocol, sizeof(int));
1793 	p += sizeof(int);
1794 
1795 	if (hostname != NULL)
1796 		memcpy(p, hostname, size);
1797 
1798 	*buffer_size = desired_size;
1799 	return (NS_SUCCESS);
1800 }
1801 
1802 static int
addrinfo_marshal_func(char * buffer,size_t * buffer_size,void * retval,va_list ap,void * cache_mdata)1803 addrinfo_marshal_func(char *buffer, size_t *buffer_size, void *retval,
1804     va_list ap, void *cache_mdata)
1805 {
1806 	struct addrinfo	*ai, *cai;
1807 	char *p;
1808 	size_t desired_size, size, ai_size;
1809 
1810 	ai = *((struct addrinfo **)retval);
1811 
1812 	desired_size = sizeof(size_t);
1813 	ai_size = 0;
1814 	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1815 		desired_size += sizeof(struct addrinfo) + cai->ai_addrlen;
1816 		if (cai->ai_canonname != NULL)
1817 			desired_size += sizeof(size_t) +
1818 			    strlen(cai->ai_canonname);
1819 		++ai_size;
1820 	}
1821 
1822 	if (desired_size > *buffer_size) {
1823 		/* this assignment is here for future use */
1824 		errno = ERANGE;
1825 		*buffer_size = desired_size;
1826 		return (NS_RETURN);
1827 	}
1828 
1829 	memset(buffer, 0, desired_size);
1830 	p = buffer;
1831 
1832 	memcpy(p, &ai_size, sizeof(size_t));
1833 	p += sizeof(size_t);
1834 	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1835 		memcpy(p, cai, sizeof(struct addrinfo));
1836 		p += sizeof(struct addrinfo);
1837 
1838 		memcpy(p, cai->ai_addr, cai->ai_addrlen);
1839 		p += cai->ai_addrlen;
1840 
1841 		if (cai->ai_canonname != NULL) {
1842 			size = strlen(cai->ai_canonname);
1843 			memcpy(p, &size, sizeof(size_t));
1844 			p += sizeof(size_t);
1845 
1846 			memcpy(p, cai->ai_canonname, size);
1847 			p += size;
1848 		}
1849 	}
1850 
1851 	return (NS_SUCCESS);
1852 }
1853 
1854 static int
addrinfo_unmarshal_func(char * buffer,size_t buffer_size,void * retval,va_list ap,void * cache_mdata)1855 addrinfo_unmarshal_func(char *buffer, size_t buffer_size, void *retval,
1856     va_list ap, void *cache_mdata)
1857 {
1858 	struct addrinfo	new_ai, *result, *sentinel, *lasts;
1859 
1860 	char *p;
1861 	size_t ai_size, ai_i, size;
1862 
1863 	p = buffer;
1864 	memcpy(&ai_size, p, sizeof(size_t));
1865 	p += sizeof(size_t);
1866 
1867 	result = NULL;
1868 	lasts = NULL;
1869 	for (ai_i = 0; ai_i < ai_size; ++ai_i) {
1870 		memcpy(&new_ai, p, sizeof(struct addrinfo));
1871 		p += sizeof(struct addrinfo);
1872 		size = new_ai.ai_addrlen + sizeof(struct addrinfo) +
1873 			_ALIGNBYTES;
1874 
1875 		sentinel = calloc(1, size);
1876 
1877 		memcpy(sentinel, &new_ai, sizeof(struct addrinfo));
1878 		sentinel->ai_addr = (struct sockaddr *)_ALIGN((char *)sentinel +
1879 		    sizeof(struct addrinfo));
1880 
1881 		memcpy(sentinel->ai_addr, p, new_ai.ai_addrlen);
1882 		p += new_ai.ai_addrlen;
1883 
1884 		if (new_ai.ai_canonname != NULL) {
1885 			memcpy(&size, p, sizeof(size_t));
1886 			p += sizeof(size_t);
1887 
1888 			sentinel->ai_canonname = calloc(1, size + 1);
1889 
1890 			memcpy(sentinel->ai_canonname, p, size);
1891 			p += size;
1892 		}
1893 
1894 		if (result == NULL) {
1895 			result = sentinel;
1896 			lasts = sentinel;
1897 		} else {
1898 			lasts->ai_next = sentinel;
1899 			lasts = sentinel;
1900 		}
1901 	}
1902 
1903 	*((struct addrinfo **)retval) = result;
1904 	return (NS_SUCCESS);
1905 }
1906 #endif /* NS_CACHING */
1907 
1908 /*
1909  * FQDN hostname, DNS lookup
1910  */
1911 static int
explore_fqdn(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res)1912 explore_fqdn(const struct addrinfo *pai, const char *hostname,
1913     const char *servname, struct addrinfo **res)
1914 {
1915 	struct addrinfo *result;
1916 	struct addrinfo *cur;
1917 	int error = 0;
1918 
1919 #ifdef NS_CACHING
1920 	static const nss_cache_info cache_info =
1921 	NS_COMMON_CACHE_INFO_INITIALIZER(
1922 		hosts, NULL, addrinfo_id_func, addrinfo_marshal_func,
1923 		addrinfo_unmarshal_func);
1924 #endif
1925 	static const ns_dtab dtab[] = {
1926 		NS_FILES_CB(_files_getaddrinfo, NULL)
1927 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
1928 		NS_NIS_CB(_yp_getaddrinfo, NULL)
1929 #ifdef NS_CACHING
1930 		NS_CACHE_CB(&cache_info)
1931 #endif
1932 		{ 0 }
1933 	};
1934 
1935 	result = NULL;
1936 
1937 	/*
1938 	 * if the servname does not match socktype/protocol, ignore it.
1939 	 */
1940 	if (get_portmatch(pai, servname) != 0)
1941 		return 0;
1942 
1943 	switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1944 			default_dns_files, hostname, pai)) {
1945 	case NS_TRYAGAIN:
1946 		error = EAI_AGAIN;
1947 		goto free;
1948 	case NS_UNAVAIL:
1949 		error = EAI_FAIL;
1950 		goto free;
1951 	case NS_NOTFOUND:
1952 		error = EAI_NONAME;
1953 		goto free;
1954 	case NS_ADDRFAMILY:
1955 		error = EAI_ADDRFAMILY;
1956 		goto free;
1957 	case NS_SUCCESS:
1958 		error = 0;
1959 		for (cur = result; cur; cur = cur->ai_next) {
1960 			GET_PORT(cur, servname);
1961 			/* canonname should be filled already */
1962 		}
1963 		break;
1964 	}
1965 
1966 	*res = result;
1967 
1968 	return 0;
1969 
1970 free:
1971 	if (result)
1972 		freeaddrinfo(result);
1973 	return error;
1974 }
1975 
1976 #ifdef DEBUG
1977 static const char AskedForGot[] =
1978 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1979 #endif
1980 
1981 static struct addrinfo *
getanswer(const querybuf * answer,int anslen,const char * qname,int qtype,const struct addrinfo * pai,res_state res)1982 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1983     const struct addrinfo *pai, res_state res)
1984 {
1985 	struct addrinfo sentinel, *cur;
1986 	struct addrinfo ai;
1987 	const struct afd *afd;
1988 	char *canonname;
1989 	const HEADER *hp;
1990 	const u_char *cp;
1991 	int n;
1992 	const u_char *eom;
1993 	char *bp, *ep;
1994 	int type, class, ancount, qdcount;
1995 	int haveanswer, had_error;
1996 	char tbuf[MAXDNAME];
1997 	int (*name_ok)(const char *);
1998 	char hostbuf[8*1024];
1999 
2000 	memset(&sentinel, 0, sizeof(sentinel));
2001 	cur = &sentinel;
2002 
2003 	canonname = NULL;
2004 	eom = answer->buf + anslen;
2005 	switch (qtype) {
2006 	case T_A:
2007 	case T_AAAA:
2008 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
2009 		name_ok = res_hnok;
2010 		break;
2011 	default:
2012 		return (NULL);	/* XXX should be abort(); */
2013 	}
2014 	/*
2015 	 * find first satisfactory answer
2016 	 */
2017 	hp = &answer->hdr;
2018 	ancount = ntohs(hp->ancount);
2019 	qdcount = ntohs(hp->qdcount);
2020 	bp = hostbuf;
2021 	ep = hostbuf + sizeof hostbuf;
2022 	cp = answer->buf + HFIXEDSZ;
2023 	if (qdcount != 1) {
2024 		RES_SET_H_ERRNO(res, NO_RECOVERY);
2025 		return (NULL);
2026 	}
2027 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
2028 	if ((n < 0) || !(*name_ok)(bp)) {
2029 		RES_SET_H_ERRNO(res, NO_RECOVERY);
2030 		return (NULL);
2031 	}
2032 	cp += n + QFIXEDSZ;
2033 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
2034 		/* res_send() has already verified that the query name is the
2035 		 * same as the one we sent; this just gets the expanded name
2036 		 * (i.e., with the succeeding search-domain tacked on).
2037 		 */
2038 		n = strlen(bp) + 1;		/* for the \0 */
2039 		if (n >= MAXHOSTNAMELEN) {
2040 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2041 			return (NULL);
2042 		}
2043 		canonname = bp;
2044 		bp += n;
2045 		/* The qname can be abbreviated, but h_name is now absolute. */
2046 		qname = canonname;
2047 	}
2048 	haveanswer = 0;
2049 	had_error = 0;
2050 	while (ancount-- > 0 && cp < eom && !had_error) {
2051 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
2052 		if ((n < 0) || !(*name_ok)(bp)) {
2053 			had_error++;
2054 			continue;
2055 		}
2056 		cp += n;			/* name */
2057 		type = _getshort(cp);
2058  		cp += INT16SZ;			/* type */
2059 		class = _getshort(cp);
2060  		cp += INT16SZ + INT32SZ;	/* class, TTL */
2061 		n = _getshort(cp);
2062 		cp += INT16SZ;			/* len */
2063 		if (class != C_IN) {
2064 			/* XXX - debug? syslog? */
2065 			cp += n;
2066 			continue;		/* XXX - had_error++ ? */
2067 		}
2068 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
2069 		    type == T_CNAME) {
2070 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
2071 			if ((n < 0) || !(*name_ok)(tbuf)) {
2072 				had_error++;
2073 				continue;
2074 			}
2075 			cp += n;
2076 			/* Get canonical name. */
2077 			n = strlen(tbuf) + 1;	/* for the \0 */
2078 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
2079 				had_error++;
2080 				continue;
2081 			}
2082 			strlcpy(bp, tbuf, ep - bp);
2083 			canonname = bp;
2084 			bp += n;
2085 			continue;
2086 		}
2087 		if (qtype == T_ANY) {
2088 			if (!(type == T_A || type == T_AAAA)) {
2089 				cp += n;
2090 				continue;
2091 			}
2092 		} else if (type != qtype) {
2093 #ifdef DEBUG
2094 			if (type != T_KEY && type != T_SIG &&
2095 			    type != T_DNAME && type != T_RRSIG)
2096 				syslog(LOG_NOTICE|LOG_AUTH,
2097 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
2098 				       qname, p_class(C_IN), p_type(qtype),
2099 				       p_type(type));
2100 #endif
2101 			cp += n;
2102 			continue;		/* XXX - had_error++ ? */
2103 		}
2104 		switch (type) {
2105 		case T_A:
2106 		case T_AAAA:
2107 			if (strcasecmp(canonname, bp) != 0) {
2108 #ifdef DEBUG
2109 				syslog(LOG_NOTICE|LOG_AUTH,
2110 				       AskedForGot, canonname, bp);
2111 #endif
2112 				cp += n;
2113 				continue;	/* XXX - had_error++ ? */
2114 			}
2115 			if (type == T_A && n != INADDRSZ) {
2116 				cp += n;
2117 				continue;
2118 			}
2119 			if (type == T_AAAA && n != IN6ADDRSZ) {
2120 				cp += n;
2121 				continue;
2122 			}
2123 #ifdef FILTER_V4MAPPED
2124 			if (type == T_AAAA) {
2125 				struct in6_addr in6;
2126 				memcpy(&in6, cp, sizeof(in6));
2127 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
2128 					cp += n;
2129 					continue;
2130 				}
2131 			}
2132 #endif
2133 			if (!haveanswer) {
2134 				int nn;
2135 
2136 				canonname = bp;
2137 				nn = strlen(bp) + 1;	/* for the \0 */
2138 				bp += nn;
2139 			}
2140 
2141 			/* don't overwrite pai */
2142 			ai = *pai;
2143 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
2144 			afd = find_afd(ai.ai_family);
2145 			if (afd == NULL) {
2146 				cp += n;
2147 				continue;
2148 			}
2149 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
2150 			if (cur->ai_next == NULL)
2151 				had_error++;
2152 			while (cur && cur->ai_next)
2153 				cur = cur->ai_next;
2154 			cp += n;
2155 			break;
2156 		default:
2157 			abort();
2158 		}
2159 		if (!had_error)
2160 			haveanswer++;
2161 	}
2162 	if (haveanswer) {
2163 #if defined(RESOLVSORT)
2164 		/*
2165 		 * We support only IPv4 address for backward
2166 		 * compatibility against gethostbyname(3).
2167 		 */
2168 		if (res->nsort && qtype == T_A) {
2169 			if (addr4sort(&sentinel, res) < 0) {
2170 				freeaddrinfo(sentinel.ai_next);
2171 				RES_SET_H_ERRNO(res, NO_RECOVERY);
2172 				return NULL;
2173 			}
2174 		}
2175 #endif /*RESOLVSORT*/
2176 		if (!canonname)
2177 			(void)get_canonname(pai, sentinel.ai_next, qname);
2178 		else
2179 			(void)get_canonname(pai, sentinel.ai_next, canonname);
2180 		RES_SET_H_ERRNO(res, NETDB_SUCCESS);
2181 		return sentinel.ai_next;
2182 	}
2183 
2184 	/*
2185 	 * We could have walked a CNAME chain, but the ultimate target
2186 	 * may not have what we looked for.
2187 	 */
2188 	RES_SET_H_ERRNO(res, ntohs(hp->ancount) > 0 ? NO_DATA : NO_RECOVERY);
2189 	return NULL;
2190 }
2191 
2192 #ifdef RESOLVSORT
2193 struct addr_ptr {
2194 	struct addrinfo *ai;
2195 	int aval;
2196 };
2197 
2198 static int
addr4sort(struct addrinfo * sentinel,res_state res)2199 addr4sort(struct addrinfo *sentinel, res_state res)
2200 {
2201 	struct addrinfo *ai;
2202 	struct addr_ptr *addrs, addr;
2203 	struct sockaddr_in *sin;
2204 	int naddrs, i, j;
2205 	int needsort = 0;
2206 
2207 	if (!sentinel)
2208 		return -1;
2209 	naddrs = 0;
2210 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
2211 		naddrs++;
2212 	if (naddrs < 2)
2213 		return 0;		/* We don't need sorting. */
2214 	if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
2215 		return -1;
2216 	i = 0;
2217 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
2218 		sin = (struct sockaddr_in *)ai->ai_addr;
2219 		for (j = 0; (unsigned)j < res->nsort; j++) {
2220 			if (res->sort_list[j].addr.s_addr ==
2221 			    (sin->sin_addr.s_addr & res->sort_list[j].mask))
2222 				break;
2223 		}
2224 		addrs[i].ai = ai;
2225 		addrs[i].aval = j;
2226 		if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
2227 			needsort = i;
2228 		i++;
2229 	}
2230 	if (!needsort) {
2231 		free(addrs);
2232 		return 0;
2233 	}
2234 
2235 	while (needsort < naddrs) {
2236 		for (j = needsort - 1; j >= 0; j--) {
2237 			if (addrs[j].aval > addrs[j+1].aval) {
2238 				addr = addrs[j];
2239 				addrs[j] = addrs[j + 1];
2240 				addrs[j + 1] = addr;
2241 			} else
2242 				break;
2243 		}
2244 		needsort++;
2245 	}
2246 
2247 	ai = sentinel;
2248 	for (i = 0; i < naddrs; ++i) {
2249 		ai->ai_next = addrs[i].ai;
2250 		ai = ai->ai_next;
2251 	}
2252 	ai->ai_next = NULL;
2253 	free(addrs);
2254 	return 0;
2255 }
2256 #endif /*RESOLVSORT*/
2257 
2258 /*ARGSUSED*/
2259 static int
_dns_getaddrinfo(void * rv,void * cb_data,va_list ap)2260 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
2261 {
2262 	struct addrinfo *ai, ai0;
2263 	querybuf *buf, *buf2;
2264 	const char *hostname;
2265 	const struct addrinfo *pai;
2266 	struct addrinfo sentinel, *cur;
2267 	struct res_target q, q2;
2268 	res_state res;
2269 
2270 	ai = NULL;
2271 
2272 	hostname = va_arg(ap, char *);
2273 	pai = va_arg(ap, const struct addrinfo *);
2274 
2275 	memset(&q, 0, sizeof(q));
2276 	memset(&q2, 0, sizeof(q2));
2277 	memset(&sentinel, 0, sizeof(sentinel));
2278 	cur = &sentinel;
2279 
2280 	res = __res_state();
2281 
2282 	buf = malloc(sizeof(*buf));
2283 	if (!buf) {
2284 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2285 		return NS_NOTFOUND;
2286 	}
2287 	buf2 = malloc(sizeof(*buf2));
2288 	if (!buf2) {
2289 		free(buf);
2290 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2291 		return NS_NOTFOUND;
2292 	}
2293 
2294 	if (pai->ai_family == AF_INET6 &&
2295 	    (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED) {
2296 		ai0 = *pai;
2297 		ai0.ai_family = AF_UNSPEC;
2298 		pai = &ai0;
2299 	}
2300 
2301 	switch (pai->ai_family) {
2302 	case AF_UNSPEC:
2303 		q.name = hostname;
2304 		q.qclass = C_IN;
2305 		q.qtype = T_A;
2306 		q.answer = buf->buf;
2307 		q.anslen = sizeof(buf->buf);
2308 		q.next = &q2;
2309 		q2.name = hostname;
2310 		q2.qclass = C_IN;
2311 		q2.qtype = T_AAAA;
2312 		q2.answer = buf2->buf;
2313 		q2.anslen = sizeof(buf2->buf);
2314 		break;
2315 	case AF_INET:
2316 		q.name = hostname;
2317 		q.qclass = C_IN;
2318 		q.qtype = T_A;
2319 		q.answer = buf->buf;
2320 		q.anslen = sizeof(buf->buf);
2321 		break;
2322 	case AF_INET6:
2323 		q.name = hostname;
2324 		q.qclass = C_IN;
2325 		q.qtype = T_AAAA;
2326 		q.answer = buf->buf;
2327 		q.anslen = sizeof(buf->buf);
2328 		break;
2329 	default:
2330 		free(buf);
2331 		free(buf2);
2332 		return NS_UNAVAIL;
2333 	}
2334 
2335 	if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
2336 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2337 		free(buf);
2338 		free(buf2);
2339 		return NS_NOTFOUND;
2340 	}
2341 
2342 	if (res_searchN(hostname, &q, res) < 0) {
2343 		free(buf);
2344 		free(buf2);
2345 		switch (res->res_h_errno) {
2346 		case NO_DATA:
2347 			return (NS_ADDRFAMILY);
2348 		case TRY_AGAIN:
2349 			return (NS_TRYAGAIN);
2350 		default:
2351 			return (NS_NOTFOUND);
2352 		}
2353 	}
2354 	/* prefer IPv6 */
2355 	if (q.next) {
2356 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res);
2357 		if (ai != NULL) {
2358 			cur->ai_next = ai;
2359 			while (cur && cur->ai_next)
2360 				cur = cur->ai_next;
2361 		}
2362 	}
2363 	if (ai == NULL || pai->ai_family != AF_UNSPEC ||
2364 	    (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) != AI_V4MAPPED) {
2365 		ai = getanswer(buf, q.n, q.name, q.qtype, pai, res);
2366 		if (ai != NULL)
2367 			cur->ai_next = ai;
2368 	}
2369 	free(buf);
2370 	free(buf2);
2371 	if (sentinel.ai_next == NULL)
2372 		switch (res->res_h_errno) {
2373 		case HOST_NOT_FOUND:
2374 			return (NS_NOTFOUND);
2375 		case NO_DATA:
2376 			return (NS_ADDRFAMILY);
2377 		case TRY_AGAIN:
2378 			return (NS_TRYAGAIN);
2379 		default:
2380 			return (NS_UNAVAIL);
2381 		}
2382 	*((struct addrinfo **)rv) = sentinel.ai_next;
2383 	return (NS_SUCCESS);
2384 }
2385 
2386 static void
_sethtent(FILE ** hostf)2387 _sethtent(FILE **hostf)
2388 {
2389 	if (!*hostf)
2390 		*hostf = fopen(_PATH_HOSTS, "re");
2391 	else
2392 		rewind(*hostf);
2393 }
2394 
2395 static void
_endhtent(FILE ** hostf)2396 _endhtent(FILE **hostf)
2397 {
2398 	if (*hostf) {
2399 		(void) fclose(*hostf);
2400 		*hostf = NULL;
2401 	}
2402 }
2403 
2404 static struct addrinfo *
_gethtent(FILE ** hostf,const char * name,const struct addrinfo * pai)2405 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2406 {
2407 	char *p;
2408 	char *cp, *tname, *cname;
2409 	struct addrinfo hints, *res0, *res;
2410 	int error;
2411 	const char *addr;
2412 	char hostbuf[8*1024];
2413 
2414 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
2415 		return (NULL);
2416 again:
2417 	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2418 		return (NULL);
2419 	if (*p == '#')
2420 		goto again;
2421 	cp = strpbrk(p, "#\n");
2422 	if (cp != NULL)
2423 		*cp = '\0';
2424 	if (!(cp = strpbrk(p, " \t")))
2425 		goto again;
2426 	*cp++ = '\0';
2427 	addr = p;
2428 	cname = NULL;
2429 	/* if this is not something we're looking for, skip it. */
2430 	while (cp && *cp) {
2431 		if (*cp == ' ' || *cp == '\t') {
2432 			cp++;
2433 			continue;
2434 		}
2435 		tname = cp;
2436 		if (cname == NULL)
2437 			cname = cp;
2438 		if ((cp = strpbrk(cp, " \t")) != NULL)
2439 			*cp++ = '\0';
2440 		if (strcasecmp(name, tname) == 0)
2441 			goto found;
2442 	}
2443 	goto again;
2444 
2445 found:
2446 	/* we should not glob socktype/protocol here */
2447 	memset(&hints, 0, sizeof(hints));
2448 	hints.ai_family = pai->ai_family;
2449 	hints.ai_socktype = SOCK_DGRAM;
2450 	hints.ai_protocol = 0;
2451 	hints.ai_flags = AI_NUMERICHOST;
2452 	if (pai->ai_family == AF_INET6 &&
2453 	    (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED)
2454 		hints.ai_flags |= AI_V4MAPPED;
2455 	error = getaddrinfo(addr, "0", &hints, &res0);
2456 	if (error)
2457 		goto again;
2458 #ifdef FILTER_V4MAPPED
2459 	/* XXX should check all items in the chain */
2460 	if (res0->ai_family == AF_INET6 &&
2461 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2462 		freeaddrinfo(res0);
2463 		goto again;
2464 	}
2465 #endif
2466 	for (res = res0; res; res = res->ai_next) {
2467 		/* cover it up */
2468 		res->ai_flags = pai->ai_flags;
2469 		res->ai_socktype = pai->ai_socktype;
2470 		res->ai_protocol = pai->ai_protocol;
2471 
2472 		if (pai->ai_flags & AI_CANONNAME) {
2473 			if (get_canonname(pai, res, cname) != 0) {
2474 				freeaddrinfo(res0);
2475 				goto again;
2476 			}
2477 		}
2478 	}
2479 	return res0;
2480 }
2481 
2482 static struct addrinfo *
_getht(FILE ** hostf,const char * name,const struct addrinfo * pai,struct addrinfo * cur)2483 _getht(FILE **hostf, const char *name, const struct addrinfo *pai,
2484      struct addrinfo *cur)
2485 {
2486 	struct addrinfo *p;
2487 
2488 	while ((p = _gethtent(hostf, name, pai)) != NULL) {
2489 		cur->ai_next = p;
2490 		while (cur && cur->ai_next)
2491 			cur = cur->ai_next;
2492 	}
2493 	return (cur);
2494 }
2495 
2496 /*ARGSUSED*/
2497 static int
_files_getaddrinfo(void * rv,void * cb_data,va_list ap)2498 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2499 {
2500 	const char *name;
2501 	const struct addrinfo *pai;
2502 	struct addrinfo sentinel, *cur;
2503 	FILE *hostf = NULL;
2504 
2505 	name = va_arg(ap, char *);
2506 	pai = va_arg(ap, struct addrinfo *);
2507 
2508 	memset(&sentinel, 0, sizeof(sentinel));
2509 	cur = &sentinel;
2510 
2511 	_sethtent(&hostf);
2512 	if (pai->ai_family == AF_INET6 &&
2513 	    (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) == AI_V4MAPPED) {
2514 		struct addrinfo ai0 = *pai;
2515 
2516 		ai0.ai_flags &= ~AI_V4MAPPED;
2517 		cur = _getht(&hostf, name, &ai0, cur);
2518 		if (sentinel.ai_next == NULL) {
2519 			_sethtent(&hostf);
2520 			ai0.ai_flags |= AI_V4MAPPED;
2521 			cur = _getht(&hostf, name, &ai0, cur);
2522 		}
2523 	} else
2524 		cur = _getht(&hostf, name, pai, cur);
2525 	_endhtent(&hostf);
2526 
2527 	*((struct addrinfo **)rv) = sentinel.ai_next;
2528 	if (sentinel.ai_next == NULL)
2529 		return NS_NOTFOUND;
2530 	return NS_SUCCESS;
2531 }
2532 
2533 #ifdef YP
2534 /*ARGSUSED*/
2535 static struct addrinfo *
_yphostent(char * line,const struct addrinfo * pai)2536 _yphostent(char *line, const struct addrinfo *pai)
2537 {
2538 	struct addrinfo sentinel, *cur;
2539 	struct addrinfo hints, *res, *res0;
2540 	int error;
2541 	char *p = line;
2542 	const char *addr, *canonname;
2543 	char *nextline;
2544 	char *cp;
2545 
2546 	addr = canonname = NULL;
2547 
2548 	memset(&sentinel, 0, sizeof(sentinel));
2549 	cur = &sentinel;
2550 
2551 nextline:
2552 	/* terminate line */
2553 	cp = strchr(p, '\n');
2554 	if (cp) {
2555 		*cp++ = '\0';
2556 		nextline = cp;
2557 	} else
2558 		nextline = NULL;
2559 
2560 	cp = strpbrk(p, " \t");
2561 	if (cp == NULL) {
2562 		if (canonname == NULL)
2563 			return (NULL);
2564 		else
2565 			goto done;
2566 	}
2567 	*cp++ = '\0';
2568 
2569 	addr = p;
2570 
2571 	while (cp && *cp) {
2572 		if (*cp == ' ' || *cp == '\t') {
2573 			cp++;
2574 			continue;
2575 		}
2576 		if (!canonname)
2577 			canonname = cp;
2578 		if ((cp = strpbrk(cp, " \t")) != NULL)
2579 			*cp++ = '\0';
2580 	}
2581 
2582 	hints = *pai;
2583 	hints.ai_flags = AI_NUMERICHOST;
2584 	if (pai->ai_family == AF_INET6 &&
2585 	    (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED)
2586 		hints.ai_flags |= AI_V4MAPPED;
2587 	error = getaddrinfo(addr, NULL, &hints, &res0);
2588 	if (error == 0) {
2589 		for (res = res0; res; res = res->ai_next) {
2590 			/* cover it up */
2591 			res->ai_flags = pai->ai_flags;
2592 
2593 			if (pai->ai_flags & AI_CANONNAME)
2594 				(void)get_canonname(pai, res, canonname);
2595 		}
2596 	} else
2597 		res0 = NULL;
2598 	if (res0) {
2599 		cur->ai_next = res0;
2600 		while (cur && cur->ai_next)
2601 			cur = cur->ai_next;
2602 	}
2603 
2604 	if (nextline) {
2605 		p = nextline;
2606 		goto nextline;
2607 	}
2608 
2609 done:
2610 	return sentinel.ai_next;
2611 }
2612 
2613 /*ARGSUSED*/
2614 static int
_yp_getaddrinfo(void * rv,void * cb_data,va_list ap)2615 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
2616 {
2617 	struct addrinfo sentinel, *cur;
2618 	struct addrinfo *ai = NULL;
2619 	char *ypbuf;
2620 	int ypbuflen, r;
2621 	const char *name;
2622 	const struct addrinfo *pai;
2623 	char *ypdomain;
2624 
2625 	if (_yp_check(&ypdomain) == 0)
2626 		return NS_UNAVAIL;
2627 
2628 	name = va_arg(ap, char *);
2629 	pai = va_arg(ap, const struct addrinfo *);
2630 
2631 	memset(&sentinel, 0, sizeof(sentinel));
2632 	cur = &sentinel;
2633 
2634 	/* ipnodes.byname can hold both IPv4/v6 */
2635 	r = yp_match(ypdomain, "ipnodes.byname", name,
2636 		(int)strlen(name), &ypbuf, &ypbuflen);
2637 	if (r == 0) {
2638 		ai = _yphostent(ypbuf, pai);
2639 		if (ai) {
2640 			cur->ai_next = ai;
2641 			while (cur && cur->ai_next)
2642 				cur = cur->ai_next;
2643 		}
2644 		free(ypbuf);
2645 	}
2646 
2647 	if (ai != NULL) {
2648 		struct sockaddr_in6 *sin6;
2649 
2650 		switch (ai->ai_family) {
2651 		case AF_INET:
2652 			goto done;
2653 		case AF_INET6:
2654 			sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2655 			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2656 				goto done;
2657 			break;
2658 		}
2659 	}
2660 
2661 	/* hosts.byname is only for IPv4 (Solaris8) */
2662 	if (pai->ai_family == AF_UNSPEC || pai->ai_family == AF_INET ||
2663 	    ((pai->ai_family == AF_INET6 &&
2664 	     (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED) &&
2665 	      (ai == NULL || (pai->ai_flags & AI_ALL) == AI_ALL))) {
2666 		r = yp_match(ypdomain, "hosts.byname", name,
2667 			(int)strlen(name), &ypbuf, &ypbuflen);
2668 		if (r == 0) {
2669 			struct addrinfo ai4;
2670 
2671 			ai4 = *pai;
2672 			if (pai->ai_family == AF_UNSPEC)
2673 				ai4.ai_family = AF_INET;
2674 			ai = _yphostent(ypbuf, &ai4);
2675 			if (ai) {
2676 				cur->ai_next = ai;
2677 				while (cur && cur->ai_next)
2678 					cur = cur->ai_next;
2679 			}
2680 			free(ypbuf);
2681 		}
2682 	}
2683 
2684 done:
2685 	if (sentinel.ai_next == NULL) {
2686 		RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND);
2687 		return NS_NOTFOUND;
2688 	}
2689 	*((struct addrinfo **)rv) = sentinel.ai_next;
2690 	return NS_SUCCESS;
2691 }
2692 #endif
2693 
2694 /* resolver logic */
2695 
2696 /*
2697  * Formulate a normal query, send, and await answer.
2698  * Returned answer is placed in supplied buffer "answer".
2699  * Perform preliminary check of answer, returning success only
2700  * if no error is indicated and the answer count is nonzero.
2701  * Return the size of the response on success, -1 on error.
2702  * Error number is left in h_errno.
2703  *
2704  * Caller must parse answer and determine whether it answers the question.
2705  */
2706 static int
res_queryN(const char * name,struct res_target * target,res_state res)2707 res_queryN(const char *name, struct res_target *target, res_state res)
2708 {
2709 	u_char *buf;
2710 	HEADER *hp;
2711 	int n;
2712 	u_int oflags;
2713 	struct res_target *t;
2714 	u_int rcode;
2715 	int ancount;
2716 
2717 	/*
2718 	 * Extend rcode values in the scope of this function.  The DNS header
2719 	 * rcode we use in this function (hp->rcode) is limited by 4 bits, so
2720 	 * anything starting from 16 is safe wrt aliasing.  However, nameser.h
2721 	 * already has extended enum __ns_rcode, so for future safety let's use
2722 	 * even larger values.
2723 	 */
2724 #define	RCODE_UNREACH	32
2725 #define	RCODE_TIMEDOUT	33
2726 	rcode = NOERROR;
2727 	ancount = 0;
2728 
2729 	buf = malloc(MAXPACKET);
2730 	if (!buf) {
2731 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2732 		return -1;
2733 	}
2734 
2735 	for (t = target; t; t = t->next) {
2736 		int class, type;
2737 		u_char *answer;
2738 		int anslen;
2739 
2740 		hp = (HEADER *)(void *)t->answer;
2741 
2742 		/* make it easier... */
2743 		class = t->qclass;
2744 		type = t->qtype;
2745 		answer = t->answer;
2746 		anslen = t->anslen;
2747 
2748 		oflags = res->_flags;
2749 
2750 again:
2751 		hp->rcode = NOERROR;	/* default */
2752 
2753 #ifdef DEBUG
2754 		if (res->options & RES_DEBUG)
2755 			printf(";; res_query(%s, %d, %d)\n", name, class, type);
2756 #endif
2757 
2758 		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2759 		    buf, MAXPACKET);
2760 		if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2761 		    (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U)
2762 			n = res_nopt(res, n, buf, MAXPACKET, anslen);
2763 		if (n <= 0) {
2764 #ifdef DEBUG
2765 			if (res->options & RES_DEBUG)
2766 				printf(";; res_query: mkquery failed\n");
2767 #endif
2768 			free(buf);
2769 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2770 			return (n);
2771 		}
2772 		n = res_nsend(res, buf, n, answer, anslen);
2773 		if (n < 0) {
2774 			/*
2775 			 * if the query choked with EDNS0, retry
2776 			 * without EDNS0
2777 			 */
2778 			if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC))
2779 			    != 0U &&
2780 			    ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2781 				res->_flags |= RES_F_EDNS0ERR;
2782 				if (res->options & RES_DEBUG)
2783 					printf(";; res_nquery: retry without EDNS0\n");
2784 				goto again;
2785 			}
2786                         /*
2787 			 * Historically if a DNS server replied with ICMP port
2788 			 * unreach res_nsend() would signal that with
2789 			 * ECONNREFUSED and the upper layers would convert that
2790 			 * into TRY_AGAIN.  See 3a0b3b673936b and deeper.
2791 			 * Also, res_nsend() may set errno to ECONNREFUSED due
2792 			 * to internal failures.  This may not be intentional,
2793 			 * but we also treat that as soft failures.
2794 			 *
2795 			 * A more practical case is when a DNS server(s) were
2796 			 * queried and didn't respond anything, which usually
2797 			 * indicates a soft network failure.
2798 			 */
2799 			switch (errno) {
2800 			case ECONNREFUSED:
2801 				rcode = RCODE_UNREACH;
2802 				break;
2803 			case ETIMEDOUT:
2804 				rcode = RCODE_TIMEDOUT;
2805 				break;
2806 			default:
2807                                 rcode = hp->rcode;
2808 			}
2809 #ifdef DEBUG
2810 			if (res->options & RES_DEBUG)
2811 				printf(";; res_query: send error\n");
2812 #endif
2813 			continue;
2814 		}
2815 
2816 		if (n > anslen)
2817 			hp->rcode = FORMERR; /* XXX not very informative */
2818 		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2819 			rcode = hp->rcode;	/* record most recent error */
2820 #ifdef DEBUG
2821 			if (res->options & RES_DEBUG)
2822 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2823 				    ntohs(hp->ancount));
2824 #endif
2825 			continue;
2826 		}
2827 
2828 		ancount += ntohs(hp->ancount);
2829 
2830 		t->n = n;
2831 	}
2832 
2833 	free(buf);
2834 
2835 	if (ancount == 0) {
2836 		switch (rcode) {
2837 		case NXDOMAIN:
2838 			RES_SET_H_ERRNO(res, HOST_NOT_FOUND);
2839 			break;
2840 		case RCODE_UNREACH:
2841 		case RCODE_TIMEDOUT:
2842 		case SERVFAIL:
2843 			RES_SET_H_ERRNO(res, TRY_AGAIN);
2844 			break;
2845 		case NOERROR:
2846 			RES_SET_H_ERRNO(res, NO_DATA);
2847 			break;
2848 		case FORMERR:
2849 		case NOTIMP:
2850 		case REFUSED:
2851 		default:
2852 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2853 			break;
2854 		}
2855 		return (-1);
2856 	}
2857 	return (ancount);
2858 }
2859 
2860 /*
2861  * Formulate a normal query, send, and retrieve answer in supplied buffer.
2862  * Return the size of the response on success, -1 on error.
2863  * If enabled, implement search rules until answer or unrecoverable failure
2864  * is detected.  Error code, if any, is left in h_errno.
2865  */
2866 static int
res_searchN(const char * name,struct res_target * target,res_state res)2867 res_searchN(const char *name, struct res_target *target, res_state res)
2868 {
2869 	const char *cp, * const *domain;
2870 	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
2871 	u_int dots;
2872 	int trailing_dot, ret, saved_herrno;
2873 	int got_nodata = 0, got_servfail = 0, root_on_list = 0;
2874 	int tried_as_is = 0;
2875 	int searched = 0;
2876 	char abuf[MAXDNAME];
2877 
2878 	errno = 0;
2879 	RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */
2880 	dots = 0;
2881 	for (cp = name; *cp; cp++)
2882 		dots += (*cp == '.');
2883 	trailing_dot = 0;
2884 	if (cp > name && *--cp == '.')
2885 		trailing_dot++;
2886 
2887 	/*
2888 	 * if there aren't any dots, it could be a user-level alias
2889 	 */
2890 	if (!dots &&
2891 	    (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL)
2892 		return (res_queryN(cp, target, res));
2893 
2894 	/*
2895 	 * If there are enough dots in the name, let's just give it a
2896 	 * try 'as is'. The threshold can be set with the "ndots" option.
2897 	 * Also, query 'as is', if there is a trailing dot in the name.
2898 	 */
2899 	saved_herrno = -1;
2900 	if (dots >= res->ndots || trailing_dot) {
2901 		ret = res_querydomainN(name, NULL, target, res);
2902 		if (ret > 0 || trailing_dot)
2903 			return (ret);
2904 		switch (res->res_h_errno) {
2905 		case NO_DATA:
2906 		case HOST_NOT_FOUND:
2907 			break;
2908 		case TRY_AGAIN:
2909 			if (hp->rcode == SERVFAIL)
2910 				break;
2911 			/* FALLTHROUGH */
2912 		default:
2913 			return (-1);
2914 		}
2915 		saved_herrno = res->res_h_errno;
2916 		tried_as_is++;
2917 	}
2918 
2919 	/*
2920 	 * We do at least one level of search if
2921 	 *	- there is no dot and RES_DEFNAME is set, or
2922 	 *	- there is at least one dot, there is no trailing dot,
2923 	 *	  and RES_DNSRCH is set.
2924 	 */
2925 	if ((!dots && (res->options & RES_DEFNAMES)) ||
2926 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2927 		int done = 0;
2928 
2929 		for (domain = (const char * const *)res->dnsrch;
2930 		   *domain && !done;
2931 		   domain++) {
2932 			searched = 1;
2933 
2934 			if (domain[0][0] == '\0' ||
2935 			    (domain[0][0] == '.' && domain[0][1] == '\0'))
2936 				root_on_list++;
2937 
2938 			if (root_on_list && tried_as_is)
2939 				continue;
2940 
2941 			ret = res_querydomainN(name, *domain, target, res);
2942 			if (ret > 0)
2943 				return (ret);
2944 			/*
2945 			 * If no server present, give up.
2946 			 * If name isn't found in this domain,
2947 			 * keep trying higher domains in the search list
2948 			 * (if that's enabled).
2949 			 * On a NO_DATA error, keep trying, otherwise
2950 			 * a wildcard entry of another type could keep us
2951 			 * from finding this entry higher in the domain.
2952 			 * If we get some other error (negative answer or
2953 			 * server failure), then stop searching up,
2954 			 * but try the input name below in case it's
2955 			 * fully-qualified.
2956 			 */
2957 			switch (res->res_h_errno) {
2958 			case NO_DATA:
2959 				got_nodata++;
2960 				/* FALLTHROUGH */
2961 			case HOST_NOT_FOUND:
2962 				/* keep trying */
2963 				break;
2964 			case TRY_AGAIN:
2965 				if (hp->rcode == SERVFAIL) {
2966 					got_servfail++;
2967 					/* try next search element, if any */
2968 					break;
2969 				}
2970 				/* FALLTHROUGH */
2971 			default:
2972 				/* anything else implies that we're done */
2973 				done++;
2974 			}
2975 			/*
2976 			 * if we got here for some reason other than DNSRCH,
2977 			 * we only wanted one iteration of the loop, so stop.
2978 			 */
2979 			if (!(res->options & RES_DNSRCH))
2980 			        done++;
2981 		}
2982 	}
2983 
2984 	switch (res->res_h_errno) {
2985 	case NO_DATA:
2986 	case HOST_NOT_FOUND:
2987 		break;
2988 	case TRY_AGAIN:
2989 		if (hp->rcode == SERVFAIL)
2990 			break;
2991 		/* FALLTHROUGH */
2992 	default:
2993 		goto giveup;
2994 	}
2995 
2996 	/*
2997 	 * If the query has not already been tried as is then try it
2998 	 * unless RES_NOTLDQUERY is set and there were no dots.
2999 	 */
3000 	if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) &&
3001 	    !(tried_as_is || root_on_list)) {
3002 		ret = res_querydomainN(name, NULL, target, res);
3003 		if (ret > 0)
3004 			return (ret);
3005 	}
3006 
3007 	/*
3008 	 * if we got here, we didn't satisfy the search.
3009 	 * if we did an initial full query, return that query's h_errno
3010 	 * (note that we wouldn't be here if that query had succeeded).
3011 	 * else if we ever got a nodata, send that back as the reason.
3012 	 * else send back meaningless h_errno, that being the one from
3013 	 * the last DNSRCH we did.
3014 	 */
3015 giveup:
3016 	if (saved_herrno != -1)
3017 		RES_SET_H_ERRNO(res, saved_herrno);
3018 	else if (got_nodata)
3019 		RES_SET_H_ERRNO(res, NO_DATA);
3020 	else if (got_servfail)
3021 		RES_SET_H_ERRNO(res, TRY_AGAIN);
3022 	return (-1);
3023 }
3024 
3025 /*
3026  * Perform a call on res_query on the concatenation of name and domain,
3027  * removing a trailing dot from name if domain is NULL.
3028  */
3029 static int
res_querydomainN(const char * name,const char * domain,struct res_target * target,res_state res)3030 res_querydomainN(const char *name, const char *domain,
3031     struct res_target *target, res_state res)
3032 {
3033 	char nbuf[MAXDNAME];
3034 	const char *longname = nbuf;
3035 	size_t n, d;
3036 
3037 #ifdef DEBUG
3038 	if (res->options & RES_DEBUG)
3039 		printf(";; res_querydomain(%s, %s)\n",
3040 			name, domain?domain:"<Nil>");
3041 #endif
3042 	if (domain == NULL) {
3043 		/*
3044 		 * Check for trailing '.';
3045 		 * copy without '.' if present.
3046 		 */
3047 		n = strlen(name);
3048 		if (n >= MAXDNAME) {
3049 			RES_SET_H_ERRNO(res, NO_RECOVERY);
3050 			return (-1);
3051 		}
3052 		if (n > 0 && name[--n] == '.') {
3053 			strncpy(nbuf, name, n);
3054 			nbuf[n] = '\0';
3055 		} else
3056 			longname = name;
3057 	} else {
3058 		n = strlen(name);
3059 		d = strlen(domain);
3060 		if (n + d + 1 >= MAXDNAME) {
3061 			RES_SET_H_ERRNO(res, NO_RECOVERY);
3062 			return (-1);
3063 		}
3064 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
3065 	}
3066 	return (res_queryN(longname, target, res));
3067 }
3068