Update.
[glibc.git] / resolv / res_send.c
blob751a5506a15a9cec0081f54a5171fdc71b88d395
1 /*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
31 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
33 * Permission to use, copy, modify, and distribute this software for any
34 * purpose with or without fee is hereby granted, provided that the above
35 * copyright notice and this permission notice appear in all copies, and that
36 * the name of Digital Equipment Corporation not be used in advertising or
37 * publicity pertaining to distribution of the document or software without
38 * specific, written prior permission.
40 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
43 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47 * SOFTWARE.
51 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
53 * Permission to use, copy, modify, and distribute this software for any
54 * purpose with or without fee is hereby granted, provided that the above
55 * copyright notice and this permission notice appear in all copies.
57 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
58 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
60 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
61 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
62 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
63 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
64 * SOFTWARE.
67 #if defined(LIBC_SCCS) && !defined(lint)
68 static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
69 static const char rcsid[] = "$BINDId: res_send.c,v 8.38 2000/03/30 20:16:51 vixie Exp $";
70 #endif /* LIBC_SCCS and not lint */
73 * Send query to name server and wait for reply.
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #include <sys/time.h>
79 #include <sys/socket.h>
80 #include <sys/uio.h>
81 #ifdef _LIBC
82 #include <sys/poll.h>
83 #endif
85 #include <netinet/in.h>
86 #include <arpa/nameser.h>
87 #include <arpa/inet.h>
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 int ns;
243 #ifdef _LIBC
244 if (inp->sin6_family == AF_INET) {
245 struct sockaddr_in *in4p = (struct sockaddr_in *) inp;
246 in_port_t port = in4p->sin_port;
247 in_addr_t addr = in4p->sin_addr.s_addr;
249 for (ns = 0; ns < MAXNS; ns++) {
250 const struct sockaddr_in *srv =
251 (struct sockaddr_in *)EXT(statp).nsaddrs[ns];
253 if ((srv != NULL) && (srv->sin_family == AF_INET) &&
254 (srv->sin_port == port) &&
255 (srv->sin_addr.s_addr == INADDR_ANY ||
256 srv->sin_addr.s_addr == addr))
257 return (1);
259 } else if (inp->sin6_family == AF_INET6) {
260 for (ns = 0; ns < MAXNS; ns++) {
261 const struct sockaddr_in6 *srv = EXT(statp).nsaddrs[ns];
262 if ((srv != NULL) && (srv->sin6_family == AF_INET6) &&
263 (srv->sin6_port == inp->sin6_port) &&
264 !(memcmp(&srv->sin6_addr, &in6addr_any,
265 sizeof (struct in6_addr)) &&
266 memcmp(&srv->sin6_addr, &inp->sin6_addr,
267 sizeof (struct in6_addr))))
268 return (1);
271 #else
272 struct sockaddr_in ina = *inp;
273 for (ns = 0; ns < statp->nscount; ns++) {
274 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
276 if (srv->sin_family == ina.sin_family &&
277 srv->sin_port == ina.sin_port &&
278 (srv->sin_addr.s_addr == INADDR_ANY ||
279 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
280 return (1);
282 #endif
283 return (0);
286 /* int
287 * res_nameinquery(name, type, class, buf, eom)
288 * look for (name,type,class) in the query section of packet (buf,eom)
289 * requires:
290 * buf + HFIXEDSZ <= eom
291 * returns:
292 * -1 : format error
293 * 0 : not found
294 * >0 : found
295 * author:
296 * paul vixie, 29may94
299 res_nameinquery(const char *name, int type, int class,
300 const u_char *buf, const u_char *eom)
302 const u_char *cp = buf + HFIXEDSZ;
303 int qdcount = ntohs(((HEADER*)buf)->qdcount);
305 while (qdcount-- > 0) {
306 char tname[MAXDNAME+1];
307 int n, ttype, tclass;
309 n = dn_expand(buf, eom, cp, tname, sizeof tname);
310 if (n < 0)
311 return (-1);
312 cp += n;
313 if (cp + 2 * INT16SZ > eom)
314 return (-1);
315 ttype = ns_get16(cp); cp += INT16SZ;
316 tclass = ns_get16(cp); cp += INT16SZ;
317 if (ttype == type && tclass == class &&
318 ns_samename(tname, name) == 1)
319 return (1);
321 return (0);
324 /* int
325 * res_queriesmatch(buf1, eom1, buf2, eom2)
326 * is there a 1:1 mapping of (name,type,class)
327 * in (buf1,eom1) and (buf2,eom2)?
328 * returns:
329 * -1 : format error
330 * 0 : not a 1:1 mapping
331 * >0 : is a 1:1 mapping
332 * author:
333 * paul vixie, 29may94
336 res_queriesmatch(const u_char *buf1, const u_char *eom1,
337 const u_char *buf2, const u_char *eom2)
339 const u_char *cp = buf1 + HFIXEDSZ;
340 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
342 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
343 return (-1);
346 * Only header section present in replies to
347 * dynamic update packets.
349 if ((((HEADER *)buf1)->opcode == ns_o_update) &&
350 (((HEADER *)buf2)->opcode == ns_o_update))
351 return (1);
353 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
354 return (0);
355 while (qdcount-- > 0) {
356 char tname[MAXDNAME+1];
357 int n, ttype, tclass;
359 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
360 if (n < 0)
361 return (-1);
362 cp += n;
363 if (cp + 2 * INT16SZ > eom1)
364 return (-1);
365 ttype = ns_get16(cp); cp += INT16SZ;
366 tclass = ns_get16(cp); cp += INT16SZ;
367 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
368 return (0);
370 return (1);
374 res_nsend(res_state statp,
375 const u_char *buf, int buflen, u_char *ans, int anssiz)
377 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
379 if (statp->nscount == 0) {
380 __set_errno (ESRCH);
381 return (-1);
383 if (anssiz < HFIXEDSZ) {
384 __set_errno (EINVAL);
385 return (-1);
387 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
388 (stdout, ";; res_send()\n"), buf, buflen);
389 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
390 gotsomewhere = 0;
391 terrno = ETIMEDOUT;
394 * If the ns_addr_list in the resolver context has changed, then
395 * invalidate our cached copy and the associated timing data.
397 if (EXT(statp).nsinit) {
398 int needclose = 0;
400 if (EXT(statp).nscount != statp->nscount)
401 needclose++;
402 else
403 for (ns = 0; ns < statp->nscount; ns++)
404 #ifdef _LIBC
405 if (!sock_eq((struct sockaddr_in6 *)
406 &statp->nsaddr_list[ns],
407 EXT(statp).nsaddrs[ns]))
408 #else
409 if (!sock_eq(&statp->nsaddr_list[ns],
410 &EXT(statp).nsaddrs[ns]))
411 #endif
413 needclose++;
414 break;
416 if (needclose)
417 res_nclose(statp);
421 * Maybe initialize our private copy of the ns_addr_list.
423 if (EXT(statp).nsinit == 0) {
424 #ifdef _LIBC
425 n = 0;
426 #endif
427 for (ns = 0; ns < statp->nscount; ns++) {
428 #ifdef _LIBC
429 /* find a hole */
430 while ((n < MAXNS) &&
431 (EXT(statp).nsaddrs[n] != NULL) &&
432 (EXT(statp).nsaddrs[n]->sin6_family == AF_INET6) &&
433 !IN6_IS_ADDR_V4MAPPED(
434 &EXT(statp).nsaddrs[n]->sin6_addr))
435 n++;
436 if (n == MAXNS)
437 break;
439 if (EXT(statp).nsaddrs[n] == NULL)
440 EXT(statp).nsaddrs[n] =
441 malloc(sizeof (struct sockaddr_in6));
442 if (EXT(statp).nsaddrs[n] != NULL) {
443 memcpy(EXT(statp).nsaddrs[n],
444 &statp->nsaddr_list[ns],
445 sizeof (struct sockaddr_in));
446 EXT(statp).nstimes[n] = RES_MAXTIME;
447 EXT(statp).nssocks[n] = -1;
448 n++;
450 #else
451 EXT(statp).nsaddrs[ns] = statp->nsaddr_list[ns];
452 EXT(statp).nstimes[ns] = RES_MAXTIME;
453 EXT(statp).nssocks[ns] = -1;
454 #endif
456 EXT(statp).nscount = statp->nscount;
457 EXT(statp).nsinit = 1;
458 #ifdef _LIBC
459 /* If holes left, free memory and set to NULL */
460 while (n < MAXNS) {
461 if ((EXT(statp).nsaddrs[n] != NULL) &&
462 ((EXT(statp).nsaddrs[n]->sin6_family != AF_INET6)
463 || IN6_IS_ADDR_V4MAPPED(
464 &EXT(statp).nsaddrs[n]->sin6_addr))) {
465 free(EXT(statp).nsaddrs[n]);
466 EXT(statp).nsaddrs[n] = NULL;
468 n++;
470 #endif
474 * Some resolvers want to even out the load on their nameservers.
475 * Note that RES_BLAST overrides RES_ROTATE.
477 if ((statp->options & RES_ROTATE) != 0 &&
478 (statp->options & RES_BLAST) == 0) {
479 #ifdef _LIBC
480 struct sockaddr_in6 *ina;
481 int lastns = statp->nscount + EXT(statp).nscount6 - 1;
483 ina = EXT(statp).nsaddrs[0];
484 for (ns = 0; ns < lastns; ns++)
485 EXT(statp).nsaddrs[ns] = EXT(statp).nsaddrs[ns + 1];
486 EXT(statp).nsaddrs[lastns] = ina;
487 #else
488 struct sockaddr_in ina;
489 int lastns = statp->nscount - 1;
491 ina = statp->nsaddr_list[0];
492 for (ns = 0; ns < lastns; ns++)
493 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
494 statp->nsaddr_list[lastns] = ina;
495 #endif
499 * Send request, RETRY times, or until successful.
501 for (try = 0; try < statp->retry; try++) {
502 #ifdef _LIBC
503 for (ns = 0; ns < MAXNS; ns++)
504 #else
505 for (ns = 0; ns < statp->nscount; ns++)
506 #endif
508 #ifdef _LIBC
509 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
511 if (nsap == NULL)
512 goto next_ns;
513 #else
514 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
515 #endif
516 same_ns:
517 if (statp->qhook) {
518 int done = 0, loops = 0;
520 do {
521 res_sendhookact act;
523 #ifdef _LIBC
524 act = (*statp->qhook)((struct sockaddr_in **)
525 &nsap, &buf, &buflen,
526 ans, anssiz, &resplen);
527 #else
528 act = (*statp->qhook)(&nsap, &buf, &buflen,
529 ans, anssiz, &resplen);
530 #endif
531 switch (act) {
532 case res_goahead:
533 done = 1;
534 break;
535 case res_nextns:
536 res_nclose(statp);
537 goto next_ns;
538 case res_done:
539 return (resplen);
540 case res_modified:
541 /* give the hook another try */
542 if (++loops < 42) /*doug adams*/
543 break;
544 /*FALLTHROUGH*/
545 case res_error:
546 /*FALLTHROUGH*/
547 default:
548 return (-1);
550 } while (!done);
553 Dprint(statp->options & RES_DEBUG,
554 (stdout, ";; Querying server (# %d) address = %s\n",
555 ns + 1, inet_ntoa(nsap->sin_addr)));
557 if (v_circuit) {
558 /* Use VC; at most one attempt per server. */
559 try = statp->retry;
560 n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
561 ns);
562 if (n < 0)
563 return (-1);
564 if (n == 0)
565 goto next_ns;
566 resplen = n;
567 } else {
568 /* Use datagrams. */
569 n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
570 ns, &v_circuit, &gotsomewhere);
571 if (n < 0)
572 return (-1);
573 if (n == 0)
574 goto next_ns;
575 if (v_circuit)
576 goto same_ns;
577 resplen = n;
580 Dprint((statp->options & RES_DEBUG) ||
581 ((statp->pfcode & RES_PRF_REPLY) &&
582 (statp->pfcode & RES_PRF_HEAD1)),
583 (stdout, ";; got answer:\n"));
585 DprintQ((statp->options & RES_DEBUG) ||
586 (statp->pfcode & RES_PRF_REPLY),
587 (stdout, ""),
588 ans, (resplen > anssiz) ? anssiz : resplen);
591 * If we have temporarily opened a virtual circuit,
592 * or if we haven't been asked to keep a socket open,
593 * close the socket.
595 if ((v_circuit && (statp->options & RES_USEVC) == 0) ||
596 (statp->options & RES_STAYOPEN) == 0) {
597 res_nclose(statp);
599 if (statp->rhook) {
600 int done = 0, loops = 0;
602 do {
603 res_sendhookact act;
605 #ifdef _LIBC
606 act = (*statp->rhook)((struct sockaddr_in *)
607 nsap, buf, buflen,
608 ans, anssiz, &resplen);
609 #else
610 act = (*statp->rhook)(nsap, buf, buflen,
611 ans, anssiz, &resplen);
612 #endif
613 switch (act) {
614 case res_goahead:
615 case res_done:
616 done = 1;
617 break;
618 case res_nextns:
619 res_nclose(statp);
620 goto next_ns;
621 case res_modified:
622 /* give the hook another try */
623 if (++loops < 42) /*doug adams*/
624 break;
625 /*FALLTHROUGH*/
626 case res_error:
627 /*FALLTHROUGH*/
628 default:
629 return (-1);
631 } while (!done);
634 return (resplen);
635 next_ns: ;
636 } /*foreach ns*/
637 } /*foreach retry*/
638 res_nclose(statp);
639 if (!v_circuit) {
640 if (!gotsomewhere)
641 __set_errno (ECONNREFUSED); /* no nameservers found */
642 else
643 __set_errno (ETIMEDOUT); /* no answer obtained */
644 } else
645 __set_errno (terrno);
646 return (-1);
649 /* Private */
651 static int
652 send_vc(res_state statp,
653 const u_char *buf, int buflen, u_char *ans, int anssiz,
654 int *terrno, int ns)
656 const HEADER *hp = (HEADER *) buf;
657 HEADER *anhp = (HEADER *) ans;
658 #ifdef _LIBC
659 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
660 #else
661 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
662 #endif
663 int truncating, connreset, resplen, n;
664 struct iovec iov[2];
665 u_short len;
666 u_char *cp;
668 connreset = 0;
669 same_ns:
670 truncating = 0;
672 /* Are we still talking to whom we want to talk to? */
673 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
674 #ifdef _LIBC
675 struct sockaddr_in6 peer;
676 #else
677 struct sockaddr_in peer;
678 #endif
679 int size = sizeof peer;
681 if (getpeername(statp->_vcsock,
682 (struct sockaddr *)&peer, &size) < 0 ||
683 !sock_eq(&peer, nsap)) {
684 res_nclose(statp);
685 statp->_flags &= ~RES_F_VC;
689 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
690 if (statp->_vcsock >= 0)
691 res_nclose(statp);
693 #ifdef _LIBC
694 statp->_vcsock = socket(nsap->sin6_family, SOCK_STREAM, 0);
695 #else
696 statp->_vcsock = socket(PF_INET, SOCK_STREAM, 0);
697 if (statp->_vcsock > highestFD) {
698 res_nclose(statp);
699 __set_errno (ENOTSOCK);
701 #endif
702 if (statp->_vcsock < 0) {
703 *terrno = errno;
704 Perror(statp, stderr, "socket(vc)", errno);
705 return (-1);
707 __set_errno (0);
708 if (connect(statp->_vcsock, (struct sockaddr *)nsap,
709 sizeof *nsap) < 0) {
710 *terrno = errno;
711 Aerror(statp, stderr, "connect/vc", errno, *nsap);
712 res_nclose(statp);
713 return (0);
715 statp->_flags |= RES_F_VC;
719 * Send length & message
721 putshort((u_short)buflen, (u_char*)&len);
722 iov[0] = evConsIovec(&len, INT16SZ);
723 iov[1] = evConsIovec((void*)buf, buflen);
724 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
725 *terrno = errno;
726 Perror(statp, stderr, "write failed", errno);
727 res_nclose(statp);
728 return (0);
731 * Receive length & response
733 read_len:
734 cp = ans;
735 len = INT16SZ;
736 while ((n = read(statp->_vcsock, (char *)cp, (int)len)) > 0) {
737 cp += n;
738 if ((len -= n) <= 0)
739 break;
741 if (n <= 0) {
742 *terrno = errno;
743 Perror(statp, stderr, "read failed", errno);
744 res_nclose(statp);
746 * A long running process might get its TCP
747 * connection reset if the remote server was
748 * restarted. Requery the server instead of
749 * trying a new one. When there is only one
750 * server, this means that a query might work
751 * instead of failing. We only allow one reset
752 * per query to prevent looping.
754 if (*terrno == ECONNRESET && !connreset) {
755 connreset = 1;
756 res_nclose(statp);
757 goto same_ns;
759 res_nclose(statp);
760 return (0);
762 resplen = ns_get16(ans);
763 if (resplen > anssiz) {
764 Dprint(statp->options & RES_DEBUG,
765 (stdout, ";; response truncated\n")
767 truncating = 1;
768 len = anssiz;
769 } else
770 len = resplen;
771 if (len < HFIXEDSZ) {
773 * Undersized message.
775 Dprint(statp->options & RES_DEBUG,
776 (stdout, ";; undersized: %d\n", len));
777 *terrno = EMSGSIZE;
778 res_nclose(statp);
779 return (0);
781 cp = ans;
782 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
783 cp += n;
784 len -= n;
786 if (n <= 0) {
787 *terrno = errno;
788 Perror(statp, stderr, "read(vc)", errno);
789 res_nclose(statp);
790 return (0);
792 if (truncating) {
794 * Flush rest of answer so connection stays in synch.
796 anhp->tc = 1;
797 len = resplen - anssiz;
798 while (len != 0) {
799 char junk[PACKETSZ];
801 n = read(statp->_vcsock, junk,
802 (len > sizeof junk) ? sizeof junk : len);
803 if (n > 0)
804 len -= n;
805 else
806 break;
810 * If the calling applicating has bailed out of
811 * a previous call and failed to arrange to have
812 * the circuit closed or the server has got
813 * itself confused, then drop the packet and
814 * wait for the correct one.
816 if (hp->id != anhp->id) {
817 DprintQ((statp->options & RES_DEBUG) ||
818 (statp->pfcode & RES_PRF_REPLY),
819 (stdout, ";; old answer (unexpected):\n"),
820 ans, (resplen > anssiz) ? anssiz: resplen);
821 goto read_len;
825 * All is well, or the error is fatal. Signal that the
826 * next nameserver ought not be tried.
828 return (resplen);
831 static int
832 send_dg(res_state statp,
833 const u_char *buf, int buflen, u_char *ans, int anssiz,
834 int *terrno, int ns, int *v_circuit, int *gotsomewhere)
836 const HEADER *hp = (HEADER *) buf;
837 HEADER *anhp = (HEADER *) ans;
838 #ifdef _LIBC
839 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
840 #else
841 const struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
842 #endif
843 struct timespec now, timeout, finish;
844 #ifdef _LIBC
845 struct pollfd pfd[1];
846 int ptimeout;
847 struct sockaddr_in6 from;
848 static int socket_pf = 0;
849 #else
850 fd_set dsmask;
851 struct sockaddr_in from;
852 #endif
853 int fromlen, resplen, seconds, n, s;
855 if (EXT(statp).nssocks[ns] == -1) {
856 #ifdef _LIBC
857 /* only try IPv6 if IPv6 NS and if not failed before */
858 if ((EXT(statp).nscount6 > 0) && (socket_pf != PF_INET)) {
859 EXT(statp).nssocks[ns] =
860 socket(PF_INET6, SOCK_DGRAM, 0);
861 socket_pf = EXT(statp).nssocks[ns] < 0 ? PF_INET
862 : PF_INET6;
864 if (EXT(statp).nssocks[ns] < 0)
865 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
866 #else
867 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
868 if (EXT(statp).nssocks[ns] > highestFD) {
869 res_nclose(statp);
870 __set_errno (ENOTSOCK);
872 #endif
873 if (EXT(statp).nssocks[ns] < 0) {
874 *terrno = errno;
875 Perror(statp, stderr, "socket(dg)", errno);
876 return (-1);
878 #ifndef CANNOT_CONNECT_DGRAM
879 #ifdef _LIBC
880 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
881 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
882 convaddr4to6(nsap);
883 #endif
885 * On a 4.3BSD+ machine (client and server,
886 * actually), sending to a nameserver datagram
887 * port with no nameserver will cause an
888 * ICMP port unreachable message to be returned.
889 * If our datagram socket is "connected" to the
890 * server, we get an ECONNREFUSED error on the next
891 * socket operation, and select returns if the
892 * error message is received. We can thus detect
893 * the absence of a nameserver without timing out.
895 if (connect(EXT(statp).nssocks[ns], (struct sockaddr *)nsap,
896 sizeof *nsap) < 0) {
897 Aerror(statp, stderr, "connect(dg)", errno, *nsap);
898 res_nclose(statp);
899 return (0);
901 #endif /* !CANNOT_CONNECT_DGRAM */
902 Dprint(statp->options & RES_DEBUG,
903 (stdout, ";; new DG socket\n"))
905 s = EXT(statp).nssocks[ns];
906 #ifndef CANNOT_CONNECT_DGRAM
907 if (send(s, (char*)buf, buflen, 0) != buflen) {
908 Perror(statp, stderr, "send", errno);
909 res_nclose(statp);
910 return (0);
912 #else /* !CANNOT_CONNECT_DGRAM */
913 #ifdef _LIBC
914 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
915 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
916 convaddr4to6(nsap);
917 #endif
918 if (sendto(s, (char*)buf, buflen, 0,
919 (struct sockaddr *)nsap, sizeof *nsap) != buflen)
921 Aerror(statp, stderr, "sendto", errno, *nsap);
922 res_nclose(statp);
923 return (0);
925 #endif /* !CANNOT_CONNECT_DGRAM */
928 * Wait for reply.
930 seconds = (statp->retrans << ns);
931 if (ns > 0)
932 seconds /= statp->nscount;
933 if (seconds <= 0)
934 seconds = 1;
935 now = evNowTime();
936 timeout = evConsTime(seconds, 0);
937 finish = evAddTime(now, timeout);
938 wait:
939 #ifdef _LIBC
940 /* Convert struct timespec in milliseconds. */
941 ptimeout = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
943 pfd[0].fd = s;
944 pfd[0].events = POLLIN;
945 n = __poll (pfd, 1, ptimeout);
946 #else
947 FD_ZERO(&dsmask);
948 FD_SET(s, &dsmask);
949 n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
950 #endif
951 if (n == 0) {
952 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
953 *gotsomewhere = 1;
954 return (0);
956 if (n < 0) {
957 if (errno == EINTR) {
958 now = evNowTime();
959 if (evCmpTime(finish, now) > 0) {
960 timeout = evSubTime(finish, now);
961 goto wait;
964 Perror(statp, stderr, "select", errno);
965 res_nclose(statp);
966 return (0);
968 __set_errno (0);
969 #ifdef _LIBC
970 fromlen = sizeof(struct sockaddr_in6);
971 #else
972 fromlen = sizeof(struct sockaddr_in);
973 #endif
974 resplen = recvfrom(s, (char*)ans, anssiz,0,
975 (struct sockaddr *)&from, &fromlen);
976 if (resplen <= 0) {
977 Perror(statp, stderr, "recvfrom", errno);
978 res_nclose(statp);
979 return (0);
981 *gotsomewhere = 1;
982 if (resplen < HFIXEDSZ) {
984 * Undersized message.
986 Dprint(statp->options & RES_DEBUG,
987 (stdout, ";; undersized: %d\n",
988 resplen));
989 *terrno = EMSGSIZE;
990 res_nclose(statp);
991 return (0);
993 if (hp->id != anhp->id) {
995 * response from old query, ignore it.
996 * XXX - potential security hazard could
997 * be detected here.
999 DprintQ((statp->options & RES_DEBUG) ||
1000 (statp->pfcode & RES_PRF_REPLY),
1001 (stdout, ";; old answer:\n"),
1002 ans, (resplen > anssiz) ? anssiz : resplen);
1003 goto wait;
1005 if (!(statp->options & RES_INSECURE1) &&
1006 !res_ourserver_p(statp, &from)) {
1008 * response from wrong server? ignore it.
1009 * XXX - potential security hazard could
1010 * be detected here.
1012 DprintQ((statp->options & RES_DEBUG) ||
1013 (statp->pfcode & RES_PRF_REPLY),
1014 (stdout, ";; not our server:\n"),
1015 ans, (resplen > anssiz) ? anssiz : resplen);
1016 goto wait;
1018 if (!(statp->options & RES_INSECURE2) &&
1019 !res_queriesmatch(buf, buf + buflen,
1020 ans, ans + anssiz)) {
1022 * response contains wrong query? ignore it.
1023 * XXX - potential security hazard could
1024 * be detected here.
1026 DprintQ((statp->options & RES_DEBUG) ||
1027 (statp->pfcode & RES_PRF_REPLY),
1028 (stdout, ";; wrong query name:\n"),
1029 ans, (resplen > anssiz) ? anssiz : resplen);
1030 goto wait;
1032 if (anhp->rcode == SERVFAIL ||
1033 anhp->rcode == NOTIMP ||
1034 anhp->rcode == REFUSED) {
1035 DprintQ(statp->options & RES_DEBUG,
1036 (stdout, "server rejected query:\n"),
1037 ans, (resplen > anssiz) ? anssiz : resplen);
1038 res_nclose(statp);
1039 /* don't retry if called from dig */
1040 if (!statp->pfcode)
1041 return (0);
1043 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1045 * To get the rest of answer,
1046 * use TCP with same server.
1048 Dprint(statp->options & RES_DEBUG,
1049 (stdout, ";; truncated answer\n"));
1050 *v_circuit = 1;
1051 res_nclose(statp);
1052 return (1);
1055 * All is well, or the error is fatal. Signal that the
1056 * next nameserver ought not be tried.
1058 return (resplen);
1061 #ifdef DEBUG
1062 static void
1063 Aerror(const res_state statp, FILE *file, const char *string, int error,
1064 struct sockaddr_in address)
1066 int save = errno;
1068 if ((statp->options & RES_DEBUG) != 0) {
1069 char tmp[sizeof "255.255.255.255"];
1071 fprintf(file, "res_send: %s ([%s].%u): %s\n",
1072 string,
1073 inet_ntop(address.sin_family, &address.sin_addr,
1074 tmp, sizeof tmp),
1075 ntohs(address.sin_port),
1076 strerror(error));
1078 __set_errno (save);
1081 static void
1082 Perror(const res_state statp, FILE *file, const char *string, int error) {
1083 int save = errno;
1085 if ((statp->options & RES_DEBUG) != 0)
1086 fprintf(file, "res_send: %s: %s\n",
1087 string, strerror(error));
1088 __set_errno (save);
1090 #endif
1092 static int
1093 #ifdef _LIBC
1094 sock_eq(struct sockaddr_in6 *a1, struct sockaddr_in6 *a2) {
1095 if (a1->sin6_family == a2->sin6_family) {
1096 if (a1->sin6_family == AF_INET)
1097 return ((((struct sockaddr_in *)a1)->sin_port ==
1098 ((struct sockaddr_in *)a2)->sin_port) &&
1099 (((struct sockaddr_in *)a1)->sin_addr.s_addr ==
1100 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1101 else
1102 return ((a1->sin6_port == a2->sin6_port) &&
1103 !memcmp(&a1->sin6_addr, &a2->sin6_addr,
1104 sizeof (struct in6_addr)));
1106 if (a1->sin6_family == AF_INET) {
1107 struct sockaddr_in6 *sap = a1;
1108 a1 = a2;
1109 a2 = sap;
1110 } /* assumes that AF_INET and AF_INET6 are the only possibilities */
1111 return ((a1->sin6_port == ((struct sockaddr_in *)a2)->sin_port) &&
1112 IN6_IS_ADDR_V4MAPPED(&a1->sin6_addr) &&
1113 (a1->sin6_addr.s6_addr32[3] ==
1114 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1116 #else
1117 sock_eq(struct sockaddr_in *a1, struct sockaddr_in *a2) {
1118 return ((a1->sin_family == a2->sin_family) &&
1119 (a1->sin_port == a2->sin_port) &&
1120 (a1->sin_addr.s_addr == a2->sin_addr.s_addr));
1122 #endif
1124 #ifdef _LIBC
1126 * Converts IPv4 family, address and port to
1127 * IPv6 family, IPv4-mapped IPv6 address and port.
1129 static void
1130 convaddr4to6(struct sockaddr_in6 *sa)
1132 struct sockaddr_in *sa4p = (struct sockaddr_in *) sa;
1133 in_port_t port = sa4p->sin_port;
1134 in_addr_t addr = sa4p->sin_addr.s_addr;
1136 sa->sin6_family = AF_INET6;
1137 sa->sin6_port = port;
1138 sa->sin6_addr.s6_addr32[0] = 0;
1139 sa->sin6_addr.s6_addr32[1] = 0;
1140 sa->sin6_addr.s6_addr32[2] = htonl(0xFFFF);
1141 sa->sin6_addr.s6_addr32[3] = addr;
1143 #endif
1145 #ifdef NEED_PSELECT
1146 /* XXX needs to move to the porting library. */
1147 static int
1148 pselect(int nfds, void *rfds, void *wfds, void *efds,
1149 struct timespec *tsp, const sigset_t *sigmask)
1151 struct timeval tv, *tvp;
1152 sigset_t sigs;
1153 int n;
1155 if (tsp) {
1156 tvp = &tv;
1157 tv = evTimeVal(*tsp);
1158 } else
1159 tvp = NULL;
1160 if (sigmask)
1161 sigprocmask(SIG_SETMASK, sigmask, &sigs);
1162 n = select(nfds, rfds, wfds, efds, tvp);
1163 if (sigmask)
1164 sigprocmask(SIG_SETMASK, &sigs, NULL);
1165 if (tsp)
1166 *tsp = evTimeSpec(tv);
1167 return (n);
1169 #endif