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