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