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