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