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