2 * Copyright (c) 1998-2004, 2006, 2010 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1986, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
18 SM_RCSID("@(#)$Id: domain.c,v 8.204 2010/06/29 15:35:33 ca Exp $ (with name server)")
19 #else /* NAMED_BIND */
20 SM_RCSID("@(#)$Id: domain.c,v 8.204 2010/06/29 15:35:33 ca Exp $ (without name server)")
21 #endif /* NAMED_BIND */
25 # include <arpa/inet.h>
28 # ifndef MXHOSTBUFSIZE
29 # define MXHOSTBUFSIZE (128 * MAXMXHOSTS)
30 # endif /* ! MXHOSTBUFSIZE */
32 static char MXHostBuf[MXHOSTBUFSIZE];
33 #if (MXHOSTBUFSIZE < 2) || (MXHOSTBUFSIZE >= INT_MAX/2)
34 ERROR: _MXHOSTBUFSIZE is out of range
35 #endif /* (MXHOSTBUFSIZE < 2) || (MXHOSTBUFSIZE >= INT_MAX/2) */
38 # define MAXDNSRCH 6 /* number of possible domains to search */
39 # endif /* ! MAXDNSRCH */
41 # ifndef RES_DNSRCH_VARIABLE
42 # define RES_DNSRCH_VARIABLE _res.dnsrch
43 # endif /* ! RES_DNSRCH_VARIABLE */
46 # define NO_DATA NO_ADDRESS
47 # endif /* ! NO_DATA */
50 # define HFIXEDSZ 12 /* sizeof(HEADER) */
51 # endif /* ! HFIXEDSZ */
53 # define MAXCNAMEDEPTH 10 /* maximum depth of CNAME recursion */
55 # if defined(__RES) && (__RES >= 19940415)
56 # define RES_UNC_T char *
57 # else /* defined(__RES) && (__RES >= 19940415) */
58 # define RES_UNC_T unsigned char *
59 # endif /* defined(__RES) && (__RES >= 19940415) */
61 static int mxrand __P((char *));
62 static int fallbackmxrr __P((int, unsigned short *, char **));
65 ** GETFALLBACKMXRR -- get MX resource records for fallback MX host.
67 ** We have to initialize this once before doing anything else.
68 ** Moreover, we have to repeat this from time to time to avoid
69 ** stale data, e.g., in persistent queue runners.
70 ** This should be done in a parent process so the child
71 ** processes have the right data.
74 ** host -- the name of the fallback MX host.
77 ** number of MX records.
80 ** Populates NumFallbackMXHosts and fbhosts.
81 ** Sets renewal time (based on TTL).
84 int NumFallbackMXHosts = 0; /* Number of fallback MX hosts (after MX expansion) */
85 static char *fbhosts[MAXMXHOSTS + 1];
93 static time_t renew = 0;
96 /* This is currently done before this function is called. */
97 if (host == NULL || *host == '\0')
100 if (NumFallbackMXHosts > 0 && renew > curtime())
101 return NumFallbackMXHosts;
105 NumFallbackMXHosts = 1;
110 for (i = 0; i < NumFallbackMXHosts; i++)
114 NumFallbackMXHosts = getmxrr(host, fbhosts, NULL, false,
115 &rcode, false, &ttl);
116 renew = curtime() + ttl;
117 for (i = 0; i < NumFallbackMXHosts; i++)
118 fbhosts[i] = newstr(fbhosts[i]);
120 return NumFallbackMXHosts;
124 ** FALLBACKMXRR -- add MX resource records for fallback MX host to list.
127 ** nmx -- current number of MX records.
128 ** prefs -- array of preferences.
129 ** mxhosts -- array of MX hosts (maximum size: MAXMXHOSTS)
132 ** new number of MX records.
135 ** If FallbackMX was set, it appends the MX records for
136 ** that host to mxhosts (and modifies prefs accordingly).
140 fallbackmxrr(nmx, prefs, mxhosts)
142 unsigned short *prefs;
147 for (i = 0; i < NumFallbackMXHosts && nmx < MAXMXHOSTS; i++)
150 prefs[nmx] = prefs[nmx - 1] + 1;
153 mxhosts[nmx++] = fbhosts[i];
159 ** GETMXRR -- get MX resource records for a domain
162 ** host -- the name of the host to MX.
163 ** mxhosts -- a pointer to a return buffer of MX records.
164 ** mxprefs -- a pointer to a return buffer of MX preferences.
165 ** If NULL, don't try to populate.
166 ** droplocalhost -- If true, all MX records less preferred
167 ** than the local host (as determined by $=w) will
169 ** rcode -- a pointer to an EX_ status code.
170 ** tryfallback -- add also fallback MX host?
171 ** pttl -- pointer to return TTL (can be NULL).
174 ** The number of MX records found.
175 ** -1 if there is an internal failure.
176 ** If no MX records are found, mxhosts[0] is set to host
177 ** and 1 is returned.
180 ** The entries made for mxhosts point to a static array
181 ** MXHostBuf[MXHOSTBUFSIZE], so the data needs to be copied,
182 ** if it must be preserved across calls to this function.
186 getmxrr(host, mxhosts, mxprefs, droplocalhost, rcode, tryfallback, pttl)
189 unsigned short *mxprefs;
195 register unsigned char *eom, *cp;
196 register int i, j, n;
201 int ancount, qdcount, buflen;
202 bool seenlocal = false;
203 unsigned short pref, type;
204 unsigned short localpref = 256;
205 char *fallbackMX = FallbackMX;
206 bool trycanon = false;
207 unsigned short *prefs;
208 int (*resfunc) __P((const char *, int, int, u_char *, int));
209 unsigned short prefer[MAXMXHOSTS];
210 int weight[MAXMXHOSTS];
212 extern int res_query(), res_search();
215 sm_dprintf("getmxrr(%s, droplocalhost=%d)\n",
216 host, droplocalhost);
219 *pttl = SM_DEFAULT_TTL;
223 if ((fallbackMX != NULL && droplocalhost &&
224 wordinclass(fallbackMX, 'w')) || !tryfallback)
226 /* don't use fallback for this pass */
235 /* efficiency hack -- numeric or non-MX lookups */
240 ** If we don't have MX records in our host switch, don't
241 ** try for MX records. Note that this really isn't "right",
242 ** since we might be set up to try NIS first and then DNS;
243 ** if the host is found in NIS we really shouldn't be doing
244 ** MX lookups. However, that should be a degenerate case.
249 if (HasWildcardMX && ConfigLevel >= 6)
252 resfunc = res_search;
255 n = (*resfunc)(host, C_IN, T_MX, (unsigned char *) &answer,
260 sm_dprintf("getmxrr: res_search(%s) failed (errno=%d, h_errno=%d)\n",
261 host, errno, h_errno);
269 /* no MX data on this host */
273 # if BROKEN_RES_SEARCH
274 case 0: /* Ultrix resolver retns failure w/ h_errno=0 */
275 # endif /* BROKEN_RES_SEARCH */
276 /* host doesn't exist in DNS; might be in /etc/hosts */
283 /* couldn't connect to the name server */
284 if (fallbackMX != NULL)
286 /* name server is hosed -- push to fallback */
287 return fallbackmxrr(nmx, prefs, mxhosts);
289 /* it might come up later; better queue it up */
290 *rcode = EX_TEMPFAIL;
294 syserr("getmxrr: res_search (%s) failed with impossible h_errno (%d)",
300 /* irreconcilable differences */
304 /* avoid problems after truncation in tcp packets */
305 if (n > sizeof(answer))
308 /* find first satisfactory answer */
309 hp = (HEADER *)&answer;
310 cp = (unsigned char *)&answer + HFIXEDSZ;
311 eom = (unsigned char *)&answer + n;
312 for (qdcount = ntohs((unsigned short) hp->qdcount);
316 if ((n = dn_skipname(cp, eom)) < 0)
320 /* NOTE: see definition of MXHostBuf! */
321 buflen = sizeof(MXHostBuf) - 1;
322 SM_ASSERT(buflen > 0);
324 ancount = ntohs((unsigned short) hp->ancount);
326 /* See RFC 1035 for layout of RRs. */
327 /* XXX leave room for FallbackMX ? */
328 while (--ancount >= 0 && cp < eom && nmx < MAXMXHOSTS - 1)
330 if ((n = dn_expand((unsigned char *)&answer, eom, cp,
331 (RES_UNC_T) bp, buflen)) < 0)
335 cp += INT16SZ; /* skip over class */
337 GETSHORT(n, cp); /* rdlength */
340 if (tTd(8, 8) || _res.options & RES_DEBUG)
341 sm_dprintf("unexpected answer type %d, size %d\n",
347 if ((n = dn_expand((unsigned char *)&answer, eom, cp,
348 (RES_UNC_T) bp, buflen)) < 0)
353 /* Can this happen? */
357 sm_syslog(LOG_ERR, NOQID,
358 "MX records for %s contain empty string",
363 if (wordinclass(bp, 'w'))
366 sm_dprintf("found localhost (%s) in MX list, pref=%d\n",
370 if (!seenlocal || pref < localpref)
378 weight[nmx] = mxrand(bp);
390 /* don't want to wrap buflen */
396 /* return only one TTL entry, that should be sufficient */
397 if (ttl > 0 && pttl != NULL)
400 /* sort the records */
401 for (i = 0; i < nmx; i++)
403 for (j = i + 1; j < nmx; j++)
405 if (prefs[i] > prefs[j] ||
406 (prefs[i] == prefs[j] && weight[i] > weight[j]))
409 register char *temp1;
415 mxhosts[i] = mxhosts[j];
418 weight[i] = weight[j];
422 if (seenlocal && prefs[i] >= localpref)
424 /* truncate higher preference part of list */
429 /* delete duplicates from list (yes, some bozos have duplicates) */
430 for (i = 0; i < nmx - 1; )
432 if (sm_strcasecmp(mxhosts[i], mxhosts[i + 1]) != 0)
436 /* compress out duplicate */
437 for (j = i + 1; j < nmx; j++)
439 mxhosts[j] = mxhosts[j + 1];
440 prefs[j] = prefs[j + 1];
451 struct hostent *h = NULL;
454 ** If we have deleted all MX entries, this is
455 ** an error -- we should NEVER send to a host that
456 ** has an MX, and this should have been caught
457 ** earlier in the config file.
459 ** Some sites prefer to go ahead and try the
460 ** A record anyway; that case is handled by
461 ** setting TryNullMXList. I believe this is a
462 ** bad idea, but it's up to you....
469 h = sm_gethostbyname(host, AF_INET);
472 if (errno == ETIMEDOUT ||
473 h_errno == TRY_AGAIN ||
474 (errno == ECONNREFUSED &&
477 *rcode = EX_TEMPFAIL;
483 h = sm_gethostbyname(host, AF_INET6);
485 (errno == ETIMEDOUT ||
486 h_errno == TRY_AGAIN ||
487 (errno == ECONNREFUSED &&
490 *rcode = EX_TEMPFAIL;
493 # endif /* NETINET6 */
500 syserr("MX list for %s points back to %s",
507 # endif /* NETINET6 */
509 if (strlen(host) >= sizeof(MXHostBuf))
512 syserr("Host name %s too long",
513 shortenstring(host, MAXSHORTSTR));
516 (void) sm_strlcpy(MXHostBuf, host, sizeof(MXHostBuf));
517 mxhosts[0] = MXHostBuf;
523 struct sockaddr_in6 tmp6;
524 # endif /* NETINET6 */
526 /* this may be an MX suppression-style address */
527 p = strchr(MXHostBuf, ']');
532 if (inet_addr(&MXHostBuf[1]) != INADDR_NONE)
538 else if (anynet_pton(AF_INET6, &MXHostBuf[1],
539 &tmp6.sin6_addr) == 1)
544 # endif /* NETINET6 */
553 getcanonname(mxhosts[0], sizeof(MXHostBuf) - 2, false, pttl))
555 /* XXX MXHostBuf == "" ? is that possible? */
556 bp = &MXHostBuf[strlen(MXHostBuf)];
566 /* if we have a default lowest preference, include that */
567 if (fallbackMX != NULL && !seenlocal)
569 nmx = fallbackmxrr(nmx, prefs, mxhosts);
574 ** MXRAND -- create a randomizer for equal MX preferences
576 ** If two MX hosts have equal preferences we want to randomize
577 ** the selection. But in order for signatures to be the same,
578 ** we need to randomize the same way each time. This function
579 ** computes a pseudo-random hash function from the host name.
582 ** host -- the name of the host.
585 ** A random but repeatable value based on the host name.
593 static unsigned int seed;
597 seed = (int) curtime() & 0xffff;
603 sm_dprintf("mxrand(%s)", host);
606 while (*host != '\0')
610 if (isascii(c) && isupper(c))
612 hfunc = ((hfunc << 1) ^ c) % 2003;
619 sm_dprintf(" = %d\n", hfunc);
623 ** BESTMX -- find the best MX for a name
625 ** This is really a hack, but I don't see any obvious way
626 ** to generalize it at the moment.
631 bestmx_map_lookup(map, name, av, statp)
638 int saveopts = _res.options;
642 char *mxhosts[MAXMXHOSTS + 1];
643 #if _FFR_BESTMX_BETTER_TRUNCATION
645 #else /* _FFR_BESTMX_BETTER_TRUNCATION */
647 char buf[PSBUFSIZE / 2];
648 #endif /* _FFR_BESTMX_BETTER_TRUNCATION */
650 _res.options &= ~(RES_DNSRCH|RES_DEFNAMES);
651 nmx = getmxrr(name, mxhosts, NULL, false, statp, false, NULL);
652 _res.options = saveopts;
655 if (bitset(MF_MATCHONLY, map->map_mflags))
656 return map_rewrite(map, name, strlen(name), NULL);
657 if ((map->map_coldelim == '\0') || (nmx == 1))
658 return map_rewrite(map, mxhosts[0], strlen(mxhosts[0]), av);
661 ** We were given a -z flag (return all MXs) and there are multiple
662 ** ones. We need to build them all into a list.
665 #if _FFR_BESTMX_BETTER_TRUNCATION
666 for (i = 0; i < nmx; i++)
668 if (strchr(mxhosts[i], map->map_coldelim) != NULL)
670 syserr("bestmx_map_lookup: MX host %.64s includes map delimiter character 0x%02X",
671 mxhosts[i], map->map_coldelim);
674 len += strlen(mxhosts[i]) + 1;
677 len -= strlen(mxhosts[i]) + 1;
681 buf = (char *) sm_malloc(len);
684 *statp = EX_UNAVAILABLE;
688 for (i = 0; i < nmx; i++)
692 end = sm_strlcat(buf, mxhosts[i], len);
693 if (i != nmx && end + 1 < len)
695 buf[end] = map->map_coldelim;
700 /* Cleanly truncate for rulesets */
701 truncate_at_delim(buf, PSBUFSIZE / 2, map->map_coldelim);
702 #else /* _FFR_BESTMX_BETTER_TRUNCATION */
704 for (i = 0; i < nmx; i++)
708 if (strchr(mxhosts[i], map->map_coldelim) != NULL)
710 syserr("bestmx_map_lookup: MX host %.64s includes map delimiter character 0x%02X",
711 mxhosts[i], map->map_coldelim);
714 slen = strlen(mxhosts[i]);
715 if (len + slen + 2 > sizeof(buf))
719 *p++ = map->map_coldelim;
722 (void) sm_strlcpy(p, mxhosts[i], sizeof(buf) - len);
726 #endif /* _FFR_BESTMX_BETTER_TRUNCATION */
728 result = map_rewrite(map, buf, len, av);
729 #if _FFR_BESTMX_BETTER_TRUNCATION
731 #endif /* _FFR_BESTMX_BETTER_TRUNCATION */
735 ** DNS_GETCANONNAME -- get the canonical name for named host using DNS
737 ** This algorithm tries to be smart about wildcard MX records.
738 ** This is hard to do because DNS doesn't tell is if we matched
739 ** against a wildcard or a specific MX.
741 ** We always prefer A & CNAME records, since these are presumed
744 ** If we match an MX in one pass and lose it in the next, we use
745 ** the old one. For example, consider an MX matching *.FOO.BAR.COM.
746 ** A hostname bletch.foo.bar.com will match against this MX, but
747 ** will stop matching when we try bletch.bar.com -- so we know
748 ** that bletch.foo.bar.com must have been right. This fails if
749 ** there was also an MX record matching *.BAR.COM, but there are
750 ** some things that just can't be fixed.
753 ** host -- a buffer containing the name of the host.
754 ** This is a value-result parameter.
755 ** hbsize -- the size of the host buffer.
756 ** trymx -- if set, try MX records as well as A and CNAME.
757 ** statp -- pointer to place to store status.
758 ** pttl -- pointer to return TTL (can be NULL).
761 ** true -- if the host matched.
762 ** false -- otherwise.
766 dns_getcanonname(host, hbsize, trymx, statp, pttl)
773 register unsigned char *eom, *ap;
778 int ancount, qdcount;
790 char nbuf[SM_MAX(MAXPACKET, MAXDNAME*2+2)];
791 char *searchlist[MAXDNSRCH + 2];
794 sm_dprintf("dns_getcanonname(%s, trymx=%d)\n", host, trymx);
796 if ((_res.options & RES_INIT) == 0 && res_init() == -1)
798 *statp = EX_UNAVAILABLE;
805 ** Initialize domain search list. If there is at least one
806 ** dot in the name, search the unmodified name first so we
807 ** find "vse.CS" in Czechoslovakia instead of in the local
808 ** domain (e.g., vse.CS.Berkeley.EDU). Note that there is no
809 ** longer a country named Czechoslovakia but this type of problem
812 ** Older versions of the resolver could create this
813 ** list by tearing apart the host name.
818 /* Check for dots in the name */
819 for (cp = host, n = 0; *cp != '\0'; cp++)
824 ** Build the search list.
825 ** If there is at least one dot in name, start with a null
826 ** domain to search the unmodified name first.
827 ** If name does not end with a dot and search up local domain
828 ** tree desired, append each local domain component to the
829 ** search list; if name contains no dots and default domain
830 ** name is desired, append default domain name to search list;
831 ** else if name ends in a dot, remove that dot.
837 if (n >= 0 && *--cp != '.' && bitset(RES_DNSRCH, _res.options))
839 /* make sure there are less than MAXDNSRCH domains */
840 for (domain = RES_DNSRCH_VARIABLE, ret = 0;
841 *domain != NULL && ret < MAXDNSRCH;
845 else if (n == 0 && bitset(RES_DEFNAMES, _res.options))
847 *dp++ = _res.defdname;
856 ** Now loop through the search list, appending each domain in turn
857 ** name and searching for a match.
863 if (InetMode == AF_INET6)
865 # endif /* NETINET6 */
868 for (dp = searchlist; *dp != NULL; )
870 if (qtype == initial)
873 sm_dprintf("dns_getcanonname: trying %s.%s (%s)\n",
876 qtype == T_AAAA ? "AAAA" :
877 # endif /* NETINET6 */
879 qtype == T_MX ? "MX" :
882 ret = res_querydomain(host, *dp, C_IN, qtype,
883 answer.qb2, sizeof(answer.qb2));
886 int save_errno = errno;
889 sm_dprintf("\tNO: errno=%d, h_errno=%d\n",
890 save_errno, h_errno);
892 if (save_errno == ECONNREFUSED || h_errno == TRY_AGAIN)
895 ** the name server seems to be down or broken.
898 SM_SET_H_ERRNO(TRY_AGAIN);
902 *statp = EX_TEMPFAIL;
905 *statp = EX_TEMPFAIL;
907 if (WorkAroundBrokenAAAA)
910 ** Only return if not TRY_AGAIN as an
911 ** attempt with a different qtype may
912 ** succeed (res_querydomain() calls
913 ** res_query() calls res_send() which
914 ** sets errno to ETIMEDOUT if the
915 ** nameservers could be contacted but
916 ** didn't give an answer).
919 if (save_errno != ETIMEDOUT)
927 if (h_errno != HOST_NOT_FOUND)
929 /* might have another type of interest */
937 # endif /* NETINET6 */
938 if (qtype == T_A && !gotmx &&
939 (trymx || **dp == '\0'))
946 /* definite no -- try the next domain */
952 sm_dprintf("\tYES\n");
954 /* avoid problems after truncation in tcp packets */
955 if (ret > sizeof(answer))
956 ret = sizeof(answer);
960 ** Appear to have a match. Confirm it by searching for A or
961 ** CNAME records. If we don't have a local domain
962 ** wild card MX record, we will accept MX as well.
965 hp = (HEADER *) &answer;
966 ap = (unsigned char *) &answer + HFIXEDSZ;
967 eom = (unsigned char *) &answer + ret;
969 /* skip question part of response -- we know what we asked */
970 for (qdcount = ntohs((unsigned short) hp->qdcount);
972 ap += ret + QFIXEDSZ)
974 if ((ret = dn_skipname(ap, eom)) < 0)
977 sm_dprintf("qdcount failure (%d)\n",
978 ntohs((unsigned short) hp->qdcount));
979 *statp = EX_SOFTWARE;
980 return false; /* ???XXX??? */
985 for (ancount = ntohs((unsigned short) hp->ancount);
986 --ancount >= 0 && ap < eom;
989 n = dn_expand((unsigned char *) &answer, eom, ap,
990 (RES_UNC_T) nbuf, sizeof(nbuf));
995 ap += INT16SZ; /* skip over class */
997 GETSHORT(n, ap); /* rdlength */
1002 if (**dp != '\0' && HasWildcardMX)
1005 ** If we are using MX matches and have
1006 ** not yet gotten one, save this one
1007 ** but keep searching for an A or
1011 if (trymx && mxmatch == NULL)
1017 ** If we did not append a domain name, this
1018 ** must have been a canonical name to start
1019 ** with. Even if we did append a domain name,
1020 ** in the absence of a wildcard MX this must
1021 ** still be a real MX match.
1022 ** Such MX matches are as good as an A match,
1029 # endif /* NETINET6 */
1031 /* Flag that a good match was found */
1034 /* continue in case a CNAME also exists */
1038 if (DontExpandCnames)
1040 /* got CNAME -- guaranteed canonical */
1045 if (loopcnt++ > MAXCNAMEDEPTH)
1047 /*XXX should notify postmaster XXX*/
1048 message("DNS failure: CNAME loop for %s",
1050 if (CurEnv->e_message == NULL)
1054 (void) sm_snprintf(ebuf,
1056 "Deferred: DNS failure: CNAME loop for %.100s",
1060 CurEnv->e_rpool, ebuf);
1062 SM_SET_H_ERRNO(NO_RECOVERY);
1067 /* value points at name */
1068 if ((ret = dn_expand((unsigned char *)&answer,
1069 eom, ap, (RES_UNC_T) nbuf,
1072 (void) sm_strlcpy(host, nbuf, hbsize);
1075 ** RFC 1034 section 3.6 specifies that CNAME
1076 ** should point at the canonical name -- but
1077 ** urges software to try again anyway.
1083 /* not a record of interest */
1091 ** Got a good match -- either an A, CNAME, or an
1092 ** exact MX record. Save it and get out of here.
1100 ** Nothing definitive yet.
1101 ** If this was a T_A query and we haven't yet found a MX
1102 ** match, try T_MX if allowed to do so.
1103 ** Otherwise, try the next domain.
1107 if (qtype == T_AAAA)
1110 # endif /* NETINET6 */
1111 if (qtype == T_A && !gotmx && (trymx || **dp == '\0'))
1120 /* if nothing was found, we are done */
1121 if (mxmatch == NULL)
1123 if (*statp == EX_OK)
1129 ** Create canonical name and return.
1130 ** If saved domain name is null, name was already canonical.
1131 ** Otherwise append the saved domain name.
1134 (void) sm_snprintf(nbuf, sizeof(nbuf), "%.*s%s%.*s", MAXDNAME, host,
1135 *mxmatch == '\0' ? "" : ".",
1137 (void) sm_strlcpy(host, nbuf, hbsize);
1139 sm_dprintf("dns_getcanonname: %s\n", host);
1142 /* return only one TTL entry, that should be sufficient */
1143 if (ttl > 0 && pttl != NULL)
1147 #endif /* NAMED_BIND */