Forgot T_SOA when adding the backup T_xxx definitions. Also, T_SOA was
[exim.git] / src / src / dns.c
1 /* $Cambridge: exim/src/src/dns.c,v 1.9 2005/06/29 10:56:35 ph10 Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2005 */
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
16 are supported. */
17
18 #if HAVE_IPV6
19 #ifdef SUPPORT_A6
20 static 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
32 the first time we have been here, and set the resolver options.
33
34 Arguments:
35   qualify_single    TRUE to set the RES_DEFNAMES option
36   search_parents    TRUE to set the RES_DNSRCH option
37
38 Returns:            nothing
39 */
40
41 void
42 dns_init(BOOL qualify_single, BOOL search_parents)
43 {
44 if ((_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);
54 if (dns_retrans > 0) _res.retrans = dns_retrans;
55 if (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
65 a name that can be used to look up PTR records.
66
67 Arguments:
68   string     the IP address as a string
69   buffer     a suitable buffer, long enough to hold the result
70
71 Returns:     nothing
72 */
73
74 void
75 dns_build_reverse(uschar *string, uschar *buffer)
76 {
77 uschar *p = string + Ustrlen(string);
78 uschar *pp = buffer;
79
80 /* Handle IPv4 address */
81
82 #if HAVE_IPV6
83 if (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
100 abbreviation in the textual form. */
101
102 #if HAVE_IPV6
103 else
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 ==
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.
159
160 Arguments:
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
165 Returns:    next dns record, or NULL when no more
166 */
167
168 dns_record *
169 dns_next_rr(dns_answer *dnsa, dns_scan *dnss, int reset)
170 {
171 HEADER *h = (HEADER *)dnsa->answer;
172 int namelen;
173
174 /* Reset the saved data when requested to, and skip to the first required RR */
175
176 if (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
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
197   records. */
198
199   if (reset == RESET_ADDITIONAL) dnss->rrcount += ntohs(h->nscount);
200
201   if (reset == RESET_AUTHORITY || reset == RESET_ADDITIONAL)
202     {
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       }
212     dnss->rrcount = (reset == RESET_AUTHORITY)
213       ? ntohs(h->nscount) : ntohs(h->arcount);
214     }
215   }
216
217 /* The variable dnss->aptr is now pointing at the next RR, and dnss->rrcount
218 contains the number of RR records left. */
219
220 if (dnss->rrcount-- <= 0) return NULL;
221
222 /* If expanding the RR domain name fails, behave as if no more records
223 (something safe). */
224
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; }
228
229 /* Move the pointer past the name and fill in the rest of the data structure
230 from the following bytes. */
231
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 */
238
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. */
241
242 return &(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. All those that Exim
253 uses should be included here.
254
255 Argument:   record type
256 Returns:    pointer to string
257 */
258
259 uschar *
260 dns_text_type(int t)
261 {
262 switch(t)
263   {
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"?";
275   }
276 }
277
278
279
280 /*************************************************
281 *        Cache a failed DNS lookup result        *
282 *************************************************/
283
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
287 caching.
288
289 Arguments:
290   name       the domain name
291   type       the lookup type
292   rc         the return code
293
294 Returns:     the return code
295 */
296
297 static int
298 dns_return(uschar *name, int type, int rc)
299 {
300 tree_node *node = store_get_perm(sizeof(tree_node) + 290);
301 sprintf(CS node->name, "%.255s-%s-%lx", name, dns_text_type(type),
302   _res.options);
303 node->data.val = rc;
304 (void)tree_insertnode(&tree_dns_fails, node);
305 return rc;
306 }
307
308
309
310 /*************************************************
311 *              Do basic DNS lookup               *
312 *************************************************/
313
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
319 host.
320
321 Arguments:
322   dnsa      pointer to dns_answer structure
323   name      name to look up
324   type      type of DNS record required (T_A, T_MX, etc)
325
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
331             DNS_FAIL      DNS failure
332 */
333
334 int
335 dns_basic_lookup(dns_answer *dnsa, uschar *name, int type)
336 {
337 #ifndef STAND_ALONE
338 int rc;
339 uschar *save;
340 #endif
341
342 tree_node *previous;
343 uschar node_name[290];
344
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. */
349
350 sprintf(CS node_name, "%.255s-%s-%lx", name, dns_text_type(type),
351   _res.options);
352 previous = tree_search(tree_dns_fails, node_name);
353 if (previous != NULL)
354   {
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;
362   }
363
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. */
367
368 if (running_in_test_harness)
369   {
370   uschar *endname = name + Ustrlen(name);
371   if (Ustrcmp(endname - 14, "test.again.dns") == 0)
372     {
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));
376     if (delay > 0)
377       {
378       DEBUG(D_dns) debug_printf("delaying %d seconds\n", delay);
379       sleep(delay);
380       }
381     DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
382     return dns_return(name, type, DNS_AGAIN);
383     }
384   if (Ustrcmp(endname - 13, "test.fail.dns") == 0)
385     {
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);
390     }
391   }
392
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.
399
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
403 more.)
404
405 For SRV records, we omit the initial _smtp._tcp. components at the start. */
406
407 #ifndef STAND_ALONE   /* Omit this for stand-alone tests */
408
409 if (check_dns_names_pattern[0] != 0 && type != T_PTR)
410   {
411   uschar *checkname = name;
412   int ovector[3*(EXPAND_MAXN+1)];
413
414   if (regex_check_dns_names == NULL)
415     regex_check_dns_names =
416       regex_must_compile(check_dns_names_pattern, FALSE, TRUE);
417
418   /* For an SRV lookup, skip over the first two components (the service and
419   protocol names, which both start with an underscore). */
420
421   if (type == T_SRV)
422     {
423     while (*checkname++ != '.');
424     while (*checkname++ != '.');
425     }
426
427   if (pcre_exec(regex_check_dns_names, NULL, CS checkname, Ustrlen(checkname),
428       0, PCRE_EOPT, ovector, sizeof(ovector)/sizeof(int)) < 0)
429     {
430     DEBUG(D_dns)
431       debug_printf("DNS name syntax check failed: %s (%s)\n", name,
432         dns_text_type(type));
433     host_find_failed_syntax = TRUE;
434     return DNS_NOMATCH;
435     }
436   }
437
438 #endif /* STAND_ALONE */
439
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. */
443
444 dnsa->answerlen = res_search(CS name, C_IN, type, dnsa->answer, MAXPACKET);
445 if (dnsa->answerlen > MAXPACKET) dnsa->answerlen = MAXPACKET;
446
447 if (dnsa->answerlen < 0) switch (h_errno)
448   {
449   case HOST_NOT_FOUND:
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);
453
454   case TRY_AGAIN:
455   DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave TRY_AGAIN\n",
456     name, dns_text_type(type));
457
458   /* Cut this out for various test programs */
459   #ifndef STAND_ALONE
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;
465   if (rc != OK)
466     {
467     DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
468     return dns_return(name, type, DNS_AGAIN);
469     }
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);
473
474   #else   /* For stand-alone tests */
475   return dns_return(name, type, DNS_AGAIN);
476   #endif
477
478   case NO_RECOVERY:
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);
482
483   case NO_DATA:
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);
487
488   default:
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);
492   }
493
494 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) succeeded\n",
495   name, dns_text_type(type));
496
497 return DNS_SUCCEED;
498 }
499
500
501
502
503 /************************************************
504 *        Do a DNS lookup and handle CNAMES      *
505 ************************************************/
506
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.
510
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
515 won't return any.
516
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.
521
522 Arguments:
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)
528
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
533                         DNS_FAIL      DNS failure
534 */
535
536 int
537 dns_lookup(dns_answer *dnsa, uschar *name, int type, uschar **fully_qualified_name)
538 {
539 int i;
540 uschar *orig_name = name;
541
542 /* Loop to follow CNAME chains so far, but no further... */
543
544 for (i = 0; i < 10; i++)
545   {
546   uschar data[256];
547   dns_record *rr, cname_rr, type_rr;
548   dns_scan dnss;
549   int datalen, rc;
550
551   /* DNS lookup failures get passed straight back. */
552
553   if ((rc = dns_basic_lookup(dnsa, name, type)) != DNS_SUCCEED) return rc;
554
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. */
560
561   cname_rr.data = type_rr.data = NULL;
562   for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
563        rr != NULL;
564        rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
565     {
566     if (rr->type == type)
567       {
568       if (type_rr.data == NULL) type_rr = *rr;
569       if (cname_rr.data != NULL) break;
570       }
571     else if (rr->type == T_CNAME) cname_rr = *rr;
572     }
573
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. */
578
579   if (fully_qualified_name != NULL)
580     {
581     if (cname_rr.data != NULL)
582       {
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);
586       }
587     else if (type_rr.data != NULL)
588       {
589       if (running_in_test_harness &&
590           Ustrcmp(type_rr.name, "uppercase.test.ex") == 0)
591         *fully_qualified_name = US"UpperCase.test.ex";
592       else
593         {
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);
597         }
598       }
599     }
600
601   /* If any data records of the correct type were found, we are done. */
602
603   if (type_rr.data != NULL) return DNS_SUCCEED;
604
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
608   its not existing. */
609
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;
614   name = data;
615   }       /* Loop back to do another lookup */
616
617 /*Control reaches here after 10 times round the CNAME loop. Something isn't
618 right... */
619
620 log_write(0, LOG_MAIN, "CNAME loop for %s encountered", orig_name);
621 return DNS_FAIL;
622 }
623
624
625
626
627
628
629 /************************************************
630 *    Do a DNS lookup and handle virtual types   *
631 ************************************************/
632
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().
636
637 Arguments:
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)
643
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
648                         DNS_FAIL      DNS failure
649 */
650
651 int
652 dns_special_lookup(dns_answer *dnsa, uschar *name, int type,
653   uschar **fully_qualified_name)
654 {
655 if (type >= 0) return dns_lookup(dnsa, name, type, fully_qualified_name);
656
657 /* The "mx hosts only" type doesn't require any special action here */
658
659 if (type == T_MXH) return dns_lookup(dnsa, name, T_MX, fully_qualified_name);
660
661 /* Find nameservers for the domain or the nearest enclosing zone, excluding the
662 root servers. */
663
664 if (type == T_ZNS)
665   {
666   uschar *d = name;
667   while (d != 0)
668     {
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;
673     }
674   return DNS_NOMATCH;
675   }
676
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
682 assertion field. */
683
684 if (type == T_CSA)
685   {
686   uschar *srvname, *namesuff, *tld, *p;
687   int priority, weight, port;
688   int limit, rc, i;
689   BOOL ipv6;
690   dns_record *rr;
691   dns_scan dnss;
692
693   DEBUG(D_dns) debug_printf("CSA lookup of %s\n", name);
694
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)
698     {
699     if (rc == DNS_SUCCEED) *fully_qualified_name = name;
700     return rc;
701     }
702
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. */
707
708   namesuff = Ustrrchr(name, '.');
709   if (namesuff == NULL) return DNS_NOMATCH;
710   tld = namesuff + 1;
711   ipv6 = FALSE;
712   limit = dns_csa_search_limit;
713
714   /* Use more appropriate search parameters if we are in the reverse DNS. */
715
716   if (strcmpic(namesuff, US".arpa") == 0)
717     {
718     if (namesuff - 8 > name && strcmpic(namesuff - 8, US".in-addr.arpa") == 0)
719       {
720       namesuff -= 8;
721       tld = namesuff + 1;
722       limit = 3;
723       }
724     else if (namesuff - 4 > name && strcmpic(namesuff - 4, US".ip6.arpa") == 0)
725       {
726       namesuff -= 4;
727       tld = namesuff + 1;
728       ipv6 = TRUE;
729       limit = 3;
730       }
731     }
732
733   DEBUG(D_dns) debug_printf("CSA TLD %s\n", tld);
734
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. */
742
743   if (rc == DNS_NOMATCH)
744     {
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. */
755
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;
762
763     for (rr = dns_next_rr(dnsa, &dnss, RESET_AUTHORITY);
764          rr != NULL;
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;
769       else break;
770     }
771
772   for (i = 0; i < limit; i++)
773     {
774     if (ipv6)
775       {
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. */
778       namesuff -= 8;
779       if (namesuff <= name) return DNS_NOMATCH;
780       }
781     else
782       /* Find the start of the preceding domain name label. */
783       do
784         if (--namesuff <= name) return DNS_NOMATCH;
785       while (*namesuff != '.');
786
787     DEBUG(D_dns) debug_printf("CSA parent search at %s\n", namesuff + 1);
788
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;
793
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. */
797
798     for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
799          rr != NULL;
800          rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
801       {
802       if (rr->type != T_SRV) continue;
803
804       /* Extract the numerical SRV fields (p is incremented) */
805       p = rr->data;
806       GETSHORT(priority, p);
807       GETSHORT(weight, p);
808       GETSHORT(port, p);
809
810       /* Check the CSA version number */
811       if (priority != 1) continue;
812
813       /* If it's making an interesting assertion, return this response. */
814       if (port & 1)
815         {
816         *fully_qualified_name = namesuff + 1;
817         return DNS_SUCCEED;
818         }
819       }
820     }
821   return DNS_NOMATCH;
822   }
823
824 /* Control should never reach here */
825
826 return DNS_FAIL;
827 }
828
829
830
831 /* Support for A6 records has been commented out since they were demoted to
832 experimental status at IETF 51. */
833
834 #if HAVE_IPV6 && defined(SUPPORT_A6)
835
836 /*************************************************
837 *        Search DNS block for prefix RRs         *
838 *************************************************/
839
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.
844
845 Arguments:
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
853
854 Returns:     TRUE if any records were found
855 */
856
857 static BOOL
858 dns_find_prefix(dns_answer *dnsa, int which, uschar *name, dns_address
859   ***yptrptr, int bits, uschar *bitvec)
860 {
861 BOOL yield = FALSE;
862 dns_record *rr;
863 dns_scan dnss;
864
865 for (rr = dns_next_rr(dnsa, &dnss, which);
866      rr != NULL;
867      rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
868   {
869   uschar cbitvec[16];
870   if (rr->type != T_A6 || strcmpic(rr->name, name) != 0) continue;
871   yield = TRUE;
872   memcpy(cbitvec, bitvec, sizeof(cbitvec));
873   dns_complete_a6(yptrptr, dnsa, rr, bits, cbitvec);
874   }
875
876 return yield;
877 }
878
879
880
881 /*************************************************
882 *            Follow chains of A6 records         *
883 *************************************************/
884
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.
888
889 Arguments:
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
896
897 Returns:     nothing
898 */
899
900 static void
901 dns_complete_a6(dns_address ***yptrptr, dns_answer *dnsa, dns_record *rr,
902   int bits, uschar *bitvec)
903 {
904 static uschar bitmask[] = { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
905 uschar *p = (uschar *)(rr->data);
906 int prefix_len, suffix_len;
907 int i, j, k;
908 uschar *chainptr;
909 uschar chain[264];
910 dns_answer cdnsa;
911
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. */
917
918 prefix_len = *p++;                      /* bits */
919 suffix_len = (128 - prefix_len + 7)/8;  /* bytes */
920
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). */
923
924 if (prefix_len > 128 - bits) return;
925
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. */
930
931 for (i = suffix_len - 1, j = 15, k = 8; i >= 0; i--)
932   {
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. */
938   }
939
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. */
943
944 if (prefix_len == 0)
945   {
946   dns_address *new = store_get(sizeof(dns_address) + 50);
947   inet_ntop(AF_INET6, bitvec, CS new->address, 50);
948   new->next = NULL;
949   **yptrptr = new;
950   *yptrptr = &(new->next);
951   return;
952   }
953
954 /* Prefix length is not zero. Reset the number of bits that we have collected
955 so far, and extract the chain name. */
956
957 bits = 128 - prefix_len;
958 p += suffix_len;
959
960 chainptr = chain;
961 while ((i = *p++) != 0)
962   {
963   if (chainptr != chain) *chainptr++ = '.';
964   memcpy(chainptr, p, i);
965   chainptr += i;
966   p += i;
967   }
968 *chainptr = 0;
969 chainptr = chain;
970
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
973 purposes. */
974
975 if (dns_find_prefix(dnsa, RESET_ADDITIONAL, chainptr, yptrptr, bits, bitvec))
976   return;
977
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. */
982
983 if (dns_lookup(&cdnsa, chainptr, T_A6, NULL) == DNS_SUCCEED)
984   (void)dns_find_prefix(&cdnsa, RESET_ANSWERS, chainptr, yptrptr, bits, bitvec);
985 }
986 #endif  /* HAVE_IPV6 && defined(SUPPORT_A6) */
987
988
989
990
991 /*************************************************
992 *          Get address(es) from DNS record       *
993 *************************************************/
994
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.
1000
1001 Argument:
1002   dnsa       the DNS answer block
1003   rr         the RR
1004
1005 Returns:     pointer a chain of dns_address items
1006 */
1007
1008 dns_address *
1009 dns_address_from_rr(dns_answer *dnsa, dns_record *rr)
1010 {
1011 dns_address *yield = NULL;
1012
1013 #if HAVE_IPV6 && defined(SUPPORT_A6)
1014 dns_address **yieldptr = &yield;
1015 uschar bitvec[16];
1016 #else
1017 dnsa = dnsa;    /* Stop picky compilers warning */
1018 #endif
1019
1020 if (rr->type == T_A)
1021   {
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]);
1025   yield->next = NULL;
1026   }
1027
1028 #if HAVE_IPV6
1029
1030 #ifdef SUPPORT_A6
1031 else if (rr->type == T_A6)
1032   {
1033   memset(bitvec, 0, sizeof(bitvec));
1034   dns_complete_a6(&yieldptr, dnsa, rr, 0, bitvec);
1035   }
1036 #endif  /* SUPPORT_A6 */
1037
1038 else
1039   {
1040   yield = store_get(sizeof(dns_address) + 50);
1041   inet_ntop(AF_INET6, (uschar *)(rr->data), CS yield->address, 50);
1042   yield->next = NULL;
1043   }
1044 #endif  /* HAVE_IPV6 */
1045
1046 return yield;
1047 }
1048
1049 /* End of dns.c */