Implement the pseudo dns lookup type "zns" for ${dnsdb lookups.
[exim.git] / src / src / dns.c
1 /* $Cambridge: exim/src/src/dns.c,v 1.2 2004/11/19 09:45:54 ph10 Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2004 */
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_ADDITIONAL to scan the additional records, and reset == RESET_NEXT to
157 get the next record. The result is in static storage which must be copied if
158 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 and NS records if wanting to look at the additional
196   records. */
197
198   if (reset == RESET_ADDITIONAL)
199     {
200     dnss->rrcount += ntohs(h->nscount);
201     while (dnss->rrcount-- > 0)
202       {
203       namelen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen,
204         dnss->aptr, (DN_EXPAND_ARG4_TYPE) &(dnss->srr.name), DNS_MAXNAME);
205       if (namelen < 0) { dnss->rrcount = 0; return NULL; }
206       dnss->aptr += namelen + 8;            /* skip name, type, class & TTL */
207       GETSHORT(dnss->srr.size, dnss->aptr); /* size of data portion */
208       dnss->aptr += dnss->srr.size;         /* skip over it */
209       }
210     dnss->rrcount = ntohs(h->arcount);
211     }
212   }
213
214
215 /* The variable dnss->aptr is now pointing at the next RR, and dnss->rrcount
216 contains the number of RR records left. */
217
218 if (dnss->rrcount-- <= 0) return NULL;
219
220 /* If expanding the RR domain name fails, behave as if no more records
221 (something safe). */
222
223 namelen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, dnss->aptr,
224   (DN_EXPAND_ARG4_TYPE) &(dnss->srr.name), DNS_MAXNAME);
225 if (namelen < 0) { dnss->rrcount = 0; return NULL; }
226
227 /* Move the pointer past the name and fill in the rest of the data structure
228 from the following bytes. */
229
230 dnss->aptr += namelen;
231 GETSHORT(dnss->srr.type, dnss->aptr); /* Record type */
232 dnss->aptr += 6;                      /* Don't want class or TTL */
233 GETSHORT(dnss->srr.size, dnss->aptr); /* Size of data portion */
234 dnss->srr.data = dnss->aptr;          /* The record's data follows */
235 dnss->aptr += dnss->srr.size;         /* Advance to next RR */
236
237 /* Return a pointer to the dns_record structure within the dns_answer. This is
238 for convenience so that the scans can use nice-looking for loops. */
239
240 return &(dnss->srr);
241 }
242
243
244
245
246 /*************************************************
247 *            Turn DNS type into text             *
248 *************************************************/
249
250 /* Turn the coded record type into a string for printing.
251
252 Argument:   record type
253 Returns:    pointer to string
254 */
255
256 uschar *
257 dns_text_type(int t)
258 {
259 switch(t)
260   {
261   case T_A:     return US"A";
262   case T_MX:    return US"MX";
263   case T_AAAA:  return US"AAAA";
264   case T_A6:    return US"A6";
265   case T_TXT:   return US"TXT";
266   case T_PTR:   return US"PTR";
267   case T_SRV:   return US"SRV";
268   case T_NS:    return US"NS";
269   case T_CNAME: return US"CNAME";  
270   default:      return US"?";
271   }
272 }
273
274
275
276 /*************************************************
277 *        Cache a failed DNS lookup result        *
278 *************************************************/
279
280 /* We cache failed lookup results so as not to experience timeouts many
281 times for the same domain. We need to retain the resolver options because they
282 may change. For successful lookups, we rely on resolver and/or name server
283 caching.
284
285 Arguments:
286   name       the domain name
287   type       the lookup type
288   rc         the return code
289
290 Returns:     the return code
291 */
292
293 static int
294 dns_return(uschar *name, int type, int rc)
295 {
296 tree_node *node = store_get_perm(sizeof(tree_node) + 290);
297 sprintf(CS node->name, "%.255s-%s-%lx", name, dns_text_type(type),
298   _res.options);
299 node->data.val = rc;
300 (void)tree_insertnode(&tree_dns_fails, node);
301 return rc;
302 }
303
304
305
306 /*************************************************
307 *              Do basic DNS lookup               *
308 *************************************************/
309
310 /* Call the resolver to look up the given domain name, using the given type,
311 and check the result. The error code TRY_AGAIN is documented as meaning "non-
312 Authoritive Host not found, or SERVERFAIL". Sometimes there are badly set
313 up nameservers that produce this error continually, so there is the option of
314 providing a list of domains for which this is treated as a non-existent
315 host.
316
317 Arguments:
318   dnsa      pointer to dns_answer structure
319   name      name to look up
320   type      type of DNS record required (T_A, T_MX, etc)
321
322 Returns:    DNS_SUCCEED   successful lookup
323             DNS_NOMATCH   name not found (NXDOMAIN)
324                           or name contains illegal characters (if checking)
325             DNS_NODATA    domain exists, but no data for this type (NODATA)
326             DNS_AGAIN     soft failure, try again later
327             DNS_FAIL      DNS failure
328 */
329
330 int
331 dns_basic_lookup(dns_answer *dnsa, uschar *name, int type)
332 {
333 #ifndef STAND_ALONE
334 int rc;
335 uschar *save;
336 #endif
337
338 tree_node *previous;
339 uschar node_name[290];
340
341 /* DNS lookup failures of any kind are cached in a tree. This is mainly so that
342 a timeout on one domain doesn't happen time and time again for messages that
343 have many addresses in the same domain. We rely on the resolver and name server
344 caching for successful lookups. */
345
346 sprintf(CS node_name, "%.255s-%s-%lx", name, dns_text_type(type),
347   _res.options);
348 previous = tree_search(tree_dns_fails, node_name);
349 if (previous != NULL)
350   {
351   DEBUG(D_dns) debug_printf("DNS lookup of %.255s-%s: using cached value %s\n",
352     name, dns_text_type(type),
353       (previous->data.val == DNS_NOMATCH)? "DNS_NOMATCH" :
354       (previous->data.val == DNS_NODATA)? "DNS_NODATA" :
355       (previous->data.val == DNS_AGAIN)? "DNS_AGAIN" :
356       (previous->data.val == DNS_FAIL)? "DNS_FAIL" : "??");
357   return previous->data.val;
358   }
359
360 /* If we are running in the test harness, recognize a couple of special
361 names that always give error returns. This makes it straightforward to
362 test the handling of DNS errors. */
363
364 if (running_in_test_harness)
365   {
366   uschar *endname = name + Ustrlen(name);
367   if (Ustrcmp(endname - 14, "test.again.dns") == 0)
368     {
369     int delay = Uatoi(name);  /* digits at the start of the name */
370     DEBUG(D_dns) debug_printf("Real DNS lookup of %s (%s) bypassed for testing\n",
371       name, dns_text_type(type));
372     if (delay > 0)
373       {
374       DEBUG(D_dns) debug_printf("delaying %d seconds\n", delay);
375       sleep(delay);
376       }
377     DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
378     return dns_return(name, type, DNS_AGAIN);
379     }
380   if (Ustrcmp(endname - 13, "test.fail.dns") == 0)
381     {
382     DEBUG(D_dns) debug_printf("Real DNS lookup of %s (%s) bypassed for testing\n",
383       name, dns_text_type(type));
384     DEBUG(D_dns) debug_printf("returning DNS_FAIL\n");
385     return dns_return(name, type, DNS_FAIL);
386     }
387   }
388
389 /* If configured, check the hygene of the name passed to lookup. Otherwise,
390 although DNS lookups may give REFUSED at the lower level, some resolvers
391 turn this into TRY_AGAIN, which is silly. Give a NOMATCH return, since such
392 domains cannot be in the DNS. The check is now done by a regular expression;
393 give it space for substring storage to save it having to get its own if the
394 regex has substrings that are used - the default uses a conditional.
395
396 This test is omitted for PTR records. These occur only in calls from the dnsdb
397 lookup, which constructs the names itself, so they should be OK. Besides,
398 bitstring labels don't conform to normal name syntax. (But the aren't used any
399 more.)
400
401 For SRV records, we omit the initial _smtp._tcp. components at the start. */
402
403 #ifndef STAND_ALONE   /* Omit this for stand-alone tests */
404
405 if (check_dns_names_pattern[0] != 0 && type != T_PTR)
406   {
407   uschar *checkname = name;
408   int ovector[3*(EXPAND_MAXN+1)];
409
410   if (regex_check_dns_names == NULL)
411     regex_check_dns_names =
412       regex_must_compile(check_dns_names_pattern, FALSE, TRUE);
413
414   /* For an SRV lookup, skip over the first two components (the service and
415   protocol names, which both start with an underscore). */
416
417   if (type == T_SRV)
418     {
419     while (*checkname++ != '.');
420     while (*checkname++ != '.');
421     }
422
423   if (pcre_exec(regex_check_dns_names, NULL, CS checkname, Ustrlen(checkname),
424       0, PCRE_EOPT, ovector, sizeof(ovector)/sizeof(int)) < 0)
425     {
426     DEBUG(D_dns)
427       debug_printf("DNS name syntax check failed: %s (%s)\n", name,
428         dns_text_type(type));
429     host_find_failed_syntax = TRUE;
430     return DNS_NOMATCH;
431     }
432   }
433
434 #endif /* STAND_ALONE */
435
436 /* Call the resolver; for an overlong response, res_search() will return the
437 number of bytes the message would need, so we need to check for this case.
438 The effect is to truncate overlong data. */
439
440 dnsa->answerlen = res_search(CS name, C_IN, type, dnsa->answer, MAXPACKET);
441 if (dnsa->answerlen > MAXPACKET) dnsa->answerlen = MAXPACKET;
442
443 if (dnsa->answerlen < 0) switch (h_errno)
444   {
445   case HOST_NOT_FOUND:
446   DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave HOST_NOT_FOUND\n"
447     "returning DNS_NOMATCH\n", name, dns_text_type(type));
448   return dns_return(name, type, DNS_NOMATCH);
449
450   case TRY_AGAIN:
451   DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave TRY_AGAIN\n",
452     name, dns_text_type(type));
453
454   /* Cut this out for various test programs */
455   #ifndef STAND_ALONE
456   save = deliver_domain;
457   deliver_domain = name;  /* set $domain */
458   rc = match_isinlist(name, &dns_again_means_nonexist, 0, NULL, NULL,
459     MCL_DOMAIN, TRUE, NULL);
460   deliver_domain = save;
461   if (rc != OK)
462     {
463     DEBUG(D_dns) debug_printf("returning DNS_AGAIN\n");
464     return dns_return(name, type, DNS_AGAIN);
465     }
466   DEBUG(D_dns) debug_printf("%s is in dns_again_means_nonexist: returning "
467     "DNS_NOMATCH\n", name);
468   return dns_return(name, type, DNS_NOMATCH);
469
470   #else   /* For stand-alone tests */
471   return dns_return(name, type, DNS_AGAIN);
472   #endif
473
474   case NO_RECOVERY:
475   DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave NO_RECOVERY\n"
476     "returning DNS_FAIL\n", name, dns_text_type(type));
477   return dns_return(name, type, DNS_FAIL);
478
479   case NO_DATA:
480   DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave NO_DATA\n"
481     "returning DNS_NODATA\n", name, dns_text_type(type));
482   return dns_return(name, type, DNS_NODATA);
483
484   default:
485   DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) gave unknown DNS error %d\n"
486     "returning DNS_FAIL\n", name, dns_text_type(type), h_errno);
487   return dns_return(name, type, DNS_FAIL);
488   }
489
490 DEBUG(D_dns) debug_printf("DNS lookup of %s (%s) succeeded\n",
491   name, dns_text_type(type));
492
493 return DNS_SUCCEED;
494 }
495
496
497
498
499 /************************************************
500 *        Do a DNS lookup and handle CNAMES      *
501 ************************************************/
502
503 /* Look up the given domain name, using the given type. Follow CNAMEs if
504 necessary, but only so many times. There aren't supposed to be CNAME chains in
505 the DNS, but you are supposed to cope with them if you find them.
506
507 The assumption is made that if the resolver gives back records of the
508 requested type *and* a CNAME, we don't need to make another call to look up
509 the CNAME. I can't see how it could return only some of the right records. If
510 it's done a CNAME lookup in the past, it will have all of them; if not, it
511 won't return any.
512
513 If fully_qualified_name is not NULL, set it to point to the full name
514 returned by the resolver, if this is different to what it is given, unless
515 the returned name starts with "*" as some nameservers seem to be returning
516 wildcards in this form.
517
518 Arguments:
519   dnsa                  pointer to dns_answer structure
520   name                  domain name to look up
521   type                  DNS record type (T_A, T_MX, etc)
522   fully_qualified_name  if not NULL, return the returned name here if its
523                           contents are different (i.e. it must be preset)
524
525 Returns:                DNS_SUCCEED   successful lookup
526                         DNS_NOMATCH   name not found
527                         DNS_NODATA    no data found
528                         DNS_AGAIN     soft failure, try again later
529                         DNS_FAIL      DNS failure
530 */
531
532 int
533 dns_lookup(dns_answer *dnsa, uschar *name, int type, uschar **fully_qualified_name)
534 {
535 int i;
536 uschar *orig_name = name;
537
538 /* Loop to follow CNAME chains so far, but no further... */
539
540 for (i = 0; i < 10; i++)
541   {
542   uschar data[256];
543   dns_record *rr, cname_rr, type_rr;
544   dns_scan dnss;
545   int datalen, rc;
546
547   /* DNS lookup failures get passed straight back. */
548
549   if ((rc = dns_basic_lookup(dnsa, name, type)) != DNS_SUCCEED) return rc;
550
551   /* We should have either records of the required type, or a CNAME record,
552   or both. We need to know whether both exist for getting the fully qualified
553   name, but avoid scanning more than necessary. Note that we must copy the
554   contents of any rr blocks returned by dns_next_rr() as they use the same
555   area in the dnsa block. */
556
557   cname_rr.data = type_rr.data = NULL;
558   for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
559        rr != NULL;
560        rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
561     {
562     if (rr->type == type)
563       {
564       if (type_rr.data == NULL) type_rr = *rr;
565       if (cname_rr.data != NULL) break;
566       }
567     else if (rr->type == T_CNAME) cname_rr = *rr;
568     }
569
570   /* If a CNAME was found, take the fully qualified name from it; otherwise
571   from the first data record, if present. For testing, there is a magic name
572   that gets its casing adjusted, because my resolver doesn't seem to pass back
573   upper case letters in domain names. */
574
575   if (fully_qualified_name != NULL)
576     {
577     if (cname_rr.data != NULL)
578       {
579       if (Ustrcmp(cname_rr.name, *fully_qualified_name) != 0 &&
580           cname_rr.name[0] != '*')
581         *fully_qualified_name = string_copy_dnsdomain(cname_rr.name);
582       }
583     else if (type_rr.data != NULL)
584       {
585       if (running_in_test_harness &&
586           Ustrcmp(type_rr.name, "uppercase.test.ex") == 0)
587         *fully_qualified_name = US"UpperCase.test.ex";
588       else
589         {
590         if (Ustrcmp(type_rr.name, *fully_qualified_name) != 0 &&
591             type_rr.name[0] != '*')
592           *fully_qualified_name = string_copy_dnsdomain(type_rr.name);
593         }
594       }
595     }
596
597   /* If any data records of the correct type were found, we are done. */
598
599   if (type_rr.data != NULL) return DNS_SUCCEED;
600
601   /* If there are no data records, we need to re-scan the DNS using the
602   domain given in the CNAME record, which should exist (otherwise we should
603   have had a failure from dns_lookup). However code against the possibility of
604   its not existing. */
605
606   if (cname_rr.data == NULL) return DNS_FAIL;
607   datalen = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen,
608     cname_rr.data, (DN_EXPAND_ARG4_TYPE)data, 256);
609   if (datalen < 0) return DNS_FAIL;
610   name = data;
611   }       /* Loop back to do another lookup */
612
613 /*Control reaches here after 10 times round the CNAME loop. Something isn't
614 right... */
615
616 log_write(0, LOG_MAIN, "CNAME loop for %s encountered", orig_name);
617 return DNS_FAIL;
618 }
619
620
621
622
623
624
625 /************************************************
626 *    Do a DNS lookup and handle virtual types   *
627 ************************************************/
628
629 /* This function handles some invented "lookup types" that synthesize feature 
630 not available in the basic types. The special types all have negative values. 
631 Positive type values are passed straight on to dns_lookup().
632
633 Arguments:
634   dnsa                  pointer to dns_answer structure
635   name                  domain name to look up
636   type                  DNS record type (T_A, T_MX, etc or a "special")
637   fully_qualified_name  if not NULL, return the returned name here if its
638                           contents are different (i.e. it must be preset)
639
640 Returns:                DNS_SUCCEED   successful lookup
641                         DNS_NOMATCH   name not found
642                         DNS_NODATA    no data found
643                         DNS_AGAIN     soft failure, try again later
644                         DNS_FAIL      DNS failure
645 */
646
647 int
648 dns_special_lookup(dns_answer *dnsa, uschar *name, int type, 
649   uschar **fully_qualified_name)
650 {
651 if (type >= 0) return dns_lookup(dnsa, name, type, fully_qualified_name);
652
653 /* Find nameservers for the domain or the nearest enclosing zone, excluding the 
654 root servers. */
655
656 if (type == T_ZNS)
657   {
658   uschar *d = name;
659   while (d != 0)
660     {
661     int rc = dns_lookup(dnsa, d, T_NS, fully_qualified_name);
662     if (rc != DNS_NOMATCH && rc != DNS_NODATA) return rc;
663     while (*d != 0 && *d != '.') d++;
664     if (*d++ == 0) break; 
665     }
666   return DNS_NOMATCH;     
667   } 
668
669 /* Control should never reach here */
670
671 return DNS_FAIL;
672 }
673
674
675
676 /* Support for A6 records has been commented out since they were demoted to
677 experimental status at IETF 51. */
678
679 #if HAVE_IPV6 && defined(SUPPORT_A6)
680
681 /*************************************************
682 *        Search DNS block for prefix RRs         *
683 *************************************************/
684
685 /* Called from dns_complete_a6() to search an additional section or a main
686 answer section for required prefix records to complete an IPv6 address obtained
687 from an A6 record. For each prefix record, a recursive call to dns_complete_a6
688 is made, with a new copy of the address so far.
689
690 Arguments:
691   dnsa       the DNS answer block
692   which      RESET_ADDITIONAL or RESET_ANSWERS
693   name       name of prefix record
694   yptrptr    pointer to the pointer that points to where to hang the next
695                dns_address structure
696   bits       number of bits we have already got
697   bitvec     the bits we have already got
698
699 Returns:     TRUE if any records were found
700 */
701
702 static BOOL
703 dns_find_prefix(dns_answer *dnsa, int which, uschar *name, dns_address
704   ***yptrptr, int bits, uschar *bitvec)
705 {
706 BOOL yield = FALSE;
707 dns_record *rr;
708 dns_scan dnss;
709
710 for (rr = dns_next_rr(dnsa, &dnss, which);
711      rr != NULL;
712      rr = dns_next_rr(dnsa, &dnss, RESET_NEXT))
713   {
714   uschar cbitvec[16];
715   if (rr->type != T_A6 || strcmpic(rr->name, name) != 0) continue;
716   yield = TRUE;
717   memcpy(cbitvec, bitvec, sizeof(cbitvec));
718   dns_complete_a6(yptrptr, dnsa, rr, bits, cbitvec);
719   }
720
721 return yield;
722 }
723
724
725
726 /*************************************************
727 *            Follow chains of A6 records         *
728 *************************************************/
729
730 /* A6 records may be incomplete, with pointers to other records containing more
731 bits of the address. There can be a tree structure, leading to a number of
732 addresses originating from a single initial A6 record.
733
734 Arguments:
735   yptrptr    pointer to the pointer that points to where to hang the next
736                dns_address structure
737   dnsa       the current DNS answer block
738   rr         the RR we have at present
739   bits       number of bits we have already got
740   bitvec     the bits we have already got
741
742 Returns:     nothing
743 */
744
745 static void
746 dns_complete_a6(dns_address ***yptrptr, dns_answer *dnsa, dns_record *rr,
747   int bits, uschar *bitvec)
748 {
749 static uschar bitmask[] = { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
750 uschar *p = (uschar *)(rr->data);
751 int prefix_len, suffix_len;
752 int i, j, k;
753 uschar *chainptr;
754 uschar chain[264];
755 dns_answer cdnsa;
756
757 /* The prefix length is the first byte. It defines the prefix which is missing
758 from the data in this record as a number of bits. Zero means this is the end of
759 a chain. The suffix is the data in this record; only sufficient bytes to hold
760 it are supplied. There may be zero bytes. We have to ignore trailing bits that
761 we have already obtained from earlier RRs in the chain. */
762
763 prefix_len = *p++;                      /* bits */
764 suffix_len = (128 - prefix_len + 7)/8;  /* bytes */
765
766 /* If the prefix in this record is greater than the prefix in the previous
767 record in the chain, we have to ignore the record (RFC 2874). */
768
769 if (prefix_len > 128 - bits) return;
770
771 /* In this little loop, the number of bits up to and including the current byte
772 is held in k. If we have none of the bits in this byte, we can just or it into
773 the current data. If we have all of the bits in this byte, we skip it.
774 Otherwise, some masking has to be done. */
775
776 for (i = suffix_len - 1, j = 15, k = 8; i >= 0; i--)
777   {
778   int required = k - bits;
779   if (required >= 8) bitvec[j] |= p[i];
780     else if (required > 0) bitvec[j] |= p[i] & bitmask[required];
781   j--;     /* I tried putting these in the "for" statement, but gcc muttered */
782   k += 8;  /* about computed values not being used. */
783   }
784
785 /* If the prefix_length is zero, we are at the end of a chain. Build a
786 dns_address item with the current data, hang it onto the end of the chain,
787 adjust the hanging pointer, and we are done. */
788
789 if (prefix_len == 0)
790   {
791   dns_address *new = store_get(sizeof(dns_address) + 50);
792   inet_ntop(AF_INET6, bitvec, CS new->address, 50);
793   new->next = NULL;
794   **yptrptr = new;
795   *yptrptr = &(new->next);
796   return;
797   }
798
799 /* Prefix length is not zero. Reset the number of bits that we have collected
800 so far, and extract the chain name. */
801
802 bits = 128 - prefix_len;
803 p += suffix_len;
804
805 chainptr = chain;
806 while ((i = *p++) != 0)
807   {
808   if (chainptr != chain) *chainptr++ = '.';
809   memcpy(chainptr, p, i);
810   chainptr += i;
811   p += i;
812   }
813 *chainptr = 0;
814 chainptr = chain;
815
816 /* Now scan the current DNS response record to see if the additional section
817 contains the records we want. This processing can be cut out for testing
818 purposes. */
819
820 if (dns_find_prefix(dnsa, RESET_ADDITIONAL, chainptr, yptrptr, bits, bitvec))
821   return;
822
823 /* No chain records were found in the current DNS response block. Do a new DNS
824 lookup to try to find these records. This opens up the possibility of DNS
825 failures. We ignore them at this point; if all branches of the tree fail, there
826 will be no addresses at the end. */
827
828 if (dns_lookup(&cdnsa, chainptr, T_A6, NULL) == DNS_SUCCEED)
829   (void)dns_find_prefix(&cdnsa, RESET_ANSWERS, chainptr, yptrptr, bits, bitvec);
830 }
831 #endif  /* HAVE_IPV6 && defined(SUPPORT_A6) */
832
833
834
835
836 /*************************************************
837 *          Get address(es) from DNS record       *
838 *************************************************/
839
840 /* The record type is either T_A for an IPv4 address or T_AAAA (or T_A6 when
841 supported) for an IPv6 address. In the A6 case, there may be several addresses,
842 generated by following chains. A recursive function does all the hard work. A6
843 records now look like passing into history, so the code is only included when
844 explicitly asked for.
845
846 Argument:
847   dnsa       the DNS answer block
848   rr         the RR
849
850 Returns:     pointer a chain of dns_address items
851 */
852
853 dns_address *
854 dns_address_from_rr(dns_answer *dnsa, dns_record *rr)
855 {
856 dns_address *yield = NULL;
857
858 #if HAVE_IPV6 && defined(SUPPORT_A6)
859 dns_address **yieldptr = &yield;
860 uschar bitvec[16];
861 #else
862 dnsa = dnsa;    /* Stop picky compilers warning */
863 #endif
864
865 if (rr->type == T_A)
866   {
867   uschar *p = (uschar *)(rr->data);
868   yield = store_get(sizeof(dns_address) + 20);
869   (void)sprintf(CS yield->address, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
870   yield->next = NULL;
871   }
872
873 #if HAVE_IPV6
874
875 #ifdef SUPPORT_A6
876 else if (rr->type == T_A6)
877   {
878   memset(bitvec, 0, sizeof(bitvec));
879   dns_complete_a6(&yieldptr, dnsa, rr, 0, bitvec);
880   }
881 #endif  /* SUPPORT_A6 */
882
883 else
884   {
885   yield = store_get(sizeof(dns_address) + 50);
886   inet_ntop(AF_INET6, (uschar *)(rr->data), CS yield->address, 50);
887   yield->next = NULL;
888   }
889 #endif  /* HAVE_IPV6 */
890
891 return yield;
892 }
893
894 /* End of dns.c */