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