#include <sendmail.h>
#include "map.h"
#if NAMED_BIND
SM_RCSID("@(#)$Id: domain.c,v 8.202 2006/12/19 01:15:07 ca Exp $ (with name server)")
#else
SM_RCSID("@(#)$Id: domain.c,v 8.202 2006/12/19 01:15:07 ca Exp $ (without name server)")
#endif
#if NAMED_BIND
# include <arpa/inet.h>
# ifndef MAXPACKET
# define MAXPACKET 8192
# endif
typedef union
{
HEADER qb1;
unsigned char qb2[MAXPACKET];
} querybuf;
# ifndef MXHOSTBUFSIZE
# define MXHOSTBUFSIZE (128 * MAXMXHOSTS)
# endif
static char MXHostBuf[MXHOSTBUFSIZE];
#if (MXHOSTBUFSIZE < 2) || (MXHOSTBUFSIZE >= INT_MAX/2)
ERROR: _MXHOSTBUFSIZE is out of range
#endif
# ifndef MAXDNSRCH
# define MAXDNSRCH 6
# endif
# ifndef RES_DNSRCH_VARIABLE
# define RES_DNSRCH_VARIABLE _res.dnsrch
# endif
# ifndef NO_DATA
# define NO_DATA NO_ADDRESS
# endif
# ifndef HFIXEDSZ
# define HFIXEDSZ 12
# endif
# define MAXCNAMEDEPTH 10
# if defined(__RES) && (__RES >= 19940415)
# define RES_UNC_T char *
# else
# define RES_UNC_T unsigned char *
# endif
static int mxrand __P((char *));
static int fallbackmxrr __P((int, unsigned short *, char **));
int NumFallbackMXHosts = 0;
static char *fbhosts[MAXMXHOSTS + 1];
int
getfallbackmxrr(host)
char *host;
{
int i, rcode;
int ttl;
static time_t renew = 0;
#if 0
if (host == NULL || *host == '\0')
return 0;
#endif
if (NumFallbackMXHosts > 0 && renew > curtime())
return NumFallbackMXHosts;
if (host[0] == '[')
{
fbhosts[0] = host;
NumFallbackMXHosts = 1;
}
else
{
for (i = 0; i < NumFallbackMXHosts; i++)
sm_free(fbhosts[i]);
NumFallbackMXHosts = getmxrr(host, fbhosts, NULL, false,
&rcode, false, &ttl);
renew = curtime() + ttl;
for (i = 0; i < NumFallbackMXHosts; i++)
fbhosts[i] = newstr(fbhosts[i]);
}
return NumFallbackMXHosts;
}
static int
fallbackmxrr(nmx, prefs, mxhosts)
int nmx;
unsigned short *prefs;
char **mxhosts;
{
int i;
for (i = 0; i < NumFallbackMXHosts && nmx < MAXMXHOSTS; i++)
{
if (nmx > 0)
prefs[nmx] = prefs[nmx - 1] + 1;
else
prefs[nmx] = 0;
mxhosts[nmx++] = fbhosts[i];
}
return nmx;
}
int
getmxrr(host, mxhosts, mxprefs, droplocalhost, rcode, tryfallback, pttl)
char *host;
char **mxhosts;
unsigned short *mxprefs;
bool droplocalhost;
int *rcode;
bool tryfallback;
int *pttl;
{
register unsigned char *eom, *cp;
register int i, j, n;
int nmx = 0;
register char *bp;
HEADER *hp;
querybuf answer;
int ancount, qdcount, buflen;
bool seenlocal = false;
unsigned short pref, type;
unsigned short localpref = 256;
char *fallbackMX = FallbackMX;
bool trycanon = false;
unsigned short *prefs;
int (*resfunc) __P((const char *, int, int, u_char *, int));
unsigned short prefer[MAXMXHOSTS];
int weight[MAXMXHOSTS];
int ttl = 0;
extern int res_query(), res_search();
if (tTd(8, 2))
sm_dprintf("getmxrr(%s, droplocalhost=%d)\n",
host, droplocalhost);
*rcode = EX_OK;
if (pttl != NULL)
*pttl = SM_DEFAULT_TTL;
if (*host == '\0')
return 0;
if ((fallbackMX != NULL && droplocalhost &&
wordinclass(fallbackMX, 'w')) || !tryfallback)
{
fallbackMX = NULL;
}
if (mxprefs != NULL)
prefs = mxprefs;
else
prefs = prefer;
if (host[0] == '[')
goto punt;
if (!UseNameServer)
goto punt;
if (HasWildcardMX && ConfigLevel >= 6)
resfunc = res_query;
else
resfunc = res_search;
errno = 0;
n = (*resfunc)(host, C_IN, T_MX, (unsigned char *) &answer,
sizeof(answer));
if (n < 0)
{
if (tTd(8, 1))
sm_dprintf("getmxrr: res_search(%s) failed (errno=%d, h_errno=%d)\n",
host, errno, h_errno);
switch (h_errno)
{
case NO_DATA:
trycanon = true;
case NO_RECOVERY:
goto punt;
case HOST_NOT_FOUND:
# if BROKEN_RES_SEARCH
case 0:
# endif
trycanon = true;
*rcode = EX_NOHOST;
goto punt;
case TRY_AGAIN:
case -1:
if (fallbackMX != NULL)
{
return fallbackmxrr(nmx, prefs, mxhosts);
}
*rcode = EX_TEMPFAIL;
break;
default:
syserr("getmxrr: res_search (%s) failed with impossible h_errno (%d)",
host, h_errno);
*rcode = EX_OSERR;
break;
}
return -1;
}
if (n > sizeof(answer))
n = sizeof(answer);
hp = (HEADER *)&answer;
cp = (unsigned char *)&answer + HFIXEDSZ;
eom = (unsigned char *)&answer + n;
for (qdcount = ntohs((unsigned short) hp->qdcount);
qdcount--;
cp += n + QFIXEDSZ)
{
if ((n = dn_skipname(cp, eom)) < 0)
goto punt;
}
buflen = sizeof(MXHostBuf) - 1;
SM_ASSERT(buflen > 0);
bp = MXHostBuf;
ancount = ntohs((unsigned short) hp->ancount);
while (--ancount >= 0 && cp < eom && nmx < MAXMXHOSTS - 1)
{
if ((n = dn_expand((unsigned char *)&answer, eom, cp,
(RES_UNC_T) bp, buflen)) < 0)
break;
cp += n;
GETSHORT(type, cp);
cp += INT16SZ;
GETLONG(ttl, cp);
GETSHORT(n, cp);
if (type != T_MX)
{
if (tTd(8, 8) || _res.options & RES_DEBUG)
sm_dprintf("unexpected answer type %d, size %d\n",
type, n);
cp += n;
continue;
}
GETSHORT(pref, cp);
if ((n = dn_expand((unsigned char *)&answer, eom, cp,
(RES_UNC_T) bp, buflen)) < 0)
break;
cp += n;
n = strlen(bp);
# if 0
if (n == 0)
{
if (LogLevel > 4)
sm_syslog(LOG_ERR, NOQID,
"MX records for %s contain empty string",
host);
continue;
}
# endif
if (wordinclass(bp, 'w'))
{
if (tTd(8, 3))
sm_dprintf("found localhost (%s) in MX list, pref=%d\n",
bp, pref);
if (droplocalhost)
{
if (!seenlocal || pref < localpref)
localpref = pref;
seenlocal = true;
continue;
}
weight[nmx] = 0;
}
else
weight[nmx] = mxrand(bp);
prefs[nmx] = pref;
mxhosts[nmx++] = bp;
bp += n;
if (bp[-1] != '.')
{
*bp++ = '.';
n++;
}
*bp++ = '\0';
if (buflen < n + 1)
{
break;
}
buflen -= n + 1;
}
if (ttl > 0 && pttl != NULL)
*pttl = ttl;
for (i = 0; i < nmx; i++)
{
for (j = i + 1; j < nmx; j++)
{
if (prefs[i] > prefs[j] ||
(prefs[i] == prefs[j] && weight[i] > weight[j]))
{
register int temp;
register char *temp1;
temp = prefs[i];
prefs[i] = prefs[j];
prefs[j] = temp;
temp1 = mxhosts[i];
mxhosts[i] = mxhosts[j];
mxhosts[j] = temp1;
temp = weight[i];
weight[i] = weight[j];
weight[j] = temp;
}
}
if (seenlocal && prefs[i] >= localpref)
{
nmx = i;
}
}
for (i = 0; i < nmx - 1; )
{
if (sm_strcasecmp(mxhosts[i], mxhosts[i + 1]) != 0)
i++;
else
{
for (j = i + 1; j < nmx; j++)
{
mxhosts[j] = mxhosts[j + 1];
prefs[j] = prefs[j + 1];
}
nmx--;
}
}
if (nmx == 0)
{
punt:
if (seenlocal)
{
struct hostent *h = NULL;
if (TryNullMXList)
{
SM_SET_H_ERRNO(0);
errno = 0;
h = sm_gethostbyname(host, AF_INET);
if (h == NULL)
{
if (errno == ETIMEDOUT ||
h_errno == TRY_AGAIN ||
(errno == ECONNREFUSED &&
UseNameServer))
{
*rcode = EX_TEMPFAIL;
return -1;
}
# if NETINET6
SM_SET_H_ERRNO(0);
errno = 0;
h = sm_gethostbyname(host, AF_INET6);
if (h == NULL &&
(errno == ETIMEDOUT ||
h_errno == TRY_AGAIN ||
(errno == ECONNREFUSED &&
UseNameServer)))
{
*rcode = EX_TEMPFAIL;
return -1;
}
# endif
}
}
if (h == NULL)
{
*rcode = EX_CONFIG;
syserr("MX list for %s points back to %s",
host, MyHostName);
return -1;
}
# if NETINET6
freehostent(h);
h = NULL;
# endif
}
if (strlen(host) >= sizeof(MXHostBuf))
{
*rcode = EX_CONFIG;
syserr("Host name %s too long",
shortenstring(host, MAXSHORTSTR));
return -1;
}
(void) sm_strlcpy(MXHostBuf, host, sizeof(MXHostBuf));
mxhosts[0] = MXHostBuf;
prefs[0] = 0;
if (host[0] == '[')
{
register char *p;
# if NETINET6
struct sockaddr_in6 tmp6;
# endif
p = strchr(MXHostBuf, ']');
if (p != NULL)
{
*p = '\0';
if (inet_addr(&MXHostBuf[1]) != INADDR_NONE)
{
nmx++;
*p = ']';
}
# if NETINET6
else if (anynet_pton(AF_INET6, &MXHostBuf[1],
&tmp6.sin6_addr) == 1)
{
nmx++;
*p = ']';
}
# endif
else
{
trycanon = true;
mxhosts[0]++;
}
}
}
if (trycanon &&
getcanonname(mxhosts[0], sizeof(MXHostBuf) - 2, false, pttl))
{
bp = &MXHostBuf[strlen(MXHostBuf)];
if (bp[-1] != '.')
{
*bp++ = '.';
*bp = '\0';
}
nmx = 1;
}
}
if (fallbackMX != NULL && !seenlocal)
{
nmx = fallbackmxrr(nmx, prefs, mxhosts);
}
return nmx;
}
static int
mxrand(host)
register char *host;
{
int hfunc;
static unsigned int seed;
if (seed == 0)
{
seed = (int) curtime() & 0xffff;
if (seed == 0)
seed++;
}
if (tTd(17, 9))
sm_dprintf("mxrand(%s)", host);
hfunc = seed;
while (*host != '\0')
{
int c = *host++;
if (isascii(c) && isupper(c))
c = tolower(c);
hfunc = ((hfunc << 1) ^ c) % 2003;
}
hfunc &= 0xff;
hfunc++;
if (tTd(17, 9))
sm_dprintf(" = %d\n", hfunc);
return hfunc;
}
char *
bestmx_map_lookup(map, name, av, statp)
MAP *map;
char *name;
char **av;
int *statp;
{
int nmx;
int saveopts = _res.options;
int i;
ssize_t len = 0;
char *result;
char *mxhosts[MAXMXHOSTS + 1];
#if _FFR_BESTMX_BETTER_TRUNCATION
char *buf;
#else
char *p;
char buf[PSBUFSIZE / 2];
#endif
_res.options &= ~(RES_DNSRCH|RES_DEFNAMES);
nmx = getmxrr(name, mxhosts, NULL, false, statp, false, NULL);
_res.options = saveopts;
if (nmx <= 0)
return NULL;
if (bitset(MF_MATCHONLY, map->map_mflags))
return map_rewrite(map, name, strlen(name), NULL);
if ((map->map_coldelim == '\0') || (nmx == 1))
return map_rewrite(map, mxhosts[0], strlen(mxhosts[0]), av);
#if _FFR_BESTMX_BETTER_TRUNCATION
for (i = 0; i < nmx; i++)
{
if (strchr(mxhosts[i], map->map_coldelim) != NULL)
{
syserr("bestmx_map_lookup: MX host %.64s includes map delimiter character 0x%02X",
mxhosts[i], map->map_coldelim);
return NULL;
}
len += strlen(mxhosts[i]) + 1;
if (len < 0)
{
len -= strlen(mxhosts[i]) + 1;
break;
}
}
buf = (char *) sm_malloc(len);
if (buf == NULL)
{
*statp = EX_UNAVAILABLE;
return NULL;
}
*buf = '\0';
for (i = 0; i < nmx; i++)
{
int end;
end = sm_strlcat(buf, mxhosts[i], len);
if (i != nmx && end + 1 < len)
{
buf[end] = map->map_coldelim;
buf[end + 1] = '\0';
}
}
truncate_at_delim(buf, PSBUFSIZE / 2, map->map_coldelim);
#else
p = buf;
for (i = 0; i < nmx; i++)
{
size_t slen;
if (strchr(mxhosts[i], map->map_coldelim) != NULL)
{
syserr("bestmx_map_lookup: MX host %.64s includes map delimiter character 0x%02X",
mxhosts[i], map->map_coldelim);
return NULL;
}
slen = strlen(mxhosts[i]);
if (len + slen + 2 > sizeof(buf))
break;
if (i > 0)
{
*p++ = map->map_coldelim;
len++;
}
(void) sm_strlcpy(p, mxhosts[i], sizeof(buf) - len);
p += slen;
len += slen;
}
#endif
result = map_rewrite(map, buf, len, av);
#if _FFR_BESTMX_BETTER_TRUNCATION
sm_free(buf);
#endif
return result;
}
bool
dns_getcanonname(host, hbsize, trymx, statp, pttl)
char *host;
int hbsize;
bool trymx;
int *statp;
int *pttl;
{
register unsigned char *eom, *ap;
register char *cp;
register int n;
HEADER *hp;
querybuf answer;
int ancount, qdcount;
int ret;
char **domain;
int type;
int ttl = 0;
char **dp;
char *mxmatch;
bool amatch;
bool gotmx = false;
int qtype;
int initial;
int loopcnt;
char nbuf[SM_MAX(MAXPACKET, MAXDNAME*2+2)];
char *searchlist[MAXDNSRCH + 2];
if (tTd(8, 2))
sm_dprintf("dns_getcanonname(%s, trymx=%d)\n", host, trymx);
if ((_res.options & RES_INIT) == 0 && res_init() == -1)
{
*statp = EX_UNAVAILABLE;
return false;
}
*statp = EX_OK;
loopcnt = 0;
cnameloop:
for (cp = host, n = 0; *cp != '\0'; cp++)
if (*cp == '.')
n++;
dp = searchlist;
if (n > 0)
*dp++ = "";
if (n >= 0 && *--cp != '.' && bitset(RES_DNSRCH, _res.options))
{
for (domain = RES_DNSRCH_VARIABLE, ret = 0;
*domain != NULL && ret < MAXDNSRCH;
ret++)
*dp++ = *domain++;
}
else if (n == 0 && bitset(RES_DEFNAMES, _res.options))
{
*dp++ = _res.defdname;
}
else if (*cp == '.')
{
*cp = '\0';
}
*dp = NULL;
mxmatch = NULL;
initial = T_A;
# if NETINET6
if (InetMode == AF_INET6)
initial = T_AAAA;
# endif
qtype = initial;
for (dp = searchlist; *dp != NULL; )
{
if (qtype == initial)
gotmx = false;
if (tTd(8, 5))
sm_dprintf("dns_getcanonname: trying %s.%s (%s)\n",
host, *dp,
# if NETINET6
qtype == T_AAAA ? "AAAA" :
# endif
qtype == T_A ? "A" :
qtype == T_MX ? "MX" :
"???");
errno = 0;
ret = res_querydomain(host, *dp, C_IN, qtype,
answer.qb2, sizeof(answer.qb2));
if (ret <= 0)
{
int save_errno = errno;
if (tTd(8, 7))
sm_dprintf("\tNO: errno=%d, h_errno=%d\n",
save_errno, h_errno);
if (save_errno == ECONNREFUSED || h_errno == TRY_AGAIN)
{
SM_SET_H_ERRNO(TRY_AGAIN);
if (**dp == '\0')
{
if (*statp == EX_OK)
*statp = EX_TEMPFAIL;
goto nexttype;
}
*statp = EX_TEMPFAIL;
if (WorkAroundBrokenAAAA)
{
if (save_errno != ETIMEDOUT)
return false;
}
else
return false;
}
nexttype:
if (h_errno != HOST_NOT_FOUND)
{
# if NETINET6
if (qtype == T_AAAA)
{
qtype = T_A;
continue;
}
else
# endif
if (qtype == T_A && !gotmx &&
(trymx || **dp == '\0'))
{
qtype = T_MX;
continue;
}
}
dp++;
qtype = initial;
continue;
}
else if (tTd(8, 7))
sm_dprintf("\tYES\n");
if (ret > sizeof(answer))
ret = sizeof(answer);
SM_ASSERT(ret >= 0);
hp = (HEADER *) &answer;
ap = (unsigned char *) &answer + HFIXEDSZ;
eom = (unsigned char *) &answer + ret;
for (qdcount = ntohs((unsigned short) hp->qdcount);
qdcount--;
ap += ret + QFIXEDSZ)
{
if ((ret = dn_skipname(ap, eom)) < 0)
{
if (tTd(8, 20))
sm_dprintf("qdcount failure (%d)\n",
ntohs((unsigned short) hp->qdcount));
*statp = EX_SOFTWARE;
return false;
}
}
amatch = false;
for (ancount = ntohs((unsigned short) hp->ancount);
--ancount >= 0 && ap < eom;
ap += n)
{
n = dn_expand((unsigned char *) &answer, eom, ap,
(RES_UNC_T) nbuf, sizeof(nbuf));
if (n < 0)
break;
ap += n;
GETSHORT(type, ap);
ap += INT16SZ;
GETLONG(ttl, ap);
GETSHORT(n, ap);
switch (type)
{
case T_MX:
gotmx = true;
if (**dp != '\0' && HasWildcardMX)
{
if (trymx && mxmatch == NULL)
mxmatch = *dp;
continue;
}
# if NETINET6
case T_AAAA:
# endif
case T_A:
amatch = true;
continue;
case T_CNAME:
if (DontExpandCnames)
{
amatch = true;
break;
}
if (loopcnt++ > MAXCNAMEDEPTH)
{
message("DNS failure: CNAME loop for %s",
host);
if (CurEnv->e_message == NULL)
{
char ebuf[MAXLINE];
(void) sm_snprintf(ebuf,
sizeof(ebuf),
"Deferred: DNS failure: CNAME loop for %.100s",
host);
CurEnv->e_message =
sm_rpool_strdup_x(
CurEnv->e_rpool, ebuf);
}
SM_SET_H_ERRNO(NO_RECOVERY);
*statp = EX_CONFIG;
return false;
}
if ((ret = dn_expand((unsigned char *)&answer,
eom, ap, (RES_UNC_T) nbuf,
sizeof(nbuf))) < 0)
break;
(void) sm_strlcpy(host, nbuf, hbsize);
goto cnameloop;
default:
continue;
}
}
if (amatch)
{
mxmatch = *dp;
break;
}
# if NETINET6
if (qtype == T_AAAA)
qtype = T_A;
else
# endif
if (qtype == T_A && !gotmx && (trymx || **dp == '\0'))
qtype = T_MX;
else
{
qtype = initial;
dp++;
}
}
if (mxmatch == NULL)
{
if (*statp == EX_OK)
*statp = EX_NOHOST;
return false;
}
(void) sm_snprintf(nbuf, sizeof(nbuf), "%.*s%s%.*s", MAXDNAME, host,
*mxmatch == '\0' ? "" : ".",
MAXDNAME, mxmatch);
(void) sm_strlcpy(host, nbuf, hbsize);
if (tTd(8, 5))
sm_dprintf("dns_getcanonname: %s\n", host);
*statp = EX_OK;
if (ttl > 0 && pttl != NULL)
*pttl = ttl;
return true;
}
#endif