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