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