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