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