Correction.
[glibc.git] / resolv / res_send.c
blobbf8158aa528f547b74b65d8235ab38e1eeca5c65
1 /*
2 * ++Copyright++ 1985, 1989, 1993
3 * -
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 * -
35 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
37 * Permission to use, copy, modify, and distribute this software for any
38 * purpose with or without fee is hereby granted, provided that the above
39 * copyright notice and this permission notice appear in all copies, and that
40 * the name of Digital Equipment Corporation not be used in advertising or
41 * publicity pertaining to distribution of the document or software without
42 * specific, written prior permission.
44 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
45 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
46 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
47 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
48 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
49 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
50 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
51 * SOFTWARE.
52 * -
53 * --Copyright--
56 #if defined(LIBC_SCCS) && !defined(lint)
57 static char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
58 static char rcsid[] = "$Id$";
59 #endif /* LIBC_SCCS and not lint */
61 /* change this to "0"
62 * if you talk to a lot
63 * of multi-homed SunOS
64 * ("broken") name servers.
66 #define CHECK_SRVR_ADDR 1 /* XXX - should be in options.h */
69 * Send query to name server and wait for reply.
72 #include <sys/param.h>
73 #include <sys/time.h>
74 #include <sys/socket.h>
75 #include <sys/uio.h>
76 #include <netinet/in.h>
77 #include <arpa/nameser.h>
78 #include <arpa/inet.h>
80 #include <stdio.h>
81 #include <netdb.h>
82 #include <errno.h>
83 #include <resolv.h>
84 #if defined(BSD) && (BSD >= 199306)
85 # include <stdlib.h>
86 # include <string.h>
87 # include <unistd.h>
88 #else
89 # include "../conf/portability.h"
90 #endif
92 #if defined(USE_OPTIONS_H)
93 # include <../conf/options.h>
94 #endif
96 void _res_close __P((void));
98 static int s = -1; /* socket used for communications */
99 static int connected = 0; /* is the socket connected */
100 static int vc = 0; /* is the socket a virtual ciruit? */
102 #ifndef FD_SET
103 /* XXX - should be in portability.h */
104 #define NFDBITS 32
105 #define FD_SETSIZE 32
106 #define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
107 #define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
108 #define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
109 #define FD_ZERO(p) bzero((char *)(p), sizeof(*(p)))
110 #endif
112 /* XXX - this should be done in portability.h */
113 #if (defined(BSD) && (BSD >= 199103)) || defined(linux)
114 # define CAN_RECONNECT 1
115 #else
116 # define CAN_RECONNECT 0
117 #endif
119 #ifndef DEBUG
120 # define Dprint(cond, args) /*empty*/
121 # define DprintQ(cond, args, query, size) /*empty*/
122 # define Aerror(file, string, error, address) /*empty*/
123 # define Perror(file, string, error) /*empty*/
124 #else
125 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
126 # define DprintQ(cond, args, query, size) if (cond) {\
127 fprintf args;\
128 __fp_nquery(query, size, stdout);\
129 } else {}
130 static void
131 Aerror(file, string, error, address)
132 FILE *file;
133 char *string;
134 int error;
135 struct sockaddr_in address;
137 int save = errno;
139 if (_res.options & RES_DEBUG) {
140 fprintf(file, "res_send: %s ([%s].%u): %s\n",
141 string,
142 inet_ntoa(address.sin_addr),
143 ntohs(address.sin_port),
144 strerror(error));
146 errno = save;
148 static void
149 Perror(file, string, error)
150 FILE *file;
151 char *string;
152 int error;
154 int save = errno;
156 if (_res.options & RES_DEBUG) {
157 fprintf(file, "res_send: %s: %s\n",
158 string, strerror(error));
160 errno = save;
162 #endif
164 static res_send_qhook Qhook = NULL;
165 static res_send_rhook Rhook = NULL;
167 void
168 res_send_setqhook(hook)
169 res_send_qhook hook;
172 Qhook = hook;
175 void
176 res_send_setrhook(hook)
177 res_send_rhook hook;
180 Rhook = hook;
183 /* int
184 * res_isourserver(ina)
185 * looks up "ina" in _res.ns_addr_list[]
186 * returns:
187 * 0 : not found
188 * >0 : found
189 * author:
190 * paul vixie, 29may94
193 res_isourserver(inp)
194 const struct sockaddr_in *inp;
196 struct sockaddr_in ina;
197 register int ns, ret;
199 ina = *inp;
200 ret = 0;
201 for (ns = 0; ns < _res.nscount; ns++) {
202 register const struct sockaddr_in *srv = &_res.nsaddr_list[ns];
204 if (srv->sin_family == ina.sin_family &&
205 srv->sin_port == ina.sin_port &&
206 (srv->sin_addr.s_addr == INADDR_ANY ||
207 srv->sin_addr.s_addr == ina.sin_addr.s_addr)) {
208 ret++;
209 break;
212 return (ret);
215 /* int
216 * res_nameinquery(name, type, class, buf, eom)
217 * look for (name,type,class) in the query section of packet (buf,eom)
218 * returns:
219 * -1 : format error
220 * 0 : not found
221 * >0 : found
222 * author:
223 * paul vixie, 29may94
226 res_nameinquery(name, type, class, buf, eom)
227 const char *name;
228 register int type, class;
229 const u_char *buf, *eom;
231 register const u_char *cp = buf + HFIXEDSZ;
232 int qdcount = ntohs(((HEADER*)buf)->qdcount);
234 while (qdcount-- > 0) {
235 char tname[MAXDNAME+1];
236 register int n, ttype, tclass;
238 n = dn_expand(buf, eom, cp, tname, sizeof tname);
239 if (n < 0)
240 return (-1);
241 cp += n;
242 ttype = _getshort(cp); cp += INT16SZ;
243 tclass = _getshort(cp); cp += INT16SZ;
244 if (ttype == type &&
245 tclass == class &&
246 strcasecmp(tname, name) == 0)
247 return (1);
249 return (0);
252 /* int
253 * res_queriesmatch(buf1, eom1, buf2, eom2)
254 * is there a 1:1 mapping of (name,type,class)
255 * in (buf1,eom1) and (buf2,eom2)?
256 * returns:
257 * -1 : format error
258 * 0 : not a 1:1 mapping
259 * >0 : is a 1:1 mapping
260 * author:
261 * paul vixie, 29may94
264 res_queriesmatch(buf1, eom1, buf2, eom2)
265 const u_char *buf1, *eom1;
266 const u_char *buf2, *eom2;
268 register const u_char *cp = buf1 + HFIXEDSZ;
269 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
271 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
272 return (0);
273 while (qdcount-- > 0) {
274 char tname[MAXDNAME+1];
275 register int n, ttype, tclass;
277 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
278 if (n < 0)
279 return (-1);
280 cp += n;
281 ttype = _getshort(cp); cp += INT16SZ;
282 tclass = _getshort(cp); cp += INT16SZ;
283 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
284 return (0);
286 return (1);
290 res_send(buf, buflen, ans, anssiz)
291 const u_char *buf;
292 int buflen;
293 u_char *ans;
294 int anssiz;
296 HEADER *hp = (HEADER *) buf;
297 HEADER *anhp = (HEADER *) ans;
298 int gotsomewhere, connreset, terrno, try, v_circuit, resplen, ns;
299 register int n;
300 u_int badns; /* XXX NSMAX can't exceed #/bits in this var */
302 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
303 /* errno should have been set by res_init() in this case. */
304 return (-1);
306 DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
307 (stdout, ";; res_send()\n"), buf, buflen);
308 v_circuit = (_res.options & RES_USEVC) || buflen > PACKETSZ;
309 gotsomewhere = 0;
310 connreset = 0;
311 terrno = ETIMEDOUT;
312 badns = 0;
315 * Send request, RETRY times, or until successful
317 for (try = 0; try < _res.retry; try++) {
318 for (ns = 0; ns < _res.nscount; ns++) {
319 struct sockaddr_in *nsap = &_res.nsaddr_list[ns];
320 same_ns:
321 if (badns & (1 << ns)) {
322 _res_close();
323 goto next_ns;
326 if (Qhook) {
327 int done = 0, loops = 0;
329 do {
330 res_sendhookact act;
332 act = (*Qhook)(&nsap, &buf, &buflen,
333 ans, anssiz, &resplen);
334 switch (act) {
335 case res_goahead:
336 done = 1;
337 break;
338 case res_nextns:
339 _res_close();
340 goto next_ns;
341 case res_done:
342 return (resplen);
343 case res_modified:
344 /* give the hook another try */
345 if (++loops < 42) /*doug adams*/
346 break;
347 /*FALLTHROUGH*/
348 case res_error:
349 /*FALLTHROUGH*/
350 default:
351 return (-1);
353 } while (!done);
356 Dprint(_res.options & RES_DEBUG,
357 (stdout, ";; Querying server (# %d) address = %s\n",
358 ns + 1, inet_ntoa(nsap->sin_addr)));
360 if (v_circuit) {
361 int truncated;
362 struct iovec iov[2];
363 u_short len;
364 u_char *cp;
367 * Use virtual circuit;
368 * at most one attempt per server.
370 try = _res.retry;
371 truncated = 0;
372 if ((s < 0) || (!vc)) {
373 if (s >= 0)
374 _res_close();
376 s = socket(PF_INET, SOCK_STREAM, 0);
377 if (s < 0) {
378 terrno = errno;
379 Perror(stderr, "socket(vc)", errno);
380 return (-1);
382 errno = 0;
383 if (connect(s, (struct sockaddr *)nsap,
384 sizeof(struct sockaddr)) < 0) {
385 terrno = errno;
386 Aerror(stderr, "connect/vc",
387 errno, *nsap);
388 badns |= (1 << ns);
389 _res_close();
390 goto next_ns;
392 vc = 1;
395 * Send length & message
397 putshort((u_short)buflen, (u_char*)&len);
398 iov[0].iov_base = (caddr_t)&len;
399 iov[0].iov_len = INT16SZ;
400 iov[1].iov_base = (caddr_t)buf;
401 iov[1].iov_len = buflen;
402 if (writev(s, iov, 2) != (INT16SZ + buflen)) {
403 terrno = errno;
404 Perror(stderr, "write failed", errno);
405 badns |= (1 << ns);
406 _res_close();
407 goto next_ns;
410 * Receive length & response
412 read_len:
413 cp = ans;
414 len = INT16SZ;
415 while ((n = read(s, (char *)cp, (int)len)) > 0) {
416 cp += n;
417 if ((len -= n) <= 0)
418 break;
420 if (n <= 0) {
421 terrno = errno;
422 Perror(stderr, "read failed", errno);
423 _res_close();
425 * A long running process might get its TCP
426 * connection reset if the remote server was
427 * restarted. Requery the server instead of
428 * trying a new one. When there is only one
429 * server, this means that a query might work
430 * instead of failing. We only allow one reset
431 * per query to prevent looping.
433 if (terrno == ECONNRESET && !connreset) {
434 connreset = 1;
435 _res_close();
436 goto same_ns;
438 _res_close();
439 goto next_ns;
441 resplen = _getshort(ans);
442 if (resplen > anssiz) {
443 Dprint(_res.options & RES_DEBUG,
444 (stdout, ";; response truncated\n")
446 truncated = 1;
447 len = anssiz;
448 } else
449 len = resplen;
450 cp = ans;
451 while (len != 0 &&
452 (n = read(s, (char *)cp, (int)len)) > 0) {
453 cp += n;
454 len -= n;
456 if (n <= 0) {
457 terrno = errno;
458 Perror(stderr, "read(vc)", errno);
459 _res_close();
460 goto next_ns;
462 if (truncated) {
464 * Flush rest of answer
465 * so connection stays in synch.
467 anhp->tc = 1;
468 len = resplen - anssiz;
469 while (len != 0) {
470 char junk[PACKETSZ];
472 n = (len > sizeof(junk)
473 ? sizeof(junk)
474 : len);
475 if ((n = read(s, junk, n)) > 0)
476 len -= n;
477 else
478 break;
482 * The calling applicating has bailed out of
483 * a previous call and failed to arrange to have
484 * the circuit closed or the server has got
485 * itself confused. Anyway drop the packet and
486 * wait for the correct one.
488 if (hp->id != anhp->id) {
489 DprintQ((_res.options & RES_DEBUG) ||
490 (_res.pfcode & RES_PRF_REPLY),
491 (stdout, ";; old answer (unexpected):\n"),
492 ans, (resplen>anssiz)?anssiz:resplen);
493 goto read_len;
495 } else {
497 * Use datagrams.
499 struct timeval timeout;
500 fd_set dsmask;
501 struct sockaddr_in from;
502 size_t fromlen;
504 if ((s < 0) || vc) {
505 if (vc)
506 _res_close();
507 s = socket(PF_INET, SOCK_DGRAM, 0);
508 if (s < 0) {
509 #if !CAN_RECONNECT
510 bad_dg_sock:
511 #endif
512 terrno = errno;
513 Perror(stderr, "socket(dg)", errno);
514 return (-1);
516 connected = 0;
519 * On a 4.3BSD+ machine (client and server,
520 * actually), sending to a nameserver datagram
521 * port with no nameserver will cause an
522 * ICMP port unreachable message to be returned.
523 * If our datagram socket is "connected" to the
524 * server, we get an ECONNREFUSED error on the next
525 * socket operation, and select returns if the
526 * error message is received. We can thus detect
527 * the absence of a nameserver without timing out.
528 * If we have sent queries to at least two servers,
529 * however, we don't want to remain connected,
530 * as we wish to receive answers from the first
531 * server to respond.
533 if (_res.nscount == 1 || (try == 0 && ns == 0)) {
535 * Connect only if we are sure we won't
536 * receive a response from another server.
538 if (!connected) {
539 if (connect(s, (struct sockaddr *)nsap,
540 sizeof(struct sockaddr)
541 ) < 0) {
542 Aerror(stderr,
543 "connect(dg)",
544 errno, *nsap);
545 badns |= (1 << ns);
546 _res_close();
547 goto next_ns;
549 connected = 1;
551 if (send(s, (char*)buf, buflen, 0) != buflen) {
552 Perror(stderr, "send", errno);
553 badns |= (1 << ns);
554 _res_close();
555 goto next_ns;
557 } else {
559 * Disconnect if we want to listen
560 * for responses from more than one server.
562 if (connected) {
563 #if CAN_RECONNECT
564 struct sockaddr_in no_addr;
566 no_addr.sin_family = AF_INET;
567 no_addr.sin_addr.s_addr = INADDR_ANY;
568 no_addr.sin_port = 0;
569 (void) connect(s,
570 (struct sockaddr *)
571 &no_addr,
572 sizeof(no_addr));
573 #else
574 int s1 = socket(PF_INET, SOCK_DGRAM,0);
575 if (s1 < 0)
576 goto bad_dg_sock;
577 (void) dup2(s1, s);
578 (void) close(s1);
579 Dprint(_res.options & RES_DEBUG,
580 (stdout, ";; new DG socket\n"))
581 #endif
582 connected = 0;
583 errno = 0;
585 if (sendto(s, (char*)buf, buflen, 0,
586 (struct sockaddr *)nsap,
587 sizeof(struct sockaddr))
588 != buflen) {
589 Aerror(stderr, "sendto", errno, *nsap);
590 badns |= (1 << ns);
591 _res_close();
592 goto next_ns;
597 * Wait for reply
599 timeout.tv_sec = (_res.retrans << try);
600 if (try > 0)
601 timeout.tv_sec /= _res.nscount;
602 if ((long) timeout.tv_sec <= 0)
603 timeout.tv_sec = 1;
604 timeout.tv_usec = 0;
605 wait:
606 FD_ZERO(&dsmask);
607 FD_SET(s, &dsmask);
608 n = select(s+1, &dsmask, (fd_set *)NULL,
609 (fd_set *)NULL, &timeout);
610 if (n < 0) {
611 if (errno == EINTR)
612 goto wait;
613 Perror(stderr, "select", errno);
614 _res_close();
615 goto next_ns;
617 if (n == 0) {
619 * timeout
621 Dprint(_res.options & RES_DEBUG,
622 (stdout, ";; timeout\n"));
623 gotsomewhere = 1;
624 _res_close();
625 goto next_ns;
627 errno = 0;
628 fromlen = sizeof(struct sockaddr_in);
629 resplen = recvfrom(s, (char*)ans, anssiz, 0,
630 (struct sockaddr *)&from, &fromlen);
631 if (resplen <= 0) {
632 Perror(stderr, "recvfrom", errno);
633 _res_close();
634 goto next_ns;
636 gotsomewhere = 1;
637 if (hp->id != anhp->id) {
639 * response from old query, ignore it.
640 * XXX - potential security hazard could
641 * be detected here.
643 DprintQ((_res.options & RES_DEBUG) ||
644 (_res.pfcode & RES_PRF_REPLY),
645 (stdout, ";; old answer:\n"),
646 ans, (resplen>anssiz)?anssiz:resplen);
647 goto wait;
649 #if CHECK_SRVR_ADDR
650 if (!(_res.options & RES_INSECURE1) &&
651 !res_isourserver(&from)) {
653 * response from wrong server? ignore it.
654 * XXX - potential security hazard could
655 * be detected here.
657 DprintQ((_res.options & RES_DEBUG) ||
658 (_res.pfcode & RES_PRF_REPLY),
659 (stdout, ";; not our server:\n"),
660 ans, (resplen>anssiz)?anssiz:resplen);
661 goto wait;
663 #endif
664 if (!(_res.options & RES_INSECURE2) &&
665 !res_queriesmatch(buf, buf + buflen,
666 ans, ans + anssiz)) {
668 * response contains wrong query? ignore it.
669 * XXX - potential security hazard could
670 * be detected here.
672 DprintQ((_res.options & RES_DEBUG) ||
673 (_res.pfcode & RES_PRF_REPLY),
674 (stdout, ";; wrong query name:\n"),
675 ans, (resplen>anssiz)?anssiz:resplen);
676 goto wait;
678 if (anhp->rcode == SERVFAIL ||
679 anhp->rcode == NOTIMP ||
680 anhp->rcode == REFUSED) {
681 DprintQ(_res.options & RES_DEBUG,
682 (stdout, "server rejected query:\n"),
683 ans, (resplen>anssiz)?anssiz:resplen);
684 badns |= (1 << ns);
685 _res_close();
686 /* don't retry if called from dig */
687 if (!_res.pfcode)
688 goto next_ns;
690 if (!(_res.options & RES_IGNTC) && anhp->tc) {
692 * get rest of answer;
693 * use TCP with same server.
695 Dprint(_res.options & RES_DEBUG,
696 (stdout, ";; truncated answer\n"));
697 v_circuit = 1;
698 _res_close();
699 goto same_ns;
701 } /*if vc/dg*/
702 Dprint((_res.options & RES_DEBUG) ||
703 ((_res.pfcode & RES_PRF_REPLY) &&
704 (_res.pfcode & RES_PRF_HEAD1)),
705 (stdout, ";; got answer:\n"));
706 DprintQ((_res.options & RES_DEBUG) ||
707 (_res.pfcode & RES_PRF_REPLY),
708 (stdout, ""),
709 ans, (resplen>anssiz)?anssiz:resplen);
711 * If using virtual circuits, we assume that the first server
712 * is preferred over the rest (i.e. it is on the local
713 * machine) and only keep that one open.
714 * If we have temporarily opened a virtual circuit,
715 * or if we haven't been asked to keep a socket open,
716 * close the socket.
718 if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) ||
719 !(_res.options & RES_STAYOPEN)) {
720 _res_close();
722 if (Rhook) {
723 int done = 0, loops = 0;
725 do {
726 res_sendhookact act;
728 act = (*Rhook)(nsap, buf, buflen,
729 ans, anssiz, &resplen);
730 switch (act) {
731 case res_goahead:
732 case res_done:
733 done = 1;
734 break;
735 case res_nextns:
736 _res_close();
737 goto next_ns;
738 case res_modified:
739 /* give the hook another try */
740 if (++loops < 42) /*doug adams*/
741 break;
742 /*FALLTHROUGH*/
743 case res_error:
744 /*FALLTHROUGH*/
745 default:
746 return (-1);
748 } while (!done);
751 return (resplen);
752 next_ns: ;
753 } /*foreach ns*/
754 } /*foreach retry*/
755 _res_close();
756 if (!v_circuit)
757 if (!gotsomewhere)
758 errno = ECONNREFUSED; /* no nameservers found */
759 else
760 errno = ETIMEDOUT; /* no answer obtained */
761 else
762 errno = terrno;
763 return (-1);
767 * This routine is for closing the socket if a virtual circuit is used and
768 * the program wants to close it. This provides support for endhostent()
769 * which expects to close the socket.
771 * This routine is not expected to be user visible.
773 void
774 _res_close()
776 if (s >= 0) {
777 (void) close(s);
778 s = -1;
779 connected = 0;
780 vc = 0;