xref: /original-bsd/usr.sbin/sendmail/src/domain.c (revision 333da485)
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.11 (Berkeley) 01/15/94 (with name server)";
14 #else
15 static char sccsid[] = "@(#)domain.c	8.11 (Berkeley) 01/15/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 	*dp = NULL;
460 
461 	/*
462 	**  Now run through the search list for the name in question.
463 	*/
464 
465 	mxmatch = NULL;
466 	qtype = T_ANY;
467 
468 	for (dp = searchlist; *dp != NULL; )
469 	{
470 		if (qtype == T_ANY)
471 			gotmx = FALSE;
472 		if (tTd(8, 5))
473 			printf("getcanonname: trying %s.%s (%s)\n", host, *dp,
474 				qtype == T_ANY ? "ANY" : qtype == T_A ? "A" :
475 				qtype == T_MX ? "MX" : "???");
476 		ret = res_querydomain(host, *dp, C_IN, qtype,
477 				      &answer, sizeof(answer));
478 		if (ret <= 0)
479 		{
480 			if (tTd(8, 7))
481 				printf("\tNO: errno=%d, h_errno=%d\n",
482 					errno, h_errno);
483 
484 			if (errno == ECONNREFUSED || h_errno == TRY_AGAIN)
485 			{
486 				/* the name server seems to be down */
487 				h_errno = TRY_AGAIN;
488 				return FALSE;
489 			}
490 
491 			if (h_errno != HOST_NOT_FOUND)
492 			{
493 				/* might have another type of interest */
494 				if (qtype == T_ANY)
495 				{
496 					qtype = T_A;
497 					continue;
498 				}
499 				else if (qtype == T_A && !gotmx && trymx)
500 				{
501 					qtype = T_MX;
502 					continue;
503 				}
504 			}
505 
506 			if (mxmatch != NULL)
507 			{
508 				/* we matched before -- use that one */
509 				break;
510 			}
511 
512 			/* otherwise, try the next name */
513 			dp++;
514 			qtype = T_ANY;
515 			continue;
516 		}
517 		else if (tTd(8, 7))
518 			printf("\tYES\n");
519 
520 		/*
521 		**  This might be a bogus match.  Search for A or
522 		**  CNAME records.  If we don't have a matching
523 		**  wild card MX record, we will accept MX as well.
524 		*/
525 
526 		hp = (HEADER *) &answer;
527 		ap = (u_char *) &answer + HEADERSZ;
528 		eom = (u_char *) &answer + ret;
529 
530 		/* skip question part of response -- we know what we asked */
531 		for (qdcount = ntohs(hp->qdcount); qdcount--; ap += ret + QFIXEDSZ)
532 		{
533 			if ((ret = dn_skipname(ap, eom)) < 0)
534 			{
535 				if (tTd(8, 20))
536 					printf("qdcount failure (%d)\n",
537 						ntohs(hp->qdcount));
538 				return FALSE;		/* ???XXX??? */
539 			}
540 		}
541 
542 		amatch = FALSE;
543 		for (ancount = ntohs(hp->ancount); --ancount >= 0 && ap < eom; ap += n)
544 		{
545 			n = dn_expand((u_char *) &answer, eom, ap,
546 				      (u_char *) nbuf, sizeof nbuf);
547 			if (n < 0)
548 				break;
549 			ap += n;
550 			GETSHORT(type, ap);
551 			ap += SHORTSIZE + LONGSIZE;
552 			GETSHORT(n, ap);
553 			switch (type)
554 			{
555 			  case T_MX:
556 				gotmx = TRUE;
557 				if (**dp != '\0')
558 				{
559 					/* got a match -- save that info */
560 					if (trymx && mxmatch == NULL)
561 						mxmatch = *dp;
562 					continue;
563 				}
564 
565 				/* exact MX matches are as good as an A match */
566 				/* fall through */
567 
568 			  case T_A:
569 				/* good show */
570 				amatch = TRUE;
571 
572 				/* continue in case a CNAME also exists */
573 				continue;
574 
575 			  case T_CNAME:
576 				if (loopcnt++ > MAXCNAMEDEPTH)
577 				{
578 					syserr("DNS failure: CNAME loop for %s",
579 						host);
580 					continue;
581 				}
582 
583 				/* value points at name */
584 				if ((ret = dn_expand((u_char *)&answer,
585 				    eom, ap, (u_char *)nbuf, sizeof(nbuf))) < 0)
586 					break;
587 				(void)strncpy(host, nbuf, hbsize); /* XXX */
588 				host[hbsize - 1] = '\0';
589 
590 				/*
591 				**  RFC 1034 section 3.6 specifies that CNAME
592 				**  should point at the canonical name -- but
593 				**  urges software to try again anyway.
594 				*/
595 
596 				goto cnameloop;
597 
598 			  default:
599 				/* not a record of interest */
600 				continue;
601 			}
602 		}
603 
604 		if (amatch)
605 		{
606 			/* got an A record and no CNAME */
607 			mxmatch = *dp;
608 			break;
609 		}
610 
611 		/*
612 		**  If this was a T_ANY query, we may have the info but
613 		**  need an explicit query.  Try T_A, then T_MX.
614 		*/
615 
616 		if (qtype == T_ANY)
617 			qtype = T_A;
618 		else if (qtype == T_A && !gotmx && trymx)
619 			qtype = T_MX;
620 		else
621 		{
622 			/* really nothing in this domain; try the next */
623 			qtype = T_ANY;
624 			dp++;
625 		}
626 	}
627 
628 	if (mxmatch == NULL)
629 		return FALSE;
630 
631 	/* create matching name and return */
632 	(void) sprintf(nbuf, "%.*s%s%.*s", MAXDNAME, host,
633 			*mxmatch == '\0' ? "" : ".",
634 			MAXDNAME, mxmatch);
635 	strncpy(host, nbuf, hbsize);
636 	host[hbsize - 1] = '\0';
637 	return TRUE;
638 }
639 
640 
641 char *
642 gethostalias(host)
643 	char *host;
644 {
645 	char *fname;
646 	FILE *fp;
647 	register char *p;
648 	char buf[MAXLINE];
649 	static char hbuf[MAXDNAME];
650 
651 	fname = getenv("HOSTALIASES");
652 	if (fname == NULL || (fp = fopen(fname, "r")) == NULL)
653 		return NULL;
654 	while (fgets(buf, sizeof buf, fp) != NULL)
655 	{
656 		for (p = buf; p != '\0' && !(isascii(*p) && isspace(*p)); p++)
657 			continue;
658 		if (*p == 0)
659 		{
660 			/* syntax error */
661 			continue;
662 		}
663 		*p++ = '\0';
664 		if (strcasecmp(buf, host) == 0)
665 			break;
666 	}
667 
668 	if (feof(fp))
669 	{
670 		/* no match */
671 		fclose(fp);
672 		return NULL;
673 	}
674 
675 	/* got a match; extract the equivalent name */
676 	while (*p != '\0' && isascii(*p) && isspace(*p))
677 		p++;
678 	host = p;
679 	while (*p != '\0' && !(isascii(*p) && isspace(*p)))
680 		p++;
681 	*p = '\0';
682 	strncpy(hbuf, host, sizeof hbuf - 1);
683 	hbuf[sizeof hbuf - 1] = '\0';
684 	return hbuf;
685 }
686 
687 
688 #else /* not NAMED_BIND */
689 
690 #include <netdb.h>
691 
692 bool
693 getcanonname(host, hbsize, trymx)
694 	char *host;
695 	int hbsize;
696 	bool trymx;
697 {
698 	struct hostent *hp;
699 
700 	hp = gethostbyname(host);
701 	if (hp == NULL)
702 		return (FALSE);
703 
704 	if (strlen(hp->h_name) >= hbsize)
705 		return (FALSE);
706 
707 	(void) strcpy(host, hp->h_name);
708 	return (TRUE);
709 }
710 
711 #endif /* not NAMED_BIND */
712