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