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