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