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