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