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