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