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