xref: /original-bsd/usr.sbin/sendmail/src/domain.c (revision c4f3b704)
1 /*
2  * Copyright (c) 1986, 1995 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #include "sendmail.h"
10 
11 #ifndef lint
12 #if NAMED_BIND
13 static char sccsid[] = "@(#)domain.c	8.41 (Berkeley) 05/28/95 (with name server)";
14 #else
15 static char sccsid[] = "@(#)domain.c	8.41 (Berkeley) 05/28/95 (without name server)";
16 #endif
17 #endif /* not lint */
18 
19 #if NAMED_BIND
20 
21 #include <errno.h>
22 #include <resolv.h>
23 
24 typedef union
25 {
26 	HEADER	qb1;
27 	u_char	qb2[PACKETSZ];
28 } querybuf;
29 
30 static char	MXHostBuf[MAXMXHOSTS*PACKETSZ];
31 
32 #ifndef MAXDNSRCH
33 #define MAXDNSRCH	6	/* number of possible domains to search */
34 #endif
35 
36 #ifndef MAX
37 #define MAX(a, b)	((a) > (b) ? (a) : (b))
38 #endif
39 
40 #ifndef NO_DATA
41 # define NO_DATA	NO_ADDRESS
42 #endif
43 
44 #ifndef HFIXEDSZ
45 # define HFIXEDSZ	12	/* sizeof(HEADER) */
46 #endif
47 
48 #define MAXCNAMEDEPTH	10	/* maximum depth of CNAME recursion */
49 
50 #if defined(__RES) && (__RES >= 19940415)
51 # define RES_UNC_T	char *
52 #else
53 # define RES_UNC_T	u_char *
54 #endif
55 /*
56 **  GETMXRR -- get MX resource records for a domain
57 **
58 **	Parameters:
59 **		host -- the name of the host to MX.
60 **		mxhosts -- a pointer to a return buffer of MX records.
61 **		droplocalhost -- If TRUE, all MX records less preferred
62 **			than the local host (as determined by $=w) will
63 **			be discarded.
64 **		rcode -- a pointer to an EX_ status code.
65 **
66 **	Returns:
67 **		The number of MX records found.
68 **		-1 if there is an internal failure.
69 **		If no MX records are found, mxhosts[0] is set to host
70 **			and 1 is returned.
71 */
72 
73 int
74 getmxrr(host, mxhosts, droplocalhost, rcode)
75 	char *host;
76 	char **mxhosts;
77 	bool droplocalhost;
78 	int *rcode;
79 {
80 	extern int h_errno;
81 	register u_char *eom, *cp;
82 	register int i, j, n;
83 	int nmx = 0;
84 	register char *bp;
85 	HEADER *hp;
86 	querybuf answer;
87 	int ancount, qdcount, buflen;
88 	bool seenlocal = FALSE;
89 	u_short pref, type;
90 	u_short localpref = 256;
91 	char *fallbackMX = FallBackMX;
92 	static bool firsttime = TRUE;
93 	bool trycanon = FALSE;
94 	u_short prefer[MAXMXHOSTS];
95 	int weight[MAXMXHOSTS];
96 	extern bool getcanonname();
97 
98 	if (tTd(8, 2))
99 		printf("getmxrr(%s, droplocalhost=%d)\n", host, droplocalhost);
100 
101 	if (fallbackMX != NULL)
102 	{
103 		if (firsttime &&
104 		    res_query(FallBackMX, C_IN, T_A,
105 			      (u_char *) &answer, sizeof answer) < 0)
106 		{
107 			/* this entry is bogus */
108 			fallbackMX = FallBackMX = NULL;
109 		}
110 		else if (droplocalhost && wordinclass(fallbackMX, 'w'))
111 		{
112 			/* don't use fallback for this pass */
113 			fallbackMX = NULL;
114 		}
115 		firsttime = FALSE;
116 	}
117 
118 	*rcode = EX_OK;
119 
120 	/* efficiency hack -- numeric or non-MX lookups */
121 	if (host[0] == '[')
122 		goto punt;
123 
124 	/*
125 	**  If we don't have MX records in our host switch, don't
126 	**  try for MX records.  Note that this really isn't "right",
127 	**  since we might be set up to try NIS first and then DNS;
128 	**  if the host is found in NIS we really shouldn't be doing
129 	**  MX lookups.  However, that should be a degenerate case.
130 	*/
131 
132 	if (!UseNameServer)
133 		goto punt;
134 
135 	errno = 0;
136 	n = res_search(host, C_IN, T_MX, (u_char *) &answer, sizeof(answer));
137 	if (n < 0)
138 	{
139 		if (tTd(8, 1))
140 			printf("getmxrr: res_search(%s) failed (errno=%d, h_errno=%d)\n",
141 			    (host == NULL) ? "<NULL>" : host, errno, h_errno);
142 		switch (h_errno)
143 		{
144 		  case NO_DATA:
145 			trycanon = TRUE;
146 			/* fall through */
147 
148 		  case NO_RECOVERY:
149 			/* no MX data on this host */
150 			goto punt;
151 
152 		  case HOST_NOT_FOUND:
153 #if BROKEN_RES_SEARCH
154 		  case 0:	/* Ultrix resolver retns failure w/ h_errno=0 */
155 #endif
156 			/* host doesn't exist in DNS; might be in /etc/hosts */
157 			*rcode = EX_NOHOST;
158 			goto punt;
159 
160 		  case TRY_AGAIN:
161 			/* couldn't connect to the name server */
162 			/* it might come up later; better queue it up */
163 			*rcode = EX_TEMPFAIL;
164 			break;
165 
166 		  default:
167 			syserr("getmxrr: res_search (%s) failed with impossible h_errno (%d)\n",
168 				host, h_errno);
169 			*rcode = EX_OSERR;
170 			break;
171 		}
172 
173 		/* irreconcilable differences */
174 		return (-1);
175 	}
176 
177 	/* find first satisfactory answer */
178 	hp = (HEADER *)&answer;
179 	cp = (u_char *)&answer + HFIXEDSZ;
180 	eom = (u_char *)&answer + n;
181 	for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
182 		if ((n = dn_skipname(cp, eom)) < 0)
183 			goto punt;
184 	buflen = sizeof(MXHostBuf) - 1;
185 	bp = MXHostBuf;
186 	ancount = ntohs(hp->ancount);
187 	while (--ancount >= 0 && cp < eom && nmx < MAXMXHOSTS - 1)
188 	{
189 		if ((n = dn_expand((u_char *)&answer,
190 		    eom, cp, (RES_UNC_T) bp, buflen)) < 0)
191 			break;
192 		cp += n;
193 		GETSHORT(type, cp);
194  		cp += INT16SZ + INT32SZ;
195 		GETSHORT(n, cp);
196 		if (type != T_MX)
197 		{
198 			if (tTd(8, 8) || _res.options & RES_DEBUG)
199 				printf("unexpected answer type %d, size %d\n",
200 				    type, n);
201 			cp += n;
202 			continue;
203 		}
204 		GETSHORT(pref, cp);
205 		if ((n = dn_expand((u_char *)&answer, eom, cp,
206 				   (RES_UNC_T) bp, buflen)) < 0)
207 			break;
208 		cp += n;
209 		if (droplocalhost && wordinclass(bp, 'w'))
210 		{
211 			if (tTd(8, 3))
212 				printf("found localhost (%s) in MX list, pref=%d\n",
213 					bp, pref);
214 			if (!seenlocal || pref < localpref)
215 				localpref = pref;
216 			seenlocal = TRUE;
217 			continue;
218 		}
219 		weight[nmx] = mxrand(bp);
220 		prefer[nmx] = pref;
221 		mxhosts[nmx++] = bp;
222 		n = strlen(bp);
223 		bp += n;
224 		if (bp[-1] != '.')
225 		{
226 			*bp++ = '.';
227 			n++;
228 		}
229 		*bp++ = '\0';
230 		buflen -= n + 1;
231 	}
232 
233 	/* sort the records */
234 	for (i = 0; i < nmx; i++)
235 	{
236 		for (j = i + 1; j < nmx; j++)
237 		{
238 			if (prefer[i] > prefer[j] ||
239 			    (prefer[i] == prefer[j] && weight[i] > weight[j]))
240 			{
241 				register int temp;
242 				register char *temp1;
243 
244 				temp = prefer[i];
245 				prefer[i] = prefer[j];
246 				prefer[j] = temp;
247 				temp1 = mxhosts[i];
248 				mxhosts[i] = mxhosts[j];
249 				mxhosts[j] = temp1;
250 				temp = weight[i];
251 				weight[i] = weight[j];
252 				weight[j] = temp;
253 			}
254 		}
255 		if (seenlocal && prefer[i] >= localpref)
256 		{
257 			/* truncate higher preference part of list */
258 			nmx = i;
259 		}
260 	}
261 
262 	if (nmx == 0)
263 	{
264 punt:
265 		if (seenlocal &&
266 		    (!TryNullMXList || sm_gethostbyname(host) == NULL))
267 		{
268 			/*
269 			**  If we have deleted all MX entries, this is
270 			**  an error -- we should NEVER send to a host that
271 			**  has an MX, and this should have been caught
272 			**  earlier in the config file.
273 			**
274 			**  Some sites prefer to go ahead and try the
275 			**  A record anyway; that case is handled by
276 			**  setting TryNullMXList.  I believe this is a
277 			**  bad idea, but it's up to you....
278 			*/
279 
280 			*rcode = EX_CONFIG;
281 			syserr("MX list for %s points back to %s",
282 				host, MyHostName);
283 			return -1;
284 		}
285 		strcpy(MXHostBuf, host);
286 		mxhosts[0] = MXHostBuf;
287 		if (host[0] == '[')
288 		{
289 			register char *p;
290 
291 			/* this may be an MX suppression-style address */
292 			p = strchr(MXHostBuf, ']');
293 			if (p != NULL)
294 			{
295 				*p = '\0';
296 				if (inet_addr(&MXHostBuf[1]) != -1)
297 					*p = ']';
298 				else
299 				{
300 					trycanon = TRUE;
301 					mxhosts[0]++;
302 				}
303 			}
304 		}
305 		if (trycanon &&
306 		    getcanonname(mxhosts[0], sizeof MXHostBuf - 2, FALSE))
307 		{
308 			bp = &MXHostBuf[strlen(MXHostBuf)];
309 			if (bp[-1] != '.')
310 			{
311 				*bp++ = '.';
312 				*bp = '\0';
313 			}
314 			nmx = 1;
315 		}
316 	}
317 
318 	/* if we have a default lowest preference, include that */
319 	if (fallbackMX != NULL && !seenlocal)
320 		mxhosts[nmx++] = fallbackMX;
321 
322 	return (nmx);
323 }
324 /*
325 **  MXRAND -- create a randomizer for equal MX preferences
326 **
327 **	If two MX hosts have equal preferences we want to randomize
328 **	the selection.  But in order for signatures to be the same,
329 **	we need to randomize the same way each time.  This function
330 **	computes a pseudo-random hash function from the host name.
331 **
332 **	Parameters:
333 **		host -- the name of the host.
334 **
335 **	Returns:
336 **		A random but repeatable value based on the host name.
337 **
338 **	Side Effects:
339 **		none.
340 */
341 
342 int
343 mxrand(host)
344 	register char *host;
345 {
346 	int hfunc;
347 	static unsigned int seed;
348 
349 	if (seed == 0)
350 	{
351 		seed = (int) curtime() & 0xffff;
352 		if (seed == 0)
353 			seed++;
354 	}
355 
356 	if (tTd(17, 9))
357 		printf("mxrand(%s)", host);
358 
359 	hfunc = seed;
360 	while (*host != '\0')
361 	{
362 		int c = *host++;
363 
364 		if (isascii(c) && isupper(c))
365 			c = tolower(c);
366 		hfunc = ((hfunc << 1) ^ c) % 2003;
367 	}
368 
369 	hfunc &= 0xff;
370 
371 	if (tTd(17, 9))
372 		printf(" = %d\n", hfunc);
373 	return hfunc;
374 }
375 /*
376 **  DNS_GETCANONNAME -- get the canonical name for named host using DNS
377 **
378 **	This algorithm tries to be smart about wildcard MX records.
379 **	This is hard to do because DNS doesn't tell is if we matched
380 **	against a wildcard or a specific MX.
381 **
382 **	We always prefer A & CNAME records, since these are presumed
383 **	to be specific.
384 **
385 **	If we match an MX in one pass and lose it in the next, we use
386 **	the old one.  For example, consider an MX matching *.FOO.BAR.COM.
387 **	A hostname bletch.foo.bar.com will match against this MX, but
388 **	will stop matching when we try bletch.bar.com -- so we know
389 **	that bletch.foo.bar.com must have been right.  This fails if
390 **	there was also an MX record matching *.BAR.COM, but there are
391 **	some things that just can't be fixed.
392 **
393 **	Parameters:
394 **		host -- a buffer containing the name of the host.
395 **			This is a value-result parameter.
396 **		hbsize -- the size of the host buffer.
397 **		trymx -- if set, try MX records as well as A and CNAME.
398 **		statp -- pointer to place to store status.
399 **
400 **	Returns:
401 **		TRUE -- if the host matched.
402 **		FALSE -- otherwise.
403 */
404 
405 bool
406 dns_getcanonname(host, hbsize, trymx, statp)
407 	char *host;
408 	int hbsize;
409 	bool trymx;
410 	int *statp;
411 {
412 	extern int h_errno;
413 	register u_char *eom, *ap;
414 	register char *cp;
415 	register int n;
416 	HEADER *hp;
417 	querybuf answer;
418 	int ancount, qdcount;
419 	int ret;
420 	char **domain;
421 	int type;
422 	char **dp;
423 	char *mxmatch;
424 	bool amatch;
425 	bool gotmx = FALSE;
426 	int qtype;
427 	int loopcnt;
428 	char *xp;
429 	char nbuf[MAX(PACKETSZ, MAXDNAME*2+2)];
430 	char *searchlist[MAXDNSRCH+2];
431 	extern char *gethostalias();
432 
433 	if (tTd(8, 2))
434 		printf("getcanonname(%s)\n", host);
435 
436 	if ((_res.options & RES_INIT) == 0 && res_init() == -1)
437 	{
438 		*statp = EX_UNAVAILABLE;
439 		return FALSE;
440 	}
441 
442 	/*
443 	**  Initialize domain search list.  If there is at least one
444 	**  dot in the name, search the unmodified name first so we
445 	**  find "vse.CS" in Czechoslovakia instead of in the local
446 	**  domain (e.g., vse.CS.Berkeley.EDU).
447 	**
448 	**  Older versions of the resolver could create this
449 	**  list by tearing apart the host name.
450 	*/
451 
452 	loopcnt = 0;
453 cnameloop:
454 	for (cp = host, n = 0; *cp; cp++)
455 		if (*cp == '.')
456 			n++;
457 
458 	if (n == 0 && (xp = gethostalias(host)) != NULL)
459 	{
460 		if (loopcnt++ > MAXCNAMEDEPTH)
461 		{
462 			syserr("loop in ${HOSTALIASES} file");
463 		}
464 		else
465 		{
466 			strncpy(host, xp, hbsize);
467 			host[hbsize - 1] = '\0';
468 			goto cnameloop;
469 		}
470 	}
471 
472 	dp = searchlist;
473 	if (n > 0)
474 		*dp++ = "";
475 	if (n >= 0 && *--cp != '.' && bitset(RES_DNSRCH, _res.options))
476 	{
477 		for (domain = _res.dnsrch; *domain != NULL; )
478 			*dp++ = *domain++;
479 	}
480 	else if (n == 0 && bitset(RES_DEFNAMES, _res.options))
481 	{
482 		*dp++ = _res.defdname;
483 	}
484 	else if (*cp == '.')
485 	{
486 		*cp = '\0';
487 	}
488 	*dp = NULL;
489 
490 	/*
491 	**  Now run through the search list for the name in question.
492 	*/
493 
494 	mxmatch = NULL;
495 	qtype = T_ANY;
496 
497 	for (dp = searchlist; *dp != NULL; )
498 	{
499 		if (qtype == T_ANY)
500 			gotmx = FALSE;
501 		if (tTd(8, 5))
502 			printf("getcanonname: trying %s.%s (%s)\n", host, *dp,
503 				qtype == T_ANY ? "ANY" : qtype == T_A ? "A" :
504 				qtype == T_MX ? "MX" : "???");
505 		ret = res_querydomain(host, *dp, C_IN, qtype,
506 				      answer.qb2, sizeof(answer.qb2));
507 		if (ret <= 0)
508 		{
509 			if (tTd(8, 7))
510 				printf("\tNO: errno=%d, h_errno=%d\n",
511 					errno, h_errno);
512 
513 			if (errno == ECONNREFUSED || h_errno == TRY_AGAIN)
514 			{
515 				/* the name server seems to be down */
516 				h_errno = TRY_AGAIN;
517 				*statp = EX_TEMPFAIL;
518 				return FALSE;
519 			}
520 
521 			if (h_errno != HOST_NOT_FOUND)
522 			{
523 				/* might have another type of interest */
524 				if (qtype == T_ANY)
525 				{
526 					qtype = T_A;
527 					continue;
528 				}
529 				else if (qtype == T_A && !gotmx && trymx)
530 				{
531 					qtype = T_MX;
532 					continue;
533 				}
534 			}
535 
536 			if (mxmatch != NULL)
537 			{
538 				/* we matched before -- use that one */
539 				break;
540 			}
541 
542 			/* otherwise, try the next name */
543 			dp++;
544 			qtype = T_ANY;
545 			continue;
546 		}
547 		else if (tTd(8, 7))
548 			printf("\tYES\n");
549 
550 		/*
551 		**  This might be a bogus match.  Search for A or
552 		**  CNAME records.  If we don't have a matching
553 		**  wild card MX record, we will accept MX as well.
554 		*/
555 
556 		hp = (HEADER *) &answer;
557 		ap = (u_char *) &answer + HFIXEDSZ;
558 		eom = (u_char *) &answer + ret;
559 
560 		/* skip question part of response -- we know what we asked */
561 		for (qdcount = ntohs(hp->qdcount); qdcount--; ap += ret + QFIXEDSZ)
562 		{
563 			if ((ret = dn_skipname(ap, eom)) < 0)
564 			{
565 				if (tTd(8, 20))
566 					printf("qdcount failure (%d)\n",
567 						ntohs(hp->qdcount));
568 				*statp = EX_SOFTWARE;
569 				return FALSE;		/* ???XXX??? */
570 			}
571 		}
572 
573 		amatch = FALSE;
574 		for (ancount = ntohs(hp->ancount); --ancount >= 0 && ap < eom; ap += n)
575 		{
576 			n = dn_expand((u_char *) &answer, eom, ap,
577 				      (RES_UNC_T) nbuf, sizeof nbuf);
578 			if (n < 0)
579 				break;
580 			ap += n;
581 			GETSHORT(type, ap);
582 			ap += INT16SZ + INT32SZ;
583 			GETSHORT(n, ap);
584 			switch (type)
585 			{
586 			  case T_MX:
587 				gotmx = TRUE;
588 				if (**dp != '\0')
589 				{
590 					/* got a match -- save that info */
591 					if (trymx && mxmatch == NULL)
592 						mxmatch = *dp;
593 					continue;
594 				}
595 
596 				/* exact MX matches are as good as an A match */
597 				/* fall through */
598 
599 			  case T_A:
600 				/* good show */
601 				amatch = TRUE;
602 
603 				/* continue in case a CNAME also exists */
604 				continue;
605 
606 			  case T_CNAME:
607 				if (loopcnt++ > MAXCNAMEDEPTH)
608 				{
609 					/*XXX should notify postmaster XXX*/
610 					message("DNS failure: CNAME loop for %s",
611 						host);
612 					if (CurEnv->e_message == NULL)
613 					{
614 						char ebuf[MAXLINE];
615 
616 						sprintf(ebuf, "Deferred: DNS failure: CNAME loop for %s",
617 							host);
618 						CurEnv->e_message = newstr(ebuf);
619 					}
620 					h_errno = NO_RECOVERY;
621 					*statp = EX_CONFIG;
622 					return FALSE;
623 				}
624 
625 				/* value points at name */
626 				if ((ret = dn_expand((u_char *)&answer,
627 				    eom, ap, (RES_UNC_T) nbuf, sizeof(nbuf))) < 0)
628 					break;
629 				(void)strncpy(host, nbuf, hbsize); /* XXX */
630 				host[hbsize - 1] = '\0';
631 
632 				/*
633 				**  RFC 1034 section 3.6 specifies that CNAME
634 				**  should point at the canonical name -- but
635 				**  urges software to try again anyway.
636 				*/
637 
638 				goto cnameloop;
639 
640 			  default:
641 				/* not a record of interest */
642 				continue;
643 			}
644 		}
645 
646 		if (amatch)
647 		{
648 			/* got an A record and no CNAME */
649 			mxmatch = *dp;
650 			break;
651 		}
652 
653 		/*
654 		**  If this was a T_ANY query, we may have the info but
655 		**  need an explicit query.  Try T_A, then T_MX.
656 		*/
657 
658 		if (qtype == T_ANY)
659 			qtype = T_A;
660 		else if (qtype == T_A && !gotmx && trymx)
661 			qtype = T_MX;
662 		else
663 		{
664 			/* really nothing in this domain; try the next */
665 			qtype = T_ANY;
666 			dp++;
667 		}
668 	}
669 
670 	if (mxmatch == NULL)
671 	{
672 		*statp = EX_NOHOST;
673 		return FALSE;
674 	}
675 
676 	/* create matching name and return */
677 	(void) sprintf(nbuf, "%.*s%s%.*s", MAXDNAME, host,
678 			*mxmatch == '\0' ? "" : ".",
679 			MAXDNAME, mxmatch);
680 	strncpy(host, nbuf, hbsize);
681 	host[hbsize - 1] = '\0';
682 	*statp = EX_OK;
683 	return TRUE;
684 }
685 
686 
687 char *
688 gethostalias(host)
689 	char *host;
690 {
691 	char *fname;
692 	FILE *fp;
693 	register char *p = NULL;
694 	char buf[MAXLINE];
695 	static char hbuf[MAXDNAME];
696 
697 	fname = getenv("HOSTALIASES");
698 	if (fname == NULL ||
699 	    (fp = safefopen(fname, O_RDONLY, 0, SFF_REGONLY)) == NULL)
700 		return NULL;
701 	while (fgets(buf, sizeof buf, fp) != NULL)
702 	{
703 		for (p = buf; p != '\0' && !(isascii(*p) && isspace(*p)); p++)
704 			continue;
705 		if (*p == 0)
706 		{
707 			/* syntax error */
708 			continue;
709 		}
710 		*p++ = '\0';
711 		if (strcasecmp(buf, host) == 0)
712 			break;
713 	}
714 
715 	if (feof(fp))
716 	{
717 		/* no match */
718 		fclose(fp);
719 		return NULL;
720 	}
721 
722 	/* got a match; extract the equivalent name */
723 	while (*p != '\0' && isascii(*p) && isspace(*p))
724 		p++;
725 	host = p;
726 	while (*p != '\0' && !(isascii(*p) && isspace(*p)))
727 		p++;
728 	*p = '\0';
729 	strncpy(hbuf, host, sizeof hbuf - 1);
730 	hbuf[sizeof hbuf - 1] = '\0';
731 	return hbuf;
732 }
733 
734 #endif /* NAMED_BIND */
735