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