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