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