xref: /dflybsd-src/lib/libc/resolv/res_send.c (revision 5d7d35b17f98588c39b30036f1a3fe8802935c2c)
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(const struct sockaddr *sa)
591 {
592 
593 #ifdef HAVE_SA_LEN
594 	/* There are people do not set sa_len.  Be forgiving to them. */
595 	if (sa->sa_len)
596 		return (sa->sa_len);
597 #endif
598 
599 	if (sa->sa_family == AF_INET)
600 		return (sizeof(struct sockaddr_in));
601 	else if (sa->sa_family == AF_INET6)
602 		return (sizeof(struct sockaddr_in6));
603 	else
604 		return (0);	/*%< unknown, die on connect */
605 }
606 
607 /*%
608  * pick appropriate nsaddr_list for use.  see res_init() for initialization.
609  */
610 static struct sockaddr *
611 get_nsaddr(res_state statp, size_t n)
612 {
613 
614 	if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
615 		/*
616 		 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
617 		 *   than struct sockaddr, and
618 		 * - user code did not update statp->nsaddr_list[n].
619 		 */
620 		return (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[n];
621 	} else {
622 		/*
623 		 * - user code updated statp->nsaddr_list[n], or
624 		 * - statp->nsaddr_list[n] has the same content as
625 		 *   EXT(statp).ext->nsaddrs[n].
626 		 */
627 		return (struct sockaddr *)(void *)&statp->nsaddr_list[n];
628 	}
629 }
630 
631 static int
632 send_vc(res_state statp,
633 	const u_char *buf, int buflen, u_char *ans, int anssiz,
634 	int *terrno, int ns)
635 {
636 	const HEADER *hp = (const HEADER *) buf;
637 	HEADER *anhp = (HEADER *) ans;
638 	struct sockaddr *nsap;
639 	int nsaplen;
640 	int truncating, connreset, resplen, n;
641 	struct iovec iov[2];
642 	u_short len;
643 	u_char *cp;
644 	void *tmp;
645 #ifdef SO_NOSIGPIPE
646 	int on = 1;
647 #endif
648 
649 	nsap = get_nsaddr(statp, ns);
650 	nsaplen = get_salen(nsap);
651 
652 	connreset = 0;
653  same_ns:
654 	truncating = 0;
655 
656 	/* Are we still talking to whom we want to talk to? */
657 	if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
658 		struct sockaddr_storage peer;
659 		ISC_SOCKLEN_T size = sizeof peer;
660 #ifndef _LIBC
661 		if (getpeername(statp->_vcsock,
662 #else
663 		if (_getpeername(statp->_vcsock,
664 #endif
665 				(struct sockaddr *)&peer, &size) < 0 ||
666 		    !sock_eq((struct sockaddr *)&peer, nsap)) {
667 			res_nclose(statp);
668 			statp->_flags &= ~RES_F_VC;
669 		}
670 	}
671 
672 	if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
673 		if (statp->_vcsock >= 0)
674 			res_nclose(statp);
675 #ifndef _LIBC
676 		statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM, 0);
677 #else
678 		statp->_vcsock = _socket(nsap->sa_family, SOCK_STREAM, 0);
679 #endif
680 #if !defined(USE_POLL) && !defined(USE_KQUEUE)
681 		if (statp->_vcsock > highestFD) {
682 			res_nclose(statp);
683 			errno = ENOTSOCK;
684 		}
685 #endif
686 		if (statp->_vcsock < 0) {
687 			switch (errno) {
688 			case EPROTONOSUPPORT:
689 #ifdef EPFNOSUPPORT
690 			case EPFNOSUPPORT:
691 #endif
692 			case EAFNOSUPPORT:
693 				Perror(statp, stderr, "socket(vc)", errno);
694 				return (0);
695 			default:
696 				*terrno = errno;
697 				Perror(statp, stderr, "socket(vc)", errno);
698 				return (-1);
699 			}
700 		}
701 #ifdef SO_NOSIGPIPE
702 		/*
703 		 * Disable generation of SIGPIPE when writing to a closed
704 		 * socket.  Write should return -1 and set errno to EPIPE
705 		 * instead.
706 		 *
707 		 * Push on even if setsockopt(SO_NOSIGPIPE) fails.
708 		 */
709 		(void)setsockopt(statp->_vcsock, SOL_SOCKET, SO_NOSIGPIPE, &on,
710 			         sizeof(on));
711 #endif
712 		errno = 0;
713 #ifndef _LIBC
714 		if (connect(statp->_vcsock, nsap, nsaplen) < 0) {
715 #else
716 		if (_connect(statp->_vcsock, nsap, nsaplen) < 0) {
717 #endif
718 			*terrno = errno;
719 			Aerror(statp, stderr, "connect/vc", errno, nsap,
720 			    nsaplen);
721 			res_nclose(statp);
722 			return (0);
723 		}
724 		statp->_flags |= RES_F_VC;
725 	}
726 
727 	/*
728 	 * Send length & message
729 	 */
730 	ns_put16((u_short)buflen, (u_char*)&len);
731 	iov[0] = evConsIovec(&len, INT16SZ);
732 	DE_CONST(buf, tmp);
733 	iov[1] = evConsIovec(tmp, buflen);
734 #ifndef _LIBC
735 	if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
736 #else
737 	if (_writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
738 #endif
739 		*terrno = errno;
740 		Perror(statp, stderr, "write failed", errno);
741 		res_nclose(statp);
742 		return (0);
743 	}
744 	/*
745 	 * Receive length & response
746 	 */
747  read_len:
748 	cp = ans;
749 	len = INT16SZ;
750 #ifndef _LIBC
751 	while ((n = read(statp->_vcsock, (char *)cp, (int)len)) > 0) {
752 #else
753 	while ((n = _read(statp->_vcsock, (char *)cp, (int)len)) > 0) {
754 #endif
755 		cp += n;
756 		if ((len -= n) == 0)
757 			break;
758 	}
759 	if (n <= 0) {
760 		*terrno = errno;
761 		Perror(statp, stderr, "read failed", errno);
762 		res_nclose(statp);
763 		/*
764 		 * A long running process might get its TCP
765 		 * connection reset if the remote server was
766 		 * restarted.  Requery the server instead of
767 		 * trying a new one.  When there is only one
768 		 * server, this means that a query might work
769 		 * instead of failing.  We only allow one reset
770 		 * per query to prevent looping.
771 		 */
772 		if (*terrno == ECONNRESET && !connreset) {
773 			connreset = 1;
774 			res_nclose(statp);
775 			goto same_ns;
776 		}
777 		res_nclose(statp);
778 		return (0);
779 	}
780 	resplen = ns_get16(ans);
781 	if (resplen > anssiz) {
782 		Dprint(statp->options & RES_DEBUG,
783 		       (stdout, ";; response truncated\n")
784 		       );
785 		truncating = 1;
786 		len = anssiz;
787 	} else
788 		len = resplen;
789 	if (len < HFIXEDSZ) {
790 		/*
791 		 * Undersized message.
792 		 */
793 		Dprint(statp->options & RES_DEBUG,
794 		       (stdout, ";; undersized: %d\n", len));
795 		*terrno = EMSGSIZE;
796 		res_nclose(statp);
797 		return (0);
798 	}
799 	cp = ans;
800 #ifndef _LIBC
801 	while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
802 #else
803 	while (len != 0 && (n = _read(statp->_vcsock, (char *)cp, (int)len)) > 0){
804 #endif
805 		cp += n;
806 		len -= n;
807 	}
808 	if (n <= 0) {
809 		*terrno = errno;
810 		Perror(statp, stderr, "read(vc)", errno);
811 		res_nclose(statp);
812 		return (0);
813 	}
814 	if (truncating) {
815 		/*
816 		 * Flush rest of answer so connection stays in synch.
817 		 */
818 		anhp->tc = 1;
819 		len = resplen - anssiz;
820 		while (len != 0) {
821 			char junk[PACKETSZ];
822 
823 #ifndef _LIBC
824 			n = read(statp->_vcsock, junk,
825 #else
826 			n = _read(statp->_vcsock, junk,
827 #endif
828 				 (len > sizeof junk) ? sizeof junk : len);
829 			if (n > 0)
830 				len -= n;
831 			else
832 				break;
833 		}
834 	}
835 	/*
836 	 * If the calling applicating has bailed out of
837 	 * a previous call and failed to arrange to have
838 	 * the circuit closed or the server has got
839 	 * itself confused, then drop the packet and
840 	 * wait for the correct one.
841 	 */
842 	if (hp->id != anhp->id) {
843 		DprintQ((statp->options & RES_DEBUG) ||
844 			(statp->pfcode & RES_PRF_REPLY),
845 			(stdout, ";; old answer (unexpected):\n"),
846 			ans, (resplen > anssiz) ? anssiz: resplen);
847 		goto read_len;
848 	}
849 
850 	/*
851 	 * All is well, or the error is fatal.  Signal that the
852 	 * next nameserver ought not be tried.
853 	 */
854 	return (resplen);
855 }
856 
857 static int
858 send_dg(res_state statp,
859 #ifdef USE_KQUEUE
860 	int kq,
861 #endif
862 	const u_char *buf, int buflen, u_char *ans,
863 	int anssiz, int *terrno, int ns, int tries, int *v_circuit,
864 	int *gotsomewhere)
865 {
866 	const HEADER *hp = (const HEADER *) buf;
867 	HEADER *anhp = (HEADER *) ans;
868 	const struct sockaddr *nsap;
869 	int nsaplen;
870 	struct timespec now, timeout, finish;
871 	struct sockaddr_storage from;
872 	ISC_SOCKLEN_T fromlen;
873 	int resplen, seconds, n, s;
874 #ifdef USE_KQUEUE
875 	struct kevent kv;
876 #else
877 #ifdef USE_POLL
878 	int     polltimeout;
879 	struct pollfd   pollfd;
880 #else
881 	fd_set dsmask;
882 #endif
883 #endif
884 
885 	nsap = get_nsaddr(statp, ns);
886 	nsaplen = get_salen(nsap);
887 	if (EXT(statp).nssocks[ns] == -1) {
888 #ifndef _LIBC
889 		EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM, 0);
890 #else
891 		EXT(statp).nssocks[ns] = _socket(nsap->sa_family, SOCK_DGRAM, 0);
892 #endif
893 #if !defined(USE_POLL) && !defined(USE_KQUEUE)
894 		if (EXT(statp).nssocks[ns] > highestFD) {
895 			res_nclose(statp);
896 			errno = ENOTSOCK;
897 		}
898 #endif
899 		if (EXT(statp).nssocks[ns] < 0) {
900 			switch (errno) {
901 			case EPROTONOSUPPORT:
902 #ifdef EPFNOSUPPORT
903 			case EPFNOSUPPORT:
904 #endif
905 			case EAFNOSUPPORT:
906 				Perror(statp, stderr, "socket(dg)", errno);
907 				return (0);
908 			default:
909 				*terrno = errno;
910 				Perror(statp, stderr, "socket(dg)", errno);
911 				return (-1);
912 			}
913 		}
914 #ifndef CANNOT_CONNECT_DGRAM
915 		/*
916 		 * On a 4.3BSD+ machine (client and server,
917 		 * actually), sending to a nameserver datagram
918 		 * port with no nameserver will cause an
919 		 * ICMP port unreachable message to be returned.
920 		 * If our datagram socket is "connected" to the
921 		 * server, we get an ECONNREFUSED error on the next
922 		 * socket operation, and select returns if the
923 		 * error message is received.  We can thus detect
924 		 * the absence of a nameserver without timing out.
925 		 *
926 		 *
927                  * When the option "insecure1" is specified, we'd
928                  * rather expect to see responses from an "unknown"
929                  * address.  In order to let the kernel accept such
930                  * responses, do not connect the socket here.
931                  * XXX: or do we need an explicit option to disable
932                  * connecting?
933                  */
934 		if (!(statp->options & RES_INSECURE1) &&
935 #ifndef _LIBC
936 			connect(EXT(statp).nssocks[ns], nsap, nsaplen) < 0) {
937 #else
938 			_connect(EXT(statp).nssocks[ns], nsap, nsaplen) < 0) {
939 #endif
940 			Aerror(statp, stderr, "connect(dg)", errno, nsap,
941 			    nsaplen);
942 			res_nclose(statp);
943 			return (0);
944 		}
945 #endif /* !CANNOT_CONNECT_DGRAM */
946 		Dprint(statp->options & RES_DEBUG,
947 		       (stdout, ";; new DG socket\n"))
948 	}
949 	s = EXT(statp).nssocks[ns];
950 #ifndef CANNOT_CONNECT_DGRAM
951 		if (statp->options & RES_INSECURE1) {
952 #ifndef _LIBC
953 		if (sendto(s,
954 #else
955 		if (_sendto(s,
956 #endif
957 		(const char*)buf, buflen, 0, nsap, nsaplen) != buflen) {
958 			Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
959 			res_nclose(statp);
960 			return (0);
961 		}
962 	} else if (send(s, (const char*)buf, buflen, 0) != buflen) {
963 		Perror(statp, stderr, "send", errno);
964 		res_nclose(statp);
965 		return (0);
966 	}
967 #else /* !CANNOT_CONNECT_DGRAM */
968 #ifndef _LIBC
969 	if (sendto(s, (const char*)buf, buflen, 0, nsap, nsaplen) != buflen)
970 #else
971 	if (_sendto(s, (const char*)buf, buflen, 0, nsap, nsaplen) != buflen)
972 #endif
973 	{
974 		Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
975 		res_nclose(statp);
976 		return (0);
977 	}
978 #endif /* !CANNOT_CONNECT_DGRAM */
979 
980 	/*
981 	 * Wait for reply.
982 	 */
983 	seconds = (statp->retrans << tries);
984 	if (ns > 0)
985 		seconds /= statp->nscount;
986 	if (seconds <= 0)
987 		seconds = 1;
988 	now = evNowTime();
989 	timeout = evConsTime(seconds, 0);
990 	finish = evAddTime(now, timeout);
991 	goto nonow;
992  wait:
993 	now = evNowTime();
994  nonow:
995 #ifndef USE_POLL
996 	if (evCmpTime(finish, now) > 0)
997 		timeout = evSubTime(finish, now);
998 	else
999 		timeout = evConsTime(0, 0);
1000 #ifdef USE_KQUEUE
1001 	EV_SET(&kv, s, EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0, 0);
1002 	n = _kevent(kq, &kv, 1, &kv, 1, &timeout);
1003 #else
1004 	FD_ZERO(&dsmask);
1005 	FD_SET(s, &dsmask);
1006 	n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
1007 #endif
1008 #else
1009 	timeout = evSubTime(finish, now);
1010 	if (timeout.tv_sec < 0)
1011 		timeout = evConsTime(0, 0);
1012 	polltimeout = 1000*timeout.tv_sec +
1013 		timeout.tv_nsec/1000000;
1014 	pollfd.fd = s;
1015 	pollfd.events = POLLRDNORM;
1016 	n = poll(&pollfd, 1, polltimeout);
1017 #endif /* USE_POLL */
1018 
1019 	if (n == 0) {
1020 		Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1021 		*gotsomewhere = 1;
1022 		return (0);
1023 	}
1024 	if (n < 0) {
1025 		if (errno == EINTR)
1026 			goto wait;
1027 #ifdef USE_KQUEUE
1028 		Perror(statp, stderr, "kevent", errno);
1029 #else
1030 #ifndef USE_POLL
1031 		Perror(statp, stderr, "select", errno);
1032 #else
1033 		Perror(statp, stderr, "poll", errno);
1034 #endif /* USE_POLL */
1035 #endif
1036 		res_nclose(statp);
1037 		return (0);
1038 	}
1039 #ifdef USE_KQUEUE
1040 	if (kv.ident != s)
1041 		goto wait;
1042 #endif
1043 	errno = 0;
1044 	fromlen = sizeof(from);
1045 #ifndef _LIBC
1046 	resplen = recvfrom(s, (char*)ans, anssiz,0,
1047 #else
1048 	resplen = _recvfrom(s, (char*)ans, anssiz,0,
1049 #endif
1050 			   (struct sockaddr *)&from, &fromlen);
1051 	if (resplen <= 0) {
1052 		Perror(statp, stderr, "recvfrom", errno);
1053 		res_nclose(statp);
1054 		return (0);
1055 	}
1056 	*gotsomewhere = 1;
1057 	if (resplen < HFIXEDSZ) {
1058 		/*
1059 		 * Undersized message.
1060 		 */
1061 		Dprint(statp->options & RES_DEBUG,
1062 		       (stdout, ";; undersized: %d\n",
1063 			resplen));
1064 		*terrno = EMSGSIZE;
1065 		res_nclose(statp);
1066 		return (0);
1067 	}
1068 	if (hp->id != anhp->id) {
1069 		/*
1070 		 * response from old query, ignore it.
1071 		 * XXX - potential security hazard could
1072 		 *	 be detected here.
1073 		 */
1074 		DprintQ((statp->options & RES_DEBUG) ||
1075 			(statp->pfcode & RES_PRF_REPLY),
1076 			(stdout, ";; old answer:\n"),
1077 			ans, (resplen > anssiz) ? anssiz : resplen);
1078 		goto wait;
1079 	}
1080 	if (!(statp->options & RES_INSECURE1) &&
1081 	    !res_ourserver_p(statp, (struct sockaddr *)&from)) {
1082 		/*
1083 		 * response from wrong server? ignore it.
1084 		 * XXX - potential security hazard could
1085 		 *	 be detected here.
1086 		 */
1087 		DprintQ((statp->options & RES_DEBUG) ||
1088 			(statp->pfcode & RES_PRF_REPLY),
1089 			(stdout, ";; not our server:\n"),
1090 			ans, (resplen > anssiz) ? anssiz : resplen);
1091 		goto wait;
1092 	}
1093 #ifdef RES_USE_EDNS0
1094 	if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1095 		/*
1096 		 * Do not retry if the server do not understand EDNS0.
1097 		 * The case has to be captured here, as FORMERR packet do not
1098 		 * carry query section, hence res_queriesmatch() returns 0.
1099 		 */
1100 		DprintQ(statp->options & RES_DEBUG,
1101 			(stdout, "server rejected query with EDNS0:\n"),
1102 			ans, (resplen > anssiz) ? anssiz : resplen);
1103 		/* record the error */
1104 		statp->_flags |= RES_F_EDNS0ERR;
1105 		res_nclose(statp);
1106 		return (0);
1107 	}
1108 #endif
1109 	if (!(statp->options & RES_INSECURE2) &&
1110 	    !res_queriesmatch(buf, buf + buflen,
1111 			      ans, ans + anssiz)) {
1112 		/*
1113 		 * response contains wrong query? ignore it.
1114 		 * XXX - potential security hazard could
1115 		 *	 be detected here.
1116 		 */
1117 		DprintQ((statp->options & RES_DEBUG) ||
1118 			(statp->pfcode & RES_PRF_REPLY),
1119 			(stdout, ";; wrong query name:\n"),
1120 			ans, (resplen > anssiz) ? anssiz : resplen);
1121 		goto wait;
1122 	}
1123 	if (anhp->rcode == SERVFAIL ||
1124 	    anhp->rcode == NOTIMP ||
1125 	    anhp->rcode == REFUSED) {
1126 		DprintQ(statp->options & RES_DEBUG,
1127 			(stdout, "server rejected query:\n"),
1128 			ans, (resplen > anssiz) ? anssiz : resplen);
1129 		res_nclose(statp);
1130 		/* don't retry if called from dig */
1131 		if (!statp->pfcode)
1132 			return (0);
1133 	}
1134 	if (!(statp->options & RES_IGNTC) && anhp->tc) {
1135 		/*
1136 		 * To get the rest of answer,
1137 		 * use TCP with same server.
1138 		 */
1139 		Dprint(statp->options & RES_DEBUG,
1140 		       (stdout, ";; truncated answer\n"));
1141 		*v_circuit = 1;
1142 		res_nclose(statp);
1143 		return (1);
1144 	}
1145 	/*
1146 	 * All is well, or the error is fatal.  Signal that the
1147 	 * next nameserver ought not be tried.
1148 	 */
1149 	return (resplen);
1150 }
1151 
1152 static void
1153 Aerror(const res_state statp, FILE *file, const char *string, int error,
1154        const struct sockaddr *address, int alen)
1155 {
1156 	int save = errno;
1157 	char hbuf[NI_MAXHOST];
1158 	char sbuf[NI_MAXSERV];
1159 
1160 	alen = alen;
1161 
1162 	if ((statp->options & RES_DEBUG) != 0U) {
1163 		if (getnameinfo(address, alen, hbuf, sizeof(hbuf),
1164 		    sbuf, sizeof(sbuf), niflags)) {
1165 			strncpy(hbuf, "?", sizeof(hbuf) - 1);
1166 			hbuf[sizeof(hbuf) - 1] = '\0';
1167 			strncpy(sbuf, "?", sizeof(sbuf) - 1);
1168 			sbuf[sizeof(sbuf) - 1] = '\0';
1169 		}
1170 		fprintf(file, "res_send: %s ([%s].%s): %s\n",
1171 			string, hbuf, sbuf, strerror(error));
1172 	}
1173 	errno = save;
1174 }
1175 
1176 static void
1177 Perror(const res_state statp, FILE *file, const char *string, int error) {
1178 	int save = errno;
1179 
1180 	if ((statp->options & RES_DEBUG) != 0U)
1181 		fprintf(file, "res_send: %s: %s\n",
1182 			string, strerror(error));
1183 	errno = save;
1184 }
1185 
1186 static int
1187 sock_eq(struct sockaddr *a, struct sockaddr *b) {
1188 	struct sockaddr_in *a4, *b4;
1189 	struct sockaddr_in6 *a6, *b6;
1190 
1191 	if (a->sa_family != b->sa_family)
1192 		return 0;
1193 	switch (a->sa_family) {
1194 	case AF_INET:
1195 		a4 = (struct sockaddr_in *)a;
1196 		b4 = (struct sockaddr_in *)b;
1197 		return a4->sin_port == b4->sin_port &&
1198 		    a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1199 	case AF_INET6:
1200 		a6 = (struct sockaddr_in6 *)a;
1201 		b6 = (struct sockaddr_in6 *)b;
1202 		return a6->sin6_port == b6->sin6_port &&
1203 #ifdef HAVE_SIN6_SCOPE_ID
1204 		    a6->sin6_scope_id == b6->sin6_scope_id &&
1205 #endif
1206 		    IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1207 	default:
1208 		return 0;
1209 	}
1210 }
1211 
1212 #if defined(NEED_PSELECT) && !defined(USE_POLL) && !defined(USE_KQUEUE)
1213 /* XXX needs to move to the porting library. */
1214 static int
1215 pselect(int nfds, void *rfds, void *wfds, void *efds,
1216 	struct timespec *tsp, const sigset_t *sigmask)
1217 {
1218 	struct timeval tv, *tvp;
1219 	sigset_t sigs;
1220 	int n;
1221 
1222 	if (tsp) {
1223 		tvp = &tv;
1224 		tv = evTimeVal(*tsp);
1225 	} else
1226 		tvp = NULL;
1227 	if (sigmask)
1228 		sigprocmask(SIG_SETMASK, sigmask, &sigs);
1229 	n = select(nfds, rfds, wfds, efds, tvp);
1230 	if (sigmask)
1231 		sigprocmask(SIG_SETMASK, &sigs, NULL);
1232 	if (tsp)
1233 		*tsp = evTimeSpec(tv);
1234 	return (n);
1235 }
1236 #endif
1237