Fix parameter name.
[glibc/pb-stable.git] / resolv / res_send.c
blobd237c9a537d2440d177d55902238695b003bb2d8
1 /*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
31 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
33 * Permission to use, copy, modify, and distribute this software for any
34 * purpose with or without fee is hereby granted, provided that the above
35 * copyright notice and this permission notice appear in all copies, and that
36 * the name of Digital Equipment Corporation not be used in advertising or
37 * publicity pertaining to distribution of the document or software without
38 * specific, written prior permission.
40 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
43 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47 * SOFTWARE.
51 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
53 * Permission to use, copy, modify, and distribute this software for any
54 * purpose with or without fee is hereby granted, provided that the above
55 * copyright notice and this permission notice appear in all copies.
57 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
58 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
60 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
61 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
62 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
63 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
64 * SOFTWARE.
67 #if defined(LIBC_SCCS) && !defined(lint)
68 static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
69 static const char rcsid[] = "$BINDId: res_send.c,v 8.38 2000/03/30 20:16:51 vixie Exp $";
70 #endif /* LIBC_SCCS and not lint */
73 * Send query to name server and wait for reply.
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #include <sys/time.h>
79 #include <sys/socket.h>
80 #include <sys/uio.h>
81 #ifdef _LIBC
82 #include <sys/poll.h>
83 #endif
85 #include <netinet/in.h>
86 #include <arpa/nameser.h>
87 #include <arpa/inet.h>
88 #include <sys/ioctl.h>
90 #include <errno.h>
91 #include <netdb.h>
92 #include <resolv.h>
93 #include <signal.h>
94 #include <stdio.h>
95 #include <stdlib.h>
96 #include <string.h>
97 #include <unistd.h>
99 #if PACKETSZ > 65536
100 #define MAXPACKET PACKETSZ
101 #else
102 #define MAXPACKET 65536
103 #endif
105 #ifndef _LIBC
106 #include <isc/eventlib.h>
107 #else
109 /* From ev_streams.c. */
111 static inline struct iovec
112 evConsIovec(void *buf, size_t cnt) {
113 struct iovec ret;
115 memset(&ret, 0xf5, sizeof ret);
116 ret.iov_base = buf;
117 ret.iov_len = cnt;
118 return (ret);
121 /* From ev_timers.c. */
123 #define BILLION 1000000000
125 static inline struct timespec
126 evTimeSpec(struct timeval tv) {
127 struct timespec ts;
129 ts.tv_sec = tv.tv_sec;
130 ts.tv_nsec = tv.tv_usec * 1000;
131 return (ts);
134 static inline struct timespec
135 evConsTime(time_t sec, long nsec) {
136 struct timespec x;
138 x.tv_sec = sec;
139 x.tv_nsec = nsec;
140 return (x);
143 static inline struct timespec
144 evAddTime(struct timespec addend1, struct timespec addend2) {
145 struct timespec x;
147 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
148 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
149 if (x.tv_nsec >= BILLION) {
150 x.tv_sec++;
151 x.tv_nsec -= BILLION;
153 return (x);
156 static inline struct timespec
157 evSubTime(struct timespec minuend, struct timespec subtrahend) {
158 struct timespec x;
160 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
161 if (minuend.tv_nsec >= subtrahend.tv_nsec)
162 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
163 else {
164 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
165 x.tv_sec--;
167 return (x);
170 static inline int
171 evCmpTime(struct timespec a, struct timespec b) {
172 long x = a.tv_sec - b.tv_sec;
174 if (x == 0L)
175 x = a.tv_nsec - b.tv_nsec;
176 return (x < 0L ? (-1) : x > 0L ? (1) : (0));
179 static inline struct timespec
180 evNowTime() {
181 struct timeval now;
183 if (gettimeofday(&now, NULL) < 0)
184 return (evConsTime(0, 0));
185 return (evTimeSpec(now));
188 #endif
190 /* Options. Leave them on. */
191 /* #undef DEBUG */
192 #include "res_debug.h"
194 #define EXT(res) ((res)->_u._ext)
196 #ifndef _LIBC
197 static const int highestFD = FD_SETSIZE - 1;
198 #endif
200 /* Forward. */
202 static int send_vc(res_state, const u_char *, int,
203 u_char **, int *, int *, int, u_char **);
204 static int send_dg(res_state, const u_char *, int,
205 u_char **, int *, int *, int,
206 int *, int *, u_char **);
207 #ifdef DEBUG
208 static void Aerror(const res_state, FILE *, const char *, int,
209 struct sockaddr_in);
210 static void Perror(const res_state, FILE *, const char *, int);
211 #endif
212 #ifdef _LIBC
213 static int sock_eq(struct sockaddr_in6 *, struct sockaddr_in6 *);
214 #else
215 static int sock_eq(struct sockaddr_in *, struct sockaddr_in *);
216 #endif
217 #ifdef NEED_PSELECT
218 static int pselect(int, void *, void *, void *,
219 struct timespec *,
220 const sigset_t *);
221 #endif
223 /* Reachover. */
225 #ifdef _LIBC
226 static void convaddr4to6(struct sockaddr_in6 *sa);
227 #endif
228 void res_pquery(const res_state, const u_char *, int, FILE *);
230 /* Public. */
232 /* int
233 * res_isourserver(ina)
234 * looks up "ina" in _res.ns_addr_list[]
235 * returns:
236 * 0 : not found
237 * >0 : found
238 * author:
239 * paul vixie, 29may94
242 #ifdef _LIBC
243 res_ourserver_p(const res_state statp, const struct sockaddr_in6 *inp)
244 #else
245 res_ourserver_p(const res_state statp, const struct sockaddr_in *inp)
246 #endif
248 int ns;
250 #ifdef _LIBC
251 if (inp->sin6_family == AF_INET) {
252 struct sockaddr_in *in4p = (struct sockaddr_in *) inp;
253 in_port_t port = in4p->sin_port;
254 in_addr_t addr = in4p->sin_addr.s_addr;
256 for (ns = 0; ns < MAXNS; ns++) {
257 const struct sockaddr_in *srv =
258 (struct sockaddr_in *)EXT(statp).nsaddrs[ns];
260 if ((srv != NULL) && (srv->sin_family == AF_INET) &&
261 (srv->sin_port == port) &&
262 (srv->sin_addr.s_addr == INADDR_ANY ||
263 srv->sin_addr.s_addr == addr))
264 return (1);
266 } else if (inp->sin6_family == AF_INET6) {
267 for (ns = 0; ns < MAXNS; ns++) {
268 const struct sockaddr_in6 *srv = EXT(statp).nsaddrs[ns];
269 if ((srv != NULL) && (srv->sin6_family == AF_INET6) &&
270 (srv->sin6_port == inp->sin6_port) &&
271 !(memcmp(&srv->sin6_addr, &in6addr_any,
272 sizeof (struct in6_addr)) &&
273 memcmp(&srv->sin6_addr, &inp->sin6_addr,
274 sizeof (struct in6_addr))))
275 return (1);
278 #else
279 struct sockaddr_in ina = *inp;
280 for (ns = 0; ns < statp->nscount; ns++) {
281 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
283 if (srv->sin_family == ina.sin_family &&
284 srv->sin_port == ina.sin_port &&
285 (srv->sin_addr.s_addr == INADDR_ANY ||
286 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
287 return (1);
289 #endif
290 return (0);
293 /* int
294 * res_nameinquery(name, type, class, buf, eom)
295 * look for (name,type,class) in the query section of packet (buf,eom)
296 * requires:
297 * buf + HFIXEDSZ <= eom
298 * returns:
299 * -1 : format error
300 * 0 : not found
301 * >0 : found
302 * author:
303 * paul vixie, 29may94
306 res_nameinquery(const char *name, int type, int class,
307 const u_char *buf, const u_char *eom)
309 const u_char *cp = buf + HFIXEDSZ;
310 int qdcount = ntohs(((HEADER*)buf)->qdcount);
312 while (qdcount-- > 0) {
313 char tname[MAXDNAME+1];
314 int n, ttype, tclass;
316 n = dn_expand(buf, eom, cp, tname, sizeof tname);
317 if (n < 0)
318 return (-1);
319 cp += n;
320 if (cp + 2 * INT16SZ > eom)
321 return (-1);
322 ttype = ns_get16(cp); cp += INT16SZ;
323 tclass = ns_get16(cp); cp += INT16SZ;
324 if (ttype == type && tclass == class &&
325 ns_samename(tname, name) == 1)
326 return (1);
328 return (0);
331 /* int
332 * res_queriesmatch(buf1, eom1, buf2, eom2)
333 * is there a 1:1 mapping of (name,type,class)
334 * in (buf1,eom1) and (buf2,eom2)?
335 * returns:
336 * -1 : format error
337 * 0 : not a 1:1 mapping
338 * >0 : is a 1:1 mapping
339 * author:
340 * paul vixie, 29may94
343 res_queriesmatch(const u_char *buf1, const u_char *eom1,
344 const u_char *buf2, const u_char *eom2)
346 const u_char *cp = buf1 + HFIXEDSZ;
347 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
349 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
350 return (-1);
353 * Only header section present in replies to
354 * dynamic update packets.
356 if ((((HEADER *)buf1)->opcode == ns_o_update) &&
357 (((HEADER *)buf2)->opcode == ns_o_update))
358 return (1);
360 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
361 return (0);
362 while (qdcount-- > 0) {
363 char tname[MAXDNAME+1];
364 int n, ttype, tclass;
366 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
367 if (n < 0)
368 return (-1);
369 cp += n;
370 if (cp + 2 * INT16SZ > eom1)
371 return (-1);
372 ttype = ns_get16(cp); cp += INT16SZ;
373 tclass = ns_get16(cp); cp += INT16SZ;
374 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
375 return (0);
377 return (1);
381 __libc_res_nsend(res_state statp, const u_char *buf, int buflen,
382 u_char *ans, int anssiz, u_char **ansp)
384 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
386 if (statp->nscount == 0) {
387 __set_errno (ESRCH);
388 return (-1);
391 if (anssiz < HFIXEDSZ) {
392 __set_errno (EINVAL);
393 return (-1);
396 if ((statp->qhook || statp->rhook) && anssiz < MAXPACKET && ansp) {
397 u_char *buf = malloc (MAXPACKET);
398 if (buf == NULL)
399 return (-1);
400 memcpy (buf, ans, HFIXEDSZ);
401 *ansp = buf;
402 ans = buf;
403 anssiz = MAXPACKET;
406 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
407 (stdout, ";; res_send()\n"), buf, buflen);
408 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
409 gotsomewhere = 0;
410 terrno = ETIMEDOUT;
413 * If the ns_addr_list in the resolver context has changed, then
414 * invalidate our cached copy and the associated timing data.
416 if (EXT(statp).nsinit) {
417 int needclose = 0;
419 if (EXT(statp).nscount != statp->nscount)
420 needclose++;
421 else
422 #ifdef _LIBC
423 for (ns = 0; ns < MAXNS; ns++) {
424 unsigned int map = EXT(statp).nsmap[ns];
425 if (map < MAXNS
426 && !sock_eq((struct sockaddr_in6 *)
427 &statp->nsaddr_list[map],
428 EXT(statp).nsaddrs[ns]))
429 #else
430 for (ns = 0; ns < statp->nscount; ns++) {
431 if (!sock_eq(&statp->nsaddr_list[ns],
432 &EXT(statp).nsaddrs[ns]))
433 #endif
435 needclose++;
436 break;
439 if (needclose)
440 res_nclose(statp);
444 * Maybe initialize our private copy of the ns_addr_list.
446 if (EXT(statp).nsinit == 0) {
447 #ifdef _LIBC
448 unsigned char map[MAXNS];
450 memset (map, MAXNS, sizeof (map));
451 for (n = 0; n < MAXNS; n++) {
452 ns = EXT(statp).nsmap[n];
453 if (ns < statp->nscount)
454 map[ns] = n;
455 else if (ns < MAXNS) {
456 free(EXT(statp).nsaddrs[n]);
457 EXT(statp).nsaddrs[n] = NULL;
458 EXT(statp).nsmap[n] = MAXNS;
461 n = statp->nscount;
462 if (statp->nscount > EXT(statp).nscount)
463 for (n = EXT(statp).nscount, ns = 0;
464 n < statp->nscount; n++) {
465 while (ns < MAXNS
466 && EXT(statp).nsmap[ns] != MAXNS)
467 ns++;
468 if (ns == MAXNS)
469 break;
470 EXT(statp).nsmap[ns] = n;
471 map[n] = ns++;
473 EXT(statp).nscount = n;
474 for (ns = 0; ns < EXT(statp).nscount; ns++) {
475 n = map[ns];
476 if (EXT(statp).nsaddrs[n] == NULL)
477 EXT(statp).nsaddrs[n] =
478 malloc(sizeof (struct sockaddr_in6));
479 if (EXT(statp).nsaddrs[n] != NULL) {
480 memcpy(EXT(statp).nsaddrs[n],
481 &statp->nsaddr_list[ns],
482 sizeof (struct sockaddr_in));
483 EXT(statp).nssocks[n] = -1;
484 n++;
487 #else
488 for (ns = 0; ns < statp->nscount; ns++) {
489 EXT(statp).nsaddrs[ns] = statp->nsaddr_list[ns];
490 EXT(statp).nssocks[ns] = -1;
492 EXT(statp).nscount = ns;
493 #endif
494 EXT(statp).nsinit = 1;
498 * Some resolvers want to even out the load on their nameservers.
499 * Note that RES_BLAST overrides RES_ROTATE.
501 if ((statp->options & RES_ROTATE) != 0 &&
502 (statp->options & RES_BLAST) == 0) {
503 #ifdef _LIBC
504 struct sockaddr_in6 *ina;
505 unsigned int map;
507 n = 0;
508 while (n < MAXNS && EXT(statp).nsmap[n] == MAXNS)
509 n++;
510 if (n < MAXNS) {
511 ina = EXT(statp).nsaddrs[n];
512 map = EXT(statp).nsmap[n];
513 for (;;) {
514 ns = n + 1;
515 while (ns < MAXNS
516 && EXT(statp).nsmap[ns] == MAXNS)
517 ns++;
518 if (ns == MAXNS)
519 break;
520 EXT(statp).nsaddrs[n] = EXT(statp).nsaddrs[ns];
521 EXT(statp).nsmap[n] = EXT(statp).nsmap[ns];
522 n = ns;
524 EXT(statp).nsaddrs[n] = ina;
525 EXT(statp).nsmap[n] = map;
527 #else
528 struct sockaddr_in ina;
529 int lastns = statp->nscount - 1;
531 ina = statp->nsaddr_list[0];
532 for (ns = 0; ns < lastns; ns++)
533 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
534 statp->nsaddr_list[lastns] = ina;
535 #endif
539 * Send request, RETRY times, or until successful.
541 for (try = 0; try < statp->retry; try++) {
542 #ifdef _LIBC
543 for (ns = 0; ns < MAXNS; ns++)
544 #else
545 for (ns = 0; ns < statp->nscount; ns++)
546 #endif
548 #ifdef _LIBC
549 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
551 if (nsap == NULL)
552 goto next_ns;
553 #else
554 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
555 #endif
556 same_ns:
557 if (statp->qhook) {
558 int done = 0, loops = 0;
560 do {
561 res_sendhookact act;
563 #ifdef _LIBC
564 act = (*statp->qhook)((struct sockaddr_in **)
565 &nsap, &buf, &buflen,
566 ans, anssiz, &resplen);
567 #else
568 act = (*statp->qhook)(&nsap, &buf, &buflen,
569 ans, anssiz, &resplen);
570 #endif
571 switch (act) {
572 case res_goahead:
573 done = 1;
574 break;
575 case res_nextns:
576 res_nclose(statp);
577 goto next_ns;
578 case res_done:
579 return (resplen);
580 case res_modified:
581 /* give the hook another try */
582 if (++loops < 42) /*doug adams*/
583 break;
584 /*FALLTHROUGH*/
585 case res_error:
586 /*FALLTHROUGH*/
587 default:
588 return (-1);
590 } while (!done);
593 Dprint(statp->options & RES_DEBUG,
594 (stdout, ";; Querying server (# %d) address = %s\n",
595 ns + 1, inet_ntoa(nsap->sin_addr)));
597 if (v_circuit) {
598 /* Use VC; at most one attempt per server. */
599 try = statp->retry;
600 n = send_vc(statp, buf, buflen, &ans, &anssiz, &terrno,
601 ns, ansp);
602 if (n < 0)
603 return (-1);
604 if (n == 0)
605 goto next_ns;
606 resplen = n;
607 } else {
608 /* Use datagrams. */
609 n = send_dg(statp, buf, buflen, &ans, &anssiz, &terrno,
610 ns, &v_circuit, &gotsomewhere, ansp);
611 if (n < 0)
612 return (-1);
613 if (n == 0)
614 goto next_ns;
615 if (v_circuit)
616 goto same_ns;
617 resplen = n;
620 Dprint((statp->options & RES_DEBUG) ||
621 ((statp->pfcode & RES_PRF_REPLY) &&
622 (statp->pfcode & RES_PRF_HEAD1)),
623 (stdout, ";; got answer:\n"));
625 DprintQ((statp->options & RES_DEBUG) ||
626 (statp->pfcode & RES_PRF_REPLY),
627 (stdout, ""),
628 ans, (resplen > anssiz) ? anssiz : resplen);
631 * If we have temporarily opened a virtual circuit,
632 * or if we haven't been asked to keep a socket open,
633 * close the socket.
635 if ((v_circuit && (statp->options & RES_USEVC) == 0) ||
636 (statp->options & RES_STAYOPEN) == 0) {
637 res_nclose(statp);
639 if (statp->rhook) {
640 int done = 0, loops = 0;
642 do {
643 res_sendhookact act;
645 #ifdef _LIBC
646 act = (*statp->rhook)((struct sockaddr_in *)
647 nsap, buf, buflen,
648 ans, anssiz, &resplen);
649 #else
650 act = (*statp->rhook)(nsap, buf, buflen,
651 ans, anssiz, &resplen);
652 #endif
653 switch (act) {
654 case res_goahead:
655 case res_done:
656 done = 1;
657 break;
658 case res_nextns:
659 res_nclose(statp);
660 goto next_ns;
661 case res_modified:
662 /* give the hook another try */
663 if (++loops < 42) /*doug adams*/
664 break;
665 /*FALLTHROUGH*/
666 case res_error:
667 /*FALLTHROUGH*/
668 default:
669 return (-1);
671 } while (!done);
674 return (resplen);
675 next_ns: ;
676 } /*foreach ns*/
677 } /*foreach retry*/
678 res_nclose(statp);
679 if (!v_circuit) {
680 if (!gotsomewhere)
681 __set_errno (ECONNREFUSED); /* no nameservers found */
682 else
683 __set_errno (ETIMEDOUT); /* no answer obtained */
684 } else
685 __set_errno (terrno);
686 return (-1);
690 res_nsend(res_state statp,
691 const u_char *buf, int buflen, u_char *ans, int anssiz)
693 return __libc_res_nsend(statp, buf, buflen, ans, anssiz, NULL);
696 /* Private */
698 static int
699 send_vc(res_state statp,
700 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
701 int *terrno, int ns, u_char **anscp)
703 const HEADER *hp = (HEADER *) buf;
704 u_char *ans = *ansp;
705 int anssiz = *anssizp;
706 HEADER *anhp = (HEADER *) ans;
707 #ifdef _LIBC
708 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
709 #else
710 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
711 #endif
712 int truncating, connreset, resplen, n;
713 struct iovec iov[2];
714 u_short len;
715 u_char *cp;
717 connreset = 0;
718 same_ns:
719 truncating = 0;
721 /* Are we still talking to whom we want to talk to? */
722 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
723 #ifdef _LIBC
724 struct sockaddr_in6 peer;
725 #else
726 struct sockaddr_in peer;
727 #endif
728 int size = sizeof peer;
730 if (getpeername(statp->_vcsock,
731 (struct sockaddr *)&peer, &size) < 0 ||
732 !sock_eq(&peer, nsap)) {
733 res_nclose(statp);
734 statp->_flags &= ~RES_F_VC;
738 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
739 if (statp->_vcsock >= 0)
740 res_nclose(statp);
742 #ifdef _LIBC
743 statp->_vcsock = socket(nsap->sin6_family, SOCK_STREAM, 0);
744 #else
745 statp->_vcsock = socket(PF_INET, SOCK_STREAM, 0);
746 if (statp->_vcsock > highestFD) {
747 res_nclose(statp);
748 __set_errno (ENOTSOCK);
750 #endif
751 if (statp->_vcsock < 0) {
752 *terrno = errno;
753 Perror(statp, stderr, "socket(vc)", errno);
754 return (-1);
756 __set_errno (0);
757 if (connect(statp->_vcsock, (struct sockaddr *)nsap,
758 sizeof *nsap) < 0) {
759 *terrno = errno;
760 Aerror(statp, stderr, "connect/vc", errno, *nsap);
761 res_nclose(statp);
762 return (0);
764 statp->_flags |= RES_F_VC;
768 * Send length & message
770 putshort((u_short)buflen, (u_char*)&len);
771 iov[0] = evConsIovec(&len, INT16SZ);
772 iov[1] = evConsIovec((void*)buf, buflen);
773 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
774 *terrno = errno;
775 Perror(statp, stderr, "write failed", errno);
776 res_nclose(statp);
777 return (0);
780 * Receive length & response
782 read_len:
783 cp = ans;
784 len = INT16SZ;
785 while ((n = read(statp->_vcsock, (char *)cp, (int)len)) > 0) {
786 cp += n;
787 if ((len -= n) <= 0)
788 break;
790 if (n <= 0) {
791 *terrno = errno;
792 Perror(statp, stderr, "read failed", errno);
793 res_nclose(statp);
795 * A long running process might get its TCP
796 * connection reset if the remote server was
797 * restarted. Requery the server instead of
798 * trying a new one. When there is only one
799 * server, this means that a query might work
800 * instead of failing. We only allow one reset
801 * per query to prevent looping.
803 if (*terrno == ECONNRESET && !connreset) {
804 connreset = 1;
805 res_nclose(statp);
806 goto same_ns;
808 res_nclose(statp);
809 return (0);
811 resplen = ns_get16(ans);
812 if (resplen > anssiz) {
813 if (anscp) {
814 ans = malloc (MAXPACKET);
815 if (ans == NULL) {
816 *terrno = ENOMEM;
817 res_nclose(statp);
818 return (0);
820 anssiz = MAXPACKET;
821 *anssizp = MAXPACKET;
822 *ansp = ans;
823 *anscp = ans;
824 anhp = (HEADER *) ans;
825 len = resplen;
826 } else {
827 Dprint(statp->options & RES_DEBUG,
828 (stdout, ";; response truncated\n")
830 truncating = 1;
831 len = anssiz;
833 } else
834 len = resplen;
835 if (len < HFIXEDSZ) {
837 * Undersized message.
839 Dprint(statp->options & RES_DEBUG,
840 (stdout, ";; undersized: %d\n", len));
841 *terrno = EMSGSIZE;
842 res_nclose(statp);
843 return (0);
845 cp = ans;
846 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
847 cp += n;
848 len -= n;
850 if (n <= 0) {
851 *terrno = errno;
852 Perror(statp, stderr, "read(vc)", errno);
853 res_nclose(statp);
854 return (0);
856 if (truncating) {
858 * Flush rest of answer so connection stays in synch.
860 anhp->tc = 1;
861 len = resplen - anssiz;
862 while (len != 0) {
863 char junk[PACKETSZ];
865 n = read(statp->_vcsock, junk,
866 (len > sizeof junk) ? sizeof junk : len);
867 if (n > 0)
868 len -= n;
869 else
870 break;
874 * If the calling applicating has bailed out of
875 * a previous call and failed to arrange to have
876 * the circuit closed or the server has got
877 * itself confused, then drop the packet and
878 * wait for the correct one.
880 if (hp->id != anhp->id) {
881 DprintQ((statp->options & RES_DEBUG) ||
882 (statp->pfcode & RES_PRF_REPLY),
883 (stdout, ";; old answer (unexpected):\n"),
884 ans, (resplen > anssiz) ? anssiz: resplen);
885 goto read_len;
889 * All is well, or the error is fatal. Signal that the
890 * next nameserver ought not be tried.
892 return (resplen);
895 static int
896 send_dg(res_state statp,
897 const u_char *buf, int buflen, u_char **ansp, int *anssizp,
898 int *terrno, int ns, int *v_circuit, int *gotsomewhere, u_char **anscp)
900 const HEADER *hp = (HEADER *) buf;
901 u_char *ans = *ansp;
902 int anssiz = *anssizp;
903 HEADER *anhp = (HEADER *) ans;
904 #ifdef _LIBC
905 struct sockaddr_in6 *nsap = EXT(statp).nsaddrs[ns];
906 #else
907 const struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
908 #endif
909 struct timespec now, timeout, finish;
910 #ifdef _LIBC
911 struct pollfd pfd[1];
912 int ptimeout;
913 struct sockaddr_in6 from;
914 static int socket_pf = 0;
915 #else
916 fd_set dsmask;
917 struct sockaddr_in from;
918 #endif
919 int fromlen, resplen, seconds, n, s;
921 if (EXT(statp).nssocks[ns] == -1) {
922 #ifdef _LIBC
923 /* only try IPv6 if IPv6 NS and if not failed before */
924 if ((EXT(statp).nscount6 > 0) && (socket_pf != PF_INET)) {
925 EXT(statp).nssocks[ns] =
926 socket(PF_INET6, SOCK_DGRAM, 0);
927 socket_pf = EXT(statp).nssocks[ns] < 0 ? PF_INET
928 : PF_INET6;
930 if (EXT(statp).nssocks[ns] < 0)
931 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
932 #else
933 EXT(statp).nssocks[ns] = socket(PF_INET, SOCK_DGRAM, 0);
934 if (EXT(statp).nssocks[ns] > highestFD) {
935 res_nclose(statp);
936 __set_errno (ENOTSOCK);
938 #endif
939 if (EXT(statp).nssocks[ns] < 0) {
940 *terrno = errno;
941 Perror(statp, stderr, "socket(dg)", errno);
942 return (-1);
944 #ifndef CANNOT_CONNECT_DGRAM
945 #ifdef _LIBC
946 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
947 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
948 convaddr4to6(nsap);
949 #endif
951 * On a 4.3BSD+ machine (client and server,
952 * actually), sending to a nameserver datagram
953 * port with no nameserver will cause an
954 * ICMP port unreachable message to be returned.
955 * If our datagram socket is "connected" to the
956 * server, we get an ECONNREFUSED error on the next
957 * socket operation, and select returns if the
958 * error message is received. We can thus detect
959 * the absence of a nameserver without timing out.
961 if (connect(EXT(statp).nssocks[ns], (struct sockaddr *)nsap,
962 sizeof *nsap) < 0) {
963 Aerror(statp, stderr, "connect(dg)", errno, *nsap);
964 res_nclose(statp);
965 return (0);
967 #endif /* !CANNOT_CONNECT_DGRAM */
968 Dprint(statp->options & RES_DEBUG,
969 (stdout, ";; new DG socket\n"))
971 s = EXT(statp).nssocks[ns];
972 #ifndef CANNOT_CONNECT_DGRAM
973 if (send(s, (char*)buf, buflen, 0) != buflen) {
974 Perror(statp, stderr, "send", errno);
975 res_nclose(statp);
976 return (0);
978 #else /* !CANNOT_CONNECT_DGRAM */
979 #ifdef _LIBC
980 /* If IPv6 socket and nsap is IPv4, make it IPv4-mapped */
981 if ((socket_pf == PF_INET6) && (nsap->sin6_family == AF_INET))
982 convaddr4to6(nsap);
983 #endif
984 if (sendto(s, (char*)buf, buflen, 0,
985 (struct sockaddr *)nsap, sizeof *nsap) != buflen)
987 Aerror(statp, stderr, "sendto", errno, *nsap);
988 res_nclose(statp);
989 return (0);
991 #endif /* !CANNOT_CONNECT_DGRAM */
994 * Wait for reply.
996 seconds = (statp->retrans << ns);
997 if (ns > 0)
998 seconds /= statp->nscount;
999 if (seconds <= 0)
1000 seconds = 1;
1001 now = evNowTime();
1002 timeout = evConsTime(seconds, 0);
1003 finish = evAddTime(now, timeout);
1004 wait:
1005 #ifdef _LIBC
1006 /* Convert struct timespec in milliseconds. */
1007 ptimeout = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
1009 pfd[0].fd = s;
1010 pfd[0].events = POLLIN;
1011 n = __poll (pfd, 1, ptimeout);
1012 #else
1013 FD_ZERO(&dsmask);
1014 FD_SET(s, &dsmask);
1015 n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
1016 #endif
1017 if (n == 0) {
1018 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1019 *gotsomewhere = 1;
1020 return (0);
1022 if (n < 0) {
1023 if (errno == EINTR) {
1024 now = evNowTime();
1025 if (evCmpTime(finish, now) > 0) {
1026 timeout = evSubTime(finish, now);
1027 goto wait;
1030 Perror(statp, stderr, "select", errno);
1031 res_nclose(statp);
1032 return (0);
1034 __set_errno (0);
1035 #ifdef _LIBC
1036 fromlen = sizeof(struct sockaddr_in6);
1037 #else
1038 fromlen = sizeof(struct sockaddr_in);
1039 #endif
1040 if (anssiz < MAXPACKET
1041 && anscp
1042 && (ioctl (s, FIONREAD, &resplen) < 0
1043 || anssiz < resplen)) {
1044 ans = malloc (MAXPACKET);
1045 if (ans == NULL)
1046 ans = *ansp;
1047 else {
1048 anssiz = MAXPACKET;
1049 *anssizp = MAXPACKET;
1050 *ansp = ans;
1051 *anscp = ans;
1052 anhp = (HEADER *) ans;
1055 resplen = recvfrom(s, (char*)ans, anssiz,0,
1056 (struct sockaddr *)&from, &fromlen);
1057 if (resplen <= 0) {
1058 Perror(statp, stderr, "recvfrom", errno);
1059 res_nclose(statp);
1060 return (0);
1062 *gotsomewhere = 1;
1063 if (resplen < HFIXEDSZ) {
1065 * Undersized message.
1067 Dprint(statp->options & RES_DEBUG,
1068 (stdout, ";; undersized: %d\n",
1069 resplen));
1070 *terrno = EMSGSIZE;
1071 res_nclose(statp);
1072 return (0);
1074 if (hp->id != anhp->id) {
1076 * response from old query, ignore it.
1077 * XXX - potential security hazard could
1078 * be detected here.
1080 DprintQ((statp->options & RES_DEBUG) ||
1081 (statp->pfcode & RES_PRF_REPLY),
1082 (stdout, ";; old answer:\n"),
1083 ans, (resplen > anssiz) ? anssiz : resplen);
1084 goto wait;
1086 if (!(statp->options & RES_INSECURE1) &&
1087 !res_ourserver_p(statp, &from)) {
1089 * response from wrong server? ignore it.
1090 * XXX - potential security hazard could
1091 * be detected here.
1093 DprintQ((statp->options & RES_DEBUG) ||
1094 (statp->pfcode & RES_PRF_REPLY),
1095 (stdout, ";; not our server:\n"),
1096 ans, (resplen > anssiz) ? anssiz : resplen);
1097 goto wait;
1099 if (!(statp->options & RES_INSECURE2) &&
1100 !res_queriesmatch(buf, buf + buflen,
1101 ans, ans + anssiz)) {
1103 * response contains wrong query? ignore it.
1104 * XXX - potential security hazard could
1105 * be detected here.
1107 DprintQ((statp->options & RES_DEBUG) ||
1108 (statp->pfcode & RES_PRF_REPLY),
1109 (stdout, ";; wrong query name:\n"),
1110 ans, (resplen > anssiz) ? anssiz : resplen);
1111 goto wait;
1113 if (anhp->rcode == SERVFAIL ||
1114 anhp->rcode == NOTIMP ||
1115 anhp->rcode == REFUSED) {
1116 DprintQ(statp->options & RES_DEBUG,
1117 (stdout, "server rejected query:\n"),
1118 ans, (resplen > anssiz) ? anssiz : resplen);
1119 res_nclose(statp);
1120 /* don't retry if called from dig */
1121 if (!statp->pfcode)
1122 return (0);
1124 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1126 * To get the rest of answer,
1127 * use TCP with same server.
1129 Dprint(statp->options & RES_DEBUG,
1130 (stdout, ";; truncated answer\n"));
1131 *v_circuit = 1;
1132 res_nclose(statp);
1133 return (1);
1136 * All is well, or the error is fatal. Signal that the
1137 * next nameserver ought not be tried.
1139 return (resplen);
1142 #ifdef DEBUG
1143 static void
1144 Aerror(const res_state statp, FILE *file, const char *string, int error,
1145 struct sockaddr_in address)
1147 int save = errno;
1149 if ((statp->options & RES_DEBUG) != 0) {
1150 char tmp[sizeof "255.255.255.255"];
1152 fprintf(file, "res_send: %s ([%s].%u): %s\n",
1153 string,
1154 inet_ntop(address.sin_family, &address.sin_addr,
1155 tmp, sizeof tmp),
1156 ntohs(address.sin_port),
1157 strerror(error));
1159 __set_errno (save);
1162 static void
1163 Perror(const res_state statp, FILE *file, const char *string, int error) {
1164 int save = errno;
1166 if ((statp->options & RES_DEBUG) != 0)
1167 fprintf(file, "res_send: %s: %s\n",
1168 string, strerror(error));
1169 __set_errno (save);
1171 #endif
1173 static int
1174 #ifdef _LIBC
1175 sock_eq(struct sockaddr_in6 *a1, struct sockaddr_in6 *a2) {
1176 if (a1->sin6_family == a2->sin6_family) {
1177 if (a1->sin6_family == AF_INET)
1178 return ((((struct sockaddr_in *)a1)->sin_port ==
1179 ((struct sockaddr_in *)a2)->sin_port) &&
1180 (((struct sockaddr_in *)a1)->sin_addr.s_addr ==
1181 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1182 else
1183 return ((a1->sin6_port == a2->sin6_port) &&
1184 !memcmp(&a1->sin6_addr, &a2->sin6_addr,
1185 sizeof (struct in6_addr)));
1187 if (a1->sin6_family == AF_INET) {
1188 struct sockaddr_in6 *sap = a1;
1189 a1 = a2;
1190 a2 = sap;
1191 } /* assumes that AF_INET and AF_INET6 are the only possibilities */
1192 return ((a1->sin6_port == ((struct sockaddr_in *)a2)->sin_port) &&
1193 IN6_IS_ADDR_V4MAPPED(&a1->sin6_addr) &&
1194 (a1->sin6_addr.s6_addr32[3] ==
1195 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1197 #else
1198 sock_eq(struct sockaddr_in *a1, struct sockaddr_in *a2) {
1199 return ((a1->sin_family == a2->sin_family) &&
1200 (a1->sin_port == a2->sin_port) &&
1201 (a1->sin_addr.s_addr == a2->sin_addr.s_addr));
1203 #endif
1205 #ifdef _LIBC
1207 * Converts IPv4 family, address and port to
1208 * IPv6 family, IPv4-mapped IPv6 address and port.
1210 static void
1211 convaddr4to6(struct sockaddr_in6 *sa)
1213 struct sockaddr_in *sa4p = (struct sockaddr_in *) sa;
1214 in_port_t port = sa4p->sin_port;
1215 in_addr_t addr = sa4p->sin_addr.s_addr;
1217 sa->sin6_family = AF_INET6;
1218 sa->sin6_port = port;
1219 sa->sin6_addr.s6_addr32[0] = 0;
1220 sa->sin6_addr.s6_addr32[1] = 0;
1221 sa->sin6_addr.s6_addr32[2] = htonl(0xFFFF);
1222 sa->sin6_addr.s6_addr32[3] = addr;
1224 #endif
1226 #ifdef NEED_PSELECT
1227 /* XXX needs to move to the porting library. */
1228 static int
1229 pselect(int nfds, void *rfds, void *wfds, void *efds,
1230 struct timespec *tsp, const sigset_t *sigmask)
1232 struct timeval tv, *tvp;
1233 sigset_t sigs;
1234 int n;
1236 if (tsp) {
1237 tvp = &tv;
1238 tv = evTimeVal(*tsp);
1239 } else
1240 tvp = NULL;
1241 if (sigmask)
1242 sigprocmask(SIG_SETMASK, sigmask, &sigs);
1243 n = select(nfds, rfds, wfds, efds, tvp);
1244 if (sigmask)
1245 sigprocmask(SIG_SETMASK, &sigs, NULL);
1246 if (tsp)
1247 *tsp = evTimeSpec(tv);
1248 return (n);
1250 #endif