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