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