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