* locales/en_US: Add first_weekday and first_workday.
[glibc.git] / resolv / res_send.c
blob23306a2fb47c10645643bb5633dedcaa61097325
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 memset (mempcpy(EXT(statp).nsaddrs[n],
429 &statp->nsaddr_list[ns],
430 sizeof (struct sockaddr_in)),
431 '\0',
432 sizeof (struct sockaddr_in6)
433 - sizeof (struct sockaddr_in));
434 EXT(statp).nssocks[n] = -1;
435 n++;
438 EXT(statp).nsinit = 1;
442 * Some resolvers want to even out the load on their nameservers.
443 * Note that RES_BLAST overrides RES_ROTATE.
445 if ((statp->options & RES_ROTATE) != 0 &&
446 (statp->options & RES_BLAST) == 0) {
447 struct sockaddr_in6 *ina;
448 unsigned int map;
450 n = 0;
451 while (n < MAXNS && EXT(statp).nsmap[n] == MAXNS)
452 n++;
453 if (n < MAXNS) {
454 ina = EXT(statp).nsaddrs[n];
455 map = EXT(statp).nsmap[n];
456 for (;;) {
457 ns = n + 1;
458 while (ns < MAXNS
459 && EXT(statp).nsmap[ns] == MAXNS)
460 ns++;
461 if (ns == MAXNS)
462 break;
463 EXT(statp).nsaddrs[n] = EXT(statp).nsaddrs[ns];
464 EXT(statp).nsmap[n] = EXT(statp).nsmap[ns];
465 n = ns;
467 EXT(statp).nsaddrs[n] = ina;
468 EXT(statp).nsmap[n] = map;
473 * Send request, RETRY times, or until successful.
475 for (try = 0; try < statp->retry; try++) {
476 for (ns = 0; ns < MAXNS; ns++)
478 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
480 if (nsap == NULL)
481 goto next_ns;
482 same_ns:
483 if (statp->qhook) {
484 int done = 0, loops = 0;
486 do {
487 res_sendhookact act;
489 struct sockaddr_in *nsap4;
490 nsap4 = (struct sockaddr_in *) nsap;
491 act = (*statp->qhook)(&nsap4, &buf, &buflen,
492 ans, anssiz, &resplen);
493 nsap = (struct sockaddr_in6 *) nsap4;
494 switch (act) {
495 case res_goahead:
496 done = 1;
497 break;
498 case res_nextns:
499 __res_iclose(statp, false);
500 goto next_ns;
501 case res_done:
502 return (resplen);
503 case res_modified:
504 /* give the hook another try */
505 if (++loops < 42) /*doug adams*/
506 break;
507 /*FALLTHROUGH*/
508 case res_error:
509 /*FALLTHROUGH*/
510 default:
511 return (-1);
513 } while (!done);
516 #ifdef DEBUG
517 char tmpbuf[40];
518 #endif
519 Dprint(statp->options & RES_DEBUG,
520 (stdout, ";; Querying server (# %d) address = %s\n",
521 ns + 1, inet_ntop(AF_INET6, &nsap->sin6_addr,
522 tmpbuf, sizeof (tmpbuf))));
524 if (v_circuit) {
525 /* Use VC; at most one attempt per server. */
526 try = statp->retry;
527 n = send_vc(statp, buf, buflen, &ans, &anssiz, &terrno,
528 ns, ansp);
529 if (n < 0)
530 return (-1);
531 if (n == 0)
532 goto next_ns;
533 resplen = n;
534 } else {
535 /* Use datagrams. */
536 n = send_dg(statp, buf, buflen, &ans, &anssiz, &terrno,
537 ns, &v_circuit, &gotsomewhere, ansp);
538 if (n < 0)
539 return (-1);
540 if (n == 0)
541 goto next_ns;
542 if (v_circuit)
543 goto same_ns;
544 resplen = n;
547 Dprint((statp->options & RES_DEBUG) ||
548 ((statp->pfcode & RES_PRF_REPLY) &&
549 (statp->pfcode & RES_PRF_HEAD1)),
550 (stdout, ";; got answer:\n"));
552 DprintQ((statp->options & RES_DEBUG) ||
553 (statp->pfcode & RES_PRF_REPLY),
554 (stdout, "%s", ""),
555 ans, (resplen > anssiz) ? anssiz : resplen);
558 * If we have temporarily opened a virtual circuit,
559 * or if we haven't been asked to keep a socket open,
560 * close the socket.
562 if ((v_circuit && (statp->options & RES_USEVC) == 0) ||
563 (statp->options & RES_STAYOPEN) == 0) {
564 __res_iclose(statp, false);
566 if (statp->rhook) {
567 int done = 0, loops = 0;
569 do {
570 res_sendhookact act;
572 act = (*statp->rhook)((struct sockaddr_in *)
573 nsap, buf, buflen,
574 ans, anssiz, &resplen);
575 switch (act) {
576 case res_goahead:
577 case res_done:
578 done = 1;
579 break;
580 case res_nextns:
581 __res_iclose(statp, false);
582 goto next_ns;
583 case res_modified:
584 /* give the hook another try */
585 if (++loops < 42) /*doug adams*/
586 break;
587 /*FALLTHROUGH*/
588 case res_error:
589 /*FALLTHROUGH*/
590 default:
591 return (-1);
593 } while (!done);
596 return (resplen);
597 next_ns: ;
598 } /*foreach ns*/
599 } /*foreach retry*/
600 __res_iclose(statp, false);
601 if (!v_circuit) {
602 if (!gotsomewhere)
603 __set_errno (ECONNREFUSED); /* no nameservers found */
604 else
605 __set_errno (ETIMEDOUT); /* no answer obtained */
606 } else
607 __set_errno (terrno);
608 return (-1);
612 res_nsend(res_state statp,
613 const u_char *buf, int buflen, u_char *ans, int anssiz)
615 return __libc_res_nsend(statp, buf, buflen, ans, anssiz, NULL);
617 libresolv_hidden_def (res_nsend)
619 /* Private */
621 static int
622 send_vc(res_state statp,
623 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
624 int *terrno, int ns, u_char **anscp)
626 const HEADER *hp = (HEADER *) buf;
627 u_char *ans = *ansp;
628 int anssiz = *anssizp;
629 HEADER *anhp = (HEADER *) ans;
630 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
631 int truncating, connreset, resplen, n;
632 struct iovec iov[2];
633 u_short len;
634 u_char *cp;
636 connreset = 0;
637 same_ns:
638 truncating = 0;
640 /* Are we still talking to whom we want to talk to? */
641 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
642 struct sockaddr_in6 peer;
643 socklen_t size = sizeof peer;
645 if (getpeername(statp->_vcsock,
646 (struct sockaddr *)&peer, &size) < 0 ||
647 !sock_eq(&peer, nsap)) {
648 __res_iclose(statp, false);
649 statp->_flags &= ~RES_F_VC;
653 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
654 if (statp->_vcsock >= 0)
655 __res_iclose(statp, false);
657 statp->_vcsock = socket(nsap->sin6_family, SOCK_STREAM, 0);
658 if (statp->_vcsock < 0) {
659 *terrno = errno;
660 Perror(statp, stderr, "socket(vc)", errno);
661 return (-1);
663 __set_errno (0);
664 if (connect(statp->_vcsock, (struct sockaddr *)nsap,
665 nsap->sin6_family == AF_INET
666 ? sizeof (struct sockaddr_in)
667 : sizeof (struct sockaddr_in6)) < 0) {
668 *terrno = errno;
669 Aerror(statp, stderr, "connect/vc", errno,
670 (struct sockaddr *) nsap);
671 __res_iclose(statp, false);
672 return (0);
674 statp->_flags |= RES_F_VC;
678 * Send length & message
680 ns_put16((u_short)buflen, (u_char*)&len);
681 evConsIovec(&len, INT16SZ, &iov[0]);
682 evConsIovec((void*)buf, buflen, &iov[1]);
683 if (TEMP_FAILURE_RETRY (writev(statp->_vcsock, iov, 2))
684 != (INT16SZ + buflen)) {
685 *terrno = errno;
686 Perror(statp, stderr, "write failed", errno);
687 __res_iclose(statp, false);
688 return (0);
691 * Receive length & response
693 read_len:
694 cp = ans;
695 len = INT16SZ;
696 while ((n = TEMP_FAILURE_RETRY (read(statp->_vcsock, (char *)cp,
697 (int)len))) > 0) {
698 cp += n;
699 if ((len -= n) <= 0)
700 break;
702 if (n <= 0) {
703 *terrno = errno;
704 Perror(statp, stderr, "read failed", errno);
705 __res_iclose(statp, false);
707 * A long running process might get its TCP
708 * connection reset if the remote server was
709 * restarted. Requery the server instead of
710 * trying a new one. When there is only one
711 * server, this means that a query might work
712 * instead of failing. We only allow one reset
713 * per query to prevent looping.
715 if (*terrno == ECONNRESET && !connreset) {
716 connreset = 1;
717 goto same_ns;
719 return (0);
721 resplen = ns_get16(ans);
722 if (resplen > anssiz) {
723 if (anscp) {
724 ans = malloc (MAXPACKET);
725 if (ans == NULL) {
726 *terrno = ENOMEM;
727 __res_iclose(statp, false);
728 return (0);
730 anssiz = MAXPACKET;
731 *anssizp = MAXPACKET;
732 *ansp = ans;
733 *anscp = ans;
734 anhp = (HEADER *) ans;
735 len = resplen;
736 } else {
737 Dprint(statp->options & RES_DEBUG,
738 (stdout, ";; response truncated\n")
740 truncating = 1;
741 len = anssiz;
743 } else
744 len = resplen;
745 if (len < HFIXEDSZ) {
747 * Undersized message.
749 Dprint(statp->options & RES_DEBUG,
750 (stdout, ";; undersized: %d\n", len));
751 *terrno = EMSGSIZE;
752 __res_iclose(statp, false);
753 return (0);
755 cp = ans;
756 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
757 cp += n;
758 len -= n;
760 if (n <= 0) {
761 *terrno = errno;
762 Perror(statp, stderr, "read(vc)", errno);
763 __res_iclose(statp, false);
764 return (0);
766 if (truncating) {
768 * Flush rest of answer so connection stays in synch.
770 anhp->tc = 1;
771 len = resplen - anssiz;
772 while (len != 0) {
773 char junk[PACKETSZ];
775 n = read(statp->_vcsock, junk,
776 (len > sizeof junk) ? sizeof junk : len);
777 if (n > 0)
778 len -= n;
779 else
780 break;
784 * If the calling applicating has bailed out of
785 * a previous call and failed to arrange to have
786 * the circuit closed or the server has got
787 * itself confused, then drop the packet and
788 * wait for the correct one.
790 if (hp->id != anhp->id) {
791 DprintQ((statp->options & RES_DEBUG) ||
792 (statp->pfcode & RES_PRF_REPLY),
793 (stdout, ";; old answer (unexpected):\n"),
794 ans, (resplen > anssiz) ? anssiz: resplen);
795 goto read_len;
799 * All is well, or the error is fatal. Signal that the
800 * next nameserver ought not be tried.
802 return (resplen);
805 static int
806 send_dg(res_state statp,
807 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
808 int *terrno, int ns, int *v_circuit, int *gotsomewhere, u_char **anscp)
810 const HEADER *hp = (HEADER *) buf;
811 u_char *ans = *ansp;
812 int anssiz = *anssizp;
813 HEADER *anhp = (HEADER *) ans;
814 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
815 struct timespec now, timeout, finish;
816 struct pollfd pfd[1];
817 int ptimeout;
818 struct sockaddr_in6 from;
819 socklen_t fromlen;
820 int resplen, seconds, n;
822 if (EXT(statp).nssocks[ns] == -1) {
823 /* only try IPv6 if IPv6 NS and if not failed before */
824 if ((EXT(statp).nscount6 > 0) && !statp->ipv6_unavail) {
825 EXT(statp).nssocks[ns] =
826 socket(PF_INET6, SOCK_DGRAM, 0);
827 if (EXT(statp).nssocks[ns] < 0)
828 statp->ipv6_unavail = errno == EAFNOSUPPORT;
829 /* If IPv6 socket and nsap is IPv4, make it
830 IPv4-mapped */
831 else if (nsap->sin6_family == AF_INET)
832 convaddr4to6(nsap);
834 if (EXT(statp).nssocks[ns] < 0)
835 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
836 if (EXT(statp).nssocks[ns] < 0) {
837 *terrno = errno;
838 Perror(statp, stderr, "socket(dg)", errno);
839 return (-1);
843 * On a 4.3BSD+ machine (client and server,
844 * actually), sending to a nameserver datagram
845 * port with no nameserver will cause an
846 * ICMP port unreachable message to be returned.
847 * If our datagram socket is "connected" to the
848 * server, we get an ECONNREFUSED error on the next
849 * socket operation, and select returns if the
850 * error message is received. We can thus detect
851 * the absence of a nameserver without timing out.
853 if (connect(EXT(statp).nssocks[ns], (struct sockaddr *)nsap,
854 sizeof *nsap) < 0) {
855 Aerror(statp, stderr, "connect(dg)", errno,
856 (struct sockaddr *) nsap);
857 __res_iclose(statp, false);
858 return (0);
860 /* Make socket non-blocking. */
861 int fl = __fcntl (EXT(statp).nssocks[ns], F_GETFL);
862 if (fl != -1)
863 __fcntl (EXT(statp).nssocks[ns], F_SETFL,
864 fl | O_NONBLOCK);
865 Dprint(statp->options & RES_DEBUG,
866 (stdout, ";; new DG socket\n"))
870 * Compute time for the total operation.
872 seconds = (statp->retrans << ns);
873 if (ns > 0)
874 seconds /= statp->nscount;
875 if (seconds <= 0)
876 seconds = 1;
877 evNowTime(&now);
878 evConsTime(&timeout, seconds, 0);
879 evAddTime(&finish, &now, &timeout);
880 int need_recompute = 0;
881 int nwritten = 0;
882 pfd[0].fd = EXT(statp).nssocks[ns];
883 pfd[0].events = POLLOUT;
884 wait:
885 if (need_recompute) {
886 recompute_resend:
887 evNowTime(&now);
888 if (evCmpTime(finish, now) <= 0) {
889 poll_err_out:
890 Perror(statp, stderr, "poll", errno);
891 err_out:
892 __res_iclose(statp, false);
893 return (0);
895 evSubTime(&timeout, &finish, &now);
897 /* Convert struct timespec in milliseconds. */
898 ptimeout = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
900 n = 0;
901 if (nwritten == 0)
902 n = __poll (pfd, 1, 0);
903 if (__builtin_expect (n == 0, 0)) {
904 n = __poll (pfd, 1, ptimeout);
905 need_recompute = 1;
907 if (n == 0) {
908 Dprint(statp->options & RES_DEBUG, (stdout,
909 ";; timeout sending\n"));
910 *gotsomewhere = 1;
911 return (0);
913 if (n < 0) {
914 if (errno == EINTR)
915 goto recompute_resend;
917 goto poll_err_out;
919 __set_errno (0);
920 if (pfd[0].revents & POLLOUT) {
921 if (send (pfd[0].fd, buf, buflen, MSG_NOSIGNAL) != buflen) {
922 if (errno == EINTR || errno == EAGAIN)
923 goto recompute_resend;
924 Perror(statp, stderr, "send", errno);
925 goto err_out;
927 pfd[0].events = POLLIN;
928 ++nwritten;
929 goto wait;
930 } else if (pfd[0].revents & POLLIN) {
931 fromlen = sizeof(struct sockaddr_in6);
932 if (anssiz < MAXPACKET
933 && anscp
934 && (ioctl (pfd[0].fd, FIONREAD, &resplen) < 0
935 || anssiz < resplen)) {
936 ans = malloc (MAXPACKET);
937 if (ans == NULL)
938 ans = *ansp;
939 else {
940 anssiz = MAXPACKET;
941 *anssizp = MAXPACKET;
942 *ansp = ans;
943 *anscp = ans;
944 anhp = (HEADER *) ans;
947 resplen = recvfrom(pfd[0].fd, (char*)ans, anssiz,0,
948 (struct sockaddr *)&from, &fromlen);
949 if (resplen <= 0) {
950 if (errno == EINTR || errno == EAGAIN) {
951 need_recompute = 1;
952 goto wait;
954 Perror(statp, stderr, "recvfrom", errno);
955 goto err_out;
957 *gotsomewhere = 1;
958 if (resplen < HFIXEDSZ) {
960 * Undersized message.
962 Dprint(statp->options & RES_DEBUG,
963 (stdout, ";; undersized: %d\n",
964 resplen));
965 *terrno = EMSGSIZE;
966 goto err_out;
968 if (hp->id != anhp->id) {
970 * response from old query, ignore it.
971 * XXX - potential security hazard could
972 * be detected here.
974 DprintQ((statp->options & RES_DEBUG) ||
975 (statp->pfcode & RES_PRF_REPLY),
976 (stdout, ";; old answer:\n"),
977 ans, (resplen > anssiz) ? anssiz : resplen);
978 goto wait;
980 if (!(statp->options & RES_INSECURE1) &&
981 !res_ourserver_p(statp, &from)) {
983 * response from wrong server? ignore it.
984 * XXX - potential security hazard could
985 * be detected here.
987 DprintQ((statp->options & RES_DEBUG) ||
988 (statp->pfcode & RES_PRF_REPLY),
989 (stdout, ";; not our server:\n"),
990 ans, (resplen > anssiz) ? anssiz : resplen);
991 goto wait;
993 #ifdef RES_USE_EDNS0
994 if (anhp->rcode == FORMERR
995 && (statp->options & RES_USE_EDNS0) != 0U) {
997 * Do not retry if the server do not understand
998 * EDNS0. The case has to be captured here, as
999 * FORMERR packet do not carry query section, hence
1000 * res_queriesmatch() returns 0.
1002 DprintQ(statp->options & RES_DEBUG,
1003 (stdout,
1004 "server rejected query with EDNS0:\n"),
1005 ans, (resplen > anssiz) ? anssiz : resplen);
1006 /* record the error */
1007 statp->_flags |= RES_F_EDNS0ERR;
1008 goto err_out;
1010 #endif
1011 if (!(statp->options & RES_INSECURE2) &&
1012 !res_queriesmatch(buf, buf + buflen,
1013 ans, ans + anssiz)) {
1015 * response contains wrong query? ignore it.
1016 * XXX - potential security hazard could
1017 * be detected here.
1019 DprintQ((statp->options & RES_DEBUG) ||
1020 (statp->pfcode & RES_PRF_REPLY),
1021 (stdout, ";; wrong query name:\n"),
1022 ans, (resplen > anssiz) ? anssiz : resplen);
1023 goto wait;
1025 if (anhp->rcode == SERVFAIL ||
1026 anhp->rcode == NOTIMP ||
1027 anhp->rcode == REFUSED) {
1028 DprintQ(statp->options & RES_DEBUG,
1029 (stdout, "server rejected query:\n"),
1030 ans, (resplen > anssiz) ? anssiz : resplen);
1031 next_ns:
1032 __res_iclose(statp, false);
1033 /* don't retry if called from dig */
1034 if (!statp->pfcode)
1035 return (0);
1037 if (anhp->rcode == NOERROR && anhp->ancount == 0
1038 && anhp->aa == 0 && anhp->ra == 0 && anhp->arcount == 0) {
1039 DprintQ(statp->options & RES_DEBUG,
1040 (stdout, "referred query:\n"),
1041 ans, (resplen > anssiz) ? anssiz : resplen);
1042 goto next_ns;
1044 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1046 * To get the rest of answer,
1047 * use TCP with same server.
1049 Dprint(statp->options & RES_DEBUG,
1050 (stdout, ";; truncated answer\n"));
1051 *v_circuit = 1;
1052 __res_iclose(statp, false);
1053 return (1);
1056 * All is well, or the error is fatal. Signal that the
1057 * next nameserver ought not be tried.
1059 return (resplen);
1060 } else if (pfd[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
1061 /* Something went wrong. We can stop trying. */
1062 goto err_out;
1064 else {
1065 /* poll should not have returned > 0 in this case. */
1066 abort ();
1070 #ifdef DEBUG
1071 static void
1072 Aerror(const res_state statp, FILE *file, const char *string, int error,
1073 const struct sockaddr *address)
1075 int save = errno;
1077 if ((statp->options & RES_DEBUG) != 0) {
1078 char tmp[sizeof "xxxx.xxxx.xxxx.255.255.255.255"];
1080 fprintf(file, "res_send: %s ([%s].%u): %s\n",
1081 string,
1082 (address->sa_family == AF_INET
1083 ? inet_ntop(address->sa_family,
1084 &((const struct sockaddr_in *) address)->sin_addr,
1085 tmp, sizeof tmp)
1086 : inet_ntop(address->sa_family,
1087 &((const struct sockaddr_in6 *) address)->sin6_addr,
1088 tmp, sizeof tmp)),
1089 (address->sa_family == AF_INET
1090 ? ntohs(((struct sockaddr_in *) address)->sin_port)
1091 : address->sa_family == AF_INET6
1092 ? ntohs(((struct sockaddr_in6 *) address)->sin6_port)
1093 : 0),
1094 strerror(error));
1096 __set_errno (save);
1099 static void
1100 Perror(const res_state statp, FILE *file, const char *string, int error) {
1101 int save = errno;
1103 if ((statp->options & RES_DEBUG) != 0)
1104 fprintf(file, "res_send: %s: %s\n",
1105 string, strerror(error));
1106 __set_errno (save);
1108 #endif
1110 static int
1111 sock_eq(struct sockaddr_in6 *a1, struct sockaddr_in6 *a2) {
1112 if (a1->sin6_family == a2->sin6_family) {
1113 if (a1->sin6_family == AF_INET)
1114 return ((((struct sockaddr_in *)a1)->sin_port ==
1115 ((struct sockaddr_in *)a2)->sin_port) &&
1116 (((struct sockaddr_in *)a1)->sin_addr.s_addr ==
1117 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1118 else
1119 return ((a1->sin6_port == a2->sin6_port) &&
1120 !memcmp(&a1->sin6_addr, &a2->sin6_addr,
1121 sizeof (struct in6_addr)));
1123 if (a1->sin6_family == AF_INET) {
1124 struct sockaddr_in6 *sap = a1;
1125 a1 = a2;
1126 a2 = sap;
1127 } /* assumes that AF_INET and AF_INET6 are the only possibilities */
1128 return ((a1->sin6_port == ((struct sockaddr_in *)a2)->sin_port) &&
1129 IN6_IS_ADDR_V4MAPPED(&a1->sin6_addr) &&
1130 (a1->sin6_addr.s6_addr32[3] ==
1131 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1135 * Converts IPv4 family, address and port to
1136 * IPv6 family, IPv4-mapped IPv6 address and port.
1138 static void
1139 convaddr4to6(struct sockaddr_in6 *sa)
1141 struct sockaddr_in *sa4p = (struct sockaddr_in *) sa;
1142 in_port_t port = sa4p->sin_port;
1143 in_addr_t addr = sa4p->sin_addr.s_addr;
1145 sa->sin6_family = AF_INET6;
1146 sa->sin6_port = port;
1147 sa->sin6_addr.s6_addr32[0] = 0;
1148 sa->sin6_addr.s6_addr32[1] = 0;
1149 sa->sin6_addr.s6_addr32[2] = htonl(0xFFFF);
1150 sa->sin6_addr.s6_addr32[3] = addr;