Revert accidental bogus checkin, sorry
[exim.git] / src / src / dns.c
CommitLineData
97696d59 1/* $Cambridge: exim/src/src/dns.c,v 1.8 2005/06/10 13:38:06 tom Exp $ */
059ec3d9
PH
2
3/*************************************************
4* Exim - an Internet mail transport agent *
5*************************************************/
6
c988f1f4 7/* Copyright (c) University of Cambridge 1995 - 2005 */
059ec3d9
PH
8/* See the file NOTICE for conditions of use and distribution. */
9
10/* Functions for interfacing with the DNS. */
11
12#include "exim.h"
13
14
15/* Function declaration needed for mutual recursion when A6 records
16are supported. */
17
18#if HAVE_IPV6
19#ifdef SUPPORT_A6
20static void dns_complete_a6(dns_address ***, dns_answer *, dns_record *,
21 int, uschar *);
22#endif
23#endif
24
25
26
27/*************************************************
28* Initialize and configure resolver *
29*************************************************/
30
31/* Initialize the resolver and the storage for holding DNS answers if this is
32the first time we have been here, and set the resolver options.
33
34Arguments:
35 qualify_single TRUE to set the RES_DEFNAMES option
36 search_parents TRUE to set the RES_DNSRCH option
37
38Returns: nothing
39*/
40
41void
42dns_init(BOOL qualify_single, BOOL search_parents)
43{
44if ((_res.options & RES_INIT) == 0)
45 {
46 DEBUG(D_resolver) _res.options |= RES_DEBUG; /* For Cygwin */
47 res_init();
48 DEBUG(D_resolver) _res.options |= RES_DEBUG;
49 }
50
51_res.options &= ~(RES_DNSRCH | RES_DEFNAMES);
52_res.options |= (qualify_single? RES_DEFNAMES : 0) |
53 (search_parents? RES_DNSRCH : 0);
54if (dns_retrans > 0) _res.retrans = dns_retrans;
55if (dns_retry > 0) _res.retry = dns_retry;
56}
57
58
59
60/*************************************************
61* Build key name for PTR records *
62*************************************************/
63
64/* This function inverts an IP address and adds the relevant domain, to produce
65a name that can be used to look up PTR records.
66
67Arguments:
68 string the IP address as a string
69 buffer a suitable buffer, long enough to hold the result
70
71Returns: nothing
72*/
73
74void
75dns_build_reverse(uschar *string, uschar *buffer)
76{
77uschar *p = string + Ustrlen(string);
78uschar *pp = buffer;
79
80/* Handle IPv4 address */
81
82#if HAVE_IPV6
83if (Ustrchr(string, ':') == NULL)
84#endif
85 {
86 int i;
87 for (i = 0; i < 4; i++)
88 {
89 uschar *ppp = p;
90 while (ppp > string && ppp[-1] != '.') ppp--;
91 Ustrncpy(pp, ppp, p - ppp);
92 pp += p - ppp;
93 *pp++ = '.';
94 p = ppp - 1;
95 }
96 Ustrcpy(pp, "in-addr.arpa");
97 }
98
99/* Handle IPv6 address; convert to binary so as to fill out any
100abbreviation in the textual form. */
101
102#if HAVE_IPV6
103else
104 {
105 int i;
106 int v6[4];
107 (void)host_aton(string, v6);
108
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. */
112
113 for (i = 3; i >= 0; i--)
114 {
115 int j;
116 for (j = 0; j < 32; j += 4)
117 {
118 sprintf(CS pp, "%x.", (v6[i] >> j) & 15);
119 pp += 2;
120 }
121 }
122 Ustrcpy(pp, "ip6.arpa.");
123
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. */
131
132 /**************************************************
133 Ustrcpy(pp, "\\[x");
134 pp += 3;
135
136 for (i = 0; i < 4; i++)
137 {
138 sprintf(pp, "%08X", v6[i]);
139 pp += 8;
140 }
141 Ustrcpy(pp, "].ip6.arpa.");
142 **************************************************/
143
144 }
145#endif
146}
147
148
149
150
151/*************************************************
152* Get next DNS record from answer block *
153*************************************************/
154
155/* Call this with reset == RESET_ANSWERS to scan the answer block, reset ==
e5a9dba6
PH
156RESET_AUTHORITY to scan the authority records, reset == RESET_ADDITIONAL to
157scan the additional records, and reset == RESET_NEXT to get the next record.
158The result is in static storage which must be copied if it is to be preserved.
059ec3d9
PH
159
160Arguments:
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
164
165Returns: next dns record, or NULL when no more
166*/
167
168dns_record *
169dns_next_rr(dns_answer *dnsa, dns_scan *dnss, int reset)
170{
171HEADER *h = (HEADER *)dnsa->answer;
172int namelen;
173
174/* Reset the saved data when requested to, and skip to the first required RR */
175
176if (reset != RESET_NEXT)
177 {
178 dnss->rrcount = ntohs(h->qdcount);
179 dnss->aptr = dnsa->answer + sizeof(HEADER);
180
181 /* Skip over questions; failure to expand the name just gives up */
182
183 while (dnss->rrcount-- > 0)
184 {
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 */
189 }
190
191 /* Get the number of answer records. */
192
193 dnss->rrcount = ntohs(h->ancount);
194
e5a9dba6
PH
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
059ec3d9
PH
197 records. */
198
e5a9dba6
PH
199 if (reset == RESET_ADDITIONAL) dnss->rrcount += ntohs(h->nscount);
200
201 if (reset == RESET_AUTHORITY || reset == RESET_ADDITIONAL)
059ec3d9 202 {
059ec3d9
PH
203 while (dnss->rrcount-- > 0)
204 {
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 */
211 }
e5a9dba6
PH
212 dnss->rrcount = (reset == RESET_AUTHORITY)
213 ? ntohs(h->nscount) : ntohs(h->arcount);
059ec3d9
PH
214 }
215 }
216
059ec3d9
PH
217/* The variable dnss->aptr is now pointing at the next RR, and dnss->rrcount
218contains the number of RR records left. */
219
220if (dnss->rrcount-- <= 0) return NULL;
221
222/* If expanding the RR domain name fails, behave as if no more records
223(something safe). */
224
225namelen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, dnss->aptr,
226 (DN_EXPAND_ARG4_TYPE) &(dnss->srr.name), DNS_MAXNAME);
227if (namelen < 0) { dnss->rrcount = 0; return NULL; }
228
229/* Move the pointer past the name and fill in the rest of the data structure
230from the following bytes. */
231
232dnss->aptr += namelen;
233GETSHORT(dnss->srr.type, dnss->aptr); /* Record type */
234dnss->aptr += 6; /* Don't want class or TTL */
235GETSHORT(dnss->srr.size, dnss->aptr); /* Size of data portion */
236dnss->srr.data = dnss->aptr; /* The record's data follows */
237dnss->aptr += dnss->srr.size; /* Advance to next RR */
238
239/* Return a pointer to the dns_record structure within the dns_answer. This is
240for convenience so that the scans can use nice-looking for loops. */
241
242return &(dnss->srr);
243}
244
245
246
247
248/*************************************************
249* Turn DNS type into text *
250*************************************************/
251
252/* Turn the coded record type into a string for printing.
253
254Argument: record type
255Returns: pointer to string
256*/
257
258uschar *
259dns_text_type(int t)
260{
261switch(t)
262 {
33397d19
PH
263 case T_A: return US"A";
264 case T_MX: return US"MX";
265 case T_AAAA: return US"AAAA";
266 case T_A6: return US"A6";
267 case T_TXT: return US"TXT";
268 case T_PTR: return US"PTR";
269 case T_SRV: return US"SRV";
270 case T_NS: return US"NS";
8e669ac1 271 case T_CNAME: return US"CNAME";
33397d19 272 default: return US"?";
059ec3d9
PH
273 }
274}
275
276
277
278/*************************************************
279* Cache a failed DNS lookup result *
280*************************************************/
281
282/* We cache failed lookup results so as not to experience timeouts many
283times for the same domain. We need to retain the resolver options because they
284may change. For successful lookups, we rely on resolver and/or name server
285caching.
286
287Arguments:
288 name the domain name
289 type the lookup type
290 rc the return code
291
292Returns: the return code
293*/
294
295static int
296dns_return(uschar *name, int type, int rc)
297{
298tree_node *node = store_get_perm(sizeof(tree_node) + 290);
299sprintf(CS node->name, "%.255s-%s-%lx", name, dns_text_type(type),
300 _res.options);
301node->data.val = rc;
302(void)tree_insertnode(&tree_dns_fails, node);
303return rc;
304}
305
306
307
308/*************************************************
309* Do basic DNS lookup *
310*************************************************/
311
312/* Call the resolver to look up the given domain name, using the given type,
313and check the result. The error code TRY_AGAIN is documented as meaning "non-
314Authoritive Host not found, or SERVERFAIL". Sometimes there are badly set
315up nameservers that produce this error continually, so there is the option of
316providing a list of domains for which this is treated as a non-existent
317host.
318
319Arguments:
320 dnsa pointer to dns_answer structure
321 name name to look up
322 type type of DNS record required (T_A, T_MX, etc)
323
324Returns: DNS_SUCCEED successful lookup
325 DNS_NOMATCH name not found (NXDOMAIN)
326 or name contains illegal characters (if checking)
327 DNS_NODATA domain exists, but no data for this type (NODATA)
328 DNS_AGAIN soft failure, try again later
329 DNS_FAIL DNS failure
330*/
331
332int
333dns_basic_lookup(dns_answer *dnsa, uschar *name, int type)
334{
335#ifndef STAND_ALONE
336int rc;
337uschar *save;
338#endif
339
340tree_node *previous;
341uschar node_name[290];
342
343/* DNS lookup failures of any kind are cached in a tree. This is mainly so that
344a timeout on one domain doesn't happen time and time again for messages that
345have many addresses in the same domain. We rely on the resolver and name server
346caching for successful lookups. */
347
348sprintf(CS node_name, "%.255s-%s-%lx", name, dns_text_type(type),
349 _res.options);
350previous = tree_search(tree_dns_fails, node_name);
351if (previous != NULL)
352 {
353 DEBUG(D_dns) debug_printf("DNS lookup of %.255s-%s: using cached value %s\n",
354 name, dns_text_type(type),
355 (previous->data.val == DNS_NOMATCH)? "DNS_NOMATCH" :
356 (previous->data.val == DNS_NODATA)? "DNS_NODATA" :
357 (previous->data.val == DNS_AGAIN)? "DNS_AGAIN" :
358 (previous->data.val == DNS_FAIL)? "DNS_FAIL" : "??");
359 return previous->data.val;
360 }
361
362/* If we are running in the test harness, recognize a couple of special
363names that always give error returns. This makes it straightforward to
364test the handling of DNS errors. */
365
366if (running_in_test_harness)
367 {
368 uschar *endname = name + Ustrlen(name);
369 if (Ustrcmp(endname - 14, "test.again.dns") == 0)
370 {
371 int delay = Uatoi(name); /* digits at the start of the name */
372 DEBUG(D_dns) debug_printf("Real DNS lookup of %s (%s) bypassed for testing\n",
373 name, dns_text_type(type));
374 if (delay > 0)
375 {
376 DEBUG(D_dns) debug_printf("delaying %d seconds\n", delay);
377 sleep(delay);
378 }
379 DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
380 return dns_return(name, type, DNS_AGAIN);
381 }
382 if (Ustrcmp(endname - 13, "test.fail.dns") == 0)
383 {
384 DEBUG(D_dns) debug_printf("Real DNS lookup of %s (%s) bypassed for testing\n",
385 name, dns_text_type(type));
386 DEBUG(D_dns) debug_printf("returning DNS_FAIL\n");
387 return dns_return(name, type, DNS_FAIL);
388 }
389 }
390
391/* If configured, check the hygene of the name passed to lookup. Otherwise,
392although DNS lookups may give REFUSED at the lower level, some resolvers
393turn this into TRY_AGAIN, which is silly. Give a NOMATCH return, since such
394domains cannot be in the DNS. The check is now done by a regular expression;
395give it space for substring storage to save it having to get its own if the
396regex has substrings that are used - the default uses a conditional.
397
398This test is omitted for PTR records. These occur only in calls from the dnsdb
399lookup, which constructs the names itself, so they should be OK. Besides,
400bitstring labels don't conform to normal name syntax. (But the aren't used any
401more.)
402
403For SRV records, we omit the initial _smtp._tcp. components at the start. */
404
405#ifndef STAND_ALONE /* Omit this for stand-alone tests */
406
407if (check_dns_names_pattern[0] != 0 && type != T_PTR)
408 {
409 uschar *checkname = name;
410 int ovector[3*(EXPAND_MAXN+1)];
411
412 if (regex_check_dns_names == NULL)
413 regex_check_dns_names =
414 regex_must_compile(check_dns_names_pattern, FALSE, TRUE);
415
416 /* For an SRV lookup, skip over the first two components (the service and
417 protocol names, which both start with an underscore). */
418
419 if (type == T_SRV)
420 {
421 while (*checkname++ != '.');
422 while (*checkname++ != '.');
423 }
424
425 if (pcre_exec(regex_check_dns_names, NULL, CS checkname, Ustrlen(checkname),
426 0, PCRE_EOPT, ovector, sizeof(ovector)/sizeof(int)) < 0)
427 {
428 DEBUG(D_dns)
429 debug_printf("DNS name syntax check failed: %s (%s)\n", name,
430 dns_text_type(type));
431 host_find_failed_syntax = TRUE;
432 return DNS_NOMATCH;
433 }
434 }
435
436#endif /* STAND_ALONE */
437
438/* Call the resolver; for an overlong response, res_search() will return the
439number of bytes the message would need, so we need to check for this case.
440The effect is to truncate overlong data. */
441
442dnsa->answerlen = res_search(CS name, C_IN, type, dnsa->answer, MAXPACKET);
443if (dnsa->answerlen > MAXPACKET) dnsa->answerlen = MAXPACKET;
444
445if (dnsa->answerlen < 0) switch (h_errno)
446 {
447 case HOST_NOT_FOUND:
448 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave HOST_NOT_FOUND\n"
449 "returning DNS_NOMATCH\n", name, dns_text_type(type));
450 return dns_return(name, type, DNS_NOMATCH);
451
452 case TRY_AGAIN:
453 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave TRY_AGAIN\n",
454 name, dns_text_type(type));
455
456 /* Cut this out for various test programs */
457 #ifndef STAND_ALONE
458 save = deliver_domain;
459 deliver_domain = name; /* set $domain */
460 rc = match_isinlist(name, &dns_again_means_nonexist, 0, NULL, NULL,
461 MCL_DOMAIN, TRUE, NULL);
462 deliver_domain = save;
463 if (rc != OK)
464 {
465 DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
466 return dns_return(name, type, DNS_AGAIN);
467 }
468 DEBUG(D_dns) debug_printf("%s is in dns_again_means_nonexist: returning "
469 "DNS_NOMATCH\n", name);
470 return dns_return(name, type, DNS_NOMATCH);
471
472 #else /* For stand-alone tests */
473 return dns_return(name, type, DNS_AGAIN);
474 #endif
475
476 case NO_RECOVERY:
477 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave NO_RECOVERY\n"
478 "returning DNS_FAIL\n", name, dns_text_type(type));
479 return dns_return(name, type, DNS_FAIL);
480
481 case NO_DATA:
482 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave NO_DATA\n"
483 "returning DNS_NODATA\n", name, dns_text_type(type));
484 return dns_return(name, type, DNS_NODATA);
485
486 default:
487 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave unknown DNS error %d\n"
488 "returning DNS_FAIL\n", name, dns_text_type(type), h_errno);
489 return dns_return(name, type, DNS_FAIL);
490 }
491
492DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) succeeded\n",
493 name, dns_text_type(type));
494
495return DNS_SUCCEED;
496}
497
498
499
500
501/************************************************
502* Do a DNS lookup and handle CNAMES *
503************************************************/
504
505/* Look up the given domain name, using the given type. Follow CNAMEs if
506necessary, but only so many times. There aren't supposed to be CNAME chains in
507the DNS, but you are supposed to cope with them if you find them.
508
509The assumption is made that if the resolver gives back records of the
510requested type *and* a CNAME, we don't need to make another call to look up
511the CNAME. I can't see how it could return only some of the right records. If
512it's done a CNAME lookup in the past, it will have all of them; if not, it
513won't return any.
514
515If fully_qualified_name is not NULL, set it to point to the full name
516returned by the resolver, if this is different to what it is given, unless
517the returned name starts with "*" as some nameservers seem to be returning
518wildcards in this form.
519
520Arguments:
521 dnsa pointer to dns_answer structure
522 name domain name to look up
523 type DNS record type (T_A, T_MX, etc)
524 fully_qualified_name if not NULL, return the returned name here if its
525 contents are different (i.e. it must be preset)
526
527Returns: DNS_SUCCEED successful lookup
528 DNS_NOMATCH name not found
529 DNS_NODATA no data found
530 DNS_AGAIN soft failure, try again later
531 DNS_FAIL DNS failure
532*/
533
534int
535dns_lookup(dns_answer *dnsa, uschar *name, int type, uschar **fully_qualified_name)
536{
537int i;
538uschar *orig_name = name;
539
540/* Loop to follow CNAME chains so far, but no further... */
541
542for (i = 0; i < 10; i++)
543 {
544 uschar data[256];
545 dns_record *rr, cname_rr, type_rr;
546 dns_scan dnss;
547 int datalen, rc;
548
549 /* DNS lookup failures get passed straight back. */
550
551 if ((rc = dns_basic_lookup(dnsa, name, type)) != DNS_SUCCEED) return rc;
552
553 /* We should have either records of the required type, or a CNAME record,
554 or both. We need to know whether both exist for getting the fully qualified
555 name, but avoid scanning more than necessary. Note that we must copy the
556 contents of any rr blocks returned by dns_next_rr() as they use the same
557 area in the dnsa block. */
558
559 cname_rr.data = type_rr.data = NULL;
560 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
561 rr != NULL;
562 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
563 {
564 if (rr->type == type)
565 {
566 if (type_rr.data == NULL) type_rr = *rr;
567 if (cname_rr.data != NULL) break;
568 }
569 else if (rr->type == T_CNAME) cname_rr = *rr;
570 }
571
572 /* If a CNAME was found, take the fully qualified name from it; otherwise
573 from the first data record, if present. For testing, there is a magic name
574 that gets its casing adjusted, because my resolver doesn't seem to pass back
575 upper case letters in domain names. */
576
577 if (fully_qualified_name != NULL)
578 {
579 if (cname_rr.data != NULL)
580 {
581 if (Ustrcmp(cname_rr.name, *fully_qualified_name) != 0 &&
582 cname_rr.name[0] != '*')
583 *fully_qualified_name = string_copy_dnsdomain(cname_rr.name);
584 }
585 else if (type_rr.data != NULL)
586 {
587 if (running_in_test_harness &&
588 Ustrcmp(type_rr.name, "uppercase.test.ex") == 0)
589 *fully_qualified_name = US"UpperCase.test.ex";
590 else
591 {
592 if (Ustrcmp(type_rr.name, *fully_qualified_name) != 0 &&
593 type_rr.name[0] != '*')
594 *fully_qualified_name = string_copy_dnsdomain(type_rr.name);
595 }
596 }
597 }
598
599 /* If any data records of the correct type were found, we are done. */
600
601 if (type_rr.data != NULL) return DNS_SUCCEED;
602
603 /* If there are no data records, we need to re-scan the DNS using the
604 domain given in the CNAME record, which should exist (otherwise we should
605 have had a failure from dns_lookup). However code against the possibility of
606 its not existing. */
607
608 if (cname_rr.data == NULL) return DNS_FAIL;
609 datalen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen,
610 cname_rr.data, (DN_EXPAND_ARG4_TYPE)data, 256);
611 if (datalen < 0) return DNS_FAIL;
612 name = data;
613 } /* Loop back to do another lookup */
614
615/*Control reaches here after 10 times round the CNAME loop. Something isn't
616right... */
617
618log_write(0, LOG_MAIN, "CNAME loop for %s encountered", orig_name);
619return DNS_FAIL;
620}
621
622
623
33397d19
PH
624
625
626
627/************************************************
628* Do a DNS lookup and handle virtual types *
629************************************************/
630
8e669ac1
PH
631/* This function handles some invented "lookup types" that synthesize feature
632not available in the basic types. The special types all have negative values.
33397d19
PH
633Positive type values are passed straight on to dns_lookup().
634
635Arguments:
636 dnsa pointer to dns_answer structure
637 name domain name to look up
638 type DNS record type (T_A, T_MX, etc or a "special")
639 fully_qualified_name if not NULL, return the returned name here if its
640 contents are different (i.e. it must be preset)
641
642Returns: DNS_SUCCEED successful lookup
643 DNS_NOMATCH name not found
644 DNS_NODATA no data found
645 DNS_AGAIN soft failure, try again later
646 DNS_FAIL DNS failure
647*/
648
649int
8e669ac1 650dns_special_lookup(dns_answer *dnsa, uschar *name, int type,
33397d19
PH
651 uschar **fully_qualified_name)
652{
653if (type >= 0) return dns_lookup(dnsa, name, type, fully_qualified_name);
654
ea3bc19b
PH
655/* The "mx hosts only" type doesn't require any special action here */
656
657if (type == T_MXH) return dns_lookup(dnsa, name, T_MX, fully_qualified_name);
658
8e669ac1 659/* Find nameservers for the domain or the nearest enclosing zone, excluding the
33397d19
PH
660root servers. */
661
662if (type == T_ZNS)
663 {
664 uschar *d = name;
665 while (d != 0)
666 {
667 int rc = dns_lookup(dnsa, d, T_NS, fully_qualified_name);
668 if (rc != DNS_NOMATCH && rc != DNS_NODATA) return rc;
669 while (*d != 0 && *d != '.') d++;
8e669ac1 670 if (*d++ == 0) break;
33397d19 671 }
8e669ac1
PH
672 return DNS_NOMATCH;
673 }
33397d19 674
e5a9dba6
PH
675/* Try to look up the Client SMTP Authorization SRV record for the name. If
676there isn't one, search from the top downwards for a CSA record in a parent
677domain, which might be making assertions about subdomains. If we find a record
678we set fully_qualified_name to whichever lookup succeeded, so that the caller
679can tell whether to look at the explicit authorization field or the subdomain
680assertion field. */
681
682if (type == T_CSA)
683 {
684 uschar *srvname, *namesuff, *tld, *p;
685 int priority, weight, port;
686 int limit, rc, i;
687 BOOL ipv6;
688 dns_record *rr;
689 dns_scan dnss;
690
691 DEBUG(D_dns) debug_printf("CSA lookup of %s\n", name);
692
693 srvname = string_sprintf("_client._smtp.%s", name);
694 rc = dns_lookup(dnsa, srvname, T_SRV, NULL);
695 if (rc == DNS_SUCCEED || rc == DNS_AGAIN)
696 {
697 if (rc == DNS_SUCCEED) *fully_qualified_name = name;
698 return rc;
699 }
700
701 /* Search for CSA subdomain assertion SRV records from the top downwards,
702 starting with the 2nd level domain. This order maximizes cache-friendliness.
703 We skip the top level domains to avoid loading their nameservers and because
704 we know they'll never have CSA SRV records. */
705
706 namesuff = Ustrrchr(name, '.');
707 if (namesuff == NULL) return DNS_NOMATCH;
708 tld = namesuff + 1;
709 ipv6 = FALSE;
710 limit = dns_csa_search_limit;
711
712 /* Use more appropriate search parameters if we are in the reverse DNS. */
713
714 if (strcmpic(namesuff, US".arpa") == 0)
715 {
716 if (namesuff - 8 > name && strcmpic(namesuff - 8, US".in-addr.arpa") == 0)
717 {
718 namesuff -= 8;
719 tld = namesuff + 1;
720 limit = 3;
721 }
722 else if (namesuff - 4 > name && strcmpic(namesuff - 4, US".ip6.arpa") == 0)
723 {
724 namesuff -= 4;
725 tld = namesuff + 1;
726 ipv6 = TRUE;
727 limit = 3;
728 }
729 }
730
731 DEBUG(D_dns) debug_printf("CSA TLD %s\n", tld);
732
733 /* Do not perform the search if the top level or 2nd level domains do not
734 exist. This is quite common, and when it occurs all the search queries would
735 go to the root or TLD name servers, which is not friendly. So we check the
736 AUTHORITY section; if it contains the root's SOA record or the TLD's SOA then
737 the TLD or the 2LD (respectively) doesn't exist and we can skip the search.
738 If the TLD and the 2LD exist but the explicit CSA record lookup failed, then
739 the AUTHORITY SOA will be the 2LD's or a subdomain thereof. */
740
741 if (rc == DNS_NOMATCH)
742 {
743 /* This is really gross. The successful return value from res_search() is
744 the packet length, which is stored in dnsa->answerlen. If we get a
745 negative DNS reply then res_search() returns -1, which causes the bounds
746 checks for name decompression to fail when it is treated as a packet
747 length, which in turn causes the authority search to fail. The correct
748 packet length has been lost inside libresolv, so we have to guess a
749 replacement value. (The only way to fix this properly would be to
750 re-implement res_search() and res_query() so that they don't muddle their
751 success and packet length return values.) For added safety we only reset
752 the packet length if the packet header looks plausible. */
753
754 HEADER *h = (HEADER *)dnsa->answer;
755 if (h->qr == 1 && h->opcode == QUERY && h->tc == 0
756 && (h->rcode == NOERROR || h->rcode == NXDOMAIN)
757 && ntohs(h->qdcount) == 1 && ntohs(h->ancount) == 0
758 && ntohs(h->nscount) >= 1)
759 dnsa->answerlen = MAXPACKET;
760
761 for (rr = dns_next_rr(dnsa, &dnss, RESET_AUTHORITY);
762 rr != NULL;
763 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
764 if (rr->type != T_SOA) continue;
765 else if (strcmpic(rr->name, US"") == 0 ||
766 strcmpic(rr->name, tld) == 0) return DNS_NOMATCH;
767 else break;
768 }
769
770 for (i = 0; i < limit; i++)
771 {
772 if (ipv6)
773 {
774 /* Scan through the IPv6 reverse DNS in chunks of 16 bits worth of IP
775 address, i.e. 4 hex chars and 4 dots, i.e. 8 chars. */
776 namesuff -= 8;
777 if (namesuff <= name) return DNS_NOMATCH;
778 }
779 else
780 /* Find the start of the preceding domain name label. */
781 do
782 if (--namesuff <= name) return DNS_NOMATCH;
783 while (*namesuff != '.');
784
785 DEBUG(D_dns) debug_printf("CSA parent search at %s\n", namesuff + 1);
786
787 srvname = string_sprintf("_client._smtp.%s", namesuff + 1);
788 rc = dns_lookup(dnsa, srvname, T_SRV, NULL);
789 if (rc == DNS_AGAIN) return rc;
790 if (rc != DNS_SUCCEED) continue;
791
792 /* Check that the SRV record we have found is worth returning. We don't
793 just return the first one we find, because some lower level SRV record
794 might make stricter assertions than its parent domain. */
795
796 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
797 rr != NULL;
798 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
799 {
800 if (rr->type != T_SRV) continue;
801
802 /* Extract the numerical SRV fields (p is incremented) */
803 p = rr->data;
804 GETSHORT(priority, p);
805 GETSHORT(weight, p);
806 GETSHORT(port, p);
807
808 /* Check the CSA version number */
809 if (priority != 1) continue;
810
811 /* If it's making an interesting assertion, return this response. */
812 if (port & 1)
813 {
814 *fully_qualified_name = namesuff + 1;
815 return DNS_SUCCEED;
816 }
817 }
818 }
819 return DNS_NOMATCH;
820 }
821
33397d19
PH
822/* Control should never reach here */
823
824return DNS_FAIL;
825}
826
827
828
059ec3d9
PH
829/* Support for A6 records has been commented out since they were demoted to
830experimental status at IETF 51. */
831
832#if HAVE_IPV6 && defined(SUPPORT_A6)
833
834/*************************************************
835* Search DNS block for prefix RRs *
836*************************************************/
837
838/* Called from dns_complete_a6() to search an additional section or a main
839answer section for required prefix records to complete an IPv6 address obtained
840from an A6 record. For each prefix record, a recursive call to dns_complete_a6
841is made, with a new copy of the address so far.
842
843Arguments:
844 dnsa the DNS answer block
845 which RESET_ADDITIONAL or RESET_ANSWERS
846 name name of prefix record
847 yptrptr pointer to the pointer that points to where to hang the next
848 dns_address structure
849 bits number of bits we have already got
850 bitvec the bits we have already got
851
852Returns: TRUE if any records were found
853*/
854
855static BOOL
856dns_find_prefix(dns_answer *dnsa, int which, uschar *name, dns_address
857 ***yptrptr, int bits, uschar *bitvec)
858{
859BOOL yield = FALSE;
860dns_record *rr;
861dns_scan dnss;
862
863for (rr = dns_next_rr(dnsa, &dnss, which);
864 rr != NULL;
865 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
866 {
867 uschar cbitvec[16];
868 if (rr->type != T_A6 || strcmpic(rr->name, name) != 0) continue;
869 yield = TRUE;
870 memcpy(cbitvec, bitvec, sizeof(cbitvec));
871 dns_complete_a6(yptrptr, dnsa, rr, bits, cbitvec);
872 }
873
874return yield;
875}
876
877
878
879/*************************************************
880* Follow chains of A6 records *
881*************************************************/
882
883/* A6 records may be incomplete, with pointers to other records containing more
884bits of the address. There can be a tree structure, leading to a number of
885addresses originating from a single initial A6 record.
886
887Arguments:
888 yptrptr pointer to the pointer that points to where to hang the next
889 dns_address structure
890 dnsa the current DNS answer block
891 rr the RR we have at present
892 bits number of bits we have already got
893 bitvec the bits we have already got
894
895Returns: nothing
896*/
897
898static void
899dns_complete_a6(dns_address ***yptrptr, dns_answer *dnsa, dns_record *rr,
900 int bits, uschar *bitvec)
901{
902static uschar bitmask[] = { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
903uschar *p = (uschar *)(rr->data);
904int prefix_len, suffix_len;
905int i, j, k;
906uschar *chainptr;
907uschar chain[264];
908dns_answer cdnsa;
909
910/* The prefix length is the first byte. It defines the prefix which is missing
911from the data in this record as a number of bits. Zero means this is the end of
912a chain. The suffix is the data in this record; only sufficient bytes to hold
913it are supplied. There may be zero bytes. We have to ignore trailing bits that
914we have already obtained from earlier RRs in the chain. */
915
916prefix_len = *p++; /* bits */
917suffix_len = (128 - prefix_len + 7)/8; /* bytes */
918
919/* If the prefix in this record is greater than the prefix in the previous
920record in the chain, we have to ignore the record (RFC 2874). */
921
922if (prefix_len > 128 - bits) return;
923
924/* In this little loop, the number of bits up to and including the current byte
925is held in k. If we have none of the bits in this byte, we can just or it into
926the current data. If we have all of the bits in this byte, we skip it.
927Otherwise, some masking has to be done. */
928
929for (i = suffix_len - 1, j = 15, k = 8; i >= 0; i--)
930 {
931 int required = k - bits;
932 if (required >= 8) bitvec[j] |= p[i];
933 else if (required > 0) bitvec[j] |= p[i] & bitmask[required];
934 j--; /* I tried putting these in the "for" statement, but gcc muttered */
935 k += 8; /* about computed values not being used. */
936 }
937
938/* If the prefix_length is zero, we are at the end of a chain. Build a
939dns_address item with the current data, hang it onto the end of the chain,
940adjust the hanging pointer, and we are done. */
941
942if (prefix_len == 0)
943 {
944 dns_address *new = store_get(sizeof(dns_address) + 50);
945 inet_ntop(AF_INET6, bitvec, CS new->address, 50);
946 new->next = NULL;
947 **yptrptr = new;
948 *yptrptr = &(new->next);
949 return;
950 }
951
952/* Prefix length is not zero. Reset the number of bits that we have collected
953so far, and extract the chain name. */
954
955bits = 128 - prefix_len;
956p += suffix_len;
957
958chainptr = chain;
959while ((i = *p++) != 0)
960 {
961 if (chainptr != chain) *chainptr++ = '.';
962 memcpy(chainptr, p, i);
963 chainptr += i;
964 p += i;
965 }
966*chainptr = 0;
967chainptr = chain;
968
969/* Now scan the current DNS response record to see if the additional section
970contains the records we want. This processing can be cut out for testing
971purposes. */
972
973if (dns_find_prefix(dnsa, RESET_ADDITIONAL, chainptr, yptrptr, bits, bitvec))
974 return;
975
976/* No chain records were found in the current DNS response block. Do a new DNS
977lookup to try to find these records. This opens up the possibility of DNS
978failures. We ignore them at this point; if all branches of the tree fail, there
979will be no addresses at the end. */
980
981if (dns_lookup(&cdnsa, chainptr, T_A6, NULL) == DNS_SUCCEED)
982 (void)dns_find_prefix(&cdnsa, RESET_ANSWERS, chainptr, yptrptr, bits, bitvec);
983}
984#endif /* HAVE_IPV6 && defined(SUPPORT_A6) */
985
986
987
988
989/*************************************************
990* Get address(es) from DNS record *
991*************************************************/
992
993/* The record type is either T_A for an IPv4 address or T_AAAA (or T_A6 when
994supported) for an IPv6 address. In the A6 case, there may be several addresses,
995generated by following chains. A recursive function does all the hard work. A6
996records now look like passing into history, so the code is only included when
997explicitly asked for.
998
999Argument:
1000 dnsa the DNS answer block
1001 rr the RR
1002
1003Returns: pointer a chain of dns_address items
1004*/
1005
1006dns_address *
1007dns_address_from_rr(dns_answer *dnsa, dns_record *rr)
1008{
1009dns_address *yield = NULL;
1010
1011#if HAVE_IPV6 && defined(SUPPORT_A6)
1012dns_address **yieldptr = &yield;
1013uschar bitvec[16];
1014#else
1015dnsa = dnsa; /* Stop picky compilers warning */
1016#endif
1017
1018if (rr->type == T_A)
1019 {
1020 uschar *p = (uschar *)(rr->data);
1021 yield = store_get(sizeof(dns_address) + 20);
1022 (void)sprintf(CS yield->address, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
1023 yield->next = NULL;
1024 }
1025
1026#if HAVE_IPV6
1027
1028#ifdef SUPPORT_A6
1029else if (rr->type == T_A6)
1030 {
1031 memset(bitvec, 0, sizeof(bitvec));
1032 dns_complete_a6(&yieldptr, dnsa, rr, 0, bitvec);
1033 }
1034#endif /* SUPPORT_A6 */
1035
1036else
1037 {
1038 yield = store_get(sizeof(dns_address) + 50);
1039 inet_ntop(AF_INET6, (uschar *)(rr->data), CS yield->address, 50);
1040 yield->next = NULL;
1041 }
1042#endif /* HAVE_IPV6 */
1043
1044return yield;
1045}
1046
1047/* End of dns.c */