1 /*
2 * Copyright (c) 1986, 1995 Eric P. Allman
3 * Copyright (c) 1988, 1993
4 * The Regents of the University of California. All rights reserved.
5 *
6 * %sccs.include.redist.c%
7 */
8
9 #include "sendmail.h"
10
11 #ifndef lint
12 #if NAMED_BIND
13 static char sccsid[] = "@(#)domain.c 8.47 (Berkeley) 06/20/95 (with name server)";
14 #else
15 static char sccsid[] = "@(#)domain.c 8.47 (Berkeley) 06/20/95 (without name server)";
16 #endif
17 #endif /* not lint */
18
19 #if NAMED_BIND
20
21 #include <errno.h>
22 #include <resolv.h>
23
24 typedef union
25 {
26 HEADER qb1;
27 u_char qb2[PACKETSZ];
28 } querybuf;
29
30 static char MXHostBuf[MAXMXHOSTS*PACKETSZ];
31
32 #ifndef MAXDNSRCH
33 #define MAXDNSRCH 6 /* number of possible domains to search */
34 #endif
35
36 #ifndef MAX
37 #define MAX(a, b) ((a) > (b) ? (a) : (b))
38 #endif
39
40 #ifndef NO_DATA
41 # define NO_DATA NO_ADDRESS
42 #endif
43
44 #ifndef HFIXEDSZ
45 # define HFIXEDSZ 12 /* sizeof(HEADER) */
46 #endif
47
48 #define MAXCNAMEDEPTH 10 /* maximum depth of CNAME recursion */
49
50 #if defined(__RES) && (__RES >= 19940415)
51 # define RES_UNC_T char *
52 #else
53 # define RES_UNC_T u_char *
54 #endif
55 /*
56 ** GETMXRR -- get MX resource records for a domain
57 **
58 ** Parameters:
59 ** host -- the name of the host to MX.
60 ** mxhosts -- a pointer to a return buffer of MX records.
61 ** droplocalhost -- If TRUE, all MX records less preferred
62 ** than the local host (as determined by $=w) will
63 ** be discarded.
64 ** rcode -- a pointer to an EX_ status code.
65 **
66 ** Returns:
67 ** The number of MX records found.
68 ** -1 if there is an internal failure.
69 ** If no MX records are found, mxhosts[0] is set to host
70 ** and 1 is returned.
71 */
72
73 int
getmxrr(host,mxhosts,droplocalhost,rcode)74 getmxrr(host, mxhosts, droplocalhost, rcode)
75 char *host;
76 char **mxhosts;
77 bool droplocalhost;
78 int *rcode;
79 {
80 register u_char *eom, *cp;
81 register int i, j, n;
82 int nmx = 0;
83 register char *bp;
84 HEADER *hp;
85 querybuf answer;
86 int ancount, qdcount, buflen;
87 bool seenlocal = FALSE;
88 u_short pref, type;
89 u_short localpref = 256;
90 char *fallbackMX = FallBackMX;
91 static bool firsttime = TRUE;
92 bool trycanon = FALSE;
93 int (*resfunc)();
94 extern int res_query(), res_search();
95 u_short prefer[MAXMXHOSTS];
96 int weight[MAXMXHOSTS];
97 extern bool getcanonname();
98
99 if (tTd(8, 2))
100 printf("getmxrr(%s, droplocalhost=%d)\n", host, droplocalhost);
101
102 if (fallbackMX != NULL)
103 {
104 if (firsttime &&
105 res_query(FallBackMX, C_IN, T_A,
106 (u_char *) &answer, sizeof answer) < 0)
107 {
108 /* this entry is bogus */
109 fallbackMX = FallBackMX = NULL;
110 }
111 else if (droplocalhost && wordinclass(fallbackMX, 'w'))
112 {
113 /* don't use fallback for this pass */
114 fallbackMX = NULL;
115 }
116 firsttime = FALSE;
117 }
118
119 *rcode = EX_OK;
120
121 /* efficiency hack -- numeric or non-MX lookups */
122 if (host[0] == '[')
123 goto punt;
124
125 /*
126 ** If we don't have MX records in our host switch, don't
127 ** try for MX records. Note that this really isn't "right",
128 ** since we might be set up to try NIS first and then DNS;
129 ** if the host is found in NIS we really shouldn't be doing
130 ** MX lookups. However, that should be a degenerate case.
131 */
132
133 if (!UseNameServer)
134 goto punt;
135 if (HasWildcardMX && ConfigLevel >= 6)
136 resfunc = res_query;
137 else
138 resfunc = res_search;
139
140 errno = 0;
141 n = (*resfunc)(host, C_IN, T_MX, (u_char *) &answer, sizeof(answer));
142 if (n < 0)
143 {
144 if (tTd(8, 1))
145 printf("getmxrr: res_search(%s) failed (errno=%d, h_errno=%d)\n",
146 (host == NULL) ? "<NULL>" : host, errno, h_errno);
147 switch (h_errno)
148 {
149 case NO_DATA:
150 trycanon = TRUE;
151 /* fall through */
152
153 case NO_RECOVERY:
154 /* no MX data on this host */
155 goto punt;
156
157 case HOST_NOT_FOUND:
158 #if BROKEN_RES_SEARCH
159 case 0: /* Ultrix resolver retns failure w/ h_errno=0 */
160 #endif
161 /* host doesn't exist in DNS; might be in /etc/hosts */
162 *rcode = EX_NOHOST;
163 goto punt;
164
165 case TRY_AGAIN:
166 /* couldn't connect to the name server */
167 /* it might come up later; better queue it up */
168 *rcode = EX_TEMPFAIL;
169 break;
170
171 default:
172 syserr("getmxrr: res_search (%s) failed with impossible h_errno (%d)\n",
173 host, h_errno);
174 *rcode = EX_OSERR;
175 break;
176 }
177
178 /* irreconcilable differences */
179 return (-1);
180 }
181
182 /* find first satisfactory answer */
183 hp = (HEADER *)&answer;
184 cp = (u_char *)&answer + HFIXEDSZ;
185 eom = (u_char *)&answer + n;
186 for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
187 if ((n = dn_skipname(cp, eom)) < 0)
188 goto punt;
189 buflen = sizeof(MXHostBuf) - 1;
190 bp = MXHostBuf;
191 ancount = ntohs(hp->ancount);
192 while (--ancount >= 0 && cp < eom && nmx < MAXMXHOSTS - 1)
193 {
194 if ((n = dn_expand((u_char *)&answer,
195 eom, cp, (RES_UNC_T) bp, buflen)) < 0)
196 break;
197 cp += n;
198 GETSHORT(type, cp);
199 cp += INT16SZ + INT32SZ;
200 GETSHORT(n, cp);
201 if (type != T_MX)
202 {
203 if (tTd(8, 8) || _res.options & RES_DEBUG)
204 printf("unexpected answer type %d, size %d\n",
205 type, n);
206 cp += n;
207 continue;
208 }
209 GETSHORT(pref, cp);
210 if ((n = dn_expand((u_char *)&answer, eom, cp,
211 (RES_UNC_T) bp, buflen)) < 0)
212 break;
213 cp += n;
214 if (droplocalhost && wordinclass(bp, 'w'))
215 {
216 if (tTd(8, 3))
217 printf("found localhost (%s) in MX list, pref=%d\n",
218 bp, pref);
219 if (!seenlocal || pref < localpref)
220 localpref = pref;
221 seenlocal = TRUE;
222 continue;
223 }
224 weight[nmx] = mxrand(bp);
225 prefer[nmx] = pref;
226 mxhosts[nmx++] = bp;
227 n = strlen(bp);
228 bp += n;
229 if (bp[-1] != '.')
230 {
231 *bp++ = '.';
232 n++;
233 }
234 *bp++ = '\0';
235 buflen -= n + 1;
236 }
237
238 /* sort the records */
239 for (i = 0; i < nmx; i++)
240 {
241 for (j = i + 1; j < nmx; j++)
242 {
243 if (prefer[i] > prefer[j] ||
244 (prefer[i] == prefer[j] && weight[i] > weight[j]))
245 {
246 register int temp;
247 register char *temp1;
248
249 temp = prefer[i];
250 prefer[i] = prefer[j];
251 prefer[j] = temp;
252 temp1 = mxhosts[i];
253 mxhosts[i] = mxhosts[j];
254 mxhosts[j] = temp1;
255 temp = weight[i];
256 weight[i] = weight[j];
257 weight[j] = temp;
258 }
259 }
260 if (seenlocal && prefer[i] >= localpref)
261 {
262 /* truncate higher preference part of list */
263 nmx = i;
264 }
265 }
266
267 if (nmx == 0)
268 {
269 punt:
270 if (seenlocal &&
271 (!TryNullMXList || sm_gethostbyname(host) == NULL))
272 {
273 /*
274 ** If we have deleted all MX entries, this is
275 ** an error -- we should NEVER send to a host that
276 ** has an MX, and this should have been caught
277 ** earlier in the config file.
278 **
279 ** Some sites prefer to go ahead and try the
280 ** A record anyway; that case is handled by
281 ** setting TryNullMXList. I believe this is a
282 ** bad idea, but it's up to you....
283 */
284
285 *rcode = EX_CONFIG;
286 syserr("MX list for %s points back to %s",
287 host, MyHostName);
288 return -1;
289 }
290 strcpy(MXHostBuf, host);
291 mxhosts[0] = MXHostBuf;
292 if (host[0] == '[')
293 {
294 register char *p;
295
296 /* this may be an MX suppression-style address */
297 p = strchr(MXHostBuf, ']');
298 if (p != NULL)
299 {
300 *p = '\0';
301 if (inet_addr(&MXHostBuf[1]) != -1)
302 *p = ']';
303 else
304 {
305 trycanon = TRUE;
306 mxhosts[0]++;
307 }
308 }
309 }
310 if (trycanon &&
311 getcanonname(mxhosts[0], sizeof MXHostBuf - 2, FALSE))
312 {
313 bp = &MXHostBuf[strlen(MXHostBuf)];
314 if (bp[-1] != '.')
315 {
316 *bp++ = '.';
317 *bp = '\0';
318 }
319 nmx = 1;
320 }
321 }
322
323 /* if we have a default lowest preference, include that */
324 if (fallbackMX != NULL && !seenlocal)
325 mxhosts[nmx++] = fallbackMX;
326
327 return (nmx);
328 }
329 /*
330 ** MXRAND -- create a randomizer for equal MX preferences
331 **
332 ** If two MX hosts have equal preferences we want to randomize
333 ** the selection. But in order for signatures to be the same,
334 ** we need to randomize the same way each time. This function
335 ** computes a pseudo-random hash function from the host name.
336 **
337 ** Parameters:
338 ** host -- the name of the host.
339 **
340 ** Returns:
341 ** A random but repeatable value based on the host name.
342 **
343 ** Side Effects:
344 ** none.
345 */
346
347 int
mxrand(host)348 mxrand(host)
349 register char *host;
350 {
351 int hfunc;
352 static unsigned int seed;
353
354 if (seed == 0)
355 {
356 seed = (int) curtime() & 0xffff;
357 if (seed == 0)
358 seed++;
359 }
360
361 if (tTd(17, 9))
362 printf("mxrand(%s)", host);
363
364 hfunc = seed;
365 while (*host != '\0')
366 {
367 int c = *host++;
368
369 if (isascii(c) && isupper(c))
370 c = tolower(c);
371 hfunc = ((hfunc << 1) ^ c) % 2003;
372 }
373
374 hfunc &= 0xff;
375
376 if (tTd(17, 9))
377 printf(" = %d\n", hfunc);
378 return hfunc;
379 }
380 /*
381 ** BESTMX -- find the best MX for a name
382 **
383 ** This is really a hack, but I don't see any obvious way
384 ** to generalize it at the moment.
385 */
386
387 char *
bestmx_map_lookup(map,name,av,statp)388 bestmx_map_lookup(map, name, av, statp)
389 MAP *map;
390 char *name;
391 char **av;
392 int *statp;
393 {
394 int nmx;
395 auto int rcode;
396 int saveopts = _res.options;
397 char *mxhosts[MAXMXHOSTS + 1];
398
399 _res.options &= ~(RES_DNSRCH|RES_DEFNAMES);
400 nmx = getmxrr(name, mxhosts, FALSE, &rcode);
401 _res.options = saveopts;
402 if (nmx <= 0)
403 return NULL;
404 if (bitset(MF_MATCHONLY, map->map_mflags))
405 return map_rewrite(map, name, strlen(name), NULL);
406 else
407 return map_rewrite(map, mxhosts[0], strlen(mxhosts[0]), av);
408 }
409 /*
410 ** DNS_GETCANONNAME -- get the canonical name for named host using DNS
411 **
412 ** This algorithm tries to be smart about wildcard MX records.
413 ** This is hard to do because DNS doesn't tell is if we matched
414 ** against a wildcard or a specific MX.
415 **
416 ** We always prefer A & CNAME records, since these are presumed
417 ** to be specific.
418 **
419 ** If we match an MX in one pass and lose it in the next, we use
420 ** the old one. For example, consider an MX matching *.FOO.BAR.COM.
421 ** A hostname bletch.foo.bar.com will match against this MX, but
422 ** will stop matching when we try bletch.bar.com -- so we know
423 ** that bletch.foo.bar.com must have been right. This fails if
424 ** there was also an MX record matching *.BAR.COM, but there are
425 ** some things that just can't be fixed.
426 **
427 ** Parameters:
428 ** host -- a buffer containing the name of the host.
429 ** This is a value-result parameter.
430 ** hbsize -- the size of the host buffer.
431 ** trymx -- if set, try MX records as well as A and CNAME.
432 ** statp -- pointer to place to store status.
433 **
434 ** Returns:
435 ** TRUE -- if the host matched.
436 ** FALSE -- otherwise.
437 */
438
439 bool
dns_getcanonname(host,hbsize,trymx,statp)440 dns_getcanonname(host, hbsize, trymx, statp)
441 char *host;
442 int hbsize;
443 bool trymx;
444 int *statp;
445 {
446 register u_char *eom, *ap;
447 register char *cp;
448 register int n;
449 HEADER *hp;
450 querybuf answer;
451 int ancount, qdcount;
452 int ret;
453 char **domain;
454 int type;
455 char **dp;
456 char *mxmatch;
457 bool amatch;
458 bool gotmx = FALSE;
459 int qtype;
460 int loopcnt;
461 char *xp;
462 char nbuf[MAX(PACKETSZ, MAXDNAME*2+2)];
463 char *searchlist[MAXDNSRCH+2];
464 extern char *gethostalias();
465
466 if (tTd(8, 2))
467 printf("dns_getcanonname(%s, trymx=%d)\n", host, trymx);
468
469 if ((_res.options & RES_INIT) == 0 && res_init() == -1)
470 {
471 *statp = EX_UNAVAILABLE;
472 return FALSE;
473 }
474
475 /*
476 ** Initialize domain search list. If there is at least one
477 ** dot in the name, search the unmodified name first so we
478 ** find "vse.CS" in Czechoslovakia instead of in the local
479 ** domain (e.g., vse.CS.Berkeley.EDU).
480 **
481 ** Older versions of the resolver could create this
482 ** list by tearing apart the host name.
483 */
484
485 loopcnt = 0;
486 cnameloop:
487 for (cp = host, n = 0; *cp != '\0'; cp++)
488 if (*cp == '.')
489 n++;
490
491 if (n == 0 && (xp = gethostalias(host)) != NULL)
492 {
493 if (loopcnt++ > MAXCNAMEDEPTH)
494 {
495 syserr("loop in ${HOSTALIASES} file");
496 }
497 else
498 {
499 strncpy(host, xp, hbsize);
500 host[hbsize - 1] = '\0';
501 goto cnameloop;
502 }
503 }
504
505 dp = searchlist;
506 if (n > 0)
507 *dp++ = "";
508 if (n >= 0 && *--cp != '.' && bitset(RES_DNSRCH, _res.options))
509 {
510 for (domain = _res.dnsrch; *domain != NULL; )
511 *dp++ = *domain++;
512 }
513 else if (n == 0 && bitset(RES_DEFNAMES, _res.options))
514 {
515 *dp++ = _res.defdname;
516 }
517 else if (*cp == '.')
518 {
519 *cp = '\0';
520 }
521 *dp = NULL;
522
523 /* if we have a wildcard MX and no dots, try MX anyhow */
524 if (n == 0)
525 trymx = TRUE;
526
527 /*
528 ** Now run through the search list for the name in question.
529 */
530
531 mxmatch = NULL;
532 qtype = T_ANY;
533
534 for (dp = searchlist; *dp != NULL; )
535 {
536 if (qtype == T_ANY)
537 gotmx = FALSE;
538 if (tTd(8, 5))
539 printf("dns_getcanonname: trying %s.%s (%s)\n",
540 host, *dp,
541 qtype == T_ANY ? "ANY" : qtype == T_A ? "A" :
542 qtype == T_MX ? "MX" : "???");
543 ret = res_querydomain(host, *dp, C_IN, qtype,
544 answer.qb2, sizeof(answer.qb2));
545 if (ret <= 0)
546 {
547 if (tTd(8, 7))
548 printf("\tNO: errno=%d, h_errno=%d\n",
549 errno, h_errno);
550
551 if (errno == ECONNREFUSED || h_errno == TRY_AGAIN)
552 {
553 /* the name server seems to be down */
554 h_errno = TRY_AGAIN;
555 *statp = EX_TEMPFAIL;
556 return FALSE;
557 }
558
559 if (h_errno != HOST_NOT_FOUND)
560 {
561 /* might have another type of interest */
562 if (qtype == T_ANY)
563 {
564 qtype = T_A;
565 continue;
566 }
567 else if (qtype == T_A && !gotmx && trymx)
568 {
569 qtype = T_MX;
570 continue;
571 }
572 }
573
574 /* try the next name */
575 dp++;
576 qtype = T_ANY;
577 continue;
578 }
579 else if (tTd(8, 7))
580 printf("\tYES\n");
581
582 /*
583 ** This might be a bogus match. Search for A or
584 ** CNAME records. If we don't have a matching
585 ** wild card MX record, we will accept MX as well.
586 */
587
588 hp = (HEADER *) &answer;
589 ap = (u_char *) &answer + HFIXEDSZ;
590 eom = (u_char *) &answer + ret;
591
592 /* skip question part of response -- we know what we asked */
593 for (qdcount = ntohs(hp->qdcount); qdcount--; ap += ret + QFIXEDSZ)
594 {
595 if ((ret = dn_skipname(ap, eom)) < 0)
596 {
597 if (tTd(8, 20))
598 printf("qdcount failure (%d)\n",
599 ntohs(hp->qdcount));
600 *statp = EX_SOFTWARE;
601 return FALSE; /* ???XXX??? */
602 }
603 }
604
605 amatch = FALSE;
606 for (ancount = ntohs(hp->ancount); --ancount >= 0 && ap < eom; ap += n)
607 {
608 n = dn_expand((u_char *) &answer, eom, ap,
609 (RES_UNC_T) nbuf, sizeof nbuf);
610 if (n < 0)
611 break;
612 ap += n;
613 GETSHORT(type, ap);
614 ap += INT16SZ + INT32SZ;
615 GETSHORT(n, ap);
616 switch (type)
617 {
618 case T_MX:
619 gotmx = TRUE;
620 if (**dp != '\0' || !HasWildcardMX)
621 {
622 /* got a match -- save that info */
623 if (trymx && mxmatch == NULL)
624 mxmatch = *dp;
625 continue;
626 }
627
628 /* exact MX matches are as good as an A match */
629 /* fall through */
630
631 case T_A:
632 /* good show */
633 amatch = TRUE;
634
635 /* continue in case a CNAME also exists */
636 continue;
637
638 case T_CNAME:
639 if (DontExpandCnames)
640 {
641 /* got CNAME -- guaranteed canonical */
642 amatch = TRUE;
643 break;
644 }
645
646 if (loopcnt++ > MAXCNAMEDEPTH)
647 {
648 /*XXX should notify postmaster XXX*/
649 message("DNS failure: CNAME loop for %s",
650 host);
651 if (CurEnv->e_message == NULL)
652 {
653 char ebuf[MAXLINE];
654
655 sprintf(ebuf, "Deferred: DNS failure: CNAME loop for %s",
656 host);
657 CurEnv->e_message = newstr(ebuf);
658 }
659 h_errno = NO_RECOVERY;
660 *statp = EX_CONFIG;
661 return FALSE;
662 }
663
664 /* value points at name */
665 if ((ret = dn_expand((u_char *)&answer,
666 eom, ap, (RES_UNC_T) nbuf, sizeof(nbuf))) < 0)
667 break;
668 (void)strncpy(host, nbuf, hbsize); /* XXX */
669 host[hbsize - 1] = '\0';
670
671 /*
672 ** RFC 1034 section 3.6 specifies that CNAME
673 ** should point at the canonical name -- but
674 ** urges software to try again anyway.
675 */
676
677 goto cnameloop;
678
679 default:
680 /* not a record of interest */
681 continue;
682 }
683 }
684
685 if (amatch)
686 {
687 /* got an A record and no CNAME */
688 mxmatch = *dp;
689 break;
690 }
691
692 /*
693 ** If this was a T_ANY query, we may have the info but
694 ** need an explicit query. Try T_A, then T_MX.
695 */
696
697 if (qtype == T_ANY)
698 qtype = T_A;
699 else if (qtype == T_A && !gotmx && trymx)
700 qtype = T_MX;
701 else
702 {
703 /* really nothing in this domain; try the next */
704 qtype = T_ANY;
705 dp++;
706 }
707 }
708
709 if (mxmatch == NULL)
710 {
711 *statp = EX_NOHOST;
712 return FALSE;
713 }
714
715 /* create matching name and return */
716 (void) sprintf(nbuf, "%.*s%s%.*s", MAXDNAME, host,
717 *mxmatch == '\0' ? "" : ".",
718 MAXDNAME, mxmatch);
719 strncpy(host, nbuf, hbsize);
720 host[hbsize - 1] = '\0';
721 *statp = EX_OK;
722 return TRUE;
723 }
724
725
726 char *
gethostalias(host)727 gethostalias(host)
728 char *host;
729 {
730 char *fname;
731 FILE *fp;
732 register char *p = NULL;
733 char buf[MAXLINE];
734 static char hbuf[MAXDNAME];
735
736 fname = getenv("HOSTALIASES");
737 if (fname == NULL ||
738 (fp = safefopen(fname, O_RDONLY, 0, SFF_REGONLY)) == NULL)
739 return NULL;
740 while (fgets(buf, sizeof buf, fp) != NULL)
741 {
742 for (p = buf; p != '\0' && !(isascii(*p) && isspace(*p)); p++)
743 continue;
744 if (*p == 0)
745 {
746 /* syntax error */
747 continue;
748 }
749 *p++ = '\0';
750 if (strcasecmp(buf, host) == 0)
751 break;
752 }
753
754 if (feof(fp))
755 {
756 /* no match */
757 fclose(fp);
758 return NULL;
759 }
760
761 /* got a match; extract the equivalent name */
762 while (*p != '\0' && isascii(*p) && isspace(*p))
763 p++;
764 host = p;
765 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
766 p++;
767 *p = '\0';
768 strncpy(hbuf, host, sizeof hbuf - 1);
769 hbuf[sizeof hbuf - 1] = '\0';
770 return hbuf;
771 }
772
773 #endif /* NAMED_BIND */
774