Add retrans/retry options to dnsdb lookup. Bug 1539
[exim.git] / src / src / lookups / dnsdb.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2014 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 #include "../exim.h"
9 #include "lf_functions.h"
10
11
12
13 /* Ancient systems (e.g. SunOS4) don't appear to have T_TXT defined in their
14 header files. */
15
16 #ifndef T_TXT
17 #define T_TXT 16
18 #endif
19
20 /* Many systems do not have T_SPF. */
21 #ifndef T_SPF
22 #define T_SPF 99
23 #endif
24
25 /* New TLSA record for DANE */
26 #ifndef T_TLSA
27 #define T_TLSA 52
28 #endif
29
30 /* Table of recognized DNS record types and their integer values. */
31
32 static const char *type_names[] = {
33   "a",
34 #if HAVE_IPV6
35   "a+",
36   "aaaa",
37 #endif
38   "cname",
39   "csa",
40   "mx",
41   "mxh",
42   "ns",
43   "ptr",
44   "spf",
45   "srv",
46   "tlsa",
47   "txt",
48   "zns"
49 };
50
51 static int type_values[] = {
52   T_A,
53 #if HAVE_IPV6
54   T_ADDRESSES,     /* Private type for AAAA + A */
55   T_AAAA,
56 #endif
57   T_CNAME,
58   T_CSA,     /* Private type for "Client SMTP Authorization". */
59   T_MX,
60   T_MXH,     /* Private type for "MX hostnames" */
61   T_NS,
62   T_PTR,
63   T_SPF,
64   T_SRV,
65   T_TLSA,
66   T_TXT,
67   T_ZNS      /* Private type for "zone nameservers" */
68 };
69
70
71 /*************************************************
72 *              Open entry point                  *
73 *************************************************/
74
75 /* See local README for interface description. */
76
77 static void *
78 dnsdb_open(uschar *filename, uschar **errmsg)
79 {
80 filename = filename;   /* Keep picky compilers happy */
81 errmsg = errmsg;       /* Ditto */
82 return (void *)(-1);   /* Any non-0 value */
83 }
84
85
86
87 /*************************************************
88 *           Find entry point for dnsdb           *
89 *************************************************/
90
91 /* See local README for interface description. The query in the "keystring" may
92 consist of a number of parts.
93
94 (a) If the first significant character is '>' then the next character is the
95 separator character that is used when multiple records are found. The default
96 separator is newline.
97
98 (b) If the next character is ',' then the next character is the separator
99 character used for multiple items of text in "TXT" records. Alternatively,
100 if the next character is ';' then these multiple items are concatenated with
101 no separator. With neither of these options specified, only the first item
102 is output.  Similarly for "SPF" records, but the default for joining multiple
103 items in one SPF record is the empty string, for direct concatenation.
104
105 (c) Options, all comma-terminated, in any order.  Any unrecognised option
106 terminates option processing.  Recognised options are:
107
108 - 'defer_FOO':  set the defer behaviour to FOO.  The possible behaviours are:
109 'strict', where any defer causes the whole lookup to defer; 'lax', where a defer
110 causes the whole lookup to defer only if none of the DNS queries succeeds; and
111 'never', where all defers are as if the lookup failed. The default is 'lax'.
112
113 - 'dnssec_FOO', with 'strict', 'lax' and 'never' (default).  The meanings are
114 require, try and don't-try dnssec respectively.
115
116 - 'retrans_VAL', set the timeout value.  VAL is an Exim time specification
117 (eg "5s").  The default is set by the main configuration option 'dns_retrans'.
118
119 - 'retry_VAL', set the retry count on timeouts.  VAL is an integer.  The
120 default is set by the main configuration option "dns_retry".
121
122 (d) If the next sequence of characters is a sequence of letters and digits
123 followed by '=', it is interpreted as the name of the DNS record type. The
124 default is "TXT".
125
126 (e) Then there follows list of domain names. This is a generalized Exim list,
127 which may start with '<' in order to set a specific separator. The default
128 separator, as always, is colon. */
129
130 static int
131 dnsdb_find(void *handle, uschar *filename, const uschar *keystring, int length,
132   uschar **result, uschar **errmsg, BOOL *do_cache)
133 {
134 int rc;
135 int size = 256;
136 int ptr = 0;
137 int sep = 0;
138 int defer_mode = PASS;
139 int dnssec_mode = OK;
140 int save_retrans = dns_retrans;
141 int save_retry =   dns_retry;
142 int type;
143 int failrc = FAIL;
144 const uschar *outsep = CUS"\n";
145 const uschar *outsep2 = NULL;
146 uschar *equals, *domain, *found;
147
148 /* Because we're the working in the search pool, we try to reclaim as much
149 store as possible later, so we preallocate the result here */
150
151 uschar *yield = store_get(size);
152
153 dns_record *rr;
154 dns_answer dnsa;
155 dns_scan dnss;
156
157 handle = handle;           /* Keep picky compilers happy */
158 filename = filename;
159 length = length;
160 do_cache = do_cache;
161
162 /* If the string starts with '>' we change the output separator.
163 If it's followed by ';' or ',' we set the TXT output separator. */
164
165 while (isspace(*keystring)) keystring++;
166 if (*keystring == '>')
167   {
168   outsep = keystring + 1;
169   keystring += 2;
170   if (*keystring == ',')
171     {
172     outsep2 = keystring + 1;
173     keystring += 2;
174     }
175   else if (*keystring == ';')
176     {
177     outsep2 = US"";
178     keystring++;
179     }
180   while (isspace(*keystring)) keystring++;
181   }
182
183 /* Check for a modifier keyword. */
184
185 for (;;)
186   {
187   if (strncmpic(keystring, US"defer_", 6) == 0)
188     {
189     keystring += 6;
190     if (strncmpic(keystring, US"strict", 6) == 0)
191       { defer_mode = DEFER; keystring += 6; }
192     else if (strncmpic(keystring, US"lax", 3) == 0)
193       { defer_mode = PASS; keystring += 3; }
194     else if (strncmpic(keystring, US"never", 5) == 0)
195       { defer_mode = OK; keystring += 5; }
196     else
197       {
198       *errmsg = US"unsupported dnsdb defer behaviour";
199       return DEFER;
200       }
201     }
202   else if (strncmpic(keystring, US"dnssec_", 7) == 0)
203     {
204     keystring += 7;
205     if (strncmpic(keystring, US"strict", 6) == 0)
206       { dnssec_mode = DEFER; keystring += 6; }
207     else if (strncmpic(keystring, US"lax", 3) == 0)
208       { dnssec_mode = PASS; keystring += 3; }
209     else if (strncmpic(keystring, US"never", 5) == 0)
210       { dnssec_mode = OK; keystring += 5; }
211     else
212       {
213       *errmsg = US"unsupported dnsdb dnssec behaviour";
214       return DEFER;
215       }
216     }
217   else if (strncmpic(keystring, US"retrans_", 8) == 0)
218     {
219     int timeout_sec;
220     if ((timeout_sec = readconf_readtime(keystring += 8, ',', FALSE)) <= 0)
221       {
222       *errmsg = US"unsupported dnsdb timeout value";
223       return DEFER;
224       }
225     dns_retrans = timeout_sec;
226     while (*keystring != ',') keystring++;
227     }
228   else if (strncmpic(keystring, US"retry_", 6) == 0)
229     {
230     int retries;
231     if ((retries = (int)strtol(keystring + 6, CSS &keystring, 0)) < 0)
232       {
233       *errmsg = US"unsupported dnsdb retry count";
234       return DEFER;
235       }
236     dns_retry = retries;
237     }
238   else
239     break;
240
241   while (isspace(*keystring)) keystring++;
242   if (*keystring++ != ',')
243     {
244     *errmsg = US"dnsdb modifier syntax error";
245     return DEFER;
246     }
247   while (isspace(*keystring)) keystring++;
248   }
249
250 /* Figure out the "type" value if it is not T_TXT.
251 If the keystring contains an = this must be preceded by a valid type name. */
252
253 type = T_TXT;
254 if ((equals = Ustrchr(keystring, '=')) != NULL)
255   {
256   int i, len;
257   uschar *tend = equals;
258
259   while (tend > keystring && isspace(tend[-1])) tend--;
260   len = tend - keystring;
261
262   for (i = 0; i < sizeof(type_names)/sizeof(uschar *); i++)
263     {
264     if (len == Ustrlen(type_names[i]) &&
265         strncmpic(keystring, US type_names[i], len) == 0)
266       {
267       type = type_values[i];
268       break;
269       }
270     }
271
272   if (i >= sizeof(type_names)/sizeof(uschar *))
273     {
274     *errmsg = US"unsupported DNS record type";
275     return DEFER;
276     }
277
278   keystring = equals + 1;
279   while (isspace(*keystring)) keystring++;
280   }
281
282 /* Initialize the resolver in case this is the first time it has been used. */
283
284 dns_init(FALSE, FALSE, dnssec_mode != OK);
285
286 /* The remainder of the string must be a list of domains. As long as the lookup
287 for at least one of them succeeds, we return success. Failure means that none
288 of them were found.
289
290 The original implementation did not support a list of domains. Adding the list
291 feature is compatible, except in one case: when PTR records are being looked up
292 for a single IPv6 address. Fortunately, we can hack in a compatibility feature
293 here: If the type is PTR and no list separator is specified, and the entire
294 remaining string is valid as an IP address, set an impossible separator so that
295 it is treated as one item. */
296
297 if (type == T_PTR && keystring[0] != '<' &&
298     string_is_ip_address(keystring, NULL) != 0)
299   sep = -1;
300
301 /* SPF strings should be concatenated without a separator, thus make
302 it the default if not defined (see RFC 4408 section 3.1.3).
303 Multiple SPF records are forbidden (section 3.1.2) but are currently
304 not handled specially, thus they are concatenated with \n by default.
305 MX priority and value are space-separated by default.
306 SRV and TLSA record parts are space-separated by default. */
307
308 if (!outsep2) switch(type)
309   {
310   case T_SPF:                         outsep2 = US"";  break;
311   case T_SRV: case T_MX: case T_TLSA: outsep2 = US" "; break;
312   }
313
314 /* Now scan the list and do a lookup for each item */
315
316 while ((domain = string_nextinlist(&keystring, &sep, NULL, 0)))
317   {
318   uschar rbuffer[256];
319   int searchtype = (type == T_CSA)? T_SRV :         /* record type we want */
320                    (type == T_MXH)? T_MX :
321                    (type == T_ZNS)? T_NS : type;
322
323   /* If the type is PTR or CSA, we have to construct the relevant magic lookup
324   key if the original is an IP address (some experimental protocols are using
325   PTR records for different purposes where the key string is a host name, and
326   Exim's extended CSA can be keyed by domains or IP addresses). This code for
327   doing the reversal is now in a separate function. */
328
329   if ((type == T_PTR || type == T_CSA) &&
330       string_is_ip_address(domain, NULL) != 0)
331     {
332     dns_build_reverse(domain, rbuffer);
333     domain = rbuffer;
334     }
335
336   do
337     {
338     DEBUG(D_lookup) debug_printf("dnsdb key: %s\n", domain);
339
340     /* Do the lookup and sort out the result. There are four special types that
341     are handled specially: T_CSA, T_ZNS, T_ADDRESSES and T_MXH.
342     The first two are handled in a special lookup function so that the facility
343     could be used from other parts of the Exim code. T_ADDRESSES is handled by looping
344     over the types of A lookup.  T_MXH affects only what happens later on in
345     this function, but for tidiness it is handled by the "special". If the
346     lookup fails, continue with the next domain. In the case of DEFER, adjust
347     the final "nothing found" result, but carry on to the next domain. */
348
349     found = domain;
350 #if HAVE_IPV6
351     if (type == T_ADDRESSES)            /* NB cannot happen unless HAVE_IPV6 */
352       {
353       if (searchtype == T_ADDRESSES) searchtype = T_AAAA;
354       else if (searchtype == T_AAAA) searchtype = T_A;
355       rc = dns_special_lookup(&dnsa, domain, searchtype, CUSS &found);
356       }
357     else
358 #endif
359       rc = dns_special_lookup(&dnsa, domain, type, CUSS &found);
360
361     lookup_dnssec_authenticated = dnssec_mode==OK ? NULL
362       : dns_is_secure(&dnsa) ? US"yes" : US"no";
363
364     if (rc == DNS_NOMATCH || rc == DNS_NODATA) continue;
365     if (  rc != DNS_SUCCEED
366        || (dnssec_mode == DEFER && !dns_is_secure(&dnsa))
367        )
368       {
369       if (defer_mode == DEFER)
370         {
371         dns_retrans = save_retrans;
372         dns_retry = save_retry;
373         dns_init(FALSE, FALSE, FALSE);                  /* clr dnssec bit */
374         return DEFER;                                   /* always defer */
375         }
376       if (defer_mode == PASS) failrc = DEFER;         /* defer only if all do */
377       continue;                                       /* treat defer as fail */
378       }
379
380
381     /* Search the returned records */
382
383     for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
384          rr != NULL;
385          rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
386       {
387       if (rr->type != searchtype) continue;
388
389       /* There may be several addresses from an A6 record. Put the configured
390       separator between them, just as for between several records. However, A6
391       support is not normally configured these days. */
392
393       if (type == T_A || type == T_AAAA || type == T_ADDRESSES)
394         {
395         dns_address *da;
396         for (da = dns_address_from_rr(&dnsa, rr); da != NULL; da = da->next)
397           {
398           if (ptr != 0) yield = string_cat(yield, &size, &ptr, outsep, 1);
399           yield = string_cat(yield, &size, &ptr, da->address,
400             Ustrlen(da->address));
401           }
402         continue;
403         }
404
405       /* Other kinds of record just have one piece of data each, but there may be
406       several of them, of course. */
407
408       if (ptr != 0) yield = string_cat(yield, &size, &ptr, outsep, 1);
409
410       if (type == T_TXT || type == T_SPF)
411         {
412         if (outsep2 == NULL)
413           {
414           /* output only the first item of data */
415           yield = string_cat(yield, &size, &ptr, (uschar *)(rr->data+1),
416             (rr->data)[0]);
417           }
418         else
419           {
420           /* output all items */
421           int data_offset = 0;
422           while (data_offset < rr->size)
423             {
424             uschar chunk_len = (rr->data)[data_offset++];
425             if (outsep2[0] != '\0' && data_offset != 1)
426               yield = string_cat(yield, &size, &ptr, outsep2, 1);
427             yield = string_cat(yield, &size, &ptr,
428                              (uschar *)((rr->data)+data_offset), chunk_len);
429             data_offset += chunk_len;
430             }
431           }
432         }
433       else if (type == T_TLSA)
434         {
435         uint8_t usage, selector, matching_type;
436         uint16_t i, payload_length;
437         uschar s[MAX_TLSA_EXPANDED_SIZE];
438         uschar * sp = s;
439         uschar *p = (uschar *)(rr->data);
440
441         usage = *p++;
442         selector = *p++;
443         matching_type = *p++;
444         /* What's left after removing the first 3 bytes above */
445         payload_length = rr->size - 3;
446         sp += sprintf(CS s, "%d%c%d%c%d%c", usage, *outsep2,
447                 selector, *outsep2, matching_type, *outsep2);
448         /* Now append the cert/identifier, one hex char at a time */
449         for (i=0;
450              i < payload_length && sp-s < (MAX_TLSA_EXPANDED_SIZE - 4);
451              i++)
452           {
453           sp += sprintf(CS sp, "%02x", (unsigned char)p[i]);
454           }
455         yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));
456         }
457       else   /* T_CNAME, T_CSA, T_MX, T_MXH, T_NS, T_PTR, T_SRV */
458         {
459         int priority, weight, port;
460         uschar s[264];
461         uschar *p = (uschar *)(rr->data);
462
463         if (type == T_MXH)
464           {
465           /* mxh ignores the priority number and includes only the hostnames */
466           GETSHORT(priority, p);
467           }
468         else if (type == T_MX)
469           {
470           GETSHORT(priority, p);
471           sprintf(CS s, "%d%c", priority, *outsep2);
472           yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));
473           }
474         else if (type == T_SRV)
475           {
476           GETSHORT(priority, p);
477           GETSHORT(weight, p);
478           GETSHORT(port, p);
479           sprintf(CS s, "%d%c%d%c%d%c", priority, *outsep2,
480                                         weight, *outsep2, port, *outsep2);
481           yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));
482           }
483         else if (type == T_CSA)
484           {
485           /* See acl_verify_csa() for more comments about CSA. */
486
487           GETSHORT(priority, p);
488           GETSHORT(weight, p);
489           GETSHORT(port, p);
490
491           if (priority != 1) continue;      /* CSA version must be 1 */
492
493           /* If the CSA record we found is not the one we asked for, analyse
494           the subdomain assertions in the port field, else analyse the direct
495           authorization status in the weight field. */
496
497           if (Ustrcmp(found, domain) != 0)
498             {
499             if (port & 1) *s = 'X';         /* explicit authorization required */
500             else *s = '?';                  /* no subdomain assertions here */
501             }
502           else
503             {
504             if (weight < 2) *s = 'N';       /* not authorized */
505             else if (weight == 2) *s = 'Y'; /* authorized */
506             else if (weight == 3) *s = '?'; /* unauthorizable */
507             else continue;                  /* invalid */
508             }
509
510           s[1] = ' ';
511           yield = string_cat(yield, &size, &ptr, s, 2);
512           }
513
514         /* GETSHORT() has advanced the pointer to the target domain. */
515
516         rc = dn_expand(dnsa.answer, dnsa.answer + dnsa.answerlen, p,
517           (DN_EXPAND_ARG4_TYPE)(s), sizeof(s));
518
519         /* If an overlong response was received, the data will have been
520         truncated and dn_expand may fail. */
521
522         if (rc < 0)
523           {
524           log_write(0, LOG_MAIN, "host name alias list truncated: type=%s "
525             "domain=%s", dns_text_type(type), domain);
526           break;
527           }
528         else yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));
529         }
530       }    /* Loop for list of returned records */
531
532            /* Loop for set of A-lookupu types */
533     } while (type == T_ADDRESSES && searchtype != T_A);
534
535   }        /* Loop for list of domains */
536
537 /* Reclaim unused memory */
538
539 store_reset(yield + ptr + 1);
540
541 /* If ptr == 0 we have not found anything. Otherwise, insert the terminating
542 zero and return the result. */
543
544 dns_retrans = save_retrans;
545 dns_retry = save_retry;
546 dns_init(FALSE, FALSE, FALSE);  /* clear the dnssec bit for getaddrbyname */
547
548 if (ptr == 0) return failrc;
549 yield[ptr] = 0;
550 *result = yield;
551 return OK;
552 }
553
554
555
556 /*************************************************
557 *         Version reporting entry point          *
558 *************************************************/
559
560 /* See local README for interface description. */
561
562 #include "../version.h"
563
564 void
565 dnsdb_version_report(FILE *f)
566 {
567 #ifdef DYNLOOKUP
568 fprintf(f, "Library version: DNSDB: Exim version %s\n", EXIM_VERSION_STR);
569 #endif
570 }
571
572
573 static lookup_info _lookup_info = {
574   US"dnsdb",                     /* lookup name */
575   lookup_querystyle,             /* query style */
576   dnsdb_open,                    /* open function */
577   NULL,                          /* check function */
578   dnsdb_find,                    /* find function */
579   NULL,                          /* no close function */
580   NULL,                          /* no tidy function */
581   NULL,                          /* no quoting function */
582   dnsdb_version_report           /* version reporting */
583 };
584
585 #ifdef DYNLOOKUP
586 #define dnsdb_lookup_module_info _lookup_module_info
587 #endif
588
589 static lookup_info *_lookup_list[] = { &_lookup_info };
590 lookup_module_info dnsdb_lookup_module_info = { LOOKUP_MODULE_INFO_MAGIC, _lookup_list, 1 };
591
592 /* vi: aw ai sw=2
593 */
594 /* End of lookups/dnsdb.c */