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