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