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