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