Update.
[glibc.git] / resolv / res_send.c
blob2366f59cd2000afef9af28a38360ef58c721a0a0
1 /*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
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 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
31 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
33 * Permission to use, copy, modify, and distribute this software for any
34 * purpose with or without fee is hereby granted, provided that the above
35 * copyright notice and this permission notice appear in all copies, and that
36 * the name of Digital Equipment Corporation not be used in advertising or
37 * publicity pertaining to distribution of the document or software without
38 * specific, written prior permission.
40 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
43 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47 * SOFTWARE.
51 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
53 * Permission to use, copy, modify, and distribute this software for any
54 * purpose with or without fee is hereby granted, provided that the above
55 * copyright notice and this permission notice appear in all copies.
57 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
58 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
60 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
61 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
62 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
63 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
64 * SOFTWARE.
67 #if defined(LIBC_SCCS) && !defined(lint)
68 static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
69 static const char rcsid[] = "$BINDId: res_send.c,v 8.38 2000/03/30 20:16:51 vixie Exp $";
70 #endif /* LIBC_SCCS and not lint */
73 * Send query to name server and wait for reply.
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #include <sys/time.h>
79 #include <sys/socket.h>
80 #include <sys/uio.h>
81 #ifdef _LIBC
82 #include <sys/poll.h>
83 #endif
85 #include <netinet/in.h>
86 #include <arpa/nameser.h>
87 #include <arpa/inet.h>
88 #include <sys/ioctl.h>
90 #include <errno.h>
91 #include <netdb.h>
92 #include <resolv.h>
93 #include <signal.h>
94 #include <stdio.h>
95 #include <stdlib.h>
96 #include <string.h>
97 #include <unistd.h>
99 #if PACKETSZ > 65536
100 #define MAXPACKET PACKETSZ
101 #else
102 #define MAXPACKET 65536
103 #endif
105 #ifndef _LIBC
106 #include <isc/eventlib.h>
107 #else
109 /* From ev_streams.c. */
111 static inline void
112 __attribute ((always_inline))
113 evConsIovec(void *buf, size_t cnt, struct iovec *vec) {
114 memset(vec, 0xf5, sizeof (*vec));
115 vec->iov_base = buf;
116 vec->iov_len = cnt;
119 /* From ev_timers.c. */
121 #define BILLION 1000000000
123 static inline void
124 evConsTime(struct timespec *res, time_t sec, long nsec) {
125 res->tv_sec = sec;
126 res->tv_nsec = nsec;
129 static inline void
130 evAddTime(struct timespec *res, const struct timespec *addend1,
131 const struct timespec *addend2) {
132 res->tv_sec = addend1->tv_sec + addend2->tv_sec;
133 res->tv_nsec = addend1->tv_nsec + addend2->tv_nsec;
134 if (res->tv_nsec >= BILLION) {
135 res->tv_sec++;
136 res->tv_nsec -= BILLION;
140 static inline void
141 evSubTime(struct timespec *res, const struct timespec *minuend,
142 const struct timespec *subtrahend) {
143 res->tv_sec = minuend->tv_sec - subtrahend->tv_sec;
144 if (minuend->tv_nsec >= subtrahend->tv_nsec)
145 res->tv_nsec = minuend->tv_nsec - subtrahend->tv_nsec;
146 else {
147 res->tv_nsec = (BILLION
148 - subtrahend->tv_nsec + minuend->tv_nsec);
149 res->tv_sec--;
153 static inline int
154 evCmpTime(struct timespec a, struct timespec b) {
155 long x = a.tv_sec - b.tv_sec;
157 if (x == 0L)
158 x = a.tv_nsec - b.tv_nsec;
159 return (x < 0L ? (-1) : x > 0L ? (1) : (0));
162 static inline void
163 evNowTime(struct timespec *res) {
164 struct timeval now;
166 if (gettimeofday(&now, NULL) < 0)
167 evConsTime(res, 0, 0);
168 else
169 TIMEVAL_TO_TIMESPEC (&now, res);
172 #endif
174 /* Options. Leave them on. */
175 /* #undef DEBUG */
176 #include "res_debug.h"
178 #define EXT(res) ((res)->_u._ext)
180 #ifndef _LIBC
181 static const int highestFD = FD_SETSIZE - 1;
182 #endif
184 /* Forward. */
186 static int send_vc(res_state, const u_char *, int,
187 u_char **, int *, int *, int, u_char **);
188 static int send_dg(res_state, const u_char *, int,
189 u_char **, int *, int *, int,
190 int *, int *, u_char **);
191 #ifdef DEBUG
192 static void Aerror(const res_state, FILE *, const char *, int,
193 const struct sockaddr *);
194 static void Perror(const res_state, FILE *, const char *, int);
195 #endif
196 #ifdef _LIBC
197 static int sock_eq(struct sockaddr_in6 *, struct sockaddr_in6 *);
198 #else
199 static int sock_eq(struct sockaddr_in *, struct sockaddr_in *);
200 #endif
201 #ifdef NEED_PSELECT
202 static int pselect(int, void *, void *, void *,
203 struct timespec *,
204 const sigset_t *);
205 #endif
207 /* Reachover. */
209 #ifdef _LIBC
210 static void convaddr4to6(struct sockaddr_in6 *sa);
211 #endif
212 void res_pquery(const res_state, const u_char *, int, FILE *);
214 /* Public. */
216 /* int
217 * res_isourserver(ina)
218 * looks up "ina" in _res.ns_addr_list[]
219 * returns:
220 * 0 : not found
221 * >0 : found
222 * author:
223 * paul vixie, 29may94
226 #ifdef _LIBC
227 res_ourserver_p(const res_state statp, const struct sockaddr_in6 *inp)
228 #else
229 res_ourserver_p(const res_state statp, const struct sockaddr_in *inp)
230 #endif
232 int ns;
234 #ifdef _LIBC
235 if (inp->sin6_family == AF_INET) {
236 struct sockaddr_in *in4p = (struct sockaddr_in *) inp;
237 in_port_t port = in4p->sin_port;
238 in_addr_t addr = in4p->sin_addr.s_addr;
240 for (ns = 0; ns < MAXNS; ns++) {
241 const struct sockaddr_in *srv =
242 (struct sockaddr_in *)EXT(statp).nsaddrs[ns];
244 if ((srv != NULL) && (srv->sin_family == AF_INET) &&
245 (srv->sin_port == port) &&
246 (srv->sin_addr.s_addr == INADDR_ANY ||
247 srv->sin_addr.s_addr == addr))
248 return (1);
250 } else if (inp->sin6_family == AF_INET6) {
251 for (ns = 0; ns < MAXNS; ns++) {
252 const struct sockaddr_in6 *srv = EXT(statp).nsaddrs[ns];
253 if ((srv != NULL) && (srv->sin6_family == AF_INET6) &&
254 (srv->sin6_port == inp->sin6_port) &&
255 !(memcmp(&srv->sin6_addr, &in6addr_any,
256 sizeof (struct in6_addr)) &&
257 memcmp(&srv->sin6_addr, &inp->sin6_addr,
258 sizeof (struct in6_addr))))
259 return (1);
262 #else
263 struct sockaddr_in ina = *inp;
264 for (ns = 0; ns < statp->nscount; ns++) {
265 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
267 if (srv->sin_family == ina.sin_family &&
268 srv->sin_port == ina.sin_port &&
269 (srv->sin_addr.s_addr == INADDR_ANY ||
270 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
271 return (1);
273 #endif
274 return (0);
277 /* int
278 * res_nameinquery(name, type, class, buf, eom)
279 * look for (name,type,class) in the query section of packet (buf,eom)
280 * requires:
281 * buf + HFIXEDSZ <= eom
282 * returns:
283 * -1 : format error
284 * 0 : not found
285 * >0 : found
286 * author:
287 * paul vixie, 29may94
290 res_nameinquery(const char *name, int type, int class,
291 const u_char *buf, const u_char *eom)
293 const u_char *cp = buf + HFIXEDSZ;
294 int qdcount = ntohs(((HEADER*)buf)->qdcount);
296 while (qdcount-- > 0) {
297 char tname[MAXDNAME+1];
298 int n, ttype, tclass;
300 n = dn_expand(buf, eom, cp, tname, sizeof tname);
301 if (n < 0)
302 return (-1);
303 cp += n;
304 if (cp + 2 * INT16SZ > eom)
305 return (-1);
306 ttype = ns_get16(cp); cp += INT16SZ;
307 tclass = ns_get16(cp); cp += INT16SZ;
308 if (ttype == type && tclass == class &&
309 ns_samename(tname, name) == 1)
310 return (1);
312 return (0);
315 /* int
316 * res_queriesmatch(buf1, eom1, buf2, eom2)
317 * is there a 1:1 mapping of (name,type,class)
318 * in (buf1,eom1) and (buf2,eom2)?
319 * returns:
320 * -1 : format error
321 * 0 : not a 1:1 mapping
322 * >0 : is a 1:1 mapping
323 * author:
324 * paul vixie, 29may94
327 res_queriesmatch(const u_char *buf1, const u_char *eom1,
328 const u_char *buf2, const u_char *eom2)
330 const u_char *cp = buf1 + HFIXEDSZ;
331 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
333 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
334 return (-1);
337 * Only header section present in replies to
338 * dynamic update packets.
340 if ((((HEADER *)buf1)->opcode == ns_o_update) &&
341 (((HEADER *)buf2)->opcode == ns_o_update))
342 return (1);
344 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
345 return (0);
346 while (qdcount-- > 0) {
347 char tname[MAXDNAME+1];
348 int n, ttype, tclass;
350 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
351 if (n < 0)
352 return (-1);
353 cp += n;
354 if (cp + 2 * INT16SZ > eom1)
355 return (-1);
356 ttype = ns_get16(cp); cp += INT16SZ;
357 tclass = ns_get16(cp); cp += INT16SZ;
358 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
359 return (0);
361 return (1);
365 __libc_res_nsend(res_state statp, const u_char *buf, int buflen,
366 u_char *ans, int anssiz, u_char **ansp)
368 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
370 if (statp->nscount == 0) {
371 __set_errno (ESRCH);
372 return (-1);
375 if (anssiz < HFIXEDSZ) {
376 __set_errno (EINVAL);
377 return (-1);
380 if ((statp->qhook || statp->rhook) && anssiz < MAXPACKET && ansp) {
381 u_char *buf = malloc (MAXPACKET);
382 if (buf == NULL)
383 return (-1);
384 memcpy (buf, ans, HFIXEDSZ);
385 *ansp = buf;
386 ans = buf;
387 anssiz = MAXPACKET;
390 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
391 (stdout, ";; res_send()\n"), buf, buflen);
392 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
393 gotsomewhere = 0;
394 terrno = ETIMEDOUT;
397 * If the ns_addr_list in the resolver context has changed, then
398 * invalidate our cached copy and the associated timing data.
400 if (EXT(statp).nsinit) {
401 int needclose = 0;
403 if (EXT(statp).nscount != statp->nscount)
404 needclose++;
405 else
406 #ifdef _LIBC
407 for (ns = 0; ns < MAXNS; ns++) {
408 unsigned int map = EXT(statp).nsmap[ns];
409 if (map < MAXNS
410 && !sock_eq((struct sockaddr_in6 *)
411 &statp->nsaddr_list[map],
412 EXT(statp).nsaddrs[ns]))
413 #else
414 for (ns = 0; ns < statp->nscount; ns++) {
415 if (!sock_eq(&statp->nsaddr_list[ns],
416 &EXT(statp).nsaddrs[ns]))
417 #endif
419 needclose++;
420 break;
423 if (needclose)
424 res_nclose(statp);
428 * Maybe initialize our private copy of the ns_addr_list.
430 if (EXT(statp).nsinit == 0) {
431 #ifdef _LIBC
432 unsigned char map[MAXNS];
434 memset (map, MAXNS, sizeof (map));
435 for (n = 0; n < MAXNS; n++) {
436 ns = EXT(statp).nsmap[n];
437 if (ns < statp->nscount)
438 map[ns] = n;
439 else if (ns < MAXNS) {
440 free(EXT(statp).nsaddrs[n]);
441 EXT(statp).nsaddrs[n] = NULL;
442 EXT(statp).nsmap[n] = MAXNS;
445 n = statp->nscount;
446 if (statp->nscount > EXT(statp).nscount)
447 for (n = EXT(statp).nscount, ns = 0;
448 n < statp->nscount; n++) {
449 while (ns < MAXNS
450 && EXT(statp).nsmap[ns] != MAXNS)
451 ns++;
452 if (ns == MAXNS)
453 break;
454 EXT(statp).nsmap[ns] = n;
455 map[n] = ns++;
457 EXT(statp).nscount = n;
458 for (ns = 0; ns < EXT(statp).nscount; ns++) {
459 n = map[ns];
460 if (EXT(statp).nsaddrs[n] == NULL)
461 EXT(statp).nsaddrs[n] =
462 malloc(sizeof (struct sockaddr_in6));
463 if (EXT(statp).nsaddrs[n] != NULL) {
464 memcpy(EXT(statp).nsaddrs[n],
465 &statp->nsaddr_list[ns],
466 sizeof (struct sockaddr_in));
467 EXT(statp).nssocks[n] = -1;
468 n++;
471 #else
472 for (ns = 0; ns < statp->nscount; ns++) {
473 EXT(statp).nsaddrs[ns] = statp->nsaddr_list[ns];
474 EXT(statp).nssocks[ns] = -1;
476 EXT(statp).nscount = ns;
477 #endif
478 EXT(statp).nsinit = 1;
482 * Some resolvers want to even out the load on their nameservers.
483 * Note that RES_BLAST overrides RES_ROTATE.
485 if ((statp->options & RES_ROTATE) != 0 &&
486 (statp->options & RES_BLAST) == 0) {
487 #ifdef _LIBC
488 struct sockaddr_in6 *ina;
489 unsigned int map;
491 n = 0;
492 while (n < MAXNS && EXT(statp).nsmap[n] == MAXNS)
493 n++;
494 if (n < MAXNS) {
495 ina = EXT(statp).nsaddrs[n];
496 map = EXT(statp).nsmap[n];
497 for (;;) {
498 ns = n + 1;
499 while (ns < MAXNS
500 && EXT(statp).nsmap[ns] == MAXNS)
501 ns++;
502 if (ns == MAXNS)
503 break;
504 EXT(statp).nsaddrs[n] = EXT(statp).nsaddrs[ns];
505 EXT(statp).nsmap[n] = EXT(statp).nsmap[ns];
506 n = ns;
508 EXT(statp).nsaddrs[n] = ina;
509 EXT(statp).nsmap[n] = map;
511 #else
512 struct sockaddr_in ina;
513 int lastns = statp->nscount - 1;
515 ina = statp->nsaddr_list[0];
516 for (ns = 0; ns < lastns; ns++)
517 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
518 statp->nsaddr_list[lastns] = ina;
519 #endif
523 * Send request, RETRY times, or until successful.
525 for (try = 0; try < statp->retry; try++) {
526 #ifdef _LIBC
527 for (ns = 0; ns < MAXNS; ns++)
528 #else
529 for (ns = 0; ns < statp->nscount; ns++)
530 #endif
532 #ifdef _LIBC
533 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
535 if (nsap == NULL)
536 goto next_ns;
537 #else
538 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
539 #endif
540 same_ns:
541 if (statp->qhook) {
542 int done = 0, loops = 0;
544 do {
545 res_sendhookact act;
547 #ifdef _LIBC
548 struct sockaddr_in *nsap4;
549 nsap4 = (struct sockaddr_in *) nsap;
550 act = (*statp->qhook)(&nsap4, &buf, &buflen,
551 ans, anssiz, &resplen);
552 nsap = (struct sockaddr_in6 *) nsap4;
553 #else
554 act = (*statp->qhook)(&nsap, &buf, &buflen,
555 ans, anssiz, &resplen);
556 #endif
557 switch (act) {
558 case res_goahead:
559 done = 1;
560 break;
561 case res_nextns:
562 res_nclose(statp);
563 goto next_ns;
564 case res_done:
565 return (resplen);
566 case res_modified:
567 /* give the hook another try */
568 if (++loops < 42) /*doug adams*/
569 break;
570 /*FALLTHROUGH*/
571 case res_error:
572 /*FALLTHROUGH*/
573 default:
574 return (-1);
576 } while (!done);
579 #ifdef _LIBC
580 # ifdef DEBUG
581 char tmpbuf[40];
582 # endif
583 Dprint(statp->options & RES_DEBUG,
584 (stdout, ";; Querying server (# %d) address = %s\n",
585 ns + 1, inet_ntop(AF_INET6, &nsap->sin6_addr,
586 tmpbuf, sizeof (tmpbuf))));
587 #else
588 Dprint(statp->options & RES_DEBUG,
589 (stdout, ";; Querying server (# %d) address = %s\n",
590 ns + 1, inet_ntoa(nsap->sin_addr)));
591 #endif
593 if (v_circuit) {
594 /* Use VC; at most one attempt per server. */
595 try = statp->retry;
596 n = send_vc(statp, buf, buflen, &ans, &anssiz, &terrno,
597 ns, ansp);
598 if (n < 0)
599 return (-1);
600 if (n == 0)
601 goto next_ns;
602 resplen = n;
603 } else {
604 /* Use datagrams. */
605 n = send_dg(statp, buf, buflen, &ans, &anssiz, &terrno,
606 ns, &v_circuit, &gotsomewhere, ansp);
607 if (n < 0)
608 return (-1);
609 if (n == 0)
610 goto next_ns;
611 if (v_circuit)
612 goto same_ns;
613 resplen = n;
616 Dprint((statp->options & RES_DEBUG) ||
617 ((statp->pfcode & RES_PRF_REPLY) &&
618 (statp->pfcode & RES_PRF_HEAD1)),
619 (stdout, ";; got answer:\n"));
621 DprintQ((statp->options & RES_DEBUG) ||
622 (statp->pfcode & RES_PRF_REPLY),
623 (stdout, "%s", ""),
624 ans, (resplen > anssiz) ? anssiz : resplen);
627 * If we have temporarily opened a virtual circuit,
628 * or if we haven't been asked to keep a socket open,
629 * close the socket.
631 if ((v_circuit && (statp->options & RES_USEVC) == 0) ||
632 (statp->options & RES_STAYOPEN) == 0) {
633 res_nclose(statp);
635 if (statp->rhook) {
636 int done = 0, loops = 0;
638 do {
639 res_sendhookact act;
641 #ifdef _LIBC
642 act = (*statp->rhook)((struct sockaddr_in *)
643 nsap, buf, buflen,
644 ans, anssiz, &resplen);
645 #else
646 act = (*statp->rhook)(nsap, buf, buflen,
647 ans, anssiz, &resplen);
648 #endif
649 switch (act) {
650 case res_goahead:
651 case res_done:
652 done = 1;
653 break;
654 case res_nextns:
655 res_nclose(statp);
656 goto next_ns;
657 case res_modified:
658 /* give the hook another try */
659 if (++loops < 42) /*doug adams*/
660 break;
661 /*FALLTHROUGH*/
662 case res_error:
663 /*FALLTHROUGH*/
664 default:
665 return (-1);
667 } while (!done);
670 return (resplen);
671 next_ns: ;
672 } /*foreach ns*/
673 } /*foreach retry*/
674 res_nclose(statp);
675 if (!v_circuit) {
676 if (!gotsomewhere)
677 __set_errno (ECONNREFUSED); /* no nameservers found */
678 else
679 __set_errno (ETIMEDOUT); /* no answer obtained */
680 } else
681 __set_errno (terrno);
682 return (-1);
686 res_nsend(res_state statp,
687 const u_char *buf, int buflen, u_char *ans, int anssiz)
689 return __libc_res_nsend(statp, buf, buflen, ans, anssiz, NULL);
692 /* Private */
694 static int
695 send_vc(res_state statp,
696 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
697 int *terrno, int ns, u_char **anscp)
699 const HEADER *hp = (HEADER *) buf;
700 u_char *ans = *ansp;
701 int anssiz = *anssizp;
702 HEADER *anhp = (HEADER *) ans;
703 #ifdef _LIBC
704 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
705 #else
706 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
707 #endif
708 int truncating, connreset, resplen, n;
709 struct iovec iov[2];
710 u_short len;
711 u_char *cp;
713 connreset = 0;
714 same_ns:
715 truncating = 0;
717 /* Are we still talking to whom we want to talk to? */
718 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
719 #ifdef _LIBC
720 struct sockaddr_in6 peer;
721 #else
722 struct sockaddr_in peer;
723 #endif
724 int size = sizeof peer;
726 if (getpeername(statp->_vcsock,
727 (struct sockaddr *)&peer, &size) < 0 ||
728 !sock_eq(&peer, nsap)) {
729 res_nclose(statp);
730 statp->_flags &= ~RES_F_VC;
734 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
735 if (statp->_vcsock >= 0)
736 res_nclose(statp);
738 #ifdef _LIBC
739 statp->_vcsock = socket(nsap->sin6_family, SOCK_STREAM, 0);
740 #else
741 statp->_vcsock = socket(PF_INET, SOCK_STREAM, 0);
742 if (statp->_vcsock > highestFD) {
743 res_nclose(statp);
744 __set_errno (ENOTSOCK);
746 #endif
747 if (statp->_vcsock < 0) {
748 *terrno = errno;
749 Perror(statp, stderr, "socket(vc)", errno);
750 return (-1);
752 __set_errno (0);
753 if (connect(statp->_vcsock, (struct sockaddr *)nsap,
754 sizeof *nsap) < 0) {
755 *terrno = errno;
756 Aerror(statp, stderr, "connect/vc", errno,
757 (struct sockaddr *) nsap);
758 res_nclose(statp);
759 return (0);
761 statp->_flags |= RES_F_VC;
765 * Send length & message
767 putshort((u_short)buflen, (u_char*)&len);
768 evConsIovec(&len, INT16SZ, &iov[0]);
769 evConsIovec((void*)buf, buflen, &iov[1]);
770 if (TEMP_FAILURE_RETRY (writev(statp->_vcsock, iov, 2))
771 != (INT16SZ + buflen)) {
772 *terrno = errno;
773 Perror(statp, stderr, "write failed", errno);
774 res_nclose(statp);
775 return (0);
778 * Receive length & response
780 read_len:
781 cp = ans;
782 len = INT16SZ;
783 while ((n = TEMP_FAILURE_RETRY (read(statp->_vcsock, (char *)cp,
784 (int)len))) > 0) {
785 cp += n;
786 if ((len -= n) <= 0)
787 break;
789 if (n <= 0) {
790 *terrno = errno;
791 Perror(statp, stderr, "read failed", errno);
792 res_nclose(statp);
794 * A long running process might get its TCP
795 * connection reset if the remote server was
796 * restarted. Requery the server instead of
797 * trying a new one. When there is only one
798 * server, this means that a query might work
799 * instead of failing. We only allow one reset
800 * per query to prevent looping.
802 if (*terrno == ECONNRESET && !connreset) {
803 connreset = 1;
804 res_nclose(statp);
805 goto same_ns;
807 res_nclose(statp);
808 return (0);
810 resplen = ns_get16(ans);
811 if (resplen > anssiz) {
812 if (anscp) {
813 ans = malloc (MAXPACKET);
814 if (ans == NULL) {
815 *terrno = ENOMEM;
816 res_nclose(statp);
817 return (0);
819 anssiz = MAXPACKET;
820 *anssizp = MAXPACKET;
821 *ansp = ans;
822 *anscp = ans;
823 anhp = (HEADER *) ans;
824 len = resplen;
825 } else {
826 Dprint(statp->options & RES_DEBUG,
827 (stdout, ";; response truncated\n")
829 truncating = 1;
830 len = anssiz;
832 } else
833 len = resplen;
834 if (len < HFIXEDSZ) {
836 * Undersized message.
838 Dprint(statp->options & RES_DEBUG,
839 (stdout, ";; undersized: %d\n", len));
840 *terrno = EMSGSIZE;
841 res_nclose(statp);
842 return (0);
844 cp = ans;
845 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
846 cp += n;
847 len -= n;
849 if (n <= 0) {
850 *terrno = errno;
851 Perror(statp, stderr, "read(vc)", errno);
852 res_nclose(statp);
853 return (0);
855 if (truncating) {
857 * Flush rest of answer so connection stays in synch.
859 anhp->tc = 1;
860 len = resplen - anssiz;
861 while (len != 0) {
862 char junk[PACKETSZ];
864 n = read(statp->_vcsock, junk,
865 (len > sizeof junk) ? sizeof junk : len);
866 if (n > 0)
867 len -= n;
868 else
869 break;
873 * If the calling applicating has bailed out of
874 * a previous call and failed to arrange to have
875 * the circuit closed or the server has got
876 * itself confused, then drop the packet and
877 * wait for the correct one.
879 if (hp->id != anhp->id) {
880 DprintQ((statp->options & RES_DEBUG) ||
881 (statp->pfcode & RES_PRF_REPLY),
882 (stdout, ";; old answer (unexpected):\n"),
883 ans, (resplen > anssiz) ? anssiz: resplen);
884 goto read_len;
888 * All is well, or the error is fatal. Signal that the
889 * next nameserver ought not be tried.
891 return (resplen);
894 static int
895 send_dg(res_state statp,
896 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
897 int *terrno, int ns, int *v_circuit, int *gotsomewhere, u_char **anscp)
899 const HEADER *hp = (HEADER *) buf;
900 u_char *ans = *ansp;
901 int anssiz = *anssizp;
902 HEADER *anhp = (HEADER *) ans;
903 #ifdef _LIBC
904 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
905 #else
906 const struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
907 #endif
908 struct timespec now, timeout, finish;
909 #ifdef _LIBC
910 struct pollfd pfd[1];
911 int ptimeout;
912 struct sockaddr_in6 from;
913 static int socket_pf = 0;
914 #else
915 fd_set dsmask;
916 struct sockaddr_in from;
917 #endif
918 int fromlen, resplen, seconds, n, s;
920 if (EXT(statp).nssocks[ns] == -1) {
921 #ifdef _LIBC
922 /* only try IPv6 if IPv6 NS and if not failed before */
923 if ((EXT(statp).nscount6 > 0) && (socket_pf != PF_INET)) {
924 EXT(statp).nssocks[ns] =
925 socket(PF_INET6, SOCK_DGRAM, 0);
926 socket_pf = EXT(statp).nssocks[ns] < 0 ? PF_INET
927 : PF_INET6;
929 if (EXT(statp).nssocks[ns] < 0)
930 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
931 #else
932 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
933 if (EXT(statp).nssocks[ns] > highestFD) {
934 res_nclose(statp);
935 __set_errno (ENOTSOCK);
937 #endif
938 if (EXT(statp).nssocks[ns] < 0) {
939 *terrno = errno;
940 Perror(statp, stderr, "socket(dg)", errno);
941 return (-1);
943 #ifndef CANNOT_CONNECT_DGRAM
944 #ifdef _LIBC
945 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
946 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
947 convaddr4to6(nsap);
948 #endif
950 * On a 4.3BSD+ machine (client and server,
951 * actually), sending to a nameserver datagram
952 * port with no nameserver will cause an
953 * ICMP port unreachable message to be returned.
954 * If our datagram socket is "connected" to the
955 * server, we get an ECONNREFUSED error on the next
956 * socket operation, and select returns if the
957 * error message is received. We can thus detect
958 * the absence of a nameserver without timing out.
960 if (connect(EXT(statp).nssocks[ns], (struct sockaddr *)nsap,
961 sizeof *nsap) < 0) {
962 Aerror(statp, stderr, "connect(dg)", errno,
963 (struct sockaddr *) nsap);
964 res_nclose(statp);
965 return (0);
967 #endif /* !CANNOT_CONNECT_DGRAM */
968 Dprint(statp->options & RES_DEBUG,
969 (stdout, ";; new DG socket\n"))
971 s = EXT(statp).nssocks[ns];
972 #ifndef CANNOT_CONNECT_DGRAM
973 if (send(s, (char*)buf, buflen, 0) != buflen) {
974 Perror(statp, stderr, "send", errno);
975 res_nclose(statp);
976 return (0);
978 #else /* !CANNOT_CONNECT_DGRAM */
979 #ifdef _LIBC
980 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
981 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
982 convaddr4to6(nsap);
983 #endif
984 if (sendto(s, (char*)buf, buflen, 0,
985 (struct sockaddr *)nsap, sizeof *nsap) != buflen)
987 Aerror(statp, stderr, "sendto", errno,
988 (struct sockaddr *) nsap);
989 res_nclose(statp);
990 return (0);
992 #endif /* !CANNOT_CONNECT_DGRAM */
995 * Wait for reply.
997 seconds = (statp->retrans << ns);
998 if (ns > 0)
999 seconds /= statp->nscount;
1000 if (seconds <= 0)
1001 seconds = 1;
1002 evNowTime(&now);
1003 evConsTime(&timeout, seconds, 0);
1004 evAddTime(&finish, &now, &timeout);
1005 wait:
1006 #ifdef _LIBC
1007 /* Convert struct timespec in milliseconds. */
1008 ptimeout = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
1010 pfd[0].fd = s;
1011 pfd[0].events = POLLIN;
1012 n = __poll (pfd, 1, ptimeout);
1013 #else
1014 FD_ZERO(&dsmask);
1015 FD_SET(s, &dsmask);
1016 n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
1017 #endif
1018 if (n == 0) {
1019 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1020 *gotsomewhere = 1;
1021 return (0);
1023 if (n < 0) {
1024 if (errno == EINTR) {
1025 evNowTime(&now);
1026 if (evCmpTime(finish, now) > 0) {
1027 evSubTime(&timeout, &finish, &now);
1028 goto wait;
1031 Perror(statp, stderr, "select", errno);
1032 res_nclose(statp);
1033 return (0);
1035 __set_errno (0);
1036 #ifdef _LIBC
1037 fromlen = sizeof(struct sockaddr_in6);
1038 #else
1039 fromlen = sizeof(struct sockaddr_in);
1040 #endif
1041 if (anssiz < MAXPACKET
1042 && anscp
1043 && (ioctl (s, FIONREAD, &resplen) < 0
1044 || anssiz < resplen)) {
1045 ans = malloc (MAXPACKET);
1046 if (ans == NULL)
1047 ans = *ansp;
1048 else {
1049 anssiz = MAXPACKET;
1050 *anssizp = MAXPACKET;
1051 *ansp = ans;
1052 *anscp = ans;
1053 anhp = (HEADER *) ans;
1056 resplen = recvfrom(s, (char*)ans, anssiz,0,
1057 (struct sockaddr *)&from, &fromlen);
1058 if (resplen <= 0) {
1059 Perror(statp, stderr, "recvfrom", errno);
1060 res_nclose(statp);
1061 return (0);
1063 *gotsomewhere = 1;
1064 if (resplen < HFIXEDSZ) {
1066 * Undersized message.
1068 Dprint(statp->options & RES_DEBUG,
1069 (stdout, ";; undersized: %d\n",
1070 resplen));
1071 *terrno = EMSGSIZE;
1072 res_nclose(statp);
1073 return (0);
1075 if (hp->id != anhp->id) {
1077 * response from old query, ignore it.
1078 * XXX - potential security hazard could
1079 * be detected here.
1081 DprintQ((statp->options & RES_DEBUG) ||
1082 (statp->pfcode & RES_PRF_REPLY),
1083 (stdout, ";; old answer:\n"),
1084 ans, (resplen > anssiz) ? anssiz : resplen);
1085 goto wait;
1087 if (!(statp->options & RES_INSECURE1) &&
1088 !res_ourserver_p(statp, &from)) {
1090 * response from wrong server? ignore it.
1091 * XXX - potential security hazard could
1092 * be detected here.
1094 DprintQ((statp->options & RES_DEBUG) ||
1095 (statp->pfcode & RES_PRF_REPLY),
1096 (stdout, ";; not our server:\n"),
1097 ans, (resplen > anssiz) ? anssiz : resplen);
1098 goto wait;
1100 if (!(statp->options & RES_INSECURE2) &&
1101 !res_queriesmatch(buf, buf + buflen,
1102 ans, ans + anssiz)) {
1104 * response contains wrong query? ignore it.
1105 * XXX - potential security hazard could
1106 * be detected here.
1108 DprintQ((statp->options & RES_DEBUG) ||
1109 (statp->pfcode & RES_PRF_REPLY),
1110 (stdout, ";; wrong query name:\n"),
1111 ans, (resplen > anssiz) ? anssiz : resplen);
1112 goto wait;
1114 if (anhp->rcode == SERVFAIL ||
1115 anhp->rcode == NOTIMP ||
1116 anhp->rcode == REFUSED) {
1117 DprintQ(statp->options & RES_DEBUG,
1118 (stdout, "server rejected query:\n"),
1119 ans, (resplen > anssiz) ? anssiz : resplen);
1120 res_nclose(statp);
1121 /* don't retry if called from dig */
1122 if (!statp->pfcode)
1123 return (0);
1125 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1127 * To get the rest of answer,
1128 * use TCP with same server.
1130 Dprint(statp->options & RES_DEBUG,
1131 (stdout, ";; truncated answer\n"));
1132 *v_circuit = 1;
1133 res_nclose(statp);
1134 return (1);
1137 * All is well, or the error is fatal. Signal that the
1138 * next nameserver ought not be tried.
1140 return (resplen);
1143 #ifdef DEBUG
1144 static void
1145 Aerror(const res_state statp, FILE *file, const char *string, int error,
1146 const struct sockaddr *address)
1148 int save = errno;
1150 if ((statp->options & RES_DEBUG) != 0) {
1151 char tmp[sizeof "xxxx.xxxx.xxxx.255.255.255.255"];
1153 fprintf(file, "res_send: %s ([%s].%u): %s\n",
1154 string,
1155 inet_ntop(address->sa_family, address->sa_data,
1156 tmp, sizeof tmp),
1157 (address->sa_family == AF_INET
1158 ? ntohs(((struct sockaddr_in *) address)->sin_port)
1159 : address->sa_family == AF_INET6
1160 ? ntohs(((struct sockaddr_in6 *) address)->sin6_port)
1161 : 0),
1162 strerror(error));
1164 __set_errno (save);
1167 static void
1168 Perror(const res_state statp, FILE *file, const char *string, int error) {
1169 int save = errno;
1171 if ((statp->options & RES_DEBUG) != 0)
1172 fprintf(file, "res_send: %s: %s\n",
1173 string, strerror(error));
1174 __set_errno (save);
1176 #endif
1178 static int
1179 #ifdef _LIBC
1180 sock_eq(struct sockaddr_in6 *a1, struct sockaddr_in6 *a2) {
1181 if (a1->sin6_family == a2->sin6_family) {
1182 if (a1->sin6_family == AF_INET)
1183 return ((((struct sockaddr_in *)a1)->sin_port ==
1184 ((struct sockaddr_in *)a2)->sin_port) &&
1185 (((struct sockaddr_in *)a1)->sin_addr.s_addr ==
1186 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1187 else
1188 return ((a1->sin6_port == a2->sin6_port) &&
1189 !memcmp(&a1->sin6_addr, &a2->sin6_addr,
1190 sizeof (struct in6_addr)));
1192 if (a1->sin6_family == AF_INET) {
1193 struct sockaddr_in6 *sap = a1;
1194 a1 = a2;
1195 a2 = sap;
1196 } /* assumes that AF_INET and AF_INET6 are the only possibilities */
1197 return ((a1->sin6_port == ((struct sockaddr_in *)a2)->sin_port) &&
1198 IN6_IS_ADDR_V4MAPPED(&a1->sin6_addr) &&
1199 (a1->sin6_addr.s6_addr32[3] ==
1200 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1202 #else
1203 sock_eq(struct sockaddr_in *a1, struct sockaddr_in *a2) {
1204 return ((a1->sin_family == a2->sin_family) &&
1205 (a1->sin_port == a2->sin_port) &&
1206 (a1->sin_addr.s_addr == a2->sin_addr.s_addr));
1208 #endif
1210 #ifdef _LIBC
1212 * Converts IPv4 family, address and port to
1213 * IPv6 family, IPv4-mapped IPv6 address and port.
1215 static void
1216 convaddr4to6(struct sockaddr_in6 *sa)
1218 struct sockaddr_in *sa4p = (struct sockaddr_in *) sa;
1219 in_port_t port = sa4p->sin_port;
1220 in_addr_t addr = sa4p->sin_addr.s_addr;
1222 sa->sin6_family = AF_INET6;
1223 sa->sin6_port = port;
1224 sa->sin6_addr.s6_addr32[0] = 0;
1225 sa->sin6_addr.s6_addr32[1] = 0;
1226 sa->sin6_addr.s6_addr32[2] = htonl(0xFFFF);
1227 sa->sin6_addr.s6_addr32[3] = addr;
1229 #endif
1231 #ifdef NEED_PSELECT
1232 /* XXX needs to move to the porting library. */
1233 static int
1234 pselect(int nfds, void *rfds, void *wfds, void *efds,
1235 struct timespec *tsp, const sigset_t *sigmask)
1237 struct timeval tv, *tvp;
1238 sigset_t sigs;
1239 int n;
1241 if (tsp) {
1242 tvp = &tv;
1243 tv = evTimeVal(*tsp);
1244 } else
1245 tvp = NULL;
1246 if (sigmask)
1247 sigprocmask(SIG_SETMASK, sigmask, &sigs);
1248 n = select(nfds, rfds, wfds, efds, tvp);
1249 if (sigmask)
1250 sigprocmask(SIG_SETMASK, &sigs, NULL);
1251 if (tsp)
1252 TIMEVAL_TO_TIMESPEC (tv, *tsp);
1253 return (n);
1255 #endif