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