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