* io/fts.c (fts_close): Remove redundant checks.
[glibc.git] / resolv / res_send.c
blob887d048e1958a59595b40fa35ab3469214fe71cf
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 <assert.h>
77 #include <sys/types.h>
78 #include <sys/param.h>
79 #include <sys/time.h>
80 #include <sys/socket.h>
81 #include <sys/uio.h>
82 #include <sys/poll.h>
84 #include <netinet/in.h>
85 #include <arpa/nameser.h>
86 #include <arpa/inet.h>
87 #include <sys/ioctl.h>
89 #include <errno.h>
90 #include <fcntl.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
106 /* From ev_streams.c. */
108 static inline void
109 __attribute ((always_inline))
110 evConsIovec(void *buf, size_t cnt, struct iovec *vec) {
111 memset(vec, 0xf5, sizeof (*vec));
112 vec->iov_base = buf;
113 vec->iov_len = cnt;
116 /* From ev_timers.c. */
118 #define BILLION 1000000000
120 static inline void
121 evConsTime(struct timespec *res, time_t sec, long nsec) {
122 res->tv_sec = sec;
123 res->tv_nsec = nsec;
126 static inline void
127 evAddTime(struct timespec *res, const struct timespec *addend1,
128 const struct timespec *addend2) {
129 res->tv_sec = addend1->tv_sec + addend2->tv_sec;
130 res->tv_nsec = addend1->tv_nsec + addend2->tv_nsec;
131 if (res->tv_nsec >= BILLION) {
132 res->tv_sec++;
133 res->tv_nsec -= BILLION;
137 static inline void
138 evSubTime(struct timespec *res, const struct timespec *minuend,
139 const struct timespec *subtrahend) {
140 res->tv_sec = minuend->tv_sec - subtrahend->tv_sec;
141 if (minuend->tv_nsec >= subtrahend->tv_nsec)
142 res->tv_nsec = minuend->tv_nsec - subtrahend->tv_nsec;
143 else {
144 res->tv_nsec = (BILLION
145 - subtrahend->tv_nsec + minuend->tv_nsec);
146 res->tv_sec--;
150 static inline int
151 evCmpTime(struct timespec a, struct timespec b) {
152 long x = a.tv_sec - b.tv_sec;
154 if (x == 0L)
155 x = a.tv_nsec - b.tv_nsec;
156 return (x < 0L ? (-1) : x > 0L ? (1) : (0));
159 static inline void
160 evNowTime(struct timespec *res) {
161 struct timeval now;
163 if (gettimeofday(&now, NULL) < 0)
164 evConsTime(res, 0, 0);
165 else
166 TIMEVAL_TO_TIMESPEC (&now, res);
170 /* Options. Leave them on. */
171 /* #undef DEBUG */
172 #include "res_debug.h"
174 #define EXT(res) ((res)->_u._ext)
176 /* Forward. */
178 static int send_vc(res_state, const u_char *, int,
179 u_char **, int *, int *, int, u_char **);
180 static int send_dg(res_state, const u_char *, int,
181 u_char **, int *, int *, int,
182 int *, int *, u_char **);
183 #ifdef DEBUG
184 static void Aerror(const res_state, FILE *, const char *, int,
185 const struct sockaddr *);
186 static void Perror(const res_state, FILE *, const char *, int);
187 #endif
188 static int sock_eq(struct sockaddr_in6 *, struct sockaddr_in6 *);
190 /* Reachover. */
192 static void convaddr4to6(struct sockaddr_in6 *sa);
193 void res_pquery(const res_state, const u_char *, int, FILE *);
195 /* Public. */
197 /* int
198 * res_isourserver(ina)
199 * looks up "ina" in _res.ns_addr_list[]
200 * returns:
201 * 0 : not found
202 * >0 : found
203 * author:
204 * paul vixie, 29may94
207 res_ourserver_p(const res_state statp, const struct sockaddr_in6 *inp)
209 int ns;
211 if (inp->sin6_family == AF_INET) {
212 struct sockaddr_in *in4p = (struct sockaddr_in *) inp;
213 in_port_t port = in4p->sin_port;
214 in_addr_t addr = in4p->sin_addr.s_addr;
216 for (ns = 0; ns < MAXNS; ns++) {
217 const struct sockaddr_in *srv =
218 (struct sockaddr_in *)EXT(statp).nsaddrs[ns];
220 if ((srv != NULL) && (srv->sin_family == AF_INET) &&
221 (srv->sin_port == port) &&
222 (srv->sin_addr.s_addr == INADDR_ANY ||
223 srv->sin_addr.s_addr == addr))
224 return (1);
226 } else if (inp->sin6_family == AF_INET6) {
227 for (ns = 0; ns < MAXNS; ns++) {
228 const struct sockaddr_in6 *srv = EXT(statp).nsaddrs[ns];
229 if ((srv != NULL) && (srv->sin6_family == AF_INET6) &&
230 (srv->sin6_port == inp->sin6_port) &&
231 !(memcmp(&srv->sin6_addr, &in6addr_any,
232 sizeof (struct in6_addr)) &&
233 memcmp(&srv->sin6_addr, &inp->sin6_addr,
234 sizeof (struct in6_addr))))
235 return (1);
238 return (0);
241 /* int
242 * res_nameinquery(name, type, class, buf, eom)
243 * look for (name,type,class) in the query section of packet (buf,eom)
244 * requires:
245 * buf + HFIXEDSZ <= eom
246 * returns:
247 * -1 : format error
248 * 0 : not found
249 * >0 : found
250 * author:
251 * paul vixie, 29may94
254 res_nameinquery(const char *name, int type, int class,
255 const u_char *buf, const u_char *eom)
257 const u_char *cp = buf + HFIXEDSZ;
258 int qdcount = ntohs(((HEADER*)buf)->qdcount);
260 while (qdcount-- > 0) {
261 char tname[MAXDNAME+1];
262 int n, ttype, tclass;
264 n = dn_expand(buf, eom, cp, tname, sizeof tname);
265 if (n < 0)
266 return (-1);
267 cp += n;
268 if (cp + 2 * INT16SZ > eom)
269 return (-1);
270 NS_GET16(ttype, cp);
271 NS_GET16(tclass, cp);
272 if (ttype == type && tclass == class &&
273 ns_samename(tname, name) == 1)
274 return (1);
276 return (0);
278 libresolv_hidden_def (res_nameinquery)
280 /* int
281 * res_queriesmatch(buf1, eom1, buf2, eom2)
282 * is there a 1:1 mapping of (name,type,class)
283 * in (buf1,eom1) and (buf2,eom2)?
284 * returns:
285 * -1 : format error
286 * 0 : not a 1:1 mapping
287 * >0 : is a 1:1 mapping
288 * author:
289 * paul vixie, 29may94
292 res_queriesmatch(const u_char *buf1, const u_char *eom1,
293 const u_char *buf2, const u_char *eom2)
295 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
296 return (-1);
299 * Only header section present in replies to
300 * dynamic update packets.
302 if ((((HEADER *)buf1)->opcode == ns_o_update) &&
303 (((HEADER *)buf2)->opcode == ns_o_update))
304 return (1);
306 /* Note that we initially do not convert QDCOUNT to the host byte
307 order. We can compare it with the second buffer's QDCOUNT
308 value without doing this. */
309 int qdcount = ((HEADER*)buf1)->qdcount;
310 if (qdcount != ((HEADER*)buf2)->qdcount)
311 return (0);
313 qdcount = htons (qdcount);
314 const u_char *cp = buf1 + HFIXEDSZ;
316 while (qdcount-- > 0) {
317 char tname[MAXDNAME+1];
318 int n, ttype, tclass;
320 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
321 if (n < 0)
322 return (-1);
323 cp += n;
324 if (cp + 2 * INT16SZ > eom1)
325 return (-1);
326 NS_GET16(ttype, cp);
327 NS_GET16(tclass, cp);
328 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
329 return (0);
331 return (1);
333 libresolv_hidden_def (res_queriesmatch)
336 __libc_res_nsend(res_state statp, const u_char *buf, int buflen,
337 u_char *ans, int anssiz, u_char **ansp)
339 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
341 if (statp->nscount == 0) {
342 __set_errno (ESRCH);
343 return (-1);
346 if (anssiz < HFIXEDSZ) {
347 __set_errno (EINVAL);
348 return (-1);
351 if ((statp->qhook || statp->rhook) && anssiz < MAXPACKET && ansp) {
352 u_char *buf = malloc (MAXPACKET);
353 if (buf == NULL)
354 return (-1);
355 memcpy (buf, ans, HFIXEDSZ);
356 *ansp = buf;
357 ans = buf;
358 anssiz = MAXPACKET;
361 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
362 (stdout, ";; res_send()\n"), buf, buflen);
363 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
364 gotsomewhere = 0;
365 terrno = ETIMEDOUT;
368 * If the ns_addr_list in the resolver context has changed, then
369 * invalidate our cached copy and the associated timing data.
371 if (EXT(statp).nsinit) {
372 int needclose = 0;
374 if (EXT(statp).nscount != statp->nscount)
375 needclose++;
376 else
377 for (ns = 0; ns < MAXNS; ns++) {
378 unsigned int map = EXT(statp).nsmap[ns];
379 if (map < MAXNS
380 && !sock_eq((struct sockaddr_in6 *)
381 &statp->nsaddr_list[map],
382 EXT(statp).nsaddrs[ns]))
384 needclose++;
385 break;
388 if (needclose)
389 __res_iclose(statp, false);
393 * Maybe initialize our private copy of the ns_addr_list.
395 if (EXT(statp).nsinit == 0) {
396 unsigned char map[MAXNS];
398 memset (map, MAXNS, sizeof (map));
399 for (n = 0; n < MAXNS; n++) {
400 ns = EXT(statp).nsmap[n];
401 if (ns < statp->nscount)
402 map[ns] = n;
403 else if (ns < MAXNS) {
404 free(EXT(statp).nsaddrs[n]);
405 EXT(statp).nsaddrs[n] = NULL;
406 EXT(statp).nsmap[n] = MAXNS;
409 n = statp->nscount;
410 if (statp->nscount > EXT(statp).nscount)
411 for (n = EXT(statp).nscount, ns = 0;
412 n < statp->nscount; n++) {
413 while (ns < MAXNS
414 && EXT(statp).nsmap[ns] != MAXNS)
415 ns++;
416 if (ns == MAXNS)
417 break;
418 EXT(statp).nsmap[ns] = n;
419 map[n] = ns++;
421 EXT(statp).nscount = n;
422 for (ns = 0; ns < EXT(statp).nscount; ns++) {
423 n = map[ns];
424 if (EXT(statp).nsaddrs[n] == NULL)
425 EXT(statp).nsaddrs[n] =
426 malloc(sizeof (struct sockaddr_in6));
427 if (EXT(statp).nsaddrs[n] != NULL) {
428 memcpy(EXT(statp).nsaddrs[n],
429 &statp->nsaddr_list[ns],
430 sizeof (struct sockaddr_in));
431 EXT(statp).nssocks[n] = -1;
432 n++;
435 EXT(statp).nsinit = 1;
439 * Some resolvers want to even out the load on their nameservers.
440 * Note that RES_BLAST overrides RES_ROTATE.
442 if ((statp->options & RES_ROTATE) != 0 &&
443 (statp->options & RES_BLAST) == 0) {
444 struct sockaddr_in6 *ina;
445 unsigned int map;
447 n = 0;
448 while (n < MAXNS && EXT(statp).nsmap[n] == MAXNS)
449 n++;
450 if (n < MAXNS) {
451 ina = EXT(statp).nsaddrs[n];
452 map = EXT(statp).nsmap[n];
453 for (;;) {
454 ns = n + 1;
455 while (ns < MAXNS
456 && EXT(statp).nsmap[ns] == MAXNS)
457 ns++;
458 if (ns == MAXNS)
459 break;
460 EXT(statp).nsaddrs[n] = EXT(statp).nsaddrs[ns];
461 EXT(statp).nsmap[n] = EXT(statp).nsmap[ns];
462 n = ns;
464 EXT(statp).nsaddrs[n] = ina;
465 EXT(statp).nsmap[n] = map;
470 * Send request, RETRY times, or until successful.
472 for (try = 0; try < statp->retry; try++) {
473 for (ns = 0; ns < MAXNS; ns++)
475 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
477 if (nsap == NULL)
478 goto next_ns;
479 same_ns:
480 if (statp->qhook) {
481 int done = 0, loops = 0;
483 do {
484 res_sendhookact act;
486 struct sockaddr_in *nsap4;
487 nsap4 = (struct sockaddr_in *) nsap;
488 act = (*statp->qhook)(&nsap4, &buf, &buflen,
489 ans, anssiz, &resplen);
490 nsap = (struct sockaddr_in6 *) nsap4;
491 switch (act) {
492 case res_goahead:
493 done = 1;
494 break;
495 case res_nextns:
496 __res_iclose(statp, false);
497 goto next_ns;
498 case res_done:
499 return (resplen);
500 case res_modified:
501 /* give the hook another try */
502 if (++loops < 42) /*doug adams*/
503 break;
504 /*FALLTHROUGH*/
505 case res_error:
506 /*FALLTHROUGH*/
507 default:
508 return (-1);
510 } while (!done);
513 #ifdef DEBUG
514 char tmpbuf[40];
515 #endif
516 Dprint(statp->options & RES_DEBUG,
517 (stdout, ";; Querying server (# %d) address = %s\n",
518 ns + 1, inet_ntop(AF_INET6, &nsap->sin6_addr,
519 tmpbuf, sizeof (tmpbuf))));
521 if (v_circuit) {
522 /* Use VC; at most one attempt per server. */
523 try = statp->retry;
524 n = send_vc(statp, buf, buflen, &ans, &anssiz, &terrno,
525 ns, ansp);
526 if (n < 0)
527 return (-1);
528 if (n == 0)
529 goto next_ns;
530 resplen = n;
531 } else {
532 /* Use datagrams. */
533 n = send_dg(statp, buf, buflen, &ans, &anssiz, &terrno,
534 ns, &v_circuit, &gotsomewhere, ansp);
535 if (n < 0)
536 return (-1);
537 if (n == 0)
538 goto next_ns;
539 if (v_circuit)
540 goto same_ns;
541 resplen = n;
544 Dprint((statp->options & RES_DEBUG) ||
545 ((statp->pfcode & RES_PRF_REPLY) &&
546 (statp->pfcode & RES_PRF_HEAD1)),
547 (stdout, ";; got answer:\n"));
549 DprintQ((statp->options & RES_DEBUG) ||
550 (statp->pfcode & RES_PRF_REPLY),
551 (stdout, "%s", ""),
552 ans, (resplen > anssiz) ? anssiz : resplen);
555 * If we have temporarily opened a virtual circuit,
556 * or if we haven't been asked to keep a socket open,
557 * close the socket.
559 if ((v_circuit && (statp->options & RES_USEVC) == 0) ||
560 (statp->options & RES_STAYOPEN) == 0) {
561 __res_iclose(statp, false);
563 if (statp->rhook) {
564 int done = 0, loops = 0;
566 do {
567 res_sendhookact act;
569 act = (*statp->rhook)((struct sockaddr_in *)
570 nsap, buf, buflen,
571 ans, anssiz, &resplen);
572 switch (act) {
573 case res_goahead:
574 case res_done:
575 done = 1;
576 break;
577 case res_nextns:
578 __res_iclose(statp, false);
579 goto next_ns;
580 case res_modified:
581 /* give the hook another try */
582 if (++loops < 42) /*doug adams*/
583 break;
584 /*FALLTHROUGH*/
585 case res_error:
586 /*FALLTHROUGH*/
587 default:
588 return (-1);
590 } while (!done);
593 return (resplen);
594 next_ns: ;
595 } /*foreach ns*/
596 } /*foreach retry*/
597 __res_iclose(statp, false);
598 if (!v_circuit) {
599 if (!gotsomewhere)
600 __set_errno (ECONNREFUSED); /* no nameservers found */
601 else
602 __set_errno (ETIMEDOUT); /* no answer obtained */
603 } else
604 __set_errno (terrno);
605 return (-1);
609 res_nsend(res_state statp,
610 const u_char *buf, int buflen, u_char *ans, int anssiz)
612 return __libc_res_nsend(statp, buf, buflen, ans, anssiz, NULL);
614 libresolv_hidden_def (res_nsend)
616 /* Private */
618 static int
619 send_vc(res_state statp,
620 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
621 int *terrno, int ns, u_char **anscp)
623 const HEADER *hp = (HEADER *) buf;
624 u_char *ans = *ansp;
625 int anssiz = *anssizp;
626 HEADER *anhp = (HEADER *) ans;
627 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
628 int truncating, connreset, resplen, n;
629 struct iovec iov[2];
630 u_short len;
631 u_char *cp;
633 connreset = 0;
634 same_ns:
635 truncating = 0;
637 /* Are we still talking to whom we want to talk to? */
638 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
639 struct sockaddr_in6 peer;
640 socklen_t size = sizeof peer;
642 if (getpeername(statp->_vcsock,
643 (struct sockaddr *)&peer, &size) < 0 ||
644 !sock_eq(&peer, nsap)) {
645 __res_iclose(statp, false);
646 statp->_flags &= ~RES_F_VC;
650 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
651 if (statp->_vcsock >= 0)
652 __res_iclose(statp, false);
654 statp->_vcsock = socket(nsap->sin6_family, SOCK_STREAM, 0);
655 if (statp->_vcsock < 0) {
656 *terrno = errno;
657 Perror(statp, stderr, "socket(vc)", errno);
658 return (-1);
660 __set_errno (0);
661 if (connect(statp->_vcsock, (struct sockaddr *)nsap,
662 nsap->sin6_family == AF_INET
663 ? sizeof (struct sockaddr_in)
664 : sizeof (struct sockaddr_in6)) < 0) {
665 *terrno = errno;
666 Aerror(statp, stderr, "connect/vc", errno,
667 (struct sockaddr *) nsap);
668 __res_iclose(statp, false);
669 return (0);
671 statp->_flags |= RES_F_VC;
675 * Send length & message
677 ns_put16((u_short)buflen, (u_char*)&len);
678 evConsIovec(&len, INT16SZ, &iov[0]);
679 evConsIovec((void*)buf, buflen, &iov[1]);
680 if (TEMP_FAILURE_RETRY (writev(statp->_vcsock, iov, 2))
681 != (INT16SZ + buflen)) {
682 *terrno = errno;
683 Perror(statp, stderr, "write failed", errno);
684 __res_iclose(statp, false);
685 return (0);
688 * Receive length & response
690 read_len:
691 cp = ans;
692 len = INT16SZ;
693 while ((n = TEMP_FAILURE_RETRY (read(statp->_vcsock, (char *)cp,
694 (int)len))) > 0) {
695 cp += n;
696 if ((len -= n) <= 0)
697 break;
699 if (n <= 0) {
700 *terrno = errno;
701 Perror(statp, stderr, "read failed", errno);
702 __res_iclose(statp, false);
704 * A long running process might get its TCP
705 * connection reset if the remote server was
706 * restarted. Requery the server instead of
707 * trying a new one. When there is only one
708 * server, this means that a query might work
709 * instead of failing. We only allow one reset
710 * per query to prevent looping.
712 if (*terrno == ECONNRESET && !connreset) {
713 connreset = 1;
714 goto same_ns;
716 return (0);
718 resplen = ns_get16(ans);
719 if (resplen > anssiz) {
720 if (anscp) {
721 ans = malloc (MAXPACKET);
722 if (ans == NULL) {
723 *terrno = ENOMEM;
724 __res_iclose(statp, false);
725 return (0);
727 anssiz = MAXPACKET;
728 *anssizp = MAXPACKET;
729 *ansp = ans;
730 *anscp = ans;
731 anhp = (HEADER *) ans;
732 len = resplen;
733 } else {
734 Dprint(statp->options & RES_DEBUG,
735 (stdout, ";; response truncated\n")
737 truncating = 1;
738 len = anssiz;
740 } else
741 len = resplen;
742 if (len < HFIXEDSZ) {
744 * Undersized message.
746 Dprint(statp->options & RES_DEBUG,
747 (stdout, ";; undersized: %d\n", len));
748 *terrno = EMSGSIZE;
749 __res_iclose(statp, false);
750 return (0);
752 cp = ans;
753 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
754 cp += n;
755 len -= n;
757 if (n <= 0) {
758 *terrno = errno;
759 Perror(statp, stderr, "read(vc)", errno);
760 __res_iclose(statp, false);
761 return (0);
763 if (truncating) {
765 * Flush rest of answer so connection stays in synch.
767 anhp->tc = 1;
768 len = resplen - anssiz;
769 while (len != 0) {
770 char junk[PACKETSZ];
772 n = read(statp->_vcsock, junk,
773 (len > sizeof junk) ? sizeof junk : len);
774 if (n > 0)
775 len -= n;
776 else
777 break;
781 * If the calling applicating has bailed out of
782 * a previous call and failed to arrange to have
783 * the circuit closed or the server has got
784 * itself confused, then drop the packet and
785 * wait for the correct one.
787 if (hp->id != anhp->id) {
788 DprintQ((statp->options & RES_DEBUG) ||
789 (statp->pfcode & RES_PRF_REPLY),
790 (stdout, ";; old answer (unexpected):\n"),
791 ans, (resplen > anssiz) ? anssiz: resplen);
792 goto read_len;
796 * All is well, or the error is fatal. Signal that the
797 * next nameserver ought not be tried.
799 return (resplen);
802 static int
803 send_dg(res_state statp,
804 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
805 int *terrno, int ns, int *v_circuit, int *gotsomewhere, u_char **anscp)
807 const HEADER *hp = (HEADER *) buf;
808 u_char *ans = *ansp;
809 int anssiz = *anssizp;
810 HEADER *anhp = (HEADER *) ans;
811 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
812 struct timespec now, timeout, finish;
813 struct pollfd pfd[1];
814 int ptimeout;
815 struct sockaddr_in6 from;
816 static int socket_pf = 0;
817 socklen_t fromlen;
818 int resplen, seconds, n;
820 if (EXT(statp).nssocks[ns] == -1) {
821 /* only try IPv6 if IPv6 NS and if not failed before */
822 if ((EXT(statp).nscount6 > 0) && (socket_pf != PF_INET)) {
823 EXT(statp).nssocks[ns] =
824 socket(PF_INET6, SOCK_DGRAM, 0);
825 socket_pf = EXT(statp).nssocks[ns] < 0 ? PF_INET
826 : PF_INET6;
828 if (EXT(statp).nssocks[ns] < 0)
829 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
830 if (EXT(statp).nssocks[ns] < 0) {
831 *terrno = errno;
832 Perror(statp, stderr, "socket(dg)", errno);
833 return (-1);
835 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
836 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
837 convaddr4to6(nsap);
839 * On a 4.3BSD+ machine (client and server,
840 * actually), sending to a nameserver datagram
841 * port with no nameserver will cause an
842 * ICMP port unreachable message to be returned.
843 * If our datagram socket is "connected" to the
844 * server, we get an ECONNREFUSED error on the next
845 * socket operation, and select returns if the
846 * error message is received. We can thus detect
847 * the absence of a nameserver without timing out.
849 if (connect(EXT(statp).nssocks[ns], (struct sockaddr *)nsap,
850 sizeof *nsap) < 0) {
851 Aerror(statp, stderr, "connect(dg)", errno,
852 (struct sockaddr *) nsap);
853 __res_iclose(statp, false);
854 return (0);
856 /* Make socket non-blocking. */
857 int fl = __fcntl (EXT(statp).nssocks[ns], F_GETFL);
858 if (fl != -1)
859 __fcntl (EXT(statp).nssocks[ns], F_SETFL,
860 fl | O_NONBLOCK);
861 Dprint(statp->options & RES_DEBUG,
862 (stdout, ";; new DG socket\n"))
866 * Compute time for the total operation.
868 seconds = (statp->retrans << ns);
869 if (ns > 0)
870 seconds /= statp->nscount;
871 if (seconds <= 0)
872 seconds = 1;
873 evNowTime(&now);
874 evConsTime(&timeout, seconds, 0);
875 evAddTime(&finish, &now, &timeout);
876 int need_recompute = 0;
877 int nwritten = 0;
878 pfd[0].fd = EXT(statp).nssocks[ns];
879 pfd[0].events = POLLOUT;
880 wait:
881 if (need_recompute) {
882 recompute_resend:
883 evNowTime(&now);
884 if (evCmpTime(finish, now) <= 0) {
885 poll_err_out:
886 Perror(statp, stderr, "poll", errno);
887 err_out:
888 __res_iclose(statp, false);
889 return (0);
891 evSubTime(&timeout, &finish, &now);
893 /* Convert struct timespec in milliseconds. */
894 ptimeout = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
896 n = 0;
897 if (nwritten == 0)
898 n = __poll (pfd, 1, 0);
899 if (__builtin_expect (n == 0, 0)) {
900 n = __poll (pfd, 1, ptimeout);
901 need_recompute = 1;
903 if (n == 0) {
904 Dprint(statp->options & RES_DEBUG, (stdout,
905 ";; timeout sending\n"));
906 *gotsomewhere = 1;
907 return (0);
909 if (n < 0) {
910 if (errno == EINTR)
911 goto recompute_resend;
913 goto poll_err_out;
915 __set_errno (0);
916 if (pfd[0].revents & POLLOUT) {
917 if (send (pfd[0].fd, buf, buflen, MSG_NOSIGNAL) != buflen) {
918 if (errno == EINTR || errno == EAGAIN)
919 goto recompute_resend;
920 Perror(statp, stderr, "send", errno);
921 goto err_out;
923 pfd[0].events = POLLIN;
924 ++nwritten;
925 goto wait;
926 } else if (pfd[0].revents & POLLIN) {
927 fromlen = sizeof(struct sockaddr_in6);
928 if (anssiz < MAXPACKET
929 && anscp
930 && (ioctl (pfd[0].fd, FIONREAD, &resplen) < 0
931 || anssiz < resplen)) {
932 ans = malloc (MAXPACKET);
933 if (ans == NULL)
934 ans = *ansp;
935 else {
936 anssiz = MAXPACKET;
937 *anssizp = MAXPACKET;
938 *ansp = ans;
939 *anscp = ans;
940 anhp = (HEADER *) ans;
943 resplen = recvfrom(pfd[0].fd, (char*)ans, anssiz,0,
944 (struct sockaddr *)&from, &fromlen);
945 if (resplen <= 0) {
946 if (errno == EINTR || errno == EAGAIN) {
947 need_recompute = 1;
948 goto wait;
950 Perror(statp, stderr, "recvfrom", errno);
951 goto err_out;
953 *gotsomewhere = 1;
954 if (resplen < HFIXEDSZ) {
956 * Undersized message.
958 Dprint(statp->options & RES_DEBUG,
959 (stdout, ";; undersized: %d\n",
960 resplen));
961 *terrno = EMSGSIZE;
962 goto err_out;
964 if (hp->id != anhp->id) {
966 * response from old query, ignore it.
967 * XXX - potential security hazard could
968 * be detected here.
970 DprintQ((statp->options & RES_DEBUG) ||
971 (statp->pfcode & RES_PRF_REPLY),
972 (stdout, ";; old answer:\n"),
973 ans, (resplen > anssiz) ? anssiz : resplen);
974 goto wait;
976 if (!(statp->options & RES_INSECURE1) &&
977 !res_ourserver_p(statp, &from)) {
979 * response from wrong server? ignore it.
980 * XXX - potential security hazard could
981 * be detected here.
983 DprintQ((statp->options & RES_DEBUG) ||
984 (statp->pfcode & RES_PRF_REPLY),
985 (stdout, ";; not our server:\n"),
986 ans, (resplen > anssiz) ? anssiz : resplen);
987 goto wait;
989 if (!(statp->options & RES_INSECURE2) &&
990 !res_queriesmatch(buf, buf + buflen,
991 ans, ans + anssiz)) {
993 * response contains wrong query? ignore it.
994 * XXX - potential security hazard could
995 * be detected here.
997 DprintQ((statp->options & RES_DEBUG) ||
998 (statp->pfcode & RES_PRF_REPLY),
999 (stdout, ";; wrong query name:\n"),
1000 ans, (resplen > anssiz) ? anssiz : resplen);
1001 goto wait;
1003 if (anhp->rcode == SERVFAIL ||
1004 anhp->rcode == NOTIMP ||
1005 anhp->rcode == REFUSED) {
1006 DprintQ(statp->options & RES_DEBUG,
1007 (stdout, "server rejected query:\n"),
1008 ans, (resplen > anssiz) ? anssiz : resplen);
1009 next_ns:
1010 __res_iclose(statp, false);
1011 /* don't retry if called from dig */
1012 if (!statp->pfcode)
1013 return (0);
1015 if (anhp->rcode == NOERROR && anhp->ancount == 0
1016 && anhp->aa == 0 && anhp->ra == 0 && anhp->arcount == 0) {
1017 DprintQ(statp->options & RES_DEBUG,
1018 (stdout, "referred query:\n"),
1019 ans, (resplen > anssiz) ? anssiz : resplen);
1020 goto next_ns;
1022 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1024 * To get the rest of answer,
1025 * use TCP with same server.
1027 Dprint(statp->options & RES_DEBUG,
1028 (stdout, ";; truncated answer\n"));
1029 *v_circuit = 1;
1030 __res_iclose(statp, false);
1031 return (1);
1034 * All is well, or the error is fatal. Signal that the
1035 * next nameserver ought not be tried.
1037 return (resplen);
1038 } else if (pfd[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
1039 /* Something went wrong. We can stop trying. */
1040 goto err_out;
1042 else {
1043 /* poll should not have returned > 0 in this case. */
1044 abort ();
1048 #ifdef DEBUG
1049 static void
1050 Aerror(const res_state statp, FILE *file, const char *string, int error,
1051 const struct sockaddr *address)
1053 int save = errno;
1055 if ((statp->options & RES_DEBUG) != 0) {
1056 char tmp[sizeof "xxxx.xxxx.xxxx.255.255.255.255"];
1058 fprintf(file, "res_send: %s ([%s].%u): %s\n",
1059 string,
1060 (address->sa_family == AF_INET
1061 ? inet_ntop(address->sa_family,
1062 &((const struct sockaddr_in *) address)->sin_addr,
1063 tmp, sizeof tmp)
1064 : inet_ntop(address->sa_family,
1065 &((const struct sockaddr_in6 *) address)->sin6_addr,
1066 tmp, sizeof tmp)),
1067 (address->sa_family == AF_INET
1068 ? ntohs(((struct sockaddr_in *) address)->sin_port)
1069 : address->sa_family == AF_INET6
1070 ? ntohs(((struct sockaddr_in6 *) address)->sin6_port)
1071 : 0),
1072 strerror(error));
1074 __set_errno (save);
1077 static void
1078 Perror(const res_state statp, FILE *file, const char *string, int error) {
1079 int save = errno;
1081 if ((statp->options & RES_DEBUG) != 0)
1082 fprintf(file, "res_send: %s: %s\n",
1083 string, strerror(error));
1084 __set_errno (save);
1086 #endif
1088 static int
1089 sock_eq(struct sockaddr_in6 *a1, struct sockaddr_in6 *a2) {
1090 if (a1->sin6_family == a2->sin6_family) {
1091 if (a1->sin6_family == AF_INET)
1092 return ((((struct sockaddr_in *)a1)->sin_port ==
1093 ((struct sockaddr_in *)a2)->sin_port) &&
1094 (((struct sockaddr_in *)a1)->sin_addr.s_addr ==
1095 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1096 else
1097 return ((a1->sin6_port == a2->sin6_port) &&
1098 !memcmp(&a1->sin6_addr, &a2->sin6_addr,
1099 sizeof (struct in6_addr)));
1101 if (a1->sin6_family == AF_INET) {
1102 struct sockaddr_in6 *sap = a1;
1103 a1 = a2;
1104 a2 = sap;
1105 } /* assumes that AF_INET and AF_INET6 are the only possibilities */
1106 return ((a1->sin6_port == ((struct sockaddr_in *)a2)->sin_port) &&
1107 IN6_IS_ADDR_V4MAPPED(&a1->sin6_addr) &&
1108 (a1->sin6_addr.s6_addr32[3] ==
1109 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1113 * Converts IPv4 family, address and port to
1114 * IPv6 family, IPv4-mapped IPv6 address and port.
1116 static void
1117 convaddr4to6(struct sockaddr_in6 *sa)
1119 struct sockaddr_in *sa4p = (struct sockaddr_in *) sa;
1120 in_port_t port = sa4p->sin_port;
1121 in_addr_t addr = sa4p->sin_addr.s_addr;
1123 sa->sin6_family = AF_INET6;
1124 sa->sin6_port = port;
1125 sa->sin6_addr.s6_addr32[0] = 0;
1126 sa->sin6_addr.s6_addr32[1] = 0;
1127 sa->sin6_addr.s6_addr32[2] = htonl(0xFFFF);
1128 sa->sin6_addr.s6_addr32[3] = addr;