1 /* $Cambridge: exim/src/src/dns.c,v 1.9 2005/06/29 10:56:35 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2005 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* Functions for interfacing with the DNS. */
15 /* Function declaration needed for mutual recursion when A6 records
20 static void dns_complete_a6(dns_address ***, dns_answer *, dns_record *,
27 /*************************************************
28 * Initialize and configure resolver *
29 *************************************************/
31 /* Initialize the resolver and the storage for holding DNS answers if this is
32 the first time we have been here, and set the resolver options.
35 qualify_single TRUE to set the RES_DEFNAMES option
36 search_parents TRUE to set the RES_DNSRCH option
42 dns_init(BOOL qualify_single, BOOL search_parents)
44 if ((_res.options & RES_INIT) == 0)
46 DEBUG(D_resolver) _res.options |= RES_DEBUG; /* For Cygwin */
48 DEBUG(D_resolver) _res.options |= RES_DEBUG;
51 _res.options &= ~(RES_DNSRCH | RES_DEFNAMES);
52 _res.options |= (qualify_single? RES_DEFNAMES : 0) |
53 (search_parents? RES_DNSRCH : 0);
54 if (dns_retrans > 0) _res.retrans = dns_retrans;
55 if (dns_retry > 0) _res.retry = dns_retry;
60 /*************************************************
61 * Build key name for PTR records *
62 *************************************************/
64 /* This function inverts an IP address and adds the relevant domain, to produce
65 a name that can be used to look up PTR records.
68 string the IP address as a string
69 buffer a suitable buffer, long enough to hold the result
75 dns_build_reverse(uschar *string, uschar *buffer)
77 uschar *p = string + Ustrlen(string);
80 /* Handle IPv4 address */
83 if (Ustrchr(string, ':') == NULL)
87 for (i = 0; i < 4; i++)
90 while (ppp > string && ppp[-1] != '.') ppp--;
91 Ustrncpy(pp, ppp, p - ppp);
96 Ustrcpy(pp, "in-addr.arpa");
99 /* Handle IPv6 address; convert to binary so as to fill out any
100 abbreviation in the textual form. */
107 (void)host_aton(string, v6);
109 /* The original specification for IPv6 reverse lookup was to invert each
110 nibble, and look in the ip6.int domain. The domain was subsequently
111 changed to ip6.arpa. */
113 for (i = 3; i >= 0; i--)
116 for (j = 0; j < 32; j += 4)
118 sprintf(CS pp, "%x.", (v6[i] >> j) & 15);
122 Ustrcpy(pp, "ip6.arpa.");
124 /* Another way of doing IPv6 reverse lookups was proposed in conjunction
125 with A6 records. However, it fell out of favour when they did. The
126 alternative was to construct a binary key, and look in ip6.arpa. I tried
127 to make this code do that, but I could not make it work on Solaris 8. The
128 resolver seems to lose the initial backslash somehow. However, now that
129 this style of reverse lookup has been dropped, it doesn't matter. These
130 lines are left here purely for historical interest. */
132 /**************************************************
136 for (i = 0; i < 4; i++)
138 sprintf(pp, "%08X", v6[i]);
141 Ustrcpy(pp, "].ip6.arpa.");
142 **************************************************/
151 /*************************************************
152 * Get next DNS record from answer block *
153 *************************************************/
155 /* Call this with reset == RESET_ANSWERS to scan the answer block, reset ==
156 RESET_AUTHORITY to scan the authority records, reset == RESET_ADDITIONAL to
157 scan the additional records, and reset == RESET_NEXT to get the next record.
158 The result is in static storage which must be copied if it is to be preserved.
161 dnsa pointer to dns answer block
162 dnss pointer to dns scan block
163 reset option specifing what portion to scan, as described above
165 Returns: next dns record, or NULL when no more
169 dns_next_rr(dns_answer *dnsa, dns_scan *dnss, int reset)
171 HEADER *h = (HEADER *)dnsa->answer;
174 /* Reset the saved data when requested to, and skip to the first required RR */
176 if (reset != RESET_NEXT)
178 dnss->rrcount = ntohs(h->qdcount);
179 dnss->aptr = dnsa->answer + sizeof(HEADER);
181 /* Skip over questions; failure to expand the name just gives up */
183 while (dnss->rrcount-- > 0)
185 namelen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen,
186 dnss->aptr, (DN_EXPAND_ARG4_TYPE) &(dnss->srr.name), DNS_MAXNAME);
187 if (namelen < 0) { dnss->rrcount = 0; return NULL; }
188 dnss->aptr += namelen + 4; /* skip name & type & class */
191 /* Get the number of answer records. */
193 dnss->rrcount = ntohs(h->ancount);
195 /* Skip over answers if we want to look at the authority section. Also skip
196 the NS records (i.e. authority section) if wanting to look at the additional
199 if (reset == RESET_ADDITIONAL) dnss->rrcount += ntohs(h->nscount);
201 if (reset == RESET_AUTHORITY || reset == RESET_ADDITIONAL)
203 while (dnss->rrcount-- > 0)
205 namelen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen,
206 dnss->aptr, (DN_EXPAND_ARG4_TYPE) &(dnss->srr.name), DNS_MAXNAME);
207 if (namelen < 0) { dnss->rrcount = 0; return NULL; }
208 dnss->aptr += namelen + 8; /* skip name, type, class & TTL */
209 GETSHORT(dnss->srr.size, dnss->aptr); /* size of data portion */
210 dnss->aptr += dnss->srr.size; /* skip over it */
212 dnss->rrcount = (reset == RESET_AUTHORITY)
213 ? ntohs(h->nscount) : ntohs(h->arcount);
217 /* The variable dnss->aptr is now pointing at the next RR, and dnss->rrcount
218 contains the number of RR records left. */
220 if (dnss->rrcount-- <= 0) return NULL;
222 /* If expanding the RR domain name fails, behave as if no more records
225 namelen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, dnss->aptr,
226 (DN_EXPAND_ARG4_TYPE) &(dnss->srr.name), DNS_MAXNAME);
227 if (namelen < 0) { dnss->rrcount = 0; return NULL; }
229 /* Move the pointer past the name and fill in the rest of the data structure
230 from the following bytes. */
232 dnss->aptr += namelen;
233 GETSHORT(dnss->srr.type, dnss->aptr); /* Record type */
234 dnss->aptr += 6; /* Don't want class or TTL */
235 GETSHORT(dnss->srr.size, dnss->aptr); /* Size of data portion */
236 dnss->srr.data = dnss->aptr; /* The record's data follows */
237 dnss->aptr += dnss->srr.size; /* Advance to next RR */
239 /* Return a pointer to the dns_record structure within the dns_answer. This is
240 for convenience so that the scans can use nice-looking for loops. */
248 /*************************************************
249 * Turn DNS type into text *
250 *************************************************/
252 /* Turn the coded record type into a string for printing. All those that Exim
253 uses should be included here.
255 Argument: record type
256 Returns: pointer to string
264 case T_A: return US"A";
265 case T_MX: return US"MX";
266 case T_AAAA: return US"AAAA";
267 case T_A6: return US"A6";
268 case T_TXT: return US"TXT";
269 case T_PTR: return US"PTR";
270 case T_SOA: return US"SOA";
271 case T_SRV: return US"SRV";
272 case T_NS: return US"NS";
273 case T_CNAME: return US"CNAME";
274 default: return US"?";
280 /*************************************************
281 * Cache a failed DNS lookup result *
282 *************************************************/
284 /* We cache failed lookup results so as not to experience timeouts many
285 times for the same domain. We need to retain the resolver options because they
286 may change. For successful lookups, we rely on resolver and/or name server
294 Returns: the return code
298 dns_return(uschar *name, int type, int rc)
300 tree_node *node = store_get_perm(sizeof(tree_node) + 290);
301 sprintf(CS node->name, "%.255s-%s-%lx", name, dns_text_type(type),
304 (void)tree_insertnode(&tree_dns_fails, node);
310 /*************************************************
311 * Do basic DNS lookup *
312 *************************************************/
314 /* Call the resolver to look up the given domain name, using the given type,
315 and check the result. The error code TRY_AGAIN is documented as meaning "non-
316 Authoritive Host not found, or SERVERFAIL". Sometimes there are badly set
317 up nameservers that produce this error continually, so there is the option of
318 providing a list of domains for which this is treated as a non-existent
322 dnsa pointer to dns_answer structure
324 type type of DNS record required (T_A, T_MX, etc)
326 Returns: DNS_SUCCEED successful lookup
327 DNS_NOMATCH name not found (NXDOMAIN)
328 or name contains illegal characters (if checking)
329 DNS_NODATA domain exists, but no data for this type (NODATA)
330 DNS_AGAIN soft failure, try again later
335 dns_basic_lookup(dns_answer *dnsa, uschar *name, int type)
343 uschar node_name[290];
345 /* DNS lookup failures of any kind are cached in a tree. This is mainly so that
346 a timeout on one domain doesn't happen time and time again for messages that
347 have many addresses in the same domain. We rely on the resolver and name server
348 caching for successful lookups. */
350 sprintf(CS node_name, "%.255s-%s-%lx", name, dns_text_type(type),
352 previous = tree_search(tree_dns_fails, node_name);
353 if (previous != NULL)
355 DEBUG(D_dns) debug_printf("DNS lookup of %.255s-%s: using cached value %s\n",
356 name, dns_text_type(type),
357 (previous->data.val == DNS_NOMATCH)? "DNS_NOMATCH" :
358 (previous->data.val == DNS_NODATA)? "DNS_NODATA" :
359 (previous->data.val == DNS_AGAIN)? "DNS_AGAIN" :
360 (previous->data.val == DNS_FAIL)? "DNS_FAIL" : "??");
361 return previous->data.val;
364 /* If we are running in the test harness, recognize a couple of special
365 names that always give error returns. This makes it straightforward to
366 test the handling of DNS errors. */
368 if (running_in_test_harness)
370 uschar *endname = name + Ustrlen(name);
371 if (Ustrcmp(endname - 14, "test.again.dns") == 0)
373 int delay = Uatoi(name); /* digits at the start of the name */
374 DEBUG(D_dns) debug_printf("Real DNS lookup of %s (%s) bypassed for testing\n",
375 name, dns_text_type(type));
378 DEBUG(D_dns) debug_printf("delaying %d seconds\n", delay);
381 DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
382 return dns_return(name, type, DNS_AGAIN);
384 if (Ustrcmp(endname - 13, "test.fail.dns") == 0)
386 DEBUG(D_dns) debug_printf("Real DNS lookup of %s (%s) bypassed for testing\n",
387 name, dns_text_type(type));
388 DEBUG(D_dns) debug_printf("returning DNS_FAIL\n");
389 return dns_return(name, type, DNS_FAIL);
393 /* If configured, check the hygene of the name passed to lookup. Otherwise,
394 although DNS lookups may give REFUSED at the lower level, some resolvers
395 turn this into TRY_AGAIN, which is silly. Give a NOMATCH return, since such
396 domains cannot be in the DNS. The check is now done by a regular expression;
397 give it space for substring storage to save it having to get its own if the
398 regex has substrings that are used - the default uses a conditional.
400 This test is omitted for PTR records. These occur only in calls from the dnsdb
401 lookup, which constructs the names itself, so they should be OK. Besides,
402 bitstring labels don't conform to normal name syntax. (But the aren't used any
405 For SRV records, we omit the initial _smtp._tcp. components at the start. */
407 #ifndef STAND_ALONE /* Omit this for stand-alone tests */
409 if (check_dns_names_pattern[0] != 0 && type != T_PTR)
411 uschar *checkname = name;
412 int ovector[3*(EXPAND_MAXN+1)];
414 if (regex_check_dns_names == NULL)
415 regex_check_dns_names =
416 regex_must_compile(check_dns_names_pattern, FALSE, TRUE);
418 /* For an SRV lookup, skip over the first two components (the service and
419 protocol names, which both start with an underscore). */
423 while (*checkname++ != '.');
424 while (*checkname++ != '.');
427 if (pcre_exec(regex_check_dns_names, NULL, CS checkname, Ustrlen(checkname),
428 0, PCRE_EOPT, ovector, sizeof(ovector)/sizeof(int)) < 0)
431 debug_printf("DNS name syntax check failed: %s (%s)\n", name,
432 dns_text_type(type));
433 host_find_failed_syntax = TRUE;
438 #endif /* STAND_ALONE */
440 /* Call the resolver; for an overlong response, res_search() will return the
441 number of bytes the message would need, so we need to check for this case.
442 The effect is to truncate overlong data. */
444 dnsa->answerlen = res_search(CS name, C_IN, type, dnsa->answer, MAXPACKET);
445 if (dnsa->answerlen > MAXPACKET) dnsa->answerlen = MAXPACKET;
447 if (dnsa->answerlen < 0) switch (h_errno)
450 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave HOST_NOT_FOUND\n"
451 "returning DNS_NOMATCH\n", name, dns_text_type(type));
452 return dns_return(name, type, DNS_NOMATCH);
455 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave TRY_AGAIN\n",
456 name, dns_text_type(type));
458 /* Cut this out for various test programs */
460 save = deliver_domain;
461 deliver_domain = name; /* set $domain */
462 rc = match_isinlist(name, &dns_again_means_nonexist, 0, NULL, NULL,
463 MCL_DOMAIN, TRUE, NULL);
464 deliver_domain = save;
467 DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
468 return dns_return(name, type, DNS_AGAIN);
470 DEBUG(D_dns) debug_printf("%s is in dns_again_means_nonexist: returning "
471 "DNS_NOMATCH\n", name);
472 return dns_return(name, type, DNS_NOMATCH);
474 #else /* For stand-alone tests */
475 return dns_return(name, type, DNS_AGAIN);
479 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave NO_RECOVERY\n"
480 "returning DNS_FAIL\n", name, dns_text_type(type));
481 return dns_return(name, type, DNS_FAIL);
484 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave NO_DATA\n"
485 "returning DNS_NODATA\n", name, dns_text_type(type));
486 return dns_return(name, type, DNS_NODATA);
489 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave unknown DNS error %d\n"
490 "returning DNS_FAIL\n", name, dns_text_type(type), h_errno);
491 return dns_return(name, type, DNS_FAIL);
494 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) succeeded\n",
495 name, dns_text_type(type));
503 /************************************************
504 * Do a DNS lookup and handle CNAMES *
505 ************************************************/
507 /* Look up the given domain name, using the given type. Follow CNAMEs if
508 necessary, but only so many times. There aren't supposed to be CNAME chains in
509 the DNS, but you are supposed to cope with them if you find them.
511 The assumption is made that if the resolver gives back records of the
512 requested type *and* a CNAME, we don't need to make another call to look up
513 the CNAME. I can't see how it could return only some of the right records. If
514 it's done a CNAME lookup in the past, it will have all of them; if not, it
517 If fully_qualified_name is not NULL, set it to point to the full name
518 returned by the resolver, if this is different to what it is given, unless
519 the returned name starts with "*" as some nameservers seem to be returning
520 wildcards in this form.
523 dnsa pointer to dns_answer structure
524 name domain name to look up
525 type DNS record type (T_A, T_MX, etc)
526 fully_qualified_name if not NULL, return the returned name here if its
527 contents are different (i.e. it must be preset)
529 Returns: DNS_SUCCEED successful lookup
530 DNS_NOMATCH name not found
531 DNS_NODATA no data found
532 DNS_AGAIN soft failure, try again later
537 dns_lookup(dns_answer *dnsa, uschar *name, int type, uschar **fully_qualified_name)
540 uschar *orig_name = name;
542 /* Loop to follow CNAME chains so far, but no further... */
544 for (i = 0; i < 10; i++)
547 dns_record *rr, cname_rr, type_rr;
551 /* DNS lookup failures get passed straight back. */
553 if ((rc = dns_basic_lookup(dnsa, name, type)) != DNS_SUCCEED) return rc;
555 /* We should have either records of the required type, or a CNAME record,
556 or both. We need to know whether both exist for getting the fully qualified
557 name, but avoid scanning more than necessary. Note that we must copy the
558 contents of any rr blocks returned by dns_next_rr() as they use the same
559 area in the dnsa block. */
561 cname_rr.data = type_rr.data = NULL;
562 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
564 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
566 if (rr->type == type)
568 if (type_rr.data == NULL) type_rr = *rr;
569 if (cname_rr.data != NULL) break;
571 else if (rr->type == T_CNAME) cname_rr = *rr;
574 /* If a CNAME was found, take the fully qualified name from it; otherwise
575 from the first data record, if present. For testing, there is a magic name
576 that gets its casing adjusted, because my resolver doesn't seem to pass back
577 upper case letters in domain names. */
579 if (fully_qualified_name != NULL)
581 if (cname_rr.data != NULL)
583 if (Ustrcmp(cname_rr.name, *fully_qualified_name) != 0 &&
584 cname_rr.name[0] != '*')
585 *fully_qualified_name = string_copy_dnsdomain(cname_rr.name);
587 else if (type_rr.data != NULL)
589 if (running_in_test_harness &&
590 Ustrcmp(type_rr.name, "uppercase.test.ex") == 0)
591 *fully_qualified_name = US"UpperCase.test.ex";
594 if (Ustrcmp(type_rr.name, *fully_qualified_name) != 0 &&
595 type_rr.name[0] != '*')
596 *fully_qualified_name = string_copy_dnsdomain(type_rr.name);
601 /* If any data records of the correct type were found, we are done. */
603 if (type_rr.data != NULL) return DNS_SUCCEED;
605 /* If there are no data records, we need to re-scan the DNS using the
606 domain given in the CNAME record, which should exist (otherwise we should
607 have had a failure from dns_lookup). However code against the possibility of
610 if (cname_rr.data == NULL) return DNS_FAIL;
611 datalen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen,
612 cname_rr.data, (DN_EXPAND_ARG4_TYPE)data, 256);
613 if (datalen < 0) return DNS_FAIL;
615 } /* Loop back to do another lookup */
617 /*Control reaches here after 10 times round the CNAME loop. Something isn't
620 log_write(0, LOG_MAIN, "CNAME loop for %s encountered", orig_name);
629 /************************************************
630 * Do a DNS lookup and handle virtual types *
631 ************************************************/
633 /* This function handles some invented "lookup types" that synthesize feature
634 not available in the basic types. The special types all have negative values.
635 Positive type values are passed straight on to dns_lookup().
638 dnsa pointer to dns_answer structure
639 name domain name to look up
640 type DNS record type (T_A, T_MX, etc or a "special")
641 fully_qualified_name if not NULL, return the returned name here if its
642 contents are different (i.e. it must be preset)
644 Returns: DNS_SUCCEED successful lookup
645 DNS_NOMATCH name not found
646 DNS_NODATA no data found
647 DNS_AGAIN soft failure, try again later
652 dns_special_lookup(dns_answer *dnsa, uschar *name, int type,
653 uschar **fully_qualified_name)
655 if (type >= 0) return dns_lookup(dnsa, name, type, fully_qualified_name);
657 /* The "mx hosts only" type doesn't require any special action here */
659 if (type == T_MXH) return dns_lookup(dnsa, name, T_MX, fully_qualified_name);
661 /* Find nameservers for the domain or the nearest enclosing zone, excluding the
669 int rc = dns_lookup(dnsa, d, T_NS, fully_qualified_name);
670 if (rc != DNS_NOMATCH && rc != DNS_NODATA) return rc;
671 while (*d != 0 && *d != '.') d++;
672 if (*d++ == 0) break;
677 /* Try to look up the Client SMTP Authorization SRV record for the name. If
678 there isn't one, search from the top downwards for a CSA record in a parent
679 domain, which might be making assertions about subdomains. If we find a record
680 we set fully_qualified_name to whichever lookup succeeded, so that the caller
681 can tell whether to look at the explicit authorization field or the subdomain
686 uschar *srvname, *namesuff, *tld, *p;
687 int priority, weight, port;
693 DEBUG(D_dns) debug_printf("CSA lookup of %s\n", name);
695 srvname = string_sprintf("_client._smtp.%s", name);
696 rc = dns_lookup(dnsa, srvname, T_SRV, NULL);
697 if (rc == DNS_SUCCEED || rc == DNS_AGAIN)
699 if (rc == DNS_SUCCEED) *fully_qualified_name = name;
703 /* Search for CSA subdomain assertion SRV records from the top downwards,
704 starting with the 2nd level domain. This order maximizes cache-friendliness.
705 We skip the top level domains to avoid loading their nameservers and because
706 we know they'll never have CSA SRV records. */
708 namesuff = Ustrrchr(name, '.');
709 if (namesuff == NULL) return DNS_NOMATCH;
712 limit = dns_csa_search_limit;
714 /* Use more appropriate search parameters if we are in the reverse DNS. */
716 if (strcmpic(namesuff, US".arpa") == 0)
718 if (namesuff - 8 > name && strcmpic(namesuff - 8, US".in-addr.arpa") == 0)
724 else if (namesuff - 4 > name && strcmpic(namesuff - 4, US".ip6.arpa") == 0)
733 DEBUG(D_dns) debug_printf("CSA TLD %s\n", tld);
735 /* Do not perform the search if the top level or 2nd level domains do not
736 exist. This is quite common, and when it occurs all the search queries would
737 go to the root or TLD name servers, which is not friendly. So we check the
738 AUTHORITY section; if it contains the root's SOA record or the TLD's SOA then
739 the TLD or the 2LD (respectively) doesn't exist and we can skip the search.
740 If the TLD and the 2LD exist but the explicit CSA record lookup failed, then
741 the AUTHORITY SOA will be the 2LD's or a subdomain thereof. */
743 if (rc == DNS_NOMATCH)
745 /* This is really gross. The successful return value from res_search() is
746 the packet length, which is stored in dnsa->answerlen. If we get a
747 negative DNS reply then res_search() returns -1, which causes the bounds
748 checks for name decompression to fail when it is treated as a packet
749 length, which in turn causes the authority search to fail. The correct
750 packet length has been lost inside libresolv, so we have to guess a
751 replacement value. (The only way to fix this properly would be to
752 re-implement res_search() and res_query() so that they don't muddle their
753 success and packet length return values.) For added safety we only reset
754 the packet length if the packet header looks plausible. */
756 HEADER *h = (HEADER *)dnsa->answer;
757 if (h->qr == 1 && h->opcode == QUERY && h->tc == 0
758 && (h->rcode == NOERROR || h->rcode == NXDOMAIN)
759 && ntohs(h->qdcount) == 1 && ntohs(h->ancount) == 0
760 && ntohs(h->nscount) >= 1)
761 dnsa->answerlen = MAXPACKET;
763 for (rr = dns_next_rr(dnsa, &dnss, RESET_AUTHORITY);
765 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
766 if (rr->type != T_SOA) continue;
767 else if (strcmpic(rr->name, US"") == 0 ||
768 strcmpic(rr->name, tld) == 0) return DNS_NOMATCH;
772 for (i = 0; i < limit; i++)
776 /* Scan through the IPv6 reverse DNS in chunks of 16 bits worth of IP
777 address, i.e. 4 hex chars and 4 dots, i.e. 8 chars. */
779 if (namesuff <= name) return DNS_NOMATCH;
782 /* Find the start of the preceding domain name label. */
784 if (--namesuff <= name) return DNS_NOMATCH;
785 while (*namesuff != '.');
787 DEBUG(D_dns) debug_printf("CSA parent search at %s\n", namesuff + 1);
789 srvname = string_sprintf("_client._smtp.%s", namesuff + 1);
790 rc = dns_lookup(dnsa, srvname, T_SRV, NULL);
791 if (rc == DNS_AGAIN) return rc;
792 if (rc != DNS_SUCCEED) continue;
794 /* Check that the SRV record we have found is worth returning. We don't
795 just return the first one we find, because some lower level SRV record
796 might make stricter assertions than its parent domain. */
798 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
800 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
802 if (rr->type != T_SRV) continue;
804 /* Extract the numerical SRV fields (p is incremented) */
806 GETSHORT(priority, p);
810 /* Check the CSA version number */
811 if (priority != 1) continue;
813 /* If it's making an interesting assertion, return this response. */
816 *fully_qualified_name = namesuff + 1;
824 /* Control should never reach here */
831 /* Support for A6 records has been commented out since they were demoted to
832 experimental status at IETF 51. */
834 #if HAVE_IPV6 && defined(SUPPORT_A6)
836 /*************************************************
837 * Search DNS block for prefix RRs *
838 *************************************************/
840 /* Called from dns_complete_a6() to search an additional section or a main
841 answer section for required prefix records to complete an IPv6 address obtained
842 from an A6 record. For each prefix record, a recursive call to dns_complete_a6
843 is made, with a new copy of the address so far.
846 dnsa the DNS answer block
847 which RESET_ADDITIONAL or RESET_ANSWERS
848 name name of prefix record
849 yptrptr pointer to the pointer that points to where to hang the next
850 dns_address structure
851 bits number of bits we have already got
852 bitvec the bits we have already got
854 Returns: TRUE if any records were found
858 dns_find_prefix(dns_answer *dnsa, int which, uschar *name, dns_address
859 ***yptrptr, int bits, uschar *bitvec)
865 for (rr = dns_next_rr(dnsa, &dnss, which);
867 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
870 if (rr->type != T_A6 || strcmpic(rr->name, name) != 0) continue;
872 memcpy(cbitvec, bitvec, sizeof(cbitvec));
873 dns_complete_a6(yptrptr, dnsa, rr, bits, cbitvec);
881 /*************************************************
882 * Follow chains of A6 records *
883 *************************************************/
885 /* A6 records may be incomplete, with pointers to other records containing more
886 bits of the address. There can be a tree structure, leading to a number of
887 addresses originating from a single initial A6 record.
890 yptrptr pointer to the pointer that points to where to hang the next
891 dns_address structure
892 dnsa the current DNS answer block
893 rr the RR we have at present
894 bits number of bits we have already got
895 bitvec the bits we have already got
901 dns_complete_a6(dns_address ***yptrptr, dns_answer *dnsa, dns_record *rr,
902 int bits, uschar *bitvec)
904 static uschar bitmask[] = { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
905 uschar *p = (uschar *)(rr->data);
906 int prefix_len, suffix_len;
912 /* The prefix length is the first byte. It defines the prefix which is missing
913 from the data in this record as a number of bits. Zero means this is the end of
914 a chain. The suffix is the data in this record; only sufficient bytes to hold
915 it are supplied. There may be zero bytes. We have to ignore trailing bits that
916 we have already obtained from earlier RRs in the chain. */
918 prefix_len = *p++; /* bits */
919 suffix_len = (128 - prefix_len + 7)/8; /* bytes */
921 /* If the prefix in this record is greater than the prefix in the previous
922 record in the chain, we have to ignore the record (RFC 2874). */
924 if (prefix_len > 128 - bits) return;
926 /* In this little loop, the number of bits up to and including the current byte
927 is held in k. If we have none of the bits in this byte, we can just or it into
928 the current data. If we have all of the bits in this byte, we skip it.
929 Otherwise, some masking has to be done. */
931 for (i = suffix_len - 1, j = 15, k = 8; i >= 0; i--)
933 int required = k - bits;
934 if (required >= 8) bitvec[j] |= p[i];
935 else if (required > 0) bitvec[j] |= p[i] & bitmask[required];
936 j--; /* I tried putting these in the "for" statement, but gcc muttered */
937 k += 8; /* about computed values not being used. */
940 /* If the prefix_length is zero, we are at the end of a chain. Build a
941 dns_address item with the current data, hang it onto the end of the chain,
942 adjust the hanging pointer, and we are done. */
946 dns_address *new = store_get(sizeof(dns_address) + 50);
947 inet_ntop(AF_INET6, bitvec, CS new->address, 50);
950 *yptrptr = &(new->next);
954 /* Prefix length is not zero. Reset the number of bits that we have collected
955 so far, and extract the chain name. */
957 bits = 128 - prefix_len;
961 while ((i = *p++) != 0)
963 if (chainptr != chain) *chainptr++ = '.';
964 memcpy(chainptr, p, i);
971 /* Now scan the current DNS response record to see if the additional section
972 contains the records we want. This processing can be cut out for testing
975 if (dns_find_prefix(dnsa, RESET_ADDITIONAL, chainptr, yptrptr, bits, bitvec))
978 /* No chain records were found in the current DNS response block. Do a new DNS
979 lookup to try to find these records. This opens up the possibility of DNS
980 failures. We ignore them at this point; if all branches of the tree fail, there
981 will be no addresses at the end. */
983 if (dns_lookup(&cdnsa, chainptr, T_A6, NULL) == DNS_SUCCEED)
984 (void)dns_find_prefix(&cdnsa, RESET_ANSWERS, chainptr, yptrptr, bits, bitvec);
986 #endif /* HAVE_IPV6 && defined(SUPPORT_A6) */
991 /*************************************************
992 * Get address(es) from DNS record *
993 *************************************************/
995 /* The record type is either T_A for an IPv4 address or T_AAAA (or T_A6 when
996 supported) for an IPv6 address. In the A6 case, there may be several addresses,
997 generated by following chains. A recursive function does all the hard work. A6
998 records now look like passing into history, so the code is only included when
999 explicitly asked for.
1002 dnsa the DNS answer block
1005 Returns: pointer a chain of dns_address items
1009 dns_address_from_rr(dns_answer *dnsa, dns_record *rr)
1011 dns_address *yield = NULL;
1013 #if HAVE_IPV6 && defined(SUPPORT_A6)
1014 dns_address **yieldptr = &yield;
1017 dnsa = dnsa; /* Stop picky compilers warning */
1020 if (rr->type == T_A)
1022 uschar *p = (uschar *)(rr->data);
1023 yield = store_get(sizeof(dns_address) + 20);
1024 (void)sprintf(CS yield->address, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
1031 else if (rr->type == T_A6)
1033 memset(bitvec, 0, sizeof(bitvec));
1034 dns_complete_a6(&yieldptr, dnsa, rr, 0, bitvec);
1036 #endif /* SUPPORT_A6 */
1040 yield = store_get(sizeof(dns_address) + 50);
1041 inet_ntop(AF_INET6, (uschar *)(rr->data), CS yield->address, 50);
1044 #endif /* HAVE_IPV6 */