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