BSD 4_4_Lite2 release
[unix-history] / usr / src / usr.sbin / sendmail / src / domain.c
index f55f608..61570ed 100644 (file)
@@ -1,32 +1,56 @@
 /*
 /*
- * Copyright (c) 1986 Eric P. Allman
- * Copyright (c) 1988 Regents of the University of California.
- * All rights reserved.
+ * Copyright (c) 1986, 1995 Eric P. Allman
+ * Copyright (c) 1988, 1993
+ *     The Regents of the University of California.  All rights reserved.
  *
  *
- * %sccs.include.redist.c%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
 
 #include "sendmail.h"
 
 #ifndef lint
  */
 
 #include "sendmail.h"
 
 #ifndef lint
-#ifdef NAMED_BIND
-static char sccsid[] = "@(#)domain.c   6.19 (Berkeley) %G% (with name server)";
+#if NAMED_BIND
+static char sccsid[] = "@(#)domain.c   8.47 (Berkeley) 6/20/95 (with name server)";
 #else
 #else
-static char sccsid[] = "@(#)domain.c   6.19 (Berkeley) %G% (without name server)";
+static char sccsid[] = "@(#)domain.c   8.47 (Berkeley) 6/20/95 (without name server)";
 #endif
 #endif /* not lint */
 
 #endif
 #endif /* not lint */
 
-#ifdef NAMED_BIND
+#if NAMED_BIND
 
 #include <errno.h>
 
 #include <errno.h>
-#include <arpa/nameser.h>
 #include <resolv.h>
 #include <resolv.h>
-#include <netdb.h>
 
 typedef union
 {
        HEADER  qb1;
 
 typedef union
 {
        HEADER  qb1;
-       char    qb2[PACKETSZ];
+       u_char  qb2[PACKETSZ];
 } querybuf;
 
 static char    MXHostBuf[MAXMXHOSTS*PACKETSZ];
 } querybuf;
 
 static char    MXHostBuf[MAXMXHOSTS*PACKETSZ];
@@ -39,17 +63,30 @@ static char MXHostBuf[MAXMXHOSTS*PACKETSZ];
 #define MAX(a, b)      ((a) > (b) ? (a) : (b))
 #endif
 
 #define MAX(a, b)      ((a) > (b) ? (a) : (b))
 #endif
 
-/* don't use sizeof because sizeof(long) is different on 64-bit machines */
-#define SHORTSIZE      2       /* size of a short (really, must be 2) */
-#define LONGSIZE       4       /* size of a long (really, must be 4) */
+#ifndef NO_DATA
+# define NO_DATA       NO_ADDRESS
+#endif
+
+#ifndef HFIXEDSZ
+# define HFIXEDSZ      12      /* sizeof(HEADER) */
+#endif
+
+#define MAXCNAMEDEPTH  10      /* maximum depth of CNAME recursion */
+
+#if defined(__RES) && (__RES >= 19940415)
+# define RES_UNC_T     char *
+#else
+# define RES_UNC_T     u_char *
+#endif
 \f/*
 **  GETMXRR -- get MX resource records for a domain
 **
 **     Parameters:
 **             host -- the name of the host to MX.
 **             mxhosts -- a pointer to a return buffer of MX records.
 \f/*
 **  GETMXRR -- get MX resource records for a domain
 **
 **     Parameters:
 **             host -- the name of the host to MX.
 **             mxhosts -- a pointer to a return buffer of MX records.
-**             localhost -- the name of the local host.  All MX records
-**                     less preferred than this one will be discarded.
+**             droplocalhost -- If TRUE, all MX records less preferred
+**                     than the local host (as determined by $=w) will
+**                     be discarded.
 **             rcode -- a pointer to an EX_ status code.
 **
 **     Returns:
 **             rcode -- a pointer to an EX_ status code.
 **
 **     Returns:
@@ -59,35 +96,45 @@ static char MXHostBuf[MAXMXHOSTS*PACKETSZ];
 **                     and 1 is returned.
 */
 
 **                     and 1 is returned.
 */
 
