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