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