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