1999-03-07 Mark Kettenis <kettenis@gnu.org>
[kopensolaris-gnu/glibc.git] / resolv / res_send.c
index 03055d3..608659b 100644 (file)
@@ -3,7 +3,7 @@
  * -
  * Copyright (c) 1985, 1989, 1993
  *    The Regents of the University of California.  All rights reserved.
- * 
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -19,7 +19,7 @@
  * 4. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- * 
+ *
  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * SUCH DAMAGE.
  * -
  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
- * 
+ *
  * Permission to use, copy, modify, and distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
  * copyright notice and this permission notice appear in all copies, and that
  * the name of Digital Equipment Corporation not be used in advertising or
  * publicity pertaining to distribution of the document or software without
  * specific, written prior permission.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
@@ -69,7 +69,9 @@ static char rcsid[] = "$Id$";
  * Send query to name server and wait for reply.
  */
 
+#include <sys/types.h>
 #include <sys/param.h>
+#include <sys/poll.h>
 #include <sys/time.h>
 #include <sys/socket.h>
 #include <sys/uio.h>
@@ -78,11 +80,13 @@ static char rcsid[] = "$Id$";
 #include <arpa/inet.h>
 
 #include <stdio.h>
+#include <netdb.h>
 #include <errno.h>
 #include <resolv.h>
 #if defined(BSD) && (BSD >= 199306)
 # include <stdlib.h>
 # include <string.h>
+# include <unistd.h>
 #else
 # include "../conf/portability.h"
 #endif
@@ -91,32 +95,27 @@ static char rcsid[] = "$Id$";
 # include <../conf/options.h>
 #endif
 
-void _res_close __P((void));
-
 static int s = -1;     /* socket used for communications */
 static int connected = 0;      /* is the socket connected */
-static int vc = 0;     /* is the socket a virtual ciruit? */
-
-#ifndef FD_SET
-/* XXX - should be in portability.h */
-#define        NFDBITS         32
-#define        FD_SETSIZE      32
-#define        FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
-#define        FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
-#define        FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
-#define FD_ZERO(p)     bzero((char *)(p), sizeof(*(p)))
+static int vc = 0;     /* is the socket a virtual circuit? */
+
+/* XXX - this should be done in portability.h */
+#if (defined(BSD) && (BSD >= 199103)) || defined(linux)
+# define CAN_RECONNECT 1
+#else
+# define CAN_RECONNECT 0
 #endif
 
 #ifndef DEBUG
 #   define Dprint(cond, args) /*empty*/
-#   define DprintQ(cond, args, query) /*empty*/
+#   define DprintQ(cond, args, query, size) /*empty*/
 #   define Aerror(file, string, error, address) /*empty*/
 #   define Perror(file, string, error) /*empty*/
 #else
 #   define Dprint(cond, args) if (cond) {fprintf args;} else {}
-#   define DprintQ(cond, args, query) if (cond) {\
+#   define DprintQ(cond, args, query, size) if (cond) {\
                        fprintf args;\
-                       __p_query(query);\
+                       __fp_nquery(query, size, stdout);\
                } else {}
     static void
     Aerror(file, string, error, address)
@@ -134,7 +133,7 @@ static int vc = 0;  /* is the socket a virtual ciruit? */
                        ntohs(address.sin_port),
                        strerror(error));
        }
-       errno = save;
+       __set_errno (save);
     }
     static void
     Perror(file, string, error)
@@ -148,7 +147,7 @@ static int vc = 0;  /* is the socket a virtual ciruit? */
                fprintf(file, "res_send: %s: %s\n",
                        string, strerror(error));
        }
-       errno = save;
+       __set_errno (save);
     }
 #endif
 
@@ -206,6 +205,8 @@ res_isourserver(inp)
 /* int
  * res_nameinquery(name, type, class, buf, eom)
  *     look for (name,type,class) in the query section of packet (buf,eom)
+ * requires:
+ *     buf + HFIXESDZ <= eom
  * returns:
  *     -1 : format error
  *     0  : not found
@@ -230,7 +231,9 @@ res_nameinquery(name, type, class, buf, eom)
                if (n < 0)
                        return (-1);
                cp += n;
-               ttype = _getshort(cp);  cp += INT16SZ;
+               if (cp + 2 * INT16SZ > eom)
+                       return (-1);
+               ttype = _getshort(cp); cp += INT16SZ;
                tclass = _getshort(cp); cp += INT16SZ;
                if (ttype == type &&
                    tclass == class &&
@@ -259,6 +262,9 @@ res_queriesmatch(buf1, eom1, buf2, eom2)
        register const u_char *cp = buf1 + HFIXEDSZ;
        int qdcount = ntohs(((HEADER*)buf1)->qdcount);
 
+       if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
+               return (-1);
+
        if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
                return (0);
        while (qdcount-- > 0) {
@@ -269,6 +275,8 @@ res_queriesmatch(buf1, eom1, buf2, eom2)
                if (n < 0)
                        return (-1);
                cp += n;
+               if (cp + 2 * INT16SZ > eom1)
+                       return (-1);
                ttype = _getshort(cp);  cp += INT16SZ;
                tclass = _getshort(cp); cp += INT16SZ;
                if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
@@ -290,10 +298,16 @@ res_send(buf, buflen, ans, anssiz)
        register int n;
        u_int badns;    /* XXX NSMAX can't exceed #/bits in this var */
 
-       DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
-               (stdout, ";; res_send()\n"), buf);
-       if (!(_res.options & RES_INIT) && res_init() == -1)
+       if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
+               /* errno should have been set by res_init() in this case. */
+               return (-1);
+       }
+       if (anssiz < HFIXEDSZ) {
+               __set_errno (EINVAL);
                return (-1);
+       }
+       DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
+               (stdout, ";; res_send()\n"), buf, buflen);
        v_circuit = (_res.options & RES_USEVC) || buflen > PACKETSZ;
        gotsomewhere = 0;
        connreset = 0;
@@ -308,7 +322,7 @@ res_send(buf, buflen, ans, anssiz)
                struct sockaddr_in *nsap = &_res.nsaddr_list[ns];
     same_ns:
                if (badns & (1 << ns)) {
-                       _res_close();
+                       res_close();
                        goto next_ns;
                }
 
@@ -325,7 +339,7 @@ res_send(buf, buflen, ans, anssiz)
                                        done = 1;
                                        break;
                                case res_nextns:
-                                       _res_close();
+                                       res_close();
                                        goto next_ns;
                                case res_done:
                                        return (resplen);
@@ -360,21 +374,22 @@ res_send(buf, buflen, ans, anssiz)
                        truncated = 0;
                        if ((s < 0) || (!vc)) {
                                if (s >= 0)
-                                       _res_close();
+                                       res_close();
 
-                               s = socket(AF_INET, SOCK_STREAM, PF_UNSPEC);
+                               s = socket(PF_INET, SOCK_STREAM, 0);
                                if (s < 0) {
                                        terrno = errno;
                                        Perror(stderr, "socket(vc)", errno);
                                        return (-1);
                                }
+                               __set_errno (0);
                                if (connect(s, (struct sockaddr *)nsap,
                                            sizeof(struct sockaddr)) < 0) {
                                        terrno = errno;
                                        Aerror(stderr, "connect/vc",
                                               errno, *nsap);
                                        badns |= (1 << ns);
-                                       _res_close();
+                                       res_close();
                                        goto next_ns;
                                }
                                vc = 1;
@@ -391,12 +406,13 @@ res_send(buf, buflen, ans, anssiz)
                                terrno = errno;
                                Perror(stderr, "write failed", errno);
                                badns |= (1 << ns);
-                               _res_close();
+                               res_close();
                                goto next_ns;
                        }
                        /*
                         * Receive length & response
                         */
+read_len:
                        cp = ans;
                        len = INT16SZ;
                        while ((n = read(s, (char *)cp, (int)len)) > 0) {
@@ -407,7 +423,7 @@ res_send(buf, buflen, ans, anssiz)
                        if (n <= 0) {
                                terrno = errno;
                                Perror(stderr, "read failed", errno);
-                               _res_close();
+                               res_close();
                                /*
                                 * A long running process might get its TCP
                                 * connection reset if the remote server was
@@ -419,10 +435,10 @@ res_send(buf, buflen, ans, anssiz)
                                 */
                                if (terrno == ECONNRESET && !connreset) {
                                        connreset = 1;
-                                       _res_close();
+                                       res_close();
                                        goto same_ns;
                                }
-                               _res_close();
+                               res_close();
                                goto next_ns;
                        }
                        resplen = _getshort(ans);
@@ -434,6 +450,17 @@ res_send(buf, buflen, ans, anssiz)
                                len = anssiz;
                        } else
                                len = resplen;
+                       if (len < HFIXEDSZ) {
+                               /*
+                                * Undersized message.
+                                */
+                               Dprint(_res.options & RES_DEBUG,
+                                      (stdout, ";; undersized: %d\n", len));
+                               terrno = EMSGSIZE;
+                               badns |= (1 << ns);
+                               res_close();
+                               goto next_ns;
+                       }
                        cp = ans;
                        while (len != 0 &&
                               (n = read(s, (char *)cp, (int)len)) > 0) {
@@ -443,7 +470,7 @@ res_send(buf, buflen, ans, anssiz)
                        if (n <= 0) {
                                terrno = errno;
                                Perror(stderr, "read(vc)", errno);
-                               _res_close();
+                               res_close();
                                goto next_ns;
                        }
                        if (truncated) {
@@ -456,7 +483,7 @@ res_send(buf, buflen, ans, anssiz)
                                while (len != 0) {
                                        char junk[PACKETSZ];
 
-                                       n = (len > sizeof(junk)
+                                       n = ((size_t) len > sizeof(junk)
                                             ? sizeof(junk)
                                             : len);
                                        if ((n = read(s, junk, n)) > 0)
@@ -465,21 +492,38 @@ res_send(buf, buflen, ans, anssiz)
                                                break;
                                }
                        }
+                       /*
+                        * The calling applicating has bailed out of
+                        * a previous call and failed to arrange to have
+                        * the circuit closed or the server has got
+                        * itself confused. Anyway drop the packet and
+                        * wait for the correct one.
+                        */
+                       if (hp->id != anhp->id) {
+                               DprintQ((_res.options & RES_DEBUG) ||
+                                       (_res.pfcode & RES_PRF_REPLY),
+                                       (stdout, ";; old answer (unexpected):\n"),
+                                       ans, (resplen>anssiz)?anssiz:resplen);
+                               goto read_len;
+                       }
                } else {
                        /*
                         * Use datagrams.
                         */
-                       struct timeval timeout;
-                       fd_set dsmask;
+                       int timeout;
+                       struct pollfd pfd[1];
                        struct sockaddr_in from;
-                       int fromlen;
+                       socklen_t fromlen;
 
                        if ((s < 0) || vc) {
                                if (vc)
-                                       _res_close();
-                               s = socket(AF_INET, SOCK_DGRAM, PF_UNSPEC);
+                                       res_close();
+                               s = socket(PF_INET, SOCK_DGRAM, 0);
                                if (s < 0) {
- bad_dg_sock:                          terrno = errno;
+#if !CAN_RECONNECT
+ bad_dg_sock:
+#endif
+                                       terrno = errno;
                                        Perror(stderr, "socket(dg)", errno);
                                        return (-1);
                                }
@@ -513,7 +557,7 @@ res_send(buf, buflen, ans, anssiz)
                                                       "connect(dg)",
                                                       errno, *nsap);
                                                badns |= (1 << ns);
-                                               _res_close();
+                                               res_close();
                                                goto next_ns;
                                        }
                                        connected = 1;
@@ -521,7 +565,7 @@ res_send(buf, buflen, ans, anssiz)
                                if (send(s, (char*)buf, buflen, 0) != buflen) {
                                        Perror(stderr, "send", errno);
                                        badns |= (1 << ns);
-                                       _res_close();
+                                       res_close();
                                        goto next_ns;
                                }
                        } else {
@@ -530,7 +574,7 @@ res_send(buf, buflen, ans, anssiz)
                                 * for responses from more than one server.
                                 */
                                if (connected) {
-#if defined(BSD) && (BSD >= 199103)
+#if CAN_RECONNECT
                                        struct sockaddr_in no_addr;
 
                                        no_addr.sin_family = AF_INET;
@@ -541,8 +585,7 @@ res_send(buf, buflen, ans, anssiz)
                                                        &no_addr,
                                                       sizeof(no_addr));
 #else
-                                       int s1 = socket(AF_INET, SOCK_DGRAM,
-                                                       PF_UNSPEC);
+                                       int s1 = socket(PF_INET, SOCK_DGRAM,0);
                                        if (s1 < 0)
                                                goto bad_dg_sock;
                                        (void) dup2(s1, s);
@@ -551,7 +594,7 @@ res_send(buf, buflen, ans, anssiz)
                                               (stdout, ";; new DG socket\n"))
 #endif
                                        connected = 0;
-                                       errno = 0;
+                                       __set_errno (0);
                                }
                                if (sendto(s, (char*)buf, buflen, 0,
                                           (struct sockaddr *)nsap,
@@ -559,7 +602,7 @@ res_send(buf, buflen, ans, anssiz)
                                    != buflen) {
                                        Aerror(stderr, "sendto", errno, *nsap);
                                        badns |= (1 << ns);
-                                       _res_close();
+                                       res_close();
                                        goto next_ns;
                                }
                        }
@@ -567,20 +610,25 @@ res_send(buf, buflen, ans, anssiz)
                        /*
                         * Wait for reply
                         */
-                       timeout.tv_sec = (_res.retrans << try);
+                       timeout = (_res.retrans << try) * 1000;
                        if (try > 0)
-                               timeout.tv_sec /= _res.nscount;
-                       if ((long) timeout.tv_sec <= 0)
-                               timeout.tv_sec = 1;
-                       timeout.tv_usec = 0;
+                               timeout /= _res.nscount;
+                       if (timeout <= 0)
+                               timeout = 1000;
     wait:
-                       FD_ZERO(&dsmask);
-                       FD_SET(s, &dsmask);
-                       n = select(s+1, &dsmask, (fd_set *)NULL,
-                                  (fd_set *)NULL, &timeout);
+                       if (s < 0 || s >= FD_SETSIZE) {
+                               Perror(stderr, "s out-of-bounds", EMFILE);
+                               res_close();
+                               goto next_ns;
+                       }
+                       pfd[0].fd = s;
+                       pfd[0].events = POLLIN;
+                       n = __poll(pfd, 1, timeout);
                        if (n < 0) {
-                               Perror(stderr, "select", errno);
-                               _res_close();
+                               if (errno == EINTR)
+                                       goto wait;
+                               Perror(stderr, "poll", errno);
+                               res_close();
                                goto next_ns;
                        }
                        if (n == 0) {
@@ -590,18 +638,31 @@ res_send(buf, buflen, ans, anssiz)
                                Dprint(_res.options & RES_DEBUG,
                                       (stdout, ";; timeout\n"));
                                gotsomewhere = 1;
-                               _res_close();
+                               res_close();
                                goto next_ns;
                        }
+                       __set_errno (0);
                        fromlen = sizeof(struct sockaddr_in);
                        resplen = recvfrom(s, (char*)ans, anssiz, 0,
                                           (struct sockaddr *)&from, &fromlen);
                        if (resplen <= 0) {
                                Perror(stderr, "recvfrom", errno);
-                               _res_close();
+                               res_close();
                                goto next_ns;
                        }
                        gotsomewhere = 1;
+                       if (resplen < HFIXEDSZ) {
+                               /*
+                                * Undersized message.
+                                */
+                               Dprint(_res.options & RES_DEBUG,
+                                      (stdout, ";; undersized: %d\n",
+                                       resplen));
+                               terrno = EMSGSIZE;
+                               badns |= (1 << ns);
+                               res_close();
+                               goto next_ns;
+                       }
                        if (hp->id != anhp->id) {
                                /*
                                 * response from old query, ignore it.
@@ -611,7 +672,7 @@ res_send(buf, buflen, ans, anssiz)
                                DprintQ((_res.options & RES_DEBUG) ||
                                        (_res.pfcode & RES_PRF_REPLY),
                                        (stdout, ";; old answer:\n"),
-                                       ans);
+                                       ans, (resplen>anssiz)?anssiz:resplen);
                                goto wait;
                        }
 #if CHECK_SRVR_ADDR
@@ -625,7 +686,7 @@ res_send(buf, buflen, ans, anssiz)
                                DprintQ((_res.options & RES_DEBUG) ||
                                        (_res.pfcode & RES_PRF_REPLY),
                                        (stdout, ";; not our server:\n"),
-                                       ans);
+                                       ans, (resplen>anssiz)?anssiz:resplen);
                                goto wait;
                        }
 #endif
@@ -640,7 +701,7 @@ res_send(buf, buflen, ans, anssiz)
                                DprintQ((_res.options & RES_DEBUG) ||
                                        (_res.pfcode & RES_PRF_REPLY),
                                        (stdout, ";; wrong query name:\n"),
-                                       ans);
+                                       ans, (resplen>anssiz)?anssiz:resplen);
                                goto wait;
                        }
                        if (anhp->rcode == SERVFAIL ||
@@ -648,9 +709,9 @@ res_send(buf, buflen, ans, anssiz)
                            anhp->rcode == REFUSED) {
                                DprintQ(_res.options & RES_DEBUG,
                                        (stdout, "server rejected query:\n"),
-                                       ans);
+                                       ans, (resplen>anssiz)?anssiz:resplen);
                                badns |= (1 << ns);
-                               _res_close();
+                               res_close();
                                /* don't retry if called from dig */
                                if (!_res.pfcode)
                                        goto next_ns;
@@ -663,14 +724,18 @@ res_send(buf, buflen, ans, anssiz)
                                Dprint(_res.options & RES_DEBUG,
                                       (stdout, ";; truncated answer\n"));
                                v_circuit = 1;
-                               _res_close();
+                               res_close();
                                goto same_ns;
                        }
                } /*if vc/dg*/
+               Dprint((_res.options & RES_DEBUG) ||
+                      ((_res.pfcode & RES_PRF_REPLY) &&
+                       (_res.pfcode & RES_PRF_HEAD1)),
+                      (stdout, ";; got answer:\n"));
                DprintQ((_res.options & RES_DEBUG) ||
                        (_res.pfcode & RES_PRF_REPLY),
-                       (stdout, ";; got answer:\n"),
-                       ans);
+                       (stdout, ""),
+                       ans, (resplen>anssiz)?anssiz:resplen);
                /*
                 * If using virtual circuits, we assume that the first server
                 * is preferred over the rest (i.e. it is on the local
@@ -681,7 +746,7 @@ res_send(buf, buflen, ans, anssiz)
                 */
                if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) ||
                    !(_res.options & RES_STAYOPEN)) {
-                       _res_close();
+                       res_close();
                }
                if (Rhook) {
                        int done = 0, loops = 0;
@@ -697,7 +762,7 @@ res_send(buf, buflen, ans, anssiz)
                                        done = 1;
                                        break;
                                case res_nextns:
-                                       _res_close();
+                                       res_close();
                                        goto next_ns;
                                case res_modified:
                                        /* give the hook another try */
@@ -716,14 +781,14 @@ res_send(buf, buflen, ans, anssiz)
     next_ns: ;
           } /*foreach ns*/
        } /*foreach retry*/
-       _res_close();
-       if (!v_circuit)
+       res_close();
+       if (!v_circuit) {
                if (!gotsomewhere)
-                       errno = ECONNREFUSED;   /* no nameservers found */
+                       __set_errno (ECONNREFUSED); /* no nameservers found */
                else
-                       errno = ETIMEDOUT;      /* no answer obtained */
-       else
-               errno = terrno;
+                       __set_errno (ETIMEDOUT);    /* no answer obtained */
+       else
+               __set_errno (terrno);
        return (-1);
 }
 
@@ -735,7 +800,7 @@ res_send(buf, buflen, ans, anssiz)
  * This routine is not expected to be user visible.
  */
 void
-_res_close()
+res_close()
 {
        if (s >= 0) {
                (void) close(s);
@@ -744,3 +809,26 @@ _res_close()
                vc = 0;
        }
 }
+
+#ifdef ultrix
+/* ultrix 4.0 had some icky packaging in its libc.a.  alias for it here.
+ * there is more gunk of this kind over in res_debug.c.
+ */
+
+void
+_res_close()
+{
+       res_close();
+}
+
+#undef res_send
+int
+res_send(buf, buflen, ans, anssiz)
+       const u_char *buf;
+       int buflen;
+       u_char *ans;
+       int anssiz;
+{
+       return (__res_send(buf, buflen, ans, anssiz));
+}
+#endif /* Ultrix 4.0 hackery */