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