-getmxrr(host, mxhosts, localhost, rcode)
+int
+getmxrr(host, mxhosts, droplocalhost, rcode)
        char *host;
        char **mxhosts;
        char *host;
        char **mxhosts;
-       char *localhost;
+       bool droplocalhost;
        int *rcode;
 {
        int *rcode;
 {
-       extern int h_errno;
        register u_char *eom, *cp;
        register u_char *eom, *cp;
-       register int i, j, n, nmx;
+       register int i, j, n;
+       int nmx = 0;
        register char *bp;
        HEADER *hp;
        querybuf answer;
        int ancount, qdcount, buflen;
        register char *bp;
        HEADER *hp;
        querybuf answer;
        int ancount, qdcount, buflen;
-       bool seenlocal;
-       u_short pref, localpref, type;
+       bool seenlocal = FALSE;
+       u_short pref, type;
+       u_short localpref = 256;
        char *fallbackMX = FallBackMX;
        static bool firsttime = TRUE;
        char *fallbackMX = FallBackMX;
        static bool firsttime = TRUE;
+       bool trycanon = FALSE;
+       int (*resfunc)();
+       extern int res_query(), res_search();
        u_short prefer[MAXMXHOSTS];
        int weight[MAXMXHOSTS];
        u_short prefer[MAXMXHOSTS];
        int weight[MAXMXHOSTS];
+       extern bool getcanonname();
+
+       if (tTd(8, 2))
+               printf("getmxrr(%s, droplocalhost=%d)\n", host, droplocalhost);
 
        if (fallbackMX != NULL)
        {
 
        if (fallbackMX != NULL)
        {
-               if (firsttime && res_query(FallBackMX, C_IN, T_A,
-                                          (char *) &answer, sizeof answer) < 0)
+               if (firsttime &&
+                   res_query(FallBackMX, C_IN, T_A,
+                             (u_char *) &answer, sizeof answer) < 0)
                {
                        /* this entry is bogus */
                        fallbackMX = FallBackMX = NULL;
                }
                {
                        /* this entry is bogus */
                        fallbackMX = FallBackMX = NULL;
                }
-               else if (strcasecmp(fallbackMX, localhost) == 0)
+               else if (droplocalhost && wordinclass(fallbackMX, 'w'))
                {
                        /* don't use fallback for this pass */
                        fallbackMX = NULL;
                {
                        /* don't use fallback for this pass */
                        fallbackMX = NULL;
@@ -95,8 +142,29 @@ getmxrr(host, mxhosts, localhost, rcode)
                firsttime = FALSE;
        }
 
                firsttime = FALSE;
        }
 
+       *rcode = EX_OK;
+
+       /* efficiency hack -- numeric or non-MX lookups */
+       if (host[0] == '[')
+               goto punt;
+
+       /*
+       **  If we don't have MX records in our host switch, don't
+       **  try for MX records.  Note that this really isn't "right",
+       **  since we might be set up to try NIS first and then DNS;
+       **  if the host is found in NIS we really shouldn't be doing
+       **  MX lookups.  However, that should be a degenerate case.
+       */
+
+       if (!UseNameServer)
+               goto punt;
+       if (HasWildcardMX && ConfigLevel >= 6)
+               resfunc = res_query;
+       else
+               resfunc = res_search;
+
        errno = 0;
        errno = 0;
-       n = res_search(host, C_IN, T_MX, (char *)&answer, sizeof(answer));
+       n = (*resfunc)(host, C_IN, T_MX, (u_char *) &answer, sizeof(answer));
        if (n < 0)
        {
                if (tTd(8, 1))
        if (n < 0)
        {
                if (tTd(8, 1))
@@ -105,23 +173,32 @@ getmxrr(host, mxhosts, localhost, rcode)
                switch (h_errno)
                {
                  case NO_DATA:
                switch (h_errno)
                {
                  case NO_DATA:
+                       trycanon = TRUE;
+                       /* fall through */
+
                  case NO_RECOVERY:
                        /* no MX data on this host */
                        goto punt;
 
                  case HOST_NOT_FOUND:
                  case NO_RECOVERY:
                        /* no MX data on this host */
                        goto punt;
 
                  case HOST_NOT_FOUND:
-                       /* the host just doesn't exist */
+#if BROKEN_RES_SEARCH
+                 case 0:       /* Ultrix resolver retns failure w/ h_errno=0 */
+#endif
+                       /* host doesn't exist in DNS; might be in /etc/hosts */
                        *rcode = EX_NOHOST;
                        *rcode = EX_NOHOST;
-                       break;
+                       goto punt;
 
                  case TRY_AGAIN:
                        /* couldn't connect to the name server */
 
                  case TRY_AGAIN:
                        /* couldn't connect to the name server */
-                       if (!UseNameServer && errno == ECONNREFUSED)
-                               goto punt;
-
                        /* it might come up later; better queue it up */
                        *rcode = EX_TEMPFAIL;
                        break;
                        /* it might come up later; better queue it up */
                        *rcode = EX_TEMPFAIL;
                        break;
+
+                 default:
+                       syserr("getmxrr: res_search (%s) failed with impossible h_errno (%d)\n",
+                               host, h_errno);
+                       *rcode = EX_OSERR;
+                       break;
                }
 
                /* irreconcilable differences */
                }
 
                /* irreconcilable differences */
@@ -130,24 +207,22 @@ getmxrr(host, mxhosts, localhost, rcode)
 
        /* find first satisfactory answer */
        hp = (HEADER *)&answer;
 
        /* find first satisfactory answer */
        hp = (HEADER *)&answer;
-       cp = (u_char *)&answer + sizeof(HEADER);
+       cp = (u_char *)&answer + HFIXEDSZ;
        eom = (u_char *)&answer + n;
        for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
                if ((n = dn_skipname(cp, eom)) < 0)
                        goto punt;
        eom = (u_char *)&answer + n;
        for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
                if ((n = dn_skipname(cp, eom)) < 0)
                        goto punt;
-       nmx = 0;
-       seenlocal = FALSE;
        buflen = sizeof(MXHostBuf) - 1;
        bp = MXHostBuf;
        ancount = ntohs(hp->ancount);
        while (--ancount >= 0 && cp < eom && nmx < MAXMXHOSTS - 1)
        {
                if ((n = dn_expand((u_char *)&answer,
        buflen = sizeof(MXHostBuf) - 1;
        bp = MXHostBuf;
        ancount = ntohs(hp->ancount);
        while (--ancount >= 0 && cp < eom && nmx < MAXMXHOSTS - 1)
        {
                if ((n = dn_expand((u_char *)&answer,
-                   eom, cp, (u_char *)bp, buflen)) < 0)
+                   eom, cp, (RES_UNC_T) bp, buflen)) < 0)
                        break;
                cp += n;
                GETSHORT(type, cp);
                        break;
                cp += n;
                GETSHORT(type, cp);
-               cp += SHORTSIZE + LONGSIZE;
+               cp += INT16SZ + INT32SZ;
                GETSHORT(n, cp);
                if (type != T_MX)
                {
                GETSHORT(n, cp);
                if (type != T_MX)
                {
@@ -159,11 +234,14 @@ getmxrr(host, mxhosts, localhost, rcode)
                }
                GETSHORT(pref, cp);
                if ((n = dn_expand((u_char *)&answer, eom, cp,
                }
                GETSHORT(pref, cp);
                if ((n = dn_expand((u_char *)&answer, eom, cp,
-                                  (u_char *)bp, buflen)) < 0)
+                                  (RES_UNC_T) bp, buflen)) < 0)
                        break;
                cp += n;
                        break;
                cp += n;
-               if (strcasecmp(bp, localhost) == 0)
+               if (droplocalhost && wordinclass(bp, 'w'))
                {
                {
+                       if (tTd(8, 3))
+                               printf("found localhost (%s) in MX list, pref=%d\n",
+                                       bp, pref);
                        if (!seenlocal || pref < localpref)
                                localpref = pref;
                        seenlocal = TRUE;
                        if (!seenlocal || pref < localpref)
                                localpref = pref;
                        seenlocal = TRUE;
@@ -182,63 +260,95 @@ getmxrr(host, mxhosts, localhost, rcode)
                *bp++ = '\0';
                buflen -= n + 1;
        }
                *bp++ = '\0';
                buflen -= n + 1;
        }
-       if (nmx == 0)
+
+       /* sort the records */
+       for (i = 0; i < nmx; i++)
        {
        {
-punt:
-               mxhosts[0] = strcpy(MXHostBuf, host);
-               bp = &MXHostBuf[strlen(MXHostBuf)];
-               if (bp[-1] != '.')
+               for (j = i + 1; j < nmx; j++)
                {
                {
-                       *bp++ = '.';
-                       *bp = '\0';
+                       if (prefer[i] > prefer[j] ||
+                           (prefer[i] == prefer[j] && weight[i] > weight[j]))
+                       {
+                               register int temp;
+                               register char *temp1;
+
+                               temp = prefer[i];
+                               prefer[i] = prefer[j];
+                               prefer[j] = temp;
+                               temp1 = mxhosts[i];
+                               mxhosts[i] = mxhosts[j];
+                               mxhosts[j] = temp1;
+                               temp = weight[i];
+                               weight[i] = weight[j];
+                               weight[j] = temp;
+                       }
+               }
+               if (seenlocal && prefer[i] >= localpref)
+               {
+                       /* truncate higher preference part of list */
+                       nmx = i;
                }
                }
-               nmx = 1;
        }
        }
-       else
+
+       if (nmx == 0)
        {
        {
-               /* sort the records */
-               for (i = 0; i < nmx; i++)
+punt:
+               if (seenlocal &&
+                   (!TryNullMXList || sm_gethostbyname(host) == NULL))
+               {
+                       /*
+                       **  If we have deleted all MX entries, this is
+                       **  an error -- we should NEVER send to a host that
+                       **  has an MX, and this should have been caught
+                       **  earlier in the config file.
+                       **
+                       **  Some sites prefer to go ahead and try the
+                       **  A record anyway; that case is handled by
+                       **  setting TryNullMXList.  I believe this is a
+                       **  bad idea, but it's up to you....
+                       */
+
+                       *rcode = EX_CONFIG;
+                       syserr("MX list for %s points back to %s",
+                               host, MyHostName);
+                       return -1;
+               }
+               strcpy(MXHostBuf, host);
+               mxhosts[0] = MXHostBuf;
+               if (host[0] == '[')
                {
                {
-                       for (j = i + 1; j < nmx; j++)
+                       register char *p;
+
+                       /* this may be an MX suppression-style address */
+                       p = strchr(MXHostBuf, ']');
+                       if (p != NULL)
                        {
                        {
-                               if (prefer[i] > prefer[j] ||
-                                   (prefer[i] == prefer[j] && weight[i] > weight[j]))
+                               *p = '\0';
+                               if (inet_addr(&MXHostBuf[1]) != -1)
+                                       *p = ']';
+                               else
                                {
                                {
-                                       register int temp;
-                                       register char *temp1;
-
-                                       temp = prefer[i];
-                                       prefer[i] = prefer[j];
-                                       prefer[j] = temp;
-                                       temp1 = mxhosts[i];
-                                       mxhosts[i] = mxhosts[j];
-                                       mxhosts[j] = temp1;
-                                       temp = weight[i];
-                                       weight[i] = weight[j];
-                                       weight[j] = temp;
+                                       trycanon = TRUE;
+                                       mxhosts[0]++;
                                }
                        }
                                }
                        }
-                       if (seenlocal && prefer[i] >= localpref)
+               }
+               if (trycanon &&
+                   getcanonname(mxhosts[0], sizeof MXHostBuf - 2, FALSE))
+               {
+                       bp = &MXHostBuf[strlen(MXHostBuf)];
+                       if (bp[-1] != '.')
                        {
                        {
-                               /*
-                                * truncate higher pref part of list; if we're
-                                * the best choice left, we should have realized
-                                * awhile ago that this was a local delivery.
-                                */
-                               if (i == 0)
-                               {
-                                       *rcode = EX_CONFIG;
-                                       return (-1);
-                               }
-                               nmx = i;
-                               break;
+                               *bp++ = '.';
+                               *bp = '\0';
                        }
                        }
+                       nmx = 1;
                }
        }
 
        /* if we have a default lowest preference, include that */
                }
        }
 
        /* if we have a default lowest preference, include that */
-       if (FallBackMX != NULL && !seenlocal)
-               mxhosts[nmx++] = FallBackMX;
+       if (fallbackMX != NULL && !seenlocal)
+               mxhosts[nmx++] = fallbackMX;
 
        return (nmx);
 }
 
        return (nmx);
 }
@@ -260,6 +370,7 @@ punt:
 **             none.
 */
 
 **             none.
 */
 
+int
 mxrand(host)
        register char *host;
 {
 mxrand(host)
        register char *host;
 {
@@ -283,7 +394,7 @@ mxrand(host)
 
                if (isascii(c) && isupper(c))
                        c = tolower(c);
 
                if (isascii(c) && isupper(c))
                        c = tolower(c);
-               hfunc = ((hfunc << 1) + c) % 2003;
+               hfunc = ((hfunc << 1) ^ c) % 2003;
        }
 
        hfunc &= 0xff;
        }
 
        hfunc &= 0xff;
@@ -293,7 +404,36 @@ mxrand(host)
        return hfunc;
 }
 \f/*
        return hfunc;
 }
 \f/*
-**  GETCANONNAME -- get the canonical name for named host
+**  BESTMX -- find the best MX for a name
+**
+**     This is really a hack, but I don't see any obvious way
+**     to generalize it at the moment.
+*/
+
+char *
+bestmx_map_lookup(map, name, av, statp)
+       MAP *map;
+       char *name;
+       char **av;
+       int *statp;
+{
+       int nmx;
+       auto int rcode;
+       int saveopts = _res.options;
+       char *mxhosts[MAXMXHOSTS + 1];
+
+       _res.options &= ~(RES_DNSRCH|RES_DEFNAMES);
+       nmx = getmxrr(name, mxhosts, FALSE, &rcode);
+       _res.options = saveopts;
+       if (nmx <= 0)
+               return NULL;
+       if (bitset(MF_MATCHONLY, map->map_mflags))
+               return map_rewrite(map, name, strlen(name), NULL);
+       else
+               return map_rewrite(map, mxhosts[0], strlen(mxhosts[0]), av);
+}
+\f/*
+**  DNS_GETCANONNAME -- get the canonical name for named host using DNS
 **
 **     This algorithm tries to be smart about wildcard MX records.
 **     This is hard to do because DNS doesn't tell is if we matched
 **
 **     This algorithm tries to be smart about wildcard MX records.
 **     This is hard to do because DNS doesn't tell is if we matched
@@ -314,6 +454,8 @@ mxrand(host)
 **             host -- a buffer containing the name of the host.
 **                     This is a value-result parameter.
 **             hbsize -- the size of the host buffer.
 **             host -- a buffer containing the name of the host.
 **                     This is a value-result parameter.
 **             hbsize -- the size of the host buffer.
+**             trymx -- if set, try MX records as well as A and CNAME.
+**             statp -- pointer to place to store status.
 **
 **     Returns:
 **             TRUE -- if the host matched.
 **
 **     Returns:
 **             TRUE -- if the host matched.
@@ -321,37 +463,40 @@ mxrand(host)
 */
 
 bool
 */
 
 bool
-getcanonname(host, hbsize)
+dns_getcanonname(host, hbsize, trymx, statp)
        char *host;
        int hbsize;
        char *host;
        int hbsize;
+       bool trymx;
+       int *statp;
 {
 {
-       extern int h_errno;
        register u_char *eom, *ap;
        register char *cp;
        register int n; 
        HEADER *hp;
        querybuf answer;
        register u_char *eom, *ap;
        register char *cp;
        register int n; 
        HEADER *hp;
        querybuf answer;
-       int first, ancount, qdcount;
+       int ancount, qdcount;
        int ret;
        char **domain;
        int type;
        char **dp;
        char *mxmatch;
        bool amatch;
        int ret;
        char **domain;
        int type;
        char **dp;
        char *mxmatch;
        bool amatch;
-       bool gotmx;
+       bool gotmx = FALSE;
        int qtype;
        int qtype;
+       int loopcnt;
+       char *xp;
        char nbuf[MAX(PACKETSZ, MAXDNAME*2+2)];
        char *searchlist[MAXDNSRCH+2];
        char nbuf[MAX(PACKETSZ, MAXDNAME*2+2)];
        char *searchlist[MAXDNSRCH+2];
+       extern char *gethostalias();
 
        if (tTd(8, 2))
 
        if (tTd(8, 2))
-               printf("getcanonname(%s)\n", host);
+               printf("dns_getcanonname(%s, trymx=%d)\n", host, trymx);
 
        if ((_res.options & RES_INIT) == 0 && res_init() == -1)
 
        if ((_res.options & RES_INIT) == 0 && res_init() == -1)
-               return (FALSE);
-
-       for (cp = host, n = 0; *cp; cp++)
-               if (*cp == '.')
-                       n++;
+       {
+               *statp = EX_UNAVAILABLE;
+               return FALSE;
+       }
 
        /*
        **  Initialize domain search list.  If there is at least one
 
        /*
        **  Initialize domain search list.  If there is at least one
@@ -363,6 +508,26 @@ getcanonname(host, hbsize)
        **  list by tearing apart the host name.
        */
 
        **  list by tearing apart the host name.
        */
 
+       loopcnt = 0;
+cnameloop:
+       for (cp = host, n = 0; *cp != '\0'; cp++)
+               if (*cp == '.')
+                       n++;
+
+       if (n == 0 && (xp = gethostalias(host)) != NULL)
+       {
+               if (loopcnt++ > MAXCNAMEDEPTH)
+               {
+                       syserr("loop in ${HOSTALIASES} file");
+               }
+               else
+               {
+                       strncpy(host, xp, hbsize);
+                       host[hbsize - 1] = '\0';
+                       goto cnameloop;
+               }
+       }
+
        dp = searchlist;
        if (n > 0)
                *dp++ = "";
        dp = searchlist;
        if (n > 0)
                *dp++ = "";
@@ -375,14 +540,20 @@ getcanonname(host, hbsize)
        {
                *dp++ = _res.defdname;
        }
        {
                *dp++ = _res.defdname;
        }
+       else if (*cp == '.')
+       {
+               *cp = '\0';
+       }
        *dp = NULL;
 
        *dp = NULL;
 
+       /* if we have a wildcard MX and no dots, try MX anyhow */
+       if (n == 0)
+               trymx = TRUE;
+
        /*
        **  Now run through the search list for the name in question.
        */
 
        /*
        **  Now run through the search list for the name in question.
        */
 
-cnameloop:
-       dp = searchlist;
        mxmatch = NULL;
        qtype = T_ANY;
 
        mxmatch = NULL;
        qtype = T_ANY;
 
@@ -391,11 +562,12 @@ cnameloop:
                if (qtype == T_ANY)
                        gotmx = FALSE;
                if (tTd(8, 5))
                if (qtype == T_ANY)
                        gotmx = FALSE;
                if (tTd(8, 5))
-                       printf("getcanonname: trying %s.%s (%s)\n", host, *dp,
+                       printf("dns_getcanonname: trying %s.%s (%s)\n",
+                               host, *dp,
                                qtype == T_ANY ? "ANY" : qtype == T_A ? "A" :
                                qtype == T_MX ? "MX" : "???");
                ret = res_querydomain(host, *dp, C_IN, qtype,
                                qtype == T_ANY ? "ANY" : qtype == T_A ? "A" :
                                qtype == T_MX ? "MX" : "???");
                ret = res_querydomain(host, *dp, C_IN, qtype,
-                                     &answer, sizeof(answer));
+                                     answer.qb2, sizeof(answer.qb2));
                if (ret <= 0)
                {
                        if (tTd(8, 7))
                if (ret <= 0)
                {
                        if (tTd(8, 7))
@@ -406,6 +578,7 @@ cnameloop:
                        {
                                /* the name server seems to be down */
                                h_errno = TRY_AGAIN;
                        {
                                /* the name server seems to be down */
                                h_errno = TRY_AGAIN;
+                               *statp = EX_TEMPFAIL;
                                return FALSE;
                        }
 
                                return FALSE;
                        }
 
@@ -417,20 +590,14 @@ cnameloop:
                                        qtype = T_A;
                                        continue;
                                }
                                        qtype = T_A;
                                        continue;
                                }
-                               else if (qtype == T_A && !gotmx)
+                               else if (qtype == T_A && !gotmx && trymx)
                                {
                                        qtype = T_MX;
                                        continue;
                                }
                        }
 
                                {
                                        qtype = T_MX;
                                        continue;
                                }
                        }
 
-                       if (mxmatch != NULL)
-                       {
-                               /* we matched before -- use that one */
-                               break;
-                       }
-
-                       /* otherwise, try the next name */
+                       /* try the next name */
                        dp++;
                        qtype = T_ANY;
                        continue;
                        dp++;
                        qtype = T_ANY;
                        continue;
@@ -445,7 +612,7 @@ cnameloop:
                */
 
                hp = (HEADER *) &answer;
                */
 
                hp = (HEADER *) &answer;
-               ap = (u_char *) &answer + sizeof(HEADER);
+               ap = (u_char *) &answer + HFIXEDSZ;
                eom = (u_char *) &answer + ret;
 
                /* skip question part of response -- we know what we asked */
                eom = (u_char *) &answer + ret;
 
                /* skip question part of response -- we know what we asked */
@@ -456,6 +623,7 @@ cnameloop:
                                if (tTd(8, 20))
                                        printf("qdcount failure (%d)\n",
                                                ntohs(hp->qdcount));
                                if (tTd(8, 20))
                                        printf("qdcount failure (%d)\n",
                                                ntohs(hp->qdcount));
+                               *statp = EX_SOFTWARE;
                                return FALSE;           /* ???XXX??? */
                        }
                }
                                return FALSE;           /* ???XXX??? */
                        }
                }
@@ -464,21 +632,21 @@ cnameloop:
                for (ancount = ntohs(hp->ancount); --ancount >= 0 && ap < eom; ap += n)
                {
                        n = dn_expand((u_char *) &answer, eom, ap,
                for (ancount = ntohs(hp->ancount); --ancount >= 0 && ap < eom; ap += n)
                {
                        n = dn_expand((u_char *) &answer, eom, ap,
-                                     (u_char *) nbuf, sizeof nbuf);
+                                     (RES_UNC_T) nbuf, sizeof nbuf);
                        if (n < 0)
                                break;
                        ap += n;
                        GETSHORT(type, ap);
                        if (n < 0)
                                break;
                        ap += n;
                        GETSHORT(type, ap);
-                       ap += SHORTSIZE + LONGSIZE;
+                       ap += INT16SZ + INT32SZ;
                        GETSHORT(n, ap);
                        switch (type)
                        {
                          case T_MX:
                                gotmx = TRUE;
                        GETSHORT(n, ap);
                        switch (type)
                        {
                          case T_MX:
                                gotmx = TRUE;
-                               if (**dp != '\0')
+                               if (**dp != '\0' || !HasWildcardMX)
                                {
                                        /* got a match -- save that info */
                                {
                                        /* got a match -- save that info */
-                                       if (mxmatch == NULL)
+                                       if (trymx && mxmatch == NULL)
                                                mxmatch = *dp;
                                        continue;
                                }
                                                mxmatch = *dp;
                                        continue;
                                }
@@ -494,9 +662,34 @@ cnameloop:
                                continue;
 
                          case T_CNAME:
                                continue;
 
                          case T_CNAME:
+                               if (DontExpandCnames)
+                               {
+                                       /* got CNAME -- guaranteed canonical */
+                                       amatch = TRUE;
+                                       break;
+                               }
+
+                               if (loopcnt++ > MAXCNAMEDEPTH)
+                               {
+                                       /*XXX should notify postmaster XXX*/
+                                       message("DNS failure: CNAME loop for %s",
+                                               host);
+                                       if (CurEnv->e_message == NULL)
+                                       {
+                                               char ebuf[MAXLINE];
+
+                                               sprintf(ebuf, "Deferred: DNS failure: CNAME loop for %s",
+                                                       host);
+                                               CurEnv->e_message = newstr(ebuf);
+                                       }
+                                       h_errno = NO_RECOVERY;
+                                       *statp = EX_CONFIG;
+                                       return FALSE;
+                               }
+
                                /* value points at name */
                                if ((ret = dn_expand((u_char *)&answer,
                                /* value points at name */
                                if ((ret = dn_expand((u_char *)&answer,
-                                   eom, ap, (u_char *)nbuf, sizeof(nbuf))) < 0)
+                                   eom, ap, (RES_UNC_T) nbuf, sizeof(nbuf))) < 0)
                                        break;
                                (void)strncpy(host, nbuf, hbsize); /* XXX */
                                host[hbsize - 1] = '\0';
                                        break;
                                (void)strncpy(host, nbuf, hbsize); /* XXX */
                                host[hbsize - 1] = '\0';
@@ -529,7 +722,7 @@ cnameloop:
 
                if (qtype == T_ANY)
                        qtype = T_A;
 
                if (qtype == T_ANY)
                        qtype = T_A;
-               else if (qtype == T_A && !gotmx)
+               else if (qtype == T_A && !gotmx && trymx)
                        qtype = T_MX;
                else
                {
                        qtype = T_MX;
                else
                {
@@ -540,7 +733,10 @@ cnameloop:
        }
 
        if (mxmatch == NULL)
        }
 
        if (mxmatch == NULL)
+       {
+               *statp = EX_NOHOST;
                return FALSE;
                return FALSE;
+       }
 
        /* create matching name and return */
        (void) sprintf(nbuf, "%.*s%s%.*s", MAXDNAME, host,
 
        /* create matching name and return */
        (void) sprintf(nbuf, "%.*s%s%.*s", MAXDNAME, host,
@@ -548,29 +744,56 @@ cnameloop:
                        MAXDNAME, mxmatch);
        strncpy(host, nbuf, hbsize);
        host[hbsize - 1] = '\0';
                        MAXDNAME, mxmatch);
        strncpy(host, nbuf, hbsize);
        host[hbsize - 1] = '\0';
+       *statp = EX_OK;
        return TRUE;
 }
 
        return TRUE;
 }
 
-#else /* not NAMED_BIND */
-
-#include <netdb.h>
 
 
-bool
-getcanonname(host, hbsize)
+char *
+gethostalias(host)
        char *host;
        char *host;
-       int hbsize;
 {
 {
-       struct hostent *hp;
-
-       hp = gethostbyname(host);
-       if (hp == NULL)
-               return (FALSE);
+       char *fname;
+       FILE *fp;
+       register char *p = NULL;
+       char buf[MAXLINE];
+       static char hbuf[MAXDNAME];
+
+       fname = getenv("HOSTALIASES");
+       if (fname == NULL ||
+           (fp = safefopen(fname, O_RDONLY, 0, SFF_REGONLY)) == NULL)
+               return NULL;
+       while (fgets(buf, sizeof buf, fp) != NULL)
+       {
+               for (p = buf; p != '\0' && !(isascii(*p) && isspace(*p)); p++)
+                       continue;
+               if (*p == 0)
+               {
+                       /* syntax error */
+                       continue;
+               }
+               *p++ = '\0';
+               if (strcasecmp(buf, host) == 0)
+                       break;
+       }
 
 
-       if (strlen(hp->h_name) >= hbsize)
-               return (FALSE);
+       if (feof(fp))
+       {
+               /* no match */
+               fclose(fp);
+               return NULL;
+       }
 
 
-       (void) strcpy(host, hp->h_name);
-       return (TRUE);
+       /* got a match; extract the equivalent name */
+       while (*p != '\0' && isascii(*p) && isspace(*p))
+               p++;
+       host = p;
+       while (*p != '\0' && !(isascii(*p) && isspace(*p)))
+               p++;
+       *p = '\0';
+       strncpy(hbuf, host, sizeof hbuf - 1);
+       hbuf[sizeof hbuf - 1] = '\0';
+       return hbuf;
 }
 
 }
 
-#endif /* not NAMED_BIND */
+#endif /* NAMED_BIND */