xref: /netbsd-src/lib/libc/resolv/res_send.c (revision ce099b40997c43048fb78bd578195f81d2456523)
1 /*	$NetBSD: res_send.c,v 1.13 2007/03/30 20:23:05 ghen Exp $	*/
2 
3 /*
4  * Copyright (c) 1985, 1989, 1993
5  *    The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  * 	This product includes software developed by the University of
18  * 	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 /*
37  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38  *
39  * Permission to use, copy, modify, and distribute this software for any
40  * purpose with or without fee is hereby granted, provided that the above
41  * copyright notice and this permission notice appear in all copies, and that
42  * the name of Digital Equipment Corporation not be used in advertising or
43  * publicity pertaining to distribution of the document or software without
44  * specific, written prior permission.
45  *
46  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
49  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53  * SOFTWARE.
54  */
55 
56 /*
57  * Copyright (c) 2005 by Internet Systems Consortium, Inc. ("ISC")
58  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59  *
60  * Permission to use, copy, modify, and distribute this software for any
61  * purpose with or without fee is hereby granted, provided that the above
62  * copyright notice and this permission notice appear in all copies.
63  *
64  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66  * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
67  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71  */
72 
73 #include <sys/cdefs.h>
74 #if defined(LIBC_SCCS) && !defined(lint)
75 #ifdef notdef
76 static const char sccsid[] = "@(#)res_send.c	8.1 (Berkeley) 6/4/93";
77 static const char rcsid[] = "Id: res_send.c,v 1.9.18.8 2006/10/16 23:00:58 marka Exp";
78 #else
79 __RCSID("$NetBSD: res_send.c,v 1.13 2007/03/30 20:23:05 ghen Exp $");
80 #endif
81 #endif /* LIBC_SCCS and not lint */
82 
83 /*! \file
84  * \brief
85  * Send query to name server and wait for reply.
86  */
87 
88 #include "namespace.h"
89 #include "port_before.h"
90 #include "fd_setsize.h"
91 
92 #include <sys/types.h>
93 #include <sys/param.h>
94 #include <sys/time.h>
95 #include <sys/socket.h>
96 #include <sys/uio.h>
97 
98 #include <netinet/in.h>
99 #include <arpa/nameser.h>
100 #include <arpa/inet.h>
101 
102 #include <errno.h>
103 #include <netdb.h>
104 #include <resolv.h>
105 #include <signal.h>
106 #include <stdio.h>
107 #include <stdlib.h>
108 #include <string.h>
109 #include <unistd.h>
110 
111 #include <isc/eventlib.h>
112 
113 #include "port_after.h"
114 
115 #if 0
116 #ifdef __weak_alias
117 __weak_alias(res_ourserver_p,__res_ourserver_p)
118 __weak_alias(res_nameinquery,__res_nameinquery)
119 __weak_alias(res_queriesmatch,__res_queriesmatch)
120 __weak_alias(res_nsend,__res_nsend)
121 #endif
122 #endif
123 
124 
125 #ifdef USE_POLL
126 #ifdef HAVE_STROPTS_H
127 #include <stropts.h>
128 #endif
129 #include <poll.h>
130 #endif /* USE_POLL */
131 
132 /* Options.  Leave them on. */
133 #ifndef DEBUG
134 #define DEBUG
135 #endif
136 #include "res_debug.h"
137 #include "res_private.h"
138 
139 #define EXT(res) ((res)->_u._ext)
140 
141 #ifndef USE_POLL
142 static const int highestFD = FD_SETSIZE - 1;
143 #endif
144 
145 /* Forward. */
146 
147 static int		get_salen __P((const struct sockaddr *));
148 static struct sockaddr * get_nsaddr __P((res_state, size_t));
149 static int		send_vc(res_state, const u_char *, int,
150 				u_char *, int, int *, int);
151 static int		send_dg(res_state, const u_char *, int,
152 				u_char *, int, int *, int, int,
153 				int *, int *);
154 static void		Aerror(const res_state, FILE *, const char *, int,
155 			       const struct sockaddr *, int);
156 static void		Perror(const res_state, FILE *, const char *, int);
157 static int		sock_eq(struct sockaddr *, struct sockaddr *);
158 #if defined(NEED_PSELECT) && !defined(USE_POLL)
159 static int		pselect(int, void *, void *, void *,
160 				struct timespec *,
161 				const sigset_t *);
162 #endif
163 void res_pquery(const res_state, const u_char *, int, FILE *);
164 
165 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
166 
167 /* Public. */
168 
169 /*%
170  *	looks up "ina" in _res.ns_addr_list[]
171  *
172  * returns:
173  *\li	0  : not found
174  *\li	>0 : found
175  *
176  * author:
177  *\li	paul vixie, 29may94
178  */
179 int
180 res_ourserver_p(const res_state statp, const struct sockaddr *sa) {
181 	const struct sockaddr_in *inp, *srv;
182 	const struct sockaddr_in6 *in6p, *srv6;
183 	int ns;
184 
185 	switch (sa->sa_family) {
186 	case AF_INET:
187 		inp = (const struct sockaddr_in *)(const void *)sa;
188 		for (ns = 0;  ns < statp->nscount;  ns++) {
189 			srv = (struct sockaddr_in *)(void *)get_nsaddr(statp, (size_t)ns);
190 			if (srv->sin_family == inp->sin_family &&
191 			    srv->sin_port == inp->sin_port &&
192 			    (srv->sin_addr.s_addr == INADDR_ANY ||
193 			     srv->sin_addr.s_addr == inp->sin_addr.s_addr))
194 				return (1);
195 		}
196 		break;
197 	case AF_INET6:
198 		if (EXT(statp).ext == NULL)
199 			break;
200 		in6p = (const struct sockaddr_in6 *)(const void *)sa;
201 		for (ns = 0;  ns < statp->nscount;  ns++) {
202 			srv6 = (struct sockaddr_in6 *)(void *)get_nsaddr(statp, (size_t)ns);
203 			if (srv6->sin6_family == in6p->sin6_family &&
204 			    srv6->sin6_port == in6p->sin6_port &&
205 #ifdef HAVE_SIN6_SCOPE_ID
206 			    (srv6->sin6_scope_id == 0 ||
207 			     srv6->sin6_scope_id == in6p->sin6_scope_id) &&
208 #endif
209 			    (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
210 			     IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
211 				return (1);
212 		}
213 		break;
214 	default:
215 		break;
216 	}
217 	return (0);
218 }
219 
220 /*%
221  *	look for (name,type,class) in the query section of packet (buf,eom)
222  *
223  * requires:
224  *\li	buf + HFIXEDSZ <= eom
225  *
226  * returns:
227  *\li	-1 : format error
228  *\li	0  : not found
229  *\li	>0 : found
230  *
231  * author:
232  *\li	paul vixie, 29may94
233  */
234 int
235 res_nameinquery(const char *name, int type, int class,
236 		const u_char *buf, const u_char *eom)
237 {
238 	const u_char *cp = buf + HFIXEDSZ;
239 	int qdcount = ntohs(((const HEADER*)(const void *)buf)->qdcount);
240 
241 	while (qdcount-- > 0) {
242 		char tname[MAXDNAME+1];
243 		int n, ttype, tclass;
244 
245 		n = dn_expand(buf, eom, cp, tname, sizeof tname);
246 		if (n < 0)
247 			return (-1);
248 		cp += n;
249 		if (cp + 2 * INT16SZ > eom)
250 			return (-1);
251 		ttype = ns_get16(cp); cp += INT16SZ;
252 		tclass = ns_get16(cp); cp += INT16SZ;
253 		if (ttype == type && tclass == class &&
254 		    ns_samename(tname, name) == 1)
255 			return (1);
256 	}
257 	return (0);
258 }
259 
260 /*%
261  *	is there a 1:1 mapping of (name,type,class)
262  *	in (buf1,eom1) and (buf2,eom2)?
263  *
264  * returns:
265  *\li	-1 : format error
266  *\li	0  : not a 1:1 mapping
267  *\li	>0 : is a 1:1 mapping
268  *
269  * author:
270  *\li	paul vixie, 29may94
271  */
272 int
273 res_queriesmatch(const u_char *buf1, const u_char *eom1,
274 		 const u_char *buf2, const u_char *eom2)
275 {
276 	const u_char *cp = buf1 + HFIXEDSZ;
277 	int qdcount = ntohs(((const HEADER*)(const void *)buf1)->qdcount);
278 
279 	if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
280 		return (-1);
281 
282 	/*
283 	 * Only header section present in replies to
284 	 * dynamic update packets.
285 	 */
286 	if ((((const HEADER *)(const void *)buf1)->opcode == ns_o_update) &&
287 	    (((const HEADER *)(const void *)buf2)->opcode == ns_o_update))
288 		return (1);
289 
290 	if (qdcount != ntohs(((const HEADER*)(const void *)buf2)->qdcount))
291 		return (0);
292 	while (qdcount-- > 0) {
293 		char tname[MAXDNAME+1];
294 		int n, ttype, tclass;
295 
296 		n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
297 		if (n < 0)
298 			return (-1);
299 		cp += n;
300 		if (cp + 2 * INT16SZ > eom1)
301 			return (-1);
302 		ttype = ns_get16(cp);	cp += INT16SZ;
303 		tclass = ns_get16(cp); cp += INT16SZ;
304 		if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
305 			return (0);
306 	}
307 	return (1);
308 }
309 
310 int
311 res_nsend(res_state statp,
312 	  const u_char *buf, int buflen, u_char *ans, int anssiz)
313 {
314 	int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
315 	char abuf[NI_MAXHOST];
316 
317 	/* No name servers or res_init() failure */
318 	if (statp->nscount == 0 || EXT(statp).ext == NULL) {
319 		errno = ESRCH;
320 		return (-1);
321 	}
322 	if (anssiz < HFIXEDSZ) {
323 		errno = EINVAL;
324 		return (-1);
325 	}
326 	DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
327 		(stdout, ";; res_send()\n"), buf, buflen);
328 	v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
329 	gotsomewhere = 0;
330 	terrno = ETIMEDOUT;
331 
332 	/*
333 	 * If the ns_addr_list in the resolver context has changed, then
334 	 * invalidate our cached copy and the associated timing data.
335 	 */
336 	if (EXT(statp).nscount != 0) {
337 		int needclose = 0;
338 		struct sockaddr_storage peer;
339 		ISC_SOCKLEN_T peerlen;
340 
341 		if (EXT(statp).nscount != statp->nscount)
342 			needclose++;
343 		else
344 			for (ns = 0; ns < statp->nscount; ns++) {
345 				if (statp->nsaddr_list[ns].sin_family &&
346 				    !sock_eq((struct sockaddr *)(void *)&statp->nsaddr_list[ns],
347 					     (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[ns])) {
348 					needclose++;
349 					break;
350 				}
351 
352 				if (EXT(statp).nssocks[ns] == -1)
353 					continue;
354 				peerlen = sizeof(peer);
355 				if (getsockname(EXT(statp).nssocks[ns],
356 				    (struct sockaddr *)(void *)&peer, &peerlen) < 0) {
357 					needclose++;
358 					break;
359 				}
360 				if (!sock_eq((struct sockaddr *)(void *)&peer,
361 				    get_nsaddr(statp, (size_t)ns))) {
362 					needclose++;
363 					break;
364 				}
365 			}
366 		if (needclose) {
367 			res_nclose(statp);
368 			EXT(statp).nscount = 0;
369 		}
370 	}
371 
372 	/*
373 	 * Maybe initialize our private copy of the ns_addr_list.
374 	 */
375 	if (EXT(statp).nscount == 0) {
376 		for (ns = 0; ns < statp->nscount; ns++) {
377 			EXT(statp).nstimes[ns] = RES_MAXTIME;
378 			EXT(statp).nssocks[ns] = -1;
379 			if (!statp->nsaddr_list[ns].sin_family)
380 				continue;
381 			EXT(statp).ext->nsaddrs[ns].sin =
382 				 statp->nsaddr_list[ns];
383 		}
384 		EXT(statp).nscount = statp->nscount;
385 	}
386 
387 	/*
388 	 * Some resolvers want to even out the load on their nameservers.
389 	 * Note that RES_BLAST overrides RES_ROTATE.
390 	 */
391 	if ((statp->options & RES_ROTATE) != 0U &&
392 	    (statp->options & RES_BLAST) == 0U) {
393 		union res_sockaddr_union inu;
394 		struct sockaddr_in ina;
395 		int lastns = statp->nscount - 1;
396 		int fd;
397 		u_int16_t nstime;
398 
399 		if (EXT(statp).ext != NULL)
400 			inu = EXT(statp).ext->nsaddrs[0];
401 		ina = statp->nsaddr_list[0];
402 		fd = EXT(statp).nssocks[0];
403 		nstime = EXT(statp).nstimes[0];
404 		for (ns = 0; ns < lastns; ns++) {
405 			if (EXT(statp).ext != NULL)
406                                 EXT(statp).ext->nsaddrs[ns] =
407 					EXT(statp).ext->nsaddrs[ns + 1];
408 			statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
409 			EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
410 			EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
411 		}
412 		if (EXT(statp).ext != NULL)
413 			EXT(statp).ext->nsaddrs[lastns] = inu;
414 		statp->nsaddr_list[lastns] = ina;
415 		EXT(statp).nssocks[lastns] = fd;
416 		EXT(statp).nstimes[lastns] = nstime;
417 	}
418 
419 	/*
420 	 * Send request, RETRY times, or until successful.
421 	 */
422 	for (try = 0; try < statp->retry; try++) {
423 	    for (ns = 0; ns < statp->nscount; ns++) {
424 		struct sockaddr *nsap;
425 		int nsaplen;
426 		nsap = get_nsaddr(statp, (size_t)ns);
427 		nsaplen = get_salen(nsap);
428 		statp->_flags &= ~RES_F_LASTMASK;
429 		statp->_flags |= (ns << RES_F_LASTSHIFT);
430  same_ns:
431 		if (statp->qhook) {
432 			int done = 0, loops = 0;
433 
434 			do {
435 				res_sendhookact act;
436 
437 				act = (*statp->qhook)(&nsap, &buf, &buflen,
438 						      ans, anssiz, &resplen);
439 				switch (act) {
440 				case res_goahead:
441 					done = 1;
442 					break;
443 				case res_nextns:
444 					res_nclose(statp);
445 					goto next_ns;
446 				case res_done:
447 					return (resplen);
448 				case res_modified:
449 					/* give the hook another try */
450 					if (++loops < 42) /*doug adams*/
451 						break;
452 					/*FALLTHROUGH*/
453 				case res_error:
454 					/*FALLTHROUGH*/
455 				default:
456 					goto fail;
457 				}
458 			} while (!done);
459 		}
460 
461 		Dprint(((statp->options & RES_DEBUG) &&
462 			getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf),
463 				    NULL, 0, niflags) == 0),
464 		       (stdout, ";; Querying server (# %d) address = %s\n",
465 			ns + 1, abuf));
466 
467 
468 		if (v_circuit) {
469 			/* Use VC; at most one attempt per server. */
470 			try = statp->retry;
471 			n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
472 				    ns);
473 			if (n < 0)
474 				goto fail;
475 			if (n == 0)
476 				goto next_ns;
477 			resplen = n;
478 		} else {
479 			/* Use datagrams. */
480 			n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
481 				    ns, try, &v_circuit, &gotsomewhere);
482 			if (n < 0)
483 				goto fail;
484 			if (n == 0)
485 				goto next_ns;
486 			if (v_circuit)
487 				goto same_ns;
488 			resplen = n;
489 		}
490 
491 		Dprint((statp->options & RES_DEBUG) ||
492 		       ((statp->pfcode & RES_PRF_REPLY) &&
493 			(statp->pfcode & RES_PRF_HEAD1)),
494 		       (stdout, ";; got answer:\n"));
495 
496 		DprintQ((statp->options & RES_DEBUG) ||
497 			(statp->pfcode & RES_PRF_REPLY),
498 			(stdout, "%s", ""),
499 			ans, (resplen > anssiz) ? anssiz : resplen);
500 
501 		/*
502 		 * If we have temporarily opened a virtual circuit,
503 		 * or if we haven't been asked to keep a socket open,
504 		 * close the socket.
505 		 */
506 		if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
507 		    (statp->options & RES_STAYOPEN) == 0U) {
508 			res_nclose(statp);
509 		}
510 		if (statp->rhook) {
511 			int done = 0, loops = 0;
512 
513 			do {
514 				res_sendhookact act;
515 
516 				act = (*statp->rhook)(nsap, buf, buflen,
517 						      ans, anssiz, &resplen);
518 				switch (act) {
519 				case res_goahead:
520 				case res_done:
521 					done = 1;
522 					break;
523 				case res_nextns:
524 					res_nclose(statp);
525 					goto next_ns;
526 				case res_modified:
527 					/* give the hook another try */
528 					if (++loops < 42) /*doug adams*/
529 						break;
530 					/*FALLTHROUGH*/
531 				case res_error:
532 					/*FALLTHROUGH*/
533 				default:
534 					goto fail;
535 				}
536 			} while (!done);
537 
538 		}
539 		return (resplen);
540  next_ns: ;
541 	   } /*foreach ns*/
542 	} /*foreach retry*/
543 	res_nclose(statp);
544 	if (!v_circuit) {
545 		if (!gotsomewhere)
546 			errno = ECONNREFUSED;	/*%< no nameservers found */
547 		else
548 			errno = ETIMEDOUT;	/*%< no answer obtained */
549 	} else
550 		errno = terrno;
551 	return (-1);
552  fail:
553 	res_nclose(statp);
554 	return (-1);
555 }
556 
557 /* Private */
558 
559 static int
560 get_salen(sa)
561 	const struct sockaddr *sa;
562 {
563 
564 #ifdef HAVE_SA_LEN
565 	/* There are people do not set sa_len.  Be forgiving to them. */
566 	if (sa->sa_len)
567 		return (sa->sa_len);
568 #endif
569 
570 	if (sa->sa_family == AF_INET)
571 		return (sizeof(struct sockaddr_in));
572 	else if (sa->sa_family == AF_INET6)
573 		return (sizeof(struct sockaddr_in6));
574 	else
575 		return (0);	/*%< unknown, die on connect */
576 }
577 
578 /*%
579  * pick appropriate nsaddr_list for use.  see res_init() for initialization.
580  */
581 static struct sockaddr *
582 get_nsaddr(statp, n)
583 	res_state statp;
584 	size_t n;
585 {
586 
587 	if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
588 		/*
589 		 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
590 		 *   than struct sockaddr, and
591 		 * - user code did not update statp->nsaddr_list[n].
592 		 */
593 		return (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[n];
594 	} else {
595 		/*
596 		 * - user code updated statp->nsaddr_list[n], or
597 		 * - statp->nsaddr_list[n] has the same content as
598 		 *   EXT(statp).ext->nsaddrs[n].
599 		 */
600 		return (struct sockaddr *)(void *)&statp->nsaddr_list[n];
601 	}
602 }
603 
604 static int
605 send_vc(res_state statp,
606 	const u_char *buf, int buflen, u_char *ans, int anssiz,
607 	int *terrno, int ns)
608 {
609 	const HEADER *hp = (const HEADER *)(const void *)buf;
610 	HEADER *anhp = (HEADER *)(void *)ans;
611 	struct sockaddr *nsap;
612 	int nsaplen;
613 	int truncating, connreset, resplen, n;
614 	struct iovec iov[2];
615 	u_short len;
616 	u_char *cp;
617 	void *tmp;
618 
619 	nsap = get_nsaddr(statp, (size_t)ns);
620 	nsaplen = get_salen(nsap);
621 
622 	connreset = 0;
623  same_ns:
624 	truncating = 0;
625 
626 	/* Are we still talking to whom we want to talk to? */
627 	if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
628 		struct sockaddr_storage peer;
629 		ISC_SOCKLEN_T size = sizeof peer;
630 
631 		if (getpeername(statp->_vcsock,
632 				(struct sockaddr *)(void *)&peer, &size) < 0 ||
633 		    !sock_eq((struct sockaddr *)(void *)&peer, nsap)) {
634 			res_nclose(statp);
635 			statp->_flags &= ~RES_F_VC;
636 		}
637 	}
638 
639 	if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
640 		if (statp->_vcsock >= 0)
641 			res_nclose(statp);
642 
643 		statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM, 0);
644 #ifndef USE_POLL
645 		if (statp->_vcsock > highestFD) {
646 			res_nclose(statp);
647 			errno = ENOTSOCK;
648 		}
649 #endif
650 		if (statp->_vcsock < 0) {
651 			switch (errno) {
652 			case EPROTONOSUPPORT:
653 #ifdef EPFNOSUPPORT
654 			case EPFNOSUPPORT:
655 #endif
656 			case EAFNOSUPPORT:
657 				Perror(statp, stderr, "socket(vc)", errno);
658 				return (0);
659 			default:
660 				*terrno = errno;
661 				Perror(statp, stderr, "socket(vc)", errno);
662 				return (-1);
663 			}
664 		}
665 		errno = 0;
666 		if (connect(statp->_vcsock, nsap, (socklen_t)nsaplen) < 0) {
667 			*terrno = errno;
668 			Aerror(statp, stderr, "connect/vc", errno, nsap,
669 			    nsaplen);
670 			res_nclose(statp);
671 			return (0);
672 		}
673 		statp->_flags |= RES_F_VC;
674 	}
675 
676 	/*
677 	 * Send length & message
678 	 */
679 	ns_put16((u_short)buflen, (u_char*)(void *)&len);
680 	iov[0] = evConsIovec(&len, INT16SZ);
681 	DE_CONST(buf, tmp);
682 	iov[1] = evConsIovec(tmp, (size_t)buflen);
683 	if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
684 		*terrno = errno;
685 		Perror(statp, stderr, "write failed", errno);
686 		res_nclose(statp);
687 		return (0);
688 	}
689 	/*
690 	 * Receive length & response
691 	 */
692  read_len:
693 	cp = ans;
694 	len = INT16SZ;
695 	while ((n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0) {
696 		cp += n;
697 		if ((len -= n) == 0)
698 			break;
699 	}
700 	if (n <= 0) {
701 		*terrno = errno;
702 		Perror(statp, stderr, "read failed", errno);
703 		res_nclose(statp);
704 		/*
705 		 * A long running process might get its TCP
706 		 * connection reset if the remote server was
707 		 * restarted.  Requery the server instead of
708 		 * trying a new one.  When there is only one
709 		 * server, this means that a query might work
710 		 * instead of failing.  We only allow one reset
711 		 * per query to prevent looping.
712 		 */
713 		if (*terrno == ECONNRESET && !connreset) {
714 			connreset = 1;
715 			res_nclose(statp);
716 			goto same_ns;
717 		}
718 		res_nclose(statp);
719 		return (0);
720 	}
721 	resplen = ns_get16(ans);
722 	if (resplen > anssiz) {
723 		Dprint(statp->options & RES_DEBUG,
724 		       (stdout, ";; response truncated\n")
725 		       );
726 		truncating = 1;
727 		len = anssiz;
728 	} else
729 		len = resplen;
730 	if (len < HFIXEDSZ) {
731 		/*
732 		 * Undersized message.
733 		 */
734 		Dprint(statp->options & RES_DEBUG,
735 		       (stdout, ";; undersized: %d\n", len));
736 		*terrno = EMSGSIZE;
737 		res_nclose(statp);
738 		return (0);
739 	}
740 	cp = ans;
741 	while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0){
742 		cp += n;
743 		len -= n;
744 	}
745 	if (n <= 0) {
746 		*terrno = errno;
747 		Perror(statp, stderr, "read(vc)", errno);
748 		res_nclose(statp);
749 		return (0);
750 	}
751 	if (truncating) {
752 		/*
753 		 * Flush rest of answer so connection stays in synch.
754 		 */
755 		anhp->tc = 1;
756 		len = resplen - anssiz;
757 		while (len != 0) {
758 			char junk[PACKETSZ];
759 
760 			n = read(statp->_vcsock, junk,
761 				 (len > sizeof junk) ? sizeof junk : len);
762 			if (n > 0)
763 				len -= n;
764 			else
765 				break;
766 		}
767 	}
768 	/*
769 	 * If the calling applicating has bailed out of
770 	 * a previous call and failed to arrange to have
771 	 * the circuit closed or the server has got
772 	 * itself confused, then drop the packet and
773 	 * wait for the correct one.
774 	 */
775 	if (hp->id != anhp->id) {
776 		DprintQ((statp->options & RES_DEBUG) ||
777 			(statp->pfcode & RES_PRF_REPLY),
778 			(stdout, ";; old answer (unexpected):\n"),
779 			ans, (resplen > anssiz) ? anssiz: resplen);
780 		goto read_len;
781 	}
782 
783 	/*
784 	 * All is well, or the error is fatal.  Signal that the
785 	 * next nameserver ought not be tried.
786 	 */
787 	return (resplen);
788 }
789 
790 static int
791 send_dg(res_state statp, const u_char *buf, int buflen, u_char *ans,
792 	int anssiz, int *terrno, int ns, int try, int *v_circuit,
793 	int *gotsomewhere)
794 {
795 	const HEADER *hp = (const HEADER *)(const void *)buf;
796 	HEADER *anhp = (HEADER *)(void *)ans;
797 	const struct sockaddr *nsap;
798 	int nsaplen;
799 	struct timespec now, timeout, finish;
800 	struct sockaddr_storage from;
801 	ISC_SOCKLEN_T fromlen;
802 	int resplen, seconds, n, s;
803 #ifdef USE_POLL
804 	int     polltimeout;
805 	struct pollfd   pollfd;
806 #else
807 	fd_set dsmask;
808 #endif
809 
810 	nsap = get_nsaddr(statp, (size_t)ns);
811 	nsaplen = get_salen(nsap);
812 	if (EXT(statp).nssocks[ns] == -1) {
813 		EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM, 0);
814 #ifndef USE_POLL
815 		if (EXT(statp).nssocks[ns] > highestFD) {
816 			res_nclose(statp);
817 			errno = ENOTSOCK;
818 		}
819 #endif
820 		if (EXT(statp).nssocks[ns] < 0) {
821 			switch (errno) {
822 			case EPROTONOSUPPORT:
823 #ifdef EPFNOSUPPORT
824 			case EPFNOSUPPORT:
825 #endif
826 			case EAFNOSUPPORT:
827 				Perror(statp, stderr, "socket(dg)", errno);
828 				return (0);
829 			default:
830 				*terrno = errno;
831 				Perror(statp, stderr, "socket(dg)", errno);
832 				return (-1);
833 			}
834 		}
835 #ifndef CANNOT_CONNECT_DGRAM
836 		/*
837 		 * On a 4.3BSD+ machine (client and server,
838 		 * actually), sending to a nameserver datagram
839 		 * port with no nameserver will cause an
840 		 * ICMP port unreachable message to be returned.
841 		 * If our datagram socket is "connected" to the
842 		 * server, we get an ECONNREFUSED error on the next
843 		 * socket operation, and select returns if the
844 		 * error message is received.  We can thus detect
845 		 * the absence of a nameserver without timing out.
846 		 */
847 		if (connect(EXT(statp).nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
848 			Aerror(statp, stderr, "connect(dg)", errno, nsap,
849 			    nsaplen);
850 			res_nclose(statp);
851 			return (0);
852 		}
853 #endif /* !CANNOT_CONNECT_DGRAM */
854 		Dprint(statp->options & RES_DEBUG,
855 		       (stdout, ";; new DG socket\n"))
856 	}
857 	s = EXT(statp).nssocks[ns];
858 #ifndef CANNOT_CONNECT_DGRAM
859 	if (send(s, (const char*)buf, (size_t)buflen, 0) != buflen) {
860 		Perror(statp, stderr, "send", errno);
861 		res_nclose(statp);
862 		return (0);
863 	}
864 #else /* !CANNOT_CONNECT_DGRAM */
865 	if (sendto(s, (const char*)buf, buflen, 0, nsap, nsaplen) != buflen)
866 	{
867 		Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
868 		res_nclose(statp);
869 		return (0);
870 	}
871 #endif /* !CANNOT_CONNECT_DGRAM */
872 
873 	/*
874 	 * Wait for reply.
875 	 */
876 	seconds = (statp->retrans << try);
877 	if (ns > 0)
878 		seconds /= statp->nscount;
879 	if (seconds <= 0)
880 		seconds = 1;
881 	now = evNowTime();
882 	timeout = evConsTime((long)seconds, 0L);
883 	finish = evAddTime(now, timeout);
884 	goto nonow;
885  wait:
886 	now = evNowTime();
887  nonow:
888 #ifndef USE_POLL
889 	FD_ZERO(&dsmask);
890 	FD_SET(s, &dsmask);
891 	if (evCmpTime(finish, now) > 0)
892 		timeout = evSubTime(finish, now);
893 	else
894 		timeout = evConsTime(0L, 0L);
895 	n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
896 #else
897 	timeout = evSubTime(finish, now);
898 	if (timeout.tv_sec < 0)
899 		timeout = evConsTime(0L, 0L);
900 	polltimeout = 1000*timeout.tv_sec +
901 		timeout.tv_nsec/1000000;
902 	pollfd.fd = s;
903 	pollfd.events = POLLRDNORM;
904 	n = poll(&pollfd, 1, polltimeout);
905 #endif /* USE_POLL */
906 
907 	if (n == 0) {
908 		Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
909 		*gotsomewhere = 1;
910 		return (0);
911 	}
912 	if (n < 0) {
913 		if (errno == EINTR)
914 			goto wait;
915 #ifndef USE_POLL
916 		Perror(statp, stderr, "select", errno);
917 #else
918 		Perror(statp, stderr, "poll", errno);
919 #endif /* USE_POLL */
920 		res_nclose(statp);
921 		return (0);
922 	}
923 	errno = 0;
924 	fromlen = sizeof(from);
925 	resplen = recvfrom(s, (char*)ans, (size_t)anssiz,0,
926 			   (struct sockaddr *)(void *)&from, &fromlen);
927 	if (resplen <= 0) {
928 		Perror(statp, stderr, "recvfrom", errno);
929 		res_nclose(statp);
930 		return (0);
931 	}
932 	*gotsomewhere = 1;
933 	if (resplen < HFIXEDSZ) {
934 		/*
935 		 * Undersized message.
936 		 */
937 		Dprint(statp->options & RES_DEBUG,
938 		       (stdout, ";; undersized: %d\n",
939 			resplen));
940 		*terrno = EMSGSIZE;
941 		res_nclose(statp);
942 		return (0);
943 	}
944 	if (hp->id != anhp->id) {
945 		/*
946 		 * response from old query, ignore it.
947 		 * XXX - potential security hazard could
948 		 *	 be detected here.
949 		 */
950 		DprintQ((statp->options & RES_DEBUG) ||
951 			(statp->pfcode & RES_PRF_REPLY),
952 			(stdout, ";; old answer:\n"),
953 			ans, (resplen > anssiz) ? anssiz : resplen);
954 		goto wait;
955 	}
956 	if (!(statp->options & RES_INSECURE1) &&
957 	    !res_ourserver_p(statp, (struct sockaddr *)(void *)&from)) {
958 		/*
959 		 * response from wrong server? ignore it.
960 		 * XXX - potential security hazard could
961 		 *	 be detected here.
962 		 */
963 		DprintQ((statp->options & RES_DEBUG) ||
964 			(statp->pfcode & RES_PRF_REPLY),
965 			(stdout, ";; not our server:\n"),
966 			ans, (resplen > anssiz) ? anssiz : resplen);
967 		goto wait;
968 	}
969 #ifdef RES_USE_EDNS0
970 	if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
971 		/*
972 		 * Do not retry if the server do not understand EDNS0.
973 		 * The case has to be captured here, as FORMERR packet do not
974 		 * carry query section, hence res_queriesmatch() returns 0.
975 		 */
976 		DprintQ(statp->options & RES_DEBUG,
977 			(stdout, "server rejected query with EDNS0:\n"),
978 			ans, (resplen > anssiz) ? anssiz : resplen);
979 		/* record the error */
980 		statp->_flags |= RES_F_EDNS0ERR;
981 		res_nclose(statp);
982 		return (0);
983 	}
984 #endif
985 	if (!(statp->options & RES_INSECURE2) &&
986 	    !res_queriesmatch(buf, buf + buflen,
987 			      ans, ans + anssiz)) {
988 		/*
989 		 * response contains wrong query? ignore it.
990 		 * XXX - potential security hazard could
991 		 *	 be detected here.
992 		 */
993 		DprintQ((statp->options & RES_DEBUG) ||
994 			(statp->pfcode & RES_PRF_REPLY),
995 			(stdout, ";; wrong query name:\n"),
996 			ans, (resplen > anssiz) ? anssiz : resplen);
997 		goto wait;
998 	}
999 	if (anhp->rcode == SERVFAIL ||
1000 	    anhp->rcode == NOTIMP ||
1001 	    anhp->rcode == REFUSED) {
1002 		DprintQ(statp->options & RES_DEBUG,
1003 			(stdout, "server rejected query:\n"),
1004 			ans, (resplen > anssiz) ? anssiz : resplen);
1005 		res_nclose(statp);
1006 		/* don't retry if called from dig */
1007 		if (!statp->pfcode)
1008 			return (0);
1009 	}
1010 	if (!(statp->options & RES_IGNTC) && anhp->tc) {
1011 		/*
1012 		 * To get the rest of answer,
1013 		 * use TCP with same server.
1014 		 */
1015 		Dprint(statp->options & RES_DEBUG,
1016 		       (stdout, ";; truncated answer\n"));
1017 		*v_circuit = 1;
1018 		res_nclose(statp);
1019 		return (1);
1020 	}
1021 	/*
1022 	 * All is well, or the error is fatal.  Signal that the
1023 	 * next nameserver ought not be tried.
1024 	 */
1025 	return (resplen);
1026 }
1027 
1028 static void
1029 Aerror(const res_state statp, FILE *file, const char *string, int error,
1030        const struct sockaddr *address, int alen)
1031 {
1032 	int save = errno;
1033 	char hbuf[NI_MAXHOST];
1034 	char sbuf[NI_MAXSERV];
1035 
1036 	alen = alen;
1037 
1038 	if ((statp->options & RES_DEBUG) != 0U) {
1039 		if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf),
1040 		    sbuf, sizeof(sbuf), niflags)) {
1041 			strncpy(hbuf, "?", sizeof(hbuf) - 1);
1042 			hbuf[sizeof(hbuf) - 1] = '\0';
1043 			strncpy(sbuf, "?", sizeof(sbuf) - 1);
1044 			sbuf[sizeof(sbuf) - 1] = '\0';
1045 		}
1046 		fprintf(file, "res_send: %s ([%s].%s): %s\n",
1047 			string, hbuf, sbuf, strerror(error));
1048 	}
1049 	errno = save;
1050 }
1051 
1052 static void
1053 Perror(const res_state statp, FILE *file, const char *string, int error) {
1054 	int save = errno;
1055 
1056 	if ((statp->options & RES_DEBUG) != 0U)
1057 		fprintf(file, "res_send: %s: %s\n",
1058 			string, strerror(error));
1059 	errno = save;
1060 }
1061 
1062 static int
1063 sock_eq(struct sockaddr *a, struct sockaddr *b) {
1064 	struct sockaddr_in *a4, *b4;
1065 	struct sockaddr_in6 *a6, *b6;
1066 
1067 	if (a->sa_family != b->sa_family)
1068 		return 0;
1069 	switch (a->sa_family) {
1070 	case AF_INET:
1071 		a4 = (struct sockaddr_in *)(void *)a;
1072 		b4 = (struct sockaddr_in *)(void *)b;
1073 		return a4->sin_port == b4->sin_port &&
1074 		    a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1075 	case AF_INET6:
1076 		a6 = (struct sockaddr_in6 *)(void *)a;
1077 		b6 = (struct sockaddr_in6 *)(void *)b;
1078 		return a6->sin6_port == b6->sin6_port &&
1079 #ifdef HAVE_SIN6_SCOPE_ID
1080 		    a6->sin6_scope_id == b6->sin6_scope_id &&
1081 #endif
1082 		    IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1083 	default:
1084 		return 0;
1085 	}
1086 }
1087 
1088 #if defined(NEED_PSELECT) && !defined(USE_POLL)
1089 /* XXX needs to move to the porting library. */
1090 static int
1091 pselect(int nfds, void *rfds, void *wfds, void *efds,
1092 	struct timespec *tsp, const sigset_t *sigmask)
1093 {
1094 	struct timeval tv, *tvp;
1095 	sigset_t sigs;
1096 	int n;
1097 
1098 	if (tsp) {
1099 		tvp = &tv;
1100 		tv = evTimeVal(*tsp);
1101 	} else
1102 		tvp = NULL;
1103 	if (sigmask)
1104 		sigprocmask(SIG_SETMASK, sigmask, &sigs);
1105 	n = select(nfds, rfds, wfds, efds, tvp);
1106 	if (sigmask)
1107 		sigprocmask(SIG_SETMASK, &sigs, NULL);
1108 	if (tsp)
1109 		*tsp = evTimeSpec(tv);
1110 	return (n);
1111 }
1112 #endif
1113