Update.
[glibc.git] / resolv / res_send.c
blob044f3174f5f7177120bfd854d6c1d557bef8f90c
1 /*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 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>
89 #include <errno.h>
90 #include <netdb.h>
91 #include <resolv.h>
92 #include <signal.h>
93 #include <stdio.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <unistd.h>
98 #ifndef _LIBC
99 #include <isc/eventlib.h>
100 #else
102 /* From ev_streams.c. */
104 static inline struct iovec
105 evConsIovec(void *buf, size_t cnt) {
106 struct iovec ret;
108 memset(&ret, 0xf5, sizeof ret);
109 ret.iov_base = buf;
110 ret.iov_len = cnt;
111 return (ret);
114 /* From ev_timers.c. */
116 #define BILLION 1000000000
118 static inline struct timespec
119 evTimeSpec(struct timeval tv) {
120 struct timespec ts;
122 ts.tv_sec = tv.tv_sec;
123 ts.tv_nsec = tv.tv_usec * 1000;
124 return (ts);
127 static inline struct timespec
128 evConsTime(time_t sec, long nsec) {
129 struct timespec x;
131 x.tv_sec = sec;
132 x.tv_nsec = nsec;
133 return (x);
136 static inline struct timespec
137 evAddTime(struct timespec addend1, struct timespec addend2) {
138 struct timespec x;
140 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
141 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
142 if (x.tv_nsec >= BILLION) {
143 x.tv_sec++;
144 x.tv_nsec -= BILLION;
146 return (x);
149 static inline struct timespec
150 evSubTime(struct timespec minuend, struct timespec subtrahend) {
151 struct timespec x;
153 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
154 if (minuend.tv_nsec >= subtrahend.tv_nsec)
155 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
156 else {
157 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
158 x.tv_sec--;
160 return (x);
163 static inline int
164 evCmpTime(struct timespec a, struct timespec b) {
165 long x = a.tv_sec - b.tv_sec;
167 if (x == 0L)
168 x = a.tv_nsec - b.tv_nsec;
169 return (x < 0L ? (-1) : x > 0L ? (1) : (0));
172 static inline struct timespec
173 evNowTime() {
174 struct timeval now;
176 if (gettimeofday(&now, NULL) < 0)
177 return (evConsTime(0, 0));
178 return (evTimeSpec(now));
181 #endif
183 /* Options. Leave them on. */
184 /* #undef DEBUG */
185 #include "res_debug.h"
187 #define EXT(res) ((res)->_u._ext)
189 #ifndef _LIBC
190 static const int highestFD = FD_SETSIZE - 1;
191 #endif
193 /* Forward. */
195 static int send_vc(res_state, const u_char *, int,
196 u_char *, int, int *, int);
197 static int send_dg(res_state, const u_char *, int,
198 u_char *, int, int *, int,
199 int *, int *);
200 #ifdef DEBUG
201 static void Aerror(const res_state, FILE *, const char *, int,
202 struct sockaddr_in);
203 static void Perror(const res_state, FILE *, const char *, int);
204 #endif
205 #ifdef _LIBC
206 static int sock_eq(struct sockaddr_in6 *, struct sockaddr_in6 *);
207 #else
208 static int sock_eq(struct sockaddr_in *, struct sockaddr_in *);
209 #endif
210 #ifdef NEED_PSELECT
211 static int pselect(int, void *, void *, void *,
212 struct timespec *,
213 const sigset_t *);
214 #endif
216 /* Reachover. */
218 #ifdef _LIBC
219 static void convaddr4to6(struct sockaddr_in6 *sa);
220 #endif
221 void res_pquery(const res_state, const u_char *, int, FILE *);
223 /* Public. */
225 /* int
226 * res_isourserver(ina)
227 * looks up "ina" in _res.ns_addr_list[]
228 * returns:
229 * 0 : not found
230 * >0 : found
231 * author:
232 * paul vixie, 29may94
235 #ifdef _LIBC
236 res_ourserver_p(const res_state statp, const struct sockaddr_in6 *inp)
237 #else
238 res_ourserver_p(const res_state statp, const struct sockaddr_in *inp)
239 #endif
241 struct sockaddr_in ina;
242 int ns;
244 #ifdef _LIBC
245 if (inp->sin6_family == AF_INET) {
246 ina = *(struct sockaddr_in *)inp;
248 for (ns = 0; ns < MAXNS; ns++) {
249 const struct sockaddr_in *srv =
250 (struct sockaddr_in *)EXT(statp).nsaddrs[ns];
252 if ((srv != NULL) && (srv->sin_family == AF_INET) &&
253 (srv->sin_port == ina.sin_port) &&
254 (srv->sin_addr.s_addr == INADDR_ANY ||
255 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
256 return (1);
258 } else if (inp->sin6_family == AF_INET6) {
259 for (ns = 0; ns < MAXNS; ns++) {
260 const struct sockaddr_in6 *srv = EXT(statp).nsaddrs[ns];
261 if ((srv != NULL) && (srv->sin6_family == AF_INET6) &&
262 (srv->sin6_port == inp->sin6_port) &&
263 !(memcmp(&srv->sin6_addr, &in6addr_any,
264 sizeof (struct in6_addr)) &&
265 memcmp(&srv->sin6_addr, &inp->sin6_addr,
266 sizeof (struct in6_addr))))
267 return (1);
270 #else
271 ina = *inp;
272 for (ns = 0; ns < statp->nscount; ns++) {
273 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
275 if (srv->sin_family == ina.sin_family &&
276 srv->sin_port == ina.sin_port &&
277 (srv->sin_addr.s_addr == INADDR_ANY ||
278 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
279 return (1);
281 #endif
282 return (0);
285 /* int
286 * res_nameinquery(name, type, class, buf, eom)
287 * look for (name,type,class) in the query section of packet (buf,eom)
288 * requires:
289 * buf + HFIXEDSZ <= eom
290 * returns:
291 * -1 : format error
292 * 0 : not found
293 * >0 : found
294 * author:
295 * paul vixie, 29may94
298 res_nameinquery(const char *name, int type, int class,
299 const u_char *buf, const u_char *eom)
301 const u_char *cp = buf + HFIXEDSZ;
302 int qdcount = ntohs(((HEADER*)buf)->qdcount);
304 while (qdcount-- > 0) {
305 char tname[MAXDNAME+1];
306 int n, ttype, tclass;
308 n = dn_expand(buf, eom, cp, tname, sizeof tname);
309 if (n < 0)
310 return (-1);
311 cp += n;
312 if (cp + 2 * INT16SZ > eom)
313 return (-1);
314 ttype = ns_get16(cp); cp += INT16SZ;
315 tclass = ns_get16(cp); cp += INT16SZ;
316 if (ttype == type && tclass == class &&
317 ns_samename(tname, name) == 1)
318 return (1);
320 return (0);
323 /* int
324 * res_queriesmatch(buf1, eom1, buf2, eom2)
325 * is there a 1:1 mapping of (name,type,class)
326 * in (buf1,eom1) and (buf2,eom2)?
327 * returns:
328 * -1 : format error
329 * 0 : not a 1:1 mapping
330 * >0 : is a 1:1 mapping
331 * author:
332 * paul vixie, 29may94
335 res_queriesmatch(const u_char *buf1, const u_char *eom1,
336 const u_char *buf2, const u_char *eom2)
338 const u_char *cp = buf1 + HFIXEDSZ;
339 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
341 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
342 return (-1);
345 * Only header section present in replies to
346 * dynamic update packets.
348 if ((((HEADER *)buf1)->opcode == ns_o_update) &&
349 (((HEADER *)buf2)->opcode == ns_o_update))
350 return (1);
352 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
353 return (0);
354 while (qdcount-- > 0) {
355 char tname[MAXDNAME+1];
356 int n, ttype, tclass;
358 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
359 if (n < 0)
360 return (-1);
361 cp += n;
362 if (cp + 2 * INT16SZ > eom1)
363 return (-1);
364 ttype = ns_get16(cp); cp += INT16SZ;
365 tclass = ns_get16(cp); cp += INT16SZ;
366 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
367 return (0);
369 return (1);
373 res_nsend(res_state statp,
374 const u_char *buf, int buflen, u_char *ans, int anssiz)
376 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
378 if (statp->nscount == 0) {
379 __set_errno (ESRCH);
380 return (-1);
382 if (anssiz < HFIXEDSZ) {
383 __set_errno (EINVAL);
384 return (-1);
386 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
387 (stdout, ";; res_send()\n"), buf, buflen);
388 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
389 gotsomewhere = 0;
390 terrno = ETIMEDOUT;
393 * If the ns_addr_list in the resolver context has changed, then
394 * invalidate our cached copy and the associated timing data.
396 if (EXT(statp).nscount != 0) {
397 int needclose = 0;
399 if (EXT(statp).nscount != statp->nscount)
400 needclose++;
401 else
402 for (ns = 0; ns < statp->nscount; ns++)
403 #ifdef _LIBC
404 if (!sock_eq((struct sockaddr_in6 *)
405 &statp->nsaddr_list[ns],
406 EXT(statp).nsaddrs[ns]))
407 #else
408 if (!sock_eq(&statp->nsaddr_list[ns],
409 &EXT(statp).nsaddrs[ns]))
410 #endif
412 needclose++;
413 break;
415 if (needclose)
416 res_nclose(statp);
420 * Maybe initialize our private copy of the ns_addr_list.
422 if (EXT(statp).nscount == 0) {
423 #ifdef _LIBC
424 n = 0;
425 #endif
426 for (ns = 0; ns < statp->nscount; ns++) {
427 #ifdef _LIBC
428 /* find a hole */
429 while ((n < MAXNS) &&
430 (EXT(statp).nsaddrs[n] != NULL) &&
431 (EXT(statp).nsaddrs[n]->sin6_family == AF_INET6) &&
432 !IN6_IS_ADDR_V4MAPPED(
433 &EXT(statp).nsaddrs[n]->sin6_addr))
434 n++;
435 if (n == MAXNS)
436 break;
438 if (EXT(statp).nsaddrs[n] == NULL)
439 EXT(statp).nsaddrs[n] =
440 malloc(sizeof (struct sockaddr_in6));
441 if (EXT(statp).nsaddrs[n] != NULL) {
442 memcpy(EXT(statp).nsaddrs[n],
443 &statp->nsaddr_list[ns],
444 sizeof (struct sockaddr_in));
445 EXT(statp).nstimes[n] = RES_MAXTIME;
446 EXT(statp).nssocks[n] = -1;
447 n++;
449 #else
450 EXT(statp).nsaddrs[ns] = statp->nsaddr_list[ns];
451 EXT(statp).nstimes[ns] = RES_MAXTIME;
452 EXT(statp).nssocks[ns] = -1;
453 #endif
455 EXT(statp).nscount = statp->nscount;
456 #ifdef _LIBC
457 /* If holes left, free memory and set to NULL */
458 while (n < MAXNS) {
459 if ((EXT(statp).nsaddrs[n] != NULL) &&
460 ((EXT(statp).nsaddrs[n]->sin6_family != AF_INET6)
461 || IN6_IS_ADDR_V4MAPPED(
462 &EXT(statp).nsaddrs[n]->sin6_addr))) {
463 free(EXT(statp).nsaddrs[n]);
464 EXT(statp).nsaddrs[n] = NULL;
466 n++;
468 #endif
472 * Some resolvers want to even out the load on their nameservers.
473 * Note that RES_BLAST overrides RES_ROTATE.
475 if ((statp->options & RES_ROTATE) != 0 &&
476 (statp->options & RES_BLAST) == 0) {
477 #ifdef _LIBC
478 struct sockaddr_in6 *ina;
479 int lastns = statp->nscount + EXT(statp).nscount6 - 1;
481 ina = EXT(statp).nsaddrs[0];
482 for (ns = 0; ns < lastns; ns++)
483 EXT(statp).nsaddrs[ns] = EXT(statp).nsaddrs[ns + 1];
484 EXT(statp).nsaddrs[lastns] = ina;
485 #else
486 struct sockaddr_in ina;
487 int lastns = statp->nscount - 1;
489 ina = statp->nsaddr_list[0];
490 for (ns = 0; ns < lastns; ns++)
491 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
492 statp->nsaddr_list[lastns] = ina;
493 #endif
497 * Send request, RETRY times, or until successful.
499 for (try = 0; try < statp->retry; try++) {
500 #ifdef _LIBC
501 for (ns = 0; ns < MAXNS; ns++)
502 #else
503 for (ns = 0; ns < statp->nscount; ns++)
504 #endif
506 #ifdef _LIBC
507 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
509 if (nsap == NULL)
510 goto next_ns;
511 #else
512 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
513 #endif
514 same_ns:
515 if (statp->qhook) {
516 int done = 0, loops = 0;
518 do {
519 res_sendhookact act;
521 #ifdef _LIBC
522 act = (*statp->qhook)((struct sockaddr_in **)
523 &nsap, &buf, &buflen,
524 ans, anssiz, &resplen);
525 #else
526 act = (*statp->qhook)(&nsap, &buf, &buflen,
527 ans, anssiz, &resplen);
528 #endif
529 switch (act) {
530 case res_goahead:
531 done = 1;
532 break;
533 case res_nextns:
534 res_nclose(statp);
535 goto next_ns;
536 case res_done:
537 return (resplen);
538 case res_modified:
539 /* give the hook another try */
540 if (++loops < 42) /*doug adams*/
541 break;
542 /*FALLTHROUGH*/
543 case res_error:
544 /*FALLTHROUGH*/
545 default:
546 return (-1);
548 } while (!done);
551 Dprint(statp->options & RES_DEBUG,
552 (stdout, ";; Querying server (# %d) address = %s\n",
553 ns + 1, inet_ntoa(nsap->sin_addr)));
555 if (v_circuit) {
556 /* Use VC; at most one attempt per server. */
557 try = statp->retry;
558 n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
559 ns);
560 if (n < 0)
561 return (-1);
562 if (n == 0)
563 goto next_ns;
564 resplen = n;
565 } else {
566 /* Use datagrams. */
567 n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
568 ns, &v_circuit, &gotsomewhere);
569 if (n < 0)
570 return (-1);
571 if (n == 0)
572 goto next_ns;
573 if (v_circuit)
574 goto same_ns;
575 resplen = n;
578 Dprint((statp->options & RES_DEBUG) ||
579 ((statp->pfcode & RES_PRF_REPLY) &&
580 (statp->pfcode & RES_PRF_HEAD1)),
581 (stdout, ";; got answer:\n"));
583 DprintQ((statp->options & RES_DEBUG) ||
584 (statp->pfcode & RES_PRF_REPLY),
585 (stdout, ""),
586 ans, (resplen > anssiz) ? anssiz : resplen);
589 * If we have temporarily opened a virtual circuit,
590 * or if we haven't been asked to keep a socket open,
591 * close the socket.
593 if ((v_circuit && (statp->options & RES_USEVC) == 0) ||
594 (statp->options & RES_STAYOPEN) == 0) {
595 res_nclose(statp);
597 if (statp->rhook) {
598 int done = 0, loops = 0;
600 do {
601 res_sendhookact act;
603 #ifdef _LIBC
604 act = (*statp->rhook)((struct sockaddr_in *)
605 nsap, buf, buflen,
606 ans, anssiz, &resplen);
607 #else
608 act = (*statp->rhook)(nsap, buf, buflen,
609 ans, anssiz, &resplen);
610 #endif
611 switch (act) {
612 case res_goahead:
613 case res_done:
614 done = 1;
615 break;
616 case res_nextns:
617 res_nclose(statp);
618 goto next_ns;
619 case res_modified:
620 /* give the hook another try */
621 if (++loops < 42) /*doug adams*/
622 break;
623 /*FALLTHROUGH*/
624 case res_error:
625 /*FALLTHROUGH*/
626 default:
627 return (-1);
629 } while (!done);
632 return (resplen);
633 next_ns: ;
634 } /*foreach ns*/
635 } /*foreach retry*/
636 res_nclose(statp);
637 if (!v_circuit) {
638 if (!gotsomewhere)
639 __set_errno (ECONNREFUSED); /* no nameservers found */
640 else
641 __set_errno (ETIMEDOUT); /* no answer obtained */
642 } else
643 __set_errno (terrno);
644 return (-1);
647 /* Private */
649 static int
650 send_vc(res_state statp,
651 const u_char *buf, int buflen, u_char *ans, int anssiz,
652 int *terrno, int ns)
654 const HEADER *hp = (HEADER *) buf;
655 HEADER *anhp = (HEADER *) ans;
656 #ifdef _LIBC
657 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
658 #else
659 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
660 #endif
661 int truncating, connreset, resplen, n;
662 struct iovec iov[2];
663 u_short len;
664 u_char *cp;
666 connreset = 0;
667 same_ns:
668 truncating = 0;
670 /* Are we still talking to whom we want to talk to? */
671 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
672 #ifdef _LIBC
673 struct sockaddr_in6 peer;
674 #else
675 struct sockaddr_in peer;
676 #endif
677 int size = sizeof peer;
679 if (getpeername(statp->_vcsock,
680 (struct sockaddr *)&peer, &size) < 0 ||
681 !sock_eq(&peer, nsap)) {
682 res_nclose(statp);
683 statp->_flags &= ~RES_F_VC;
687 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
688 if (statp->_vcsock >= 0)
689 res_nclose(statp);
691 #ifdef _LIBC
692 statp->_vcsock = socket(nsap->sin6_family, SOCK_STREAM, 0);
693 #else
694 statp->_vcsock = socket(PF_INET, SOCK_STREAM, 0);
695 if (statp->_vcsock > highestFD) {
696 res_nclose(statp);
697 __set_errno (ENOTSOCK);
699 #endif
700 if (statp->_vcsock < 0) {
701 *terrno = errno;
702 Perror(statp, stderr, "socket(vc)", errno);
703 return (-1);
705 __set_errno (0);
706 if (connect(statp->_vcsock, (struct sockaddr *)nsap,
707 sizeof *nsap) < 0) {
708 *terrno = errno;
709 Aerror(statp, stderr, "connect/vc", errno, *nsap);
710 res_nclose(statp);
711 return (0);
713 statp->_flags |= RES_F_VC;
717 * Send length & message
719 putshort((u_short)buflen, (u_char*)&len);
720 iov[0] = evConsIovec(&len, INT16SZ);
721 iov[1] = evConsIovec((void*)buf, buflen);
722 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
723 *terrno = errno;
724 Perror(statp, stderr, "write failed", errno);
725 res_nclose(statp);
726 return (0);
729 * Receive length & response
731 read_len:
732 cp = ans;
733 len = INT16SZ;
734 while ((n = read(statp->_vcsock, (char *)cp, (int)len)) > 0) {
735 cp += n;
736 if ((len -= n) <= 0)
737 break;
739 if (n <= 0) {
740 *terrno = errno;
741 Perror(statp, stderr, "read failed", errno);
742 res_nclose(statp);
744 * A long running process might get its TCP
745 * connection reset if the remote server was
746 * restarted. Requery the server instead of
747 * trying a new one. When there is only one
748 * server, this means that a query might work
749 * instead of failing. We only allow one reset
750 * per query to prevent looping.
752 if (*terrno == ECONNRESET && !connreset) {
753 connreset = 1;
754 res_nclose(statp);
755 goto same_ns;
757 res_nclose(statp);
758 return (0);
760 resplen = ns_get16(ans);
761 if (resplen > anssiz) {
762 Dprint(statp->options & RES_DEBUG,
763 (stdout, ";; response truncated\n")
765 truncating = 1;
766 len = anssiz;
767 } else
768 len = resplen;
769 if (len < HFIXEDSZ) {
771 * Undersized message.
773 Dprint(statp->options & RES_DEBUG,
774 (stdout, ";; undersized: %d\n", len));
775 *terrno = EMSGSIZE;
776 res_nclose(statp);
777 return (0);
779 cp = ans;
780 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
781 cp += n;
782 len -= n;
784 if (n <= 0) {
785 *terrno = errno;
786 Perror(statp, stderr, "read(vc)", errno);
787 res_nclose(statp);
788 return (0);
790 if (truncating) {
792 * Flush rest of answer so connection stays in synch.
794 anhp->tc = 1;
795 len = resplen - anssiz;
796 while (len != 0) {
797 char junk[PACKETSZ];
799 n = read(statp->_vcsock, junk,
800 (len > sizeof junk) ? sizeof junk : len);
801 if (n > 0)
802 len -= n;
803 else
804 break;
808 * If the calling applicating has bailed out of
809 * a previous call and failed to arrange to have
810 * the circuit closed or the server has got
811 * itself confused, then drop the packet and
812 * wait for the correct one.
814 if (hp->id != anhp->id) {
815 DprintQ((statp->options & RES_DEBUG) ||
816 (statp->pfcode & RES_PRF_REPLY),
817 (stdout, ";; old answer (unexpected):\n"),
818 ans, (resplen > anssiz) ? anssiz: resplen);
819 goto read_len;
823 * All is well, or the error is fatal. Signal that the
824 * next nameserver ought not be tried.
826 return (resplen);
829 static int
830 send_dg(res_state statp,
831 const u_char *buf, int buflen, u_char *ans, int anssiz,
832 int *terrno, int ns, int *v_circuit, int *gotsomewhere)
834 const HEADER *hp = (HEADER *) buf;
835 HEADER *anhp = (HEADER *) ans;
836 #ifdef _LIBC
837 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
838 #else
839 const struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
840 #endif
841 struct timespec now, timeout, finish;
842 #ifdef _LIBC
843 struct pollfd pfd[1];
844 int ptimeout;
845 struct sockaddr_in6 from;
846 static int socket_pf = 0;
847 #else
848 fd_set dsmask;
849 struct sockaddr_in from;
850 #endif
851 int fromlen, resplen, seconds, n, s;
853 if (EXT(statp).nssocks[ns] == -1) {
854 #ifdef _LIBC
855 /* only try IPv6 if IPv6 NS and if not failed before */
856 if ((EXT(statp).nscount6 > 0) && (socket_pf != PF_INET)) {
857 EXT(statp).nssocks[ns] =
858 socket(PF_INET6, SOCK_DGRAM, 0);
859 socket_pf = EXT(statp).nssocks[ns] < 0 ? PF_INET
860 : PF_INET6;
862 if (EXT(statp).nssocks[ns] < 0)
863 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
864 #else
865 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
866 if (EXT(statp).nssocks[ns] > highestFD) {
867 res_nclose(statp);
868 __set_errno (ENOTSOCK);
870 #endif
871 if (EXT(statp).nssocks[ns] < 0) {
872 *terrno = errno;
873 Perror(statp, stderr, "socket(dg)", errno);
874 return (-1);
876 #ifndef CANNOT_CONNECT_DGRAM
877 #ifdef _LIBC
878 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
879 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
880 convaddr4to6(nsap);
881 #endif
883 * On a 4.3BSD+ machine (client and server,
884 * actually), sending to a nameserver datagram
885 * port with no nameserver will cause an
886 * ICMP port unreachable message to be returned.
887 * If our datagram socket is "connected" to the
888 * server, we get an ECONNREFUSED error on the next
889 * socket operation, and select returns if the
890 * error message is received. We can thus detect
891 * the absence of a nameserver without timing out.
893 if (connect(EXT(statp).nssocks[ns], (struct sockaddr *)nsap,
894 sizeof *nsap) < 0) {
895 Aerror(statp, stderr, "connect(dg)", errno, *nsap);
896 res_nclose(statp);
897 return (0);
899 #endif /* !CANNOT_CONNECT_DGRAM */
900 Dprint(statp->options & RES_DEBUG,
901 (stdout, ";; new DG socket\n"))
903 s = EXT(statp).nssocks[ns];
904 #ifndef CANNOT_CONNECT_DGRAM
905 if (send(s, (char*)buf, buflen, 0) != buflen) {
906 Perror(statp, stderr, "send", errno);
907 res_nclose(statp);
908 return (0);
910 #else /* !CANNOT_CONNECT_DGRAM */
911 #ifdef _LIBC
912 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
913 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
914 convaddr4to6(nsap);
915 #endif
916 if (sendto(s, (char*)buf, buflen, 0,
917 (struct sockaddr *)nsap, sizeof *nsap) != buflen)
919 Aerror(statp, stderr, "sendto", errno, *nsap);
920 res_nclose(statp);
921 return (0);
923 #endif /* !CANNOT_CONNECT_DGRAM */
926 * Wait for reply.
928 seconds = (statp->retrans << ns);
929 if (ns > 0)
930 seconds /= statp->nscount;
931 if (seconds <= 0)
932 seconds = 1;
933 now = evNowTime();
934 timeout = evConsTime(seconds, 0);
935 finish = evAddTime(now, timeout);
936 wait:
937 #ifdef _LIBC
938 /* Convert struct timespec in milliseconds. */
939 ptimeout = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
941 pfd[0].fd = s;
942 pfd[0].events = POLLIN;
943 n = __poll (pfd, 1, ptimeout);
944 #else
945 FD_ZERO(&dsmask);
946 FD_SET(s, &dsmask);
947 n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
948 #endif
949 if (n == 0) {
950 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
951 *gotsomewhere = 1;
952 return (0);
954 if (n < 0) {
955 if (errno == EINTR) {
956 now = evNowTime();
957 if (evCmpTime(finish, now) > 0) {
958 timeout = evSubTime(finish, now);
959 goto wait;
962 Perror(statp, stderr, "select", errno);
963 res_nclose(statp);
964 return (0);
966 __set_errno (0);
967 #ifdef _LIBC
968 fromlen = sizeof(struct sockaddr_in6);
969 #else
970 fromlen = sizeof(struct sockaddr_in);
971 #endif
972 resplen = recvfrom(s, (char*)ans, anssiz,0,
973 (struct sockaddr *)&from, &fromlen);
974 if (resplen <= 0) {
975 Perror(statp, stderr, "recvfrom", errno);
976 res_nclose(statp);
977 return (0);
979 *gotsomewhere = 1;
980 if (resplen < HFIXEDSZ) {
982 * Undersized message.
984 Dprint(statp->options & RES_DEBUG,
985 (stdout, ";; undersized: %d\n",
986 resplen));
987 *terrno = EMSGSIZE;
988 res_nclose(statp);
989 return (0);
991 if (hp->id != anhp->id) {
993 * response from old 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, ";; old answer:\n"),
1000 ans, (resplen > anssiz) ? anssiz : resplen);
1001 goto wait;
1003 if (!(statp->options & RES_INSECURE1) &&
1004 !res_ourserver_p(statp, &from)) {
1006 * response from wrong server? ignore it.
1007 * XXX - potential security hazard could
1008 * be detected here.
1010 DprintQ((statp->options & RES_DEBUG) ||
1011 (statp->pfcode & RES_PRF_REPLY),
1012 (stdout, ";; not our server:\n"),
1013 ans, (resplen > anssiz) ? anssiz : resplen);
1014 goto wait;
1016 if (!(statp->options & RES_INSECURE2) &&
1017 !res_queriesmatch(buf, buf + buflen,
1018 ans, ans + anssiz)) {
1020 * response contains wrong query? ignore it.
1021 * XXX - potential security hazard could
1022 * be detected here.
1024 DprintQ((statp->options & RES_DEBUG) ||
1025 (statp->pfcode & RES_PRF_REPLY),
1026 (stdout, ";; wrong query name:\n"),
1027 ans, (resplen > anssiz) ? anssiz : resplen);
1028 goto wait;
1030 if (anhp->rcode == SERVFAIL ||
1031 anhp->rcode == NOTIMP ||
1032 anhp->rcode == REFUSED) {
1033 DprintQ(statp->options & RES_DEBUG,
1034 (stdout, "server rejected query:\n"),
1035 ans, (resplen > anssiz) ? anssiz : resplen);
1036 res_nclose(statp);
1037 /* don't retry if called from dig */
1038 if (!statp->pfcode)
1039 return (0);
1041 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1043 * To get the rest of answer,
1044 * use TCP with same server.
1046 Dprint(statp->options & RES_DEBUG,
1047 (stdout, ";; truncated answer\n"));
1048 *v_circuit = 1;
1049 res_nclose(statp);
1050 return (1);
1053 * All is well, or the error is fatal. Signal that the
1054 * next nameserver ought not be tried.
1056 return (resplen);
1059 #ifdef DEBUG
1060 static void
1061 Aerror(const res_state statp, FILE *file, const char *string, int error,
1062 struct sockaddr_in address)
1064 int save = errno;
1066 if ((statp->options & RES_DEBUG) != 0) {
1067 char tmp[sizeof "255.255.255.255"];
1069 fprintf(file, "res_send: %s ([%s].%u): %s\n",
1070 string,
1071 inet_ntop(address.sin_family, &address.sin_addr,
1072 tmp, sizeof tmp),
1073 ntohs(address.sin_port),
1074 strerror(error));
1076 __set_errno (save);
1079 static void
1080 Perror(const res_state statp, FILE *file, const char *string, int error) {
1081 int save = errno;
1083 if ((statp->options & RES_DEBUG) != 0)
1084 fprintf(file, "res_send: %s: %s\n",
1085 string, strerror(error));
1086 __set_errno (save);
1088 #endif
1090 static int
1091 #ifdef _LIBC
1092 sock_eq(struct sockaddr_in6 *a1, struct sockaddr_in6 *a2) {
1093 if (a1->sin6_family == a2->sin6_family) {
1094 if (a1->sin6_family == AF_INET)
1095 return ((((struct sockaddr_in *)a1)->sin_port ==
1096 ((struct sockaddr_in *)a2)->sin_port) &&
1097 (((struct sockaddr_in *)a1)->sin_addr.s_addr ==
1098 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1099 else
1100 return ((a1->sin6_port == a2->sin6_port) &&
1101 !memcmp(&a1->sin6_addr, &a2->sin6_addr,
1102 sizeof (struct in6_addr)));
1104 if (a1->sin6_family == AF_INET) {
1105 struct sockaddr_in6 *sap = a1;
1106 a1 = a2;
1107 a2 = sap;
1108 } /* assumes that AF_INET and AF_INET6 are the only possibilities */
1109 return ((a1->sin6_port == ((struct sockaddr_in *)a2)->sin_port) &&
1110 IN6_IS_ADDR_V4MAPPED(&a1->sin6_addr) &&
1111 (a1->sin6_addr.s6_addr32[3] ==
1112 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1114 #else
1115 sock_eq(struct sockaddr_in *a1, struct sockaddr_in *a2) {
1116 return ((a1->sin_family == a2->sin_family) &&
1117 (a1->sin_port == a2->sin_port) &&
1118 (a1->sin_addr.s_addr == a2->sin_addr.s_addr));
1120 #endif
1122 #ifdef _LIBC
1124 * Converts IPv4 family, address and port to
1125 * IPv6 family, IPv4-mapped IPv6 address and port.
1127 static void
1128 convaddr4to6(struct sockaddr_in6 *sa)
1130 const struct sockaddr_in sa4 = *(struct sockaddr_in *)sa;
1132 sa->sin6_family = AF_INET6;
1133 sa->sin6_port = sa4.sin_port;
1134 sa->sin6_addr.s6_addr32[0] = 0;
1135 sa->sin6_addr.s6_addr32[1] = 0;
1136 sa->sin6_addr.s6_addr32[2] = htonl(0xFFFF);
1137 sa->sin6_addr.s6_addr32[3] = sa4.sin_addr.s_addr;
1139 #endif
1141 #ifdef NEED_PSELECT
1142 /* XXX needs to move to the porting library. */
1143 static int
1144 pselect(int nfds, void *rfds, void *wfds, void *efds,
1145 struct timespec *tsp, const sigset_t *sigmask)
1147 struct timeval tv, *tvp;
1148 sigset_t sigs;
1149 int n;
1151 if (tsp) {
1152 tvp = &tv;
1153 tv = evTimeVal(*tsp);
1154 } else
1155 tvp = NULL;
1156 if (sigmask)
1157 sigprocmask(SIG_SETMASK, sigmask, &sigs);
1158 n = select(nfds, rfds, wfds, efds, tvp);
1159 if (sigmask)
1160 sigprocmask(SIG_SETMASK, &sigs, NULL);
1161 if (tsp)
1162 *tsp = evTimeSpec(tv);
1163 return (n);
1165 #endif