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