Regex compile cacheing
[exim.git] / src / src / match.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9 /* Functions for matching strings */
10
11
12 #include "exim.h"
13
14
15 /* Argument block for the check_string() function. This is used for general
16 strings, domains, and local parts. */
17
18 typedef struct check_string_block {
19   const uschar *origsubject;           /* caseful; keep these two first, in */
20   const uschar *subject;               /* step with the block below */
21   int    expand_setup;
22   mcs_flags flags;                      /* MCS_* defs in macros.h */
23 } check_string_block;
24
25
26 /* Argument block for the check_address() function. This is used for whole
27 addresses. */
28
29 typedef struct check_address_block {
30   const uschar *origaddress;         /* caseful; keep these two first, in */
31   uschar *address;                   /* step with the block above */
32   int    expand_setup;
33   mcs_flags flags;                      /* MCS_CASELESS, MCS_TEXTONLY_RE */
34 } check_address_block;
35
36
37
38 /*************************************************
39 *           Generalized string match             *
40 *************************************************/
41
42 /* This function does a single match of a subject against a pattern, and
43 optionally sets up the numeric variables according to what it matched. It is
44 called from match_isinlist() via match_check_list() when scanning a list, and
45 from match_check_string() when testing just a single item. The subject and
46 options arguments are passed in a check_string_block so as to make it easier to
47 pass them through match_check_list.
48
49 The possible types of pattern are:
50
51   . regular expression - starts with ^
52   . tail match - starts with *
53   . lookup - starts with search type
54   . if at_is_special is set in the argument block:
55       @              matches the primary host name
56       @[]            matches a local IP address in brackets
57       @mx_any        matches any domain with an MX to the local host
58       @mx_primary    matches any domain with a primary MX to the local host
59       @mx_secondary  matches any domain with a secondary MX to the local host
60   . literal - anything else
61
62 Any of the @mx_xxx options can be followed by "/ignore=<list>" where <list> is
63 a list of IP addresses that are to be ignored (typically 127.0.0.1).
64
65 Arguments:
66   arg            check_string_block pointer - see below
67   pattern        the pattern to be matched
68   valueptr       if not NULL, and a lookup is done, return the result here
69                    instead of discarding it; else set it to point to NULL
70   error          for error messages (not used in this function; it never
71                    returns ERROR)
72
73 Contents of the argument block:
74   origsubject    the subject in its original casing
75   subject        the subject string to be checked, lowercased if caseless
76   expand_setup   if < 0, don't set up any numeric expansion variables;
77                  if = 0, set $0 to whole subject, and either
78                    $1 to what matches * or
79                    $1, $2, ... to r.e. bracketed items
80                  if > 0, don't set $0, but do set either
81                    $n to what matches *, or
82                    $n, $n+1, ... to r.e. bracketed items
83                  (where n = expand_setup)
84   use_partial    if FALSE, override any partial- search types
85   caseless       TRUE for caseless matching where possible
86   at_is_special  enable special handling of items starting with @
87
88 Returns:       OK    if matched
89                FAIL  if not matched
90                DEFER if lookup deferred
91 */
92
93 static int
94 check_string(void * arg, const uschar * pattern, const uschar ** valueptr,
95   uschar ** error)
96 {
97 const check_string_block * cb = arg;
98 int search_type, partial, affixlen, starflags;
99 int expand_setup = cb->expand_setup;
100 const uschar * affix, * opts;
101 uschar *s;
102 uschar *filename = NULL;
103 uschar *keyquery, *result, *semicolon;
104 void *handle;
105
106 if (valueptr) *valueptr = NULL;
107
108 /* For regular expressions, use cb->origsubject rather than cb->subject so that
109 it works if the pattern uses (?-i) to turn off case-independence, overriding
110 "caseless". */
111
112 s = string_copy(pattern[0] == '^' ? cb->origsubject : cb->subject);
113
114 /* If required to set up $0, initialize the data but don't turn on by setting
115 expand_nmax until the match is assured. */
116
117 expand_nmax = -1;
118 if (expand_setup == 0)
119   {
120   expand_nstring[0] = s;        /* $0 (might be) the matched subject in full */
121   expand_nlength[0] = Ustrlen(s);
122   }
123 else if (expand_setup > 0) expand_setup--;
124
125 /* Regular expression match: compile, match, and set up $ variables if
126 required. */
127
128 if (pattern[0] == '^')
129   {
130   const pcre2_code * re = regex_must_compile(pattern,
131       cb->flags & (MCS_CACHEABLE | MCS_CASELESS), FALSE);
132   if (expand_setup < 0
133       ? !regex_match(re, s, -1, NULL)
134       : !regex_match_and_setup(re, s, 0, expand_setup)
135      )
136     return FAIL;
137   if (valueptr) *valueptr = pattern;    /* "value" gets the RE */
138   return OK;
139   }
140
141 /* Tail match */
142
143 if (pattern[0] == '*')
144   {
145   int slen = Ustrlen(s);
146   int patlen;    /* Sun compiler doesn't like non-constant initializer */
147
148   patlen = Ustrlen(++pattern);
149   if (patlen > slen) return FAIL;
150   if (cb->flags & MCS_CASELESS
151       ? strncmpic(s + slen - patlen, pattern, patlen) != 0
152       : Ustrncmp(s + slen - patlen, pattern, patlen) != 0)
153     return FAIL;
154   if (expand_setup >= 0)
155     {
156     expand_nstring[++expand_setup] = s;         /* write a $n, the matched subject variable-part */
157     expand_nlength[expand_setup] = slen - patlen;
158     expand_nmax = expand_setup;                 /* commit also $0, the matched subject */
159     }
160   if (valueptr) *valueptr = pattern - 1;        /* "value" gets the (original) pattern */
161   return OK;
162   }
163
164 /* Match a special item starting with @ if so enabled. On its own, "@" matches
165 the primary host name - implement this by changing the pattern. For the other
166 cases we have to do some more work. If we don't recognize a special pattern,
167 just fall through - the match will fail. */
168
169 if (cb->flags & MCS_AT_SPECIAL && pattern[0] == '@')
170   {
171   if (pattern[1] == 0)
172     {
173     pattern = primary_hostname;
174     goto NOT_AT_SPECIAL;               /* Handle as exact string match */
175     }
176
177   if (Ustrcmp(pattern, "@[]") == 0)
178     {
179     int slen = Ustrlen(s);
180     if (s[0] != '[' && s[slen-1] != ']') return FAIL;           /*XXX should this be || ? */
181     for (ip_address_item * ip = host_find_interfaces(); ip; ip = ip->next)
182       if (Ustrncmp(ip->address, s+1, slen - 2) == 0
183             && ip->address[slen - 2] == 0)
184         {
185         if (expand_setup >= 0) expand_nmax = expand_setup;      /* commit $0, the IP addr */
186         if (valueptr) *valueptr = pattern;      /* "value" gets the pattern */
187         return OK;
188         }
189     return FAIL;
190     }
191
192   if (strncmpic(pattern, US"@mx_", 4) == 0)
193     {
194     int rc;
195     host_item h;
196     BOOL prim = FALSE;
197     BOOL secy = FALSE;
198     BOOL removed = FALSE;
199     const uschar *ss = pattern + 4;
200     const uschar *ignore_target_hosts = NULL;
201
202     if (strncmpic(ss, US"any", 3) == 0) ss += 3;
203     else if (strncmpic(ss, US"primary", 7) == 0)
204       {
205       ss += 7;
206       prim = TRUE;
207       }
208     else if (strncmpic(ss, US"secondary", 9) == 0)
209       {
210       ss += 9;
211       secy = TRUE;
212       }
213     else goto NOT_AT_SPECIAL;
214
215     if (strncmpic(ss, US"/ignore=", 8) == 0) ignore_target_hosts = ss + 8;
216     else if (*ss) goto NOT_AT_SPECIAL;
217
218     h.next = NULL;
219     h.name = s;
220     h.address = NULL;
221
222     rc = host_find_bydns(&h,
223       ignore_target_hosts,
224       HOST_FIND_BY_MX,     /* search only for MX, not SRV or A */
225       NULL,                /* service name not relevant */
226       NULL,                /* srv_fail_domains not relevant */
227       NULL,                /* mx_fail_domains not relevant */
228       NULL,                /* no dnssec request/require XXX ? */
229       NULL,                /* no feedback FQDN */
230       &removed);           /* feedback if local removed */
231
232     if (rc == HOST_FIND_AGAIN)
233       {
234       search_error_message = string_sprintf("DNS lookup of \"%s\" deferred", s);
235       return DEFER;
236       }
237
238     if ((rc != HOST_FOUND_LOCAL || secy) && (prim || !removed))
239       return FAIL;
240
241     if (expand_setup >= 0) expand_nmax = expand_setup;  /* commit $0, the matched subject */
242     if (valueptr) *valueptr = pattern;  /* "value" gets the patterm */
243     return OK;
244
245     /*** The above line used to be the following line, but this is incorrect,
246     because host_find_bydns() may return HOST_NOT_FOUND if it removed some MX
247     hosts, but the remaining ones were non-existent. All we are interested in
248     is whether or not it removed some hosts.
249
250     return (rc == HOST_FOUND && removed)? OK : FAIL;
251     ***/
252     }
253   }
254
255 /* Escape point from code for specials that start with "@" */
256
257 NOT_AT_SPECIAL:
258
259 /* This is an exact string match if there is no semicolon in the pattern. */
260
261 if ((semicolon = Ustrchr(pattern, ';')) == NULL)
262   {
263   if (cb->flags & MCS_CASELESS ? strcmpic(s, pattern) != 0 : Ustrcmp(s, pattern) != 0)
264     return FAIL;
265   if (expand_setup >= 0) expand_nmax = expand_setup;    /* $0 gets the matched subject */
266   if (valueptr) *valueptr = pattern;                    /* "value" gets the pattern */
267   return OK;
268   }
269
270 /* Otherwise we have a lookup item. The lookup type, including partial, etc. is
271 the part of the string preceding the semicolon. */
272
273 *semicolon = 0;
274 search_type = search_findtype_partial(pattern, &partial, &affix, &affixlen,
275   &starflags, &opts);
276 *semicolon = ';';
277 if (search_type < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s",
278   search_error_message);
279
280 /* Partial matching is not appropriate for certain lookups (e.g. when looking
281 up user@domain for sender rejection). There's a flag to disable it. */
282
283 if (!(cb->flags & MCS_PARTIAL)) partial = -1;
284
285 /* Set the parameters for the three different kinds of lookup. */
286
287 keyquery = search_args(search_type, s, semicolon+1, &filename, opts);
288
289 /* Now do the actual lookup; throw away the data returned unless it was asked
290 for; partial matching is all handled inside search_find(). Note that there is
291 no search_close() because of the caching arrangements. */
292
293 if (!(handle = search_open(filename, search_type, 0, NULL, NULL)))
294   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", search_error_message);
295 result = search_find(handle, filename, keyquery, partial, affix, affixlen,
296   starflags, &expand_setup, opts);
297
298 if (!result) return f.search_find_defer ? DEFER : FAIL;
299 if (valueptr) *valueptr = result;
300
301 expand_nmax = expand_setup;
302 return OK;
303 }
304
305
306
307 /*************************************************
308 *      Public interface to check_string()        *
309 *************************************************/
310
311 /* This function is called from several places where is it most convenient to
312 pass the arguments individually. It places them in a check_string_block
313 structure, and then calls check_string().
314
315 Arguments:
316   s            the subject string to be checked
317   pattern      the pattern to check it against
318   expand_setup expansion setup option (see check_string())
319   flags
320    use_partial  if FALSE, override any partial- search types
321    caseless     TRUE for caseless matching where possible
322    at_is_special TRUE to recognize @, @[], etc.
323   valueptr     if not NULL, and a file lookup was done, return the result
324                  here instead of discarding it; else set it to point to NULL
325
326 Returns:       OK    if matched
327                FAIL  if not matched
328                DEFER if lookup deferred
329 */
330
331 int
332 match_check_string(const uschar * s, const uschar * pattern, int expand_setup,
333   mcs_flags flags, const uschar ** valueptr)
334 {
335 check_string_block cb;
336 cb.origsubject = s;
337 cb.subject = flags & MCS_CASELESS ? string_copylc(s) : string_copy(s);
338 cb.expand_setup = expand_setup;
339 cb.flags = flags;
340 return check_string(&cb, pattern, valueptr, NULL);
341 }
342
343
344
345 /*************************************************
346 *       Get key string from check block          *
347 *************************************************/
348
349 /* When caching the data from a lookup for a named list, we have to save the
350 key that was found, because other lookups of different keys on the same list
351 may occur. This function has knowledge of the different lookup types, and
352 extracts the appropriate key.
353
354 Arguments:
355   arg          the check block
356   type         MCL_STRING, MCL_DOMAIN, MCL_HOST, MCL_ADDRESS, or MCL_LOCALPART
357 */
358
359 static const uschar *
360 get_check_key(void *arg, int type)
361 {
362 switch(type)
363   {
364   case MCL_STRING:
365   case MCL_DOMAIN:
366   case MCL_LOCALPART:   return ((check_string_block *)arg)->subject;
367   case MCL_HOST:        return ((check_host_block *)arg)->host_address;
368   case MCL_ADDRESS:     return ((check_address_block *)arg)->address;
369   }
370 return US"";  /* In practice, should never happen */
371 }
372
373
374
375 /*************************************************
376 *       Scan list and run matching function      *
377 *************************************************/
378
379 /* This function scans a list of patterns, and runs a matching function for
380 each item in the list. It is called from the functions that match domains,
381 local parts, hosts, and addresses, because its overall structure is the same in
382 all cases. However, the details of each particular match is different, so it
383 calls back to a given function do perform an actual match.
384
385 We can't quite keep the different types anonymous here because they permit
386 different special cases. A pity.
387
388 If a list item starts with !, that implies negation if the subject matches the
389 rest of the item (ignoring white space after the !). The result when the end of
390 the list is reached is FALSE unless the last item on the list is negated, in
391 which case it is TRUE. A file name in the list causes its lines to be
392 interpolated as if items in the list. An item starting with + is a named
393 sublist, obtained by searching the tree pointed to by anchorptr, with possible
394 cached match results in cache_bits.
395
396 Arguments:
397   listptr      pointer to the pointer to the list
398   sep          separator character for string_nextinlist();
399                  normally zero for a standard list;
400                  sometimes UCHAR_MAX+1 for single items;
401   anchorptr    -> tree of named items, or NULL if no named items
402   cache_ptr    pointer to pointer to cache bits for named items, or
403                  pointer to NULL if not caching; may get set NULL if an
404                  uncacheable named list is encountered
405   func         function to call back to do one test
406   arg          pointer to pass to the function; the string to be matched is
407                  in the structure it points to
408   type         MCL_STRING, MCL_DOMAIN, MCL_HOST, MCL_ADDRESS, or MCL_LOCALPART
409                  these are used for some special handling
410                MCL_NOEXPAND (whose value is greater than any of them) may
411                  be added to any value to suppress expansion of the list
412   name         string to use in debugging info
413   valueptr     where to pass back data from a lookup
414
415 Returns:       OK    if matched a non-negated item
416                OK    if hit end of list after a negated item
417                FAIL  if expansion force-failed
418                FAIL  if matched a negated item
419                FAIL  if hit end of list after a non-negated item
420                DEFER if a something deferred or expansion failed
421 */
422
423 int
424 match_check_list(const uschar **listptr, int sep, tree_node **anchorptr,
425   unsigned int **cache_ptr, int (*func)(void *,const uschar *,const uschar **,uschar **),
426   void *arg, int type, const uschar *name, const uschar **valueptr)
427 {
428 int yield = OK;
429 unsigned int * original_cache_bits = *cache_ptr;
430 BOOL include_unknown = FALSE, ignore_unknown = FALSE,
431       include_defer = FALSE, ignore_defer = FALSE;
432 const uschar *list;
433 uschar *sss;
434 uschar *ot = NULL;
435 BOOL textonly_re;
436
437 /* Save time by not scanning for the option name when we don't need it. */
438
439 HDEBUG(D_any)
440   {
441   uschar * listname = readconf_find_option(listptr);
442   if (*listname) ot = string_sprintf("%s in %s?", name, listname);
443   }
444
445 /* If the list is empty, the answer is no. Skip the debugging output for
446 an unnamed list. */
447
448 if (!*listptr)
449   {
450   HDEBUG(D_lists) if (ot) debug_printf_indent("%s no (option unset)\n", ot);
451   return FAIL;
452   }
453
454 /* Expand the list before we scan it. A forced expansion gives the answer
455 "not in list"; other expansion errors cause DEFER to be returned. However,
456 if the type value is greater than or equal to than MCL_NOEXPAND, do not expand
457 the list. */
458
459 if (type >= MCL_NOEXPAND)
460   {
461   list = *listptr;
462   type -= MCL_NOEXPAND;       /* Remove the "no expand" flag */
463   textonly_re = TRUE;
464   }
465 else
466   {
467   /* If we are searching a domain list, and $domain is not set, set it to the
468   subject that is being sought for the duration of the expansion. */
469
470   if (type == MCL_DOMAIN && !deliver_domain)
471     {
472     check_string_block *cb = (check_string_block *)arg;
473     deliver_domain = string_copy(cb->subject);
474     list = expand_string_2(*listptr, &textonly_re);
475     deliver_domain = NULL;
476     }
477   else
478     list = expand_string_2(*listptr, &textonly_re);
479
480   if (!list)
481     {
482     if (f.expand_string_forcedfail)
483       {
484       HDEBUG(D_lists) debug_printf_indent("expansion of \"%s\" forced failure: "
485         "assume not in this list\n", *listptr);
486       return FAIL;
487       }
488     log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand \"%s\" while checking "
489       "a list: %s", *listptr, expand_string_message);
490     return DEFER;
491     }
492   }
493
494 if (textonly_re) switch (type)
495   {
496   case MCL_STRING:
497   case MCL_DOMAIN:
498   case MCL_LOCALPART: ((check_string_block *)arg)->flags |= MCS_CACHEABLE; break;
499   case MCL_HOST:     ((check_host_block *)arg)->flags |= MCS_CACHEABLE; break;
500   case MCL_ADDRESS: ((check_address_block *)arg)->flags |= MCS_CACHEABLE; break;
501   }
502
503 /* For an unnamed list, use the expanded version in comments */
504 #define LIST_LIMIT_PR 2048
505
506 HDEBUG(D_any) if (!ot)
507   {
508   int n, m;
509   gstring * g = string_fmt_append(NULL, "%s in \"%n%.*s%n\"",
510     name, &n, LIST_LIMIT_PR, list, &m);
511   if (m - n >= LIST_LIMIT_PR) g = string_catn(g, US"...", 3);
512   g = string_catn(g, US"?", 1);
513   gstring_release_unused(g);
514   ot = string_from_gstring(g);
515   }
516
517 /* Now scan the list and process each item in turn, until one of them matches,
518 or we hit an error. */
519
520 while ((sss = string_nextinlist(&list, &sep, NULL, 0)))
521   {
522   uschar * ss = sss;
523
524   /* Address lists may contain +caseful, to restore caseful matching of the
525   local part. We have to know the layout of the control block, unfortunately.
526   The lower cased address is in a temporary buffer, so we just copy the local
527   part back to the start of it (if a local part exists). */
528
529   if (type == MCL_ADDRESS)
530     {
531     if (Ustrcmp(ss, "+caseful") == 0)
532       {
533       check_address_block *cb = (check_address_block *)arg;
534       uschar *at = Ustrrchr(cb->origaddress, '@');
535
536       if (at)
537         Ustrncpy(cb->address, cb->origaddress, at - cb->origaddress);
538       cb->flags &= ~MCS_CASELESS;
539       continue;
540       }
541     }
542
543   /* Similar processing for local parts */
544
545   else if (type == MCL_LOCALPART)
546     {
547     if (Ustrcmp(ss, "+caseful") == 0)
548       {
549       check_string_block *cb = (check_string_block *)arg;
550       Ustrcpy(US cb->subject, cb->origsubject);
551       cb->flags &= ~MCS_CASELESS;
552       continue;
553       }
554     }
555
556   /* If the host item is "+include_unknown" or "+ignore_unknown", remember it
557   in case there's a subsequent failed reverse lookup. There is similar
558   processing for "defer". */
559
560   else if (type == MCL_HOST && *ss == '+')
561     {
562     if (Ustrcmp(ss, "+include_unknown") == 0)
563       {
564       include_unknown = TRUE;
565       ignore_unknown = FALSE;
566       continue;
567       }
568     if (Ustrcmp(ss, "+ignore_unknown") == 0)
569       {
570       ignore_unknown = TRUE;
571       include_unknown = FALSE;
572       continue;
573       }
574     if (Ustrcmp(ss, "+include_defer") == 0)
575       {
576       include_defer = TRUE;
577       ignore_defer = FALSE;
578       continue;
579       }
580     if (Ustrcmp(ss, "+ignore_defer") == 0)
581       {
582       ignore_defer = TRUE;
583       include_defer = FALSE;
584       continue;
585       }
586     }
587
588   /* Starting with ! specifies a negative item. It is theoretically possible
589   for a local part to start with !. In that case, a regex has to be used. */
590
591   if (*ss == '!')
592     {
593     yield = FAIL;
594     while (isspace((*(++ss))));
595     }
596   else
597     yield = OK;
598
599   /* If the item does not begin with '/', it might be a + item for a named
600   list. Otherwise, it is just a single list entry that has to be matched.
601   We recognize '+' only when supplied with a tree of named lists. */
602
603   if (*ss != '/')
604     {
605     if (*ss == '+' && anchorptr)
606       {
607       int bits = 0;
608       int offset = 0;
609       int shift = 0;
610       unsigned int *use_cache_bits = original_cache_bits;
611       uschar *cached = US"";
612       namedlist_block *nb;
613       tree_node * t;
614
615       if (!(t = tree_search(*anchorptr, ss+1)))
616         {
617         log_write(0, LOG_MAIN|LOG_PANIC, "unknown named%s list \"%s\"",
618           type == MCL_DOMAIN ?    " domain" :
619           type == MCL_HOST ?      " host" :
620           type == MCL_ADDRESS ?   " address" :
621           type == MCL_LOCALPART ? " local part" : "",
622           ss);
623         return DEFER;
624         }
625       nb = t->data.ptr;
626
627       /* If the list number is negative, it means that this list is not
628       cacheable because it contains expansion items. */
629
630       if (nb->number < 0) use_cache_bits = NULL;
631
632       /* If we have got a cache pointer, get the bits. This is not an "else"
633       because the pointer may be NULL from the start if caching is not
634       required. */
635
636       if (use_cache_bits)
637         {
638         offset = (nb->number)/16;
639         shift = ((nb->number)%16)*2;
640         bits = use_cache_bits[offset] & (3 << shift);
641         }
642
643       /* Not previously tested or no cache - run the full test */
644
645       if (bits == 0)
646         {
647         switch (match_check_list(&(nb->string), 0, anchorptr, &use_cache_bits,
648                 func, arg, type, name, valueptr))
649           {
650           case OK:   bits = 1; break;
651           case FAIL: bits = 3; break;
652           case DEFER: goto DEFER_RETURN;
653           }
654
655         /* If this list was uncacheable, or a sublist turned out to be
656         uncacheable, the value of use_cache_bits will now be NULL, even if it
657         wasn't before. Ensure that this is passed up to the next level.
658         Otherwise, remember the result of the search in the cache. */
659
660         if (!use_cache_bits)
661           *cache_ptr = NULL;
662         else
663           {
664           use_cache_bits[offset] |= bits << shift;
665
666           if (valueptr)
667             {
668             int old_pool = store_pool;
669             namedlist_cacheblock *p;
670
671             /* Cached data for hosts persists over more than one message,
672             so we use the permanent store pool */
673
674             store_pool = POOL_PERM;
675             p = store_get(sizeof(namedlist_cacheblock), GET_UNTAINTED);
676             p->key = string_copy(get_check_key(arg, type));
677
678
679             p->data = *valueptr ? string_copy(*valueptr) : NULL;
680             store_pool = old_pool;
681
682             p->next = nb->cache_data;
683             nb->cache_data = p;
684             if (*valueptr)
685               DEBUG(D_lists) debug_printf_indent("data from lookup saved for "
686                 "cache for %s: key '%s' value '%s'\n", ss, p->key, *valueptr);
687             }
688           }
689         }
690
691        /* Previously cached; to find a lookup value, search a chain of values
692        and compare keys. Typically, there is only one such, but it is possible
693        for different keys to have matched the same named list. */
694
695       else
696         {
697         DEBUG(D_lists) debug_printf_indent("cached %s match for %s\n",
698           (bits & (-bits)) == bits ? "yes" : "no", ss);
699
700         cached = US" - cached";
701         if (valueptr)
702           {
703           const uschar *key = get_check_key(arg, type);
704
705           for (namedlist_cacheblock * p = nb->cache_data; p; p = p->next)
706             if (Ustrcmp(key, p->key) == 0)
707               {
708               *valueptr = p->data;
709               break;
710               }
711           DEBUG(D_lists) debug_printf_indent("cached lookup data = %s\n", *valueptr);
712           }
713         }
714
715       /* Result of test is indicated by value in bits. For each test, we
716       have 00 => untested, 01 => tested yes, 11 => tested no. */
717
718       if ((bits & (-bits)) == bits)    /* Only one of the two bits is set */
719         {
720         HDEBUG(D_lists) debug_printf_indent("%s %s (matched \"%s\"%s)\n", ot,
721           yield == OK ? "yes" : "no", sss, cached);
722         return yield;
723         }
724       }
725
726     /* Run the provided function to do the individual test. */
727
728     else
729       {
730       uschar * error = NULL;
731       switch ((func)(arg, ss, valueptr, &error))
732         {
733         case OK:
734           HDEBUG(D_lists) debug_printf_indent("%s %s (matched \"%s\")\n", ot,
735             (yield == OK)? "yes" : "no", sss);
736           return yield;
737
738         case DEFER:
739           if (!error)
740             error = string_sprintf("DNS lookup of \"%s\" deferred", ss);
741           if (ignore_defer)
742             {
743             HDEBUG(D_lists) debug_printf_indent("%s: item ignored by +ignore_defer\n",
744               error);
745             break;
746             }
747           if (include_defer)
748             {
749             log_write(0, LOG_MAIN, "%s: accepted by +include_defer", error);
750             return OK;
751             }
752           if (!search_error_message) search_error_message = error;
753           goto DEFER_RETURN;
754
755         /* The ERROR return occurs when checking hosts, when either a forward
756         or reverse lookup has failed. It can also occur in a match_ip list if a
757         non-IP address item is encountered. The error string gives details of
758         which it was. */
759
760         case ERROR:
761           if (ignore_unknown)
762             {
763             HDEBUG(D_lists) debug_printf_indent("%s: item ignored by +ignore_unknown\n",
764               error);
765             }
766           else
767             {
768             HDEBUG(D_lists) debug_printf_indent("%s %s (%s)\n", ot,
769               include_unknown? "yes":"no", error);
770             if (!include_unknown)
771               {
772               if (LOGGING(unknown_in_list))
773                 log_write(0, LOG_MAIN, "list matching forced to fail: %s", error);
774               return FAIL;
775               }
776             log_write(0, LOG_MAIN, "%s: accepted by +include_unknown", error);
777             return OK;
778             }
779         }
780       }
781     }
782
783   /* If the item is a file name, we read the file and do a match attempt
784   on each line in the file, including possibly more negation processing. */
785
786   else
787     {
788     int file_yield = yield;       /* In case empty file */
789     uschar * filename = ss;
790     FILE * f = Ufopen(filename, "rb");
791     uschar filebuffer[1024];
792
793     /* ot will be null in non-debugging cases, and anyway, we get better
794     wording by reworking it. */
795
796     if (!f)
797       {
798       uschar * listname = readconf_find_option(listptr);
799       if (listname[0] == 0)
800         listname = string_sprintf("\"%s\"", *listptr);
801       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s",
802         string_open_failed("%s when checking %s", sss, listname));
803       }
804
805     /* Trailing comments are introduced by #, but in an address list or local
806     part list, the # must be preceded by white space or the start of the line,
807     because the # character is a legal character in local parts. */
808
809     while (Ufgets(filebuffer, sizeof(filebuffer), f) != NULL)
810       {
811       uschar *error;
812       uschar *sss = filebuffer;
813
814       while ((ss = Ustrchr(sss, '#')) != NULL)
815         {
816         if ((type != MCL_ADDRESS && type != MCL_LOCALPART) ||
817               ss == filebuffer || isspace(ss[-1]))
818           {
819           *ss = 0;
820           break;
821           }
822         sss = ss + 1;
823         }
824
825       ss = filebuffer + Ustrlen(filebuffer);            /* trailing space */
826       while (ss > filebuffer && isspace(ss[-1])) ss--;
827       *ss = 0;
828
829       ss = filebuffer;
830       while (isspace(*ss)) ss++;                        /* leading space */
831
832       if (!*ss) continue;                               /* ignore empty */
833
834       file_yield = yield;                               /* positive yield */
835       sss = ss;                                         /* for debugging */
836
837       if (*ss == '!')                                   /* negation */
838         {
839         file_yield = (file_yield == OK)? FAIL : OK;
840         while (isspace((*(++ss))));
841         }
842
843       switch ((func)(arg, ss, valueptr, &error))
844         {
845         case OK:
846           (void)fclose(f);
847           HDEBUG(D_lists) debug_printf_indent("%s %s (matched \"%s\" in %s)\n", ot,
848             yield == OK ? "yes" : "no", sss, filename);
849
850           /* The "pattern" being matched came from the file; we use a stack-local.
851           Copy it to allocated memory now we know it matched. */
852
853           if (valueptr) *valueptr = string_copy(ss);
854           return file_yield;
855
856         case DEFER:
857           if (!error)
858             error = string_sprintf("DNS lookup of %s deferred", ss);
859           if (ignore_defer)
860             {
861             HDEBUG(D_lists) debug_printf_indent("%s: item ignored by +ignore_defer\n",
862               error);
863             break;
864             }
865           (void)fclose(f);
866           if (include_defer)
867             {
868             log_write(0, LOG_MAIN, "%s: accepted by +include_defer", error);
869             return OK;
870             }
871           goto DEFER_RETURN;
872
873         case ERROR:             /* host name lookup failed - this can only */
874           if (ignore_unknown)   /* be for an incoming host (not outgoing) */
875             {
876             HDEBUG(D_lists) debug_printf_indent("%s: item ignored by +ignore_unknown\n",
877               error);
878             }
879           else
880            {
881             HDEBUG(D_lists) debug_printf_indent("%s %s (%s)\n", ot,
882               include_unknown? "yes":"no", error);
883             (void)fclose(f);
884             if (!include_unknown)
885               {
886               if (LOGGING(unknown_in_list))
887                 log_write(0, LOG_MAIN, "list matching forced to fail: %s", error);
888               return FAIL;
889               }
890             log_write(0, LOG_MAIN, "%s: accepted by +include_unknown", error);
891             return OK;
892             }
893         }
894       }
895
896     /* At the end of the file, leave the yield setting at the final setting
897     for the file, in case this is the last item in the list. */
898
899     yield = file_yield;
900     (void)fclose(f);
901     }
902   }    /* Loop for the next item on the top-level list */
903
904 /* End of list reached: if the last item was negated yield OK, else FAIL. */
905
906 HDEBUG(D_lists)
907   debug_printf_indent("%s %s (end of list)\n", ot, yield == OK ? "no":"yes");
908 return yield == OK ? FAIL : OK;
909
910 /* Something deferred */
911
912 DEFER_RETURN:
913 HDEBUG(D_lists) debug_printf("%s list match deferred for %s\n", ot, sss);
914 return DEFER;
915 }
916
917
918 /*************************************************
919 *          Match in colon-separated list         *
920 *************************************************/
921
922 /* This function is used for domain lists and local part lists. It is not used
923 for host lists or address lists, which have additional interpretation of the
924 patterns. Some calls of it set sep > UCHAR_MAX in order to use its matching
925 facilities on single items. When this is done, it arranges to set the numerical
926 variables as a result of the match.
927
928 This function is now just a short interface to match_check_list(), which does
929 list scanning in a general way. A good compiler will optimize the tail
930 recursion.
931
932 Arguments:
933   s              string to search for
934   listptr        ptr to ptr to colon separated list of patterns, or NULL
935   sep            a separator value for the list (see string_nextinlist())
936   anchorptr      ptr to tree for named items, or NULL if no named items
937   cache_bits     ptr to cache_bits for ditto, or NULL if not caching
938   type           MCL_DOMAIN when matching a domain list
939                  MCL_LOCALPART when matching a local part list (address lists
940                    have their own function)
941                  MCL_STRING for others (e.g. list of ciphers)
942                  MCL_NOEXPAND (whose value is greater than any of them) may
943                    be added to any value to suppress expansion of the list
944   caseless       TRUE for (mostly) caseless matching - passed directly to
945                    match_check_string()
946   valueptr       pointer to where any lookup data is to be passed back,
947                  or NULL (just passed on to match_check_string)
948
949 Returns:         OK    if matched a non-negated item
950                  OK    if hit end of list after a negated item
951                  FAIL  if expansion force-failed
952                  FAIL  if matched a negated item
953                  FAIL  if hit end of list after a non-negated item
954                  DEFER if a lookup deferred
955 */
956
957 int
958 match_isinlist(const uschar *s, const uschar **listptr, int sep,
959    tree_node **anchorptr,
960   unsigned int *cache_bits, int type, BOOL caseless, const uschar **valueptr)
961 {
962 unsigned int *local_cache_bits = cache_bits;
963 check_string_block cb;
964 cb.origsubject = s;
965 cb.subject = caseless ? string_copylc(s) : string_copy(s);
966 cb.flags = caseless ? MCS_PARTIAL+MCS_CASELESS : MCS_PARTIAL;
967 switch (type & ~MCL_NOEXPAND)
968   {
969   case MCL_DOMAIN:      cb.flags |= MCS_AT_SPECIAL;     /*FALLTHROUGH*/
970   case MCL_LOCALPART:   cb.expand_setup = 0;                            break;
971   default:              cb.expand_setup = sep > UCHAR_MAX ? 0 : -1;     break;
972   }
973 if (valueptr) *valueptr = NULL;
974 return  match_check_list(listptr, sep, anchorptr, &local_cache_bits,
975   check_string, &cb, type, s, valueptr);
976 }
977
978
979
980 /*************************************************
981 *    Match address to single address-list item   *
982 *************************************************/
983
984 /* This function matches an address to an item from an address list. It is
985 called from match_address_list() via match_check_list(). That is why most of
986 its arguments are in an indirect block.
987
988 Arguments:
989   arg            the argument block (see below)
990   pattern        the pattern to match
991   valueptr       where to return a value
992   error          for error messages (not used in this function; it never
993                    returns ERROR)
994
995 The argument block contains:
996   address        the start of the subject address; when called from retry.c
997                    it may be *@domain if the local part isn't relevant
998   origaddress    the original, un-case-forced address (not used here, but used
999                    in match_check_list() when +caseful is encountered)
1000   expand_setup   controls setting up of $n variables
1001   caseless       TRUE for caseless local part matching
1002
1003 Returns:         OK     for a match
1004                  FAIL   for no match
1005                  DEFER  if a lookup deferred
1006 */
1007
1008 static int
1009 check_address(void * arg, const uschar * pattern, const uschar ** valueptr,
1010   uschar ** error)
1011 {
1012 check_address_block * cb = (check_address_block *)arg;
1013 check_string_block csb;
1014 int rc;
1015 int expand_inc = 0;
1016 unsigned int * null = NULL;
1017 const uschar * listptr;
1018 uschar * subject = cb->address;
1019 const uschar * s;
1020 uschar * pdomain, * sdomain;
1021 uschar * value = NULL;
1022
1023 DEBUG(D_lists) debug_printf_indent("address match test: subject=%s pattern=%s\n",
1024   subject, pattern);
1025
1026 /* Find the subject's domain */
1027
1028 sdomain = Ustrrchr(subject, '@');
1029
1030 /* The only case where a subject may not have a domain is if the subject is
1031 empty. Otherwise, a subject with no domain is a serious configuration error. */
1032
1033 if (!sdomain && *subject)
1034   {
1035   log_write(0, LOG_MAIN|LOG_PANIC, "no @ found in the subject of an "
1036     "address list match: subject=\"%s\" pattern=\"%s\"", subject, pattern);
1037   return FAIL;
1038   }
1039
1040 /* Handle a regular expression, which must match the entire incoming address.
1041 This may be the empty address. */
1042
1043 if (*pattern == '^')
1044   return match_check_string(subject, pattern, cb->expand_setup,
1045             cb->flags | MCS_PARTIAL, NULL);
1046
1047 /* Handle a pattern that is just a lookup. Skip over possible lookup names
1048 (letters, digits, hyphens). Skip over a possible * or *@ at the end. Then we
1049 must have a semicolon for it to be a lookup. */
1050
1051 for (s = pattern; isalnum(*s) || *s == '-'; s++) ;
1052 if (*s == '*') s++;
1053 if (*s == '@') s++;
1054
1055 /* If it is a straight lookup, do a lookup for the whole address. This may be
1056 the empty address. Partial matching doesn't make sense here, so we ignore it,
1057 but write a panic log entry. However, *@ matching will be honoured. */
1058
1059 if (*s == ';')
1060   {
1061   if (Ustrncmp(pattern, "partial-", 8) == 0)
1062     log_write(0, LOG_MAIN|LOG_PANIC, "partial matching is not applicable to "
1063       "whole-address lookups: ignored \"partial-\" in \"%s\"", pattern);
1064   return match_check_string(subject, pattern, -1, cb->flags, valueptr);
1065   }
1066
1067 /* For the remaining cases, an empty subject matches only an empty pattern,
1068 because other patterns expect to have a local part and a domain to match
1069 against. */
1070
1071 if (!*subject) return *pattern ? FAIL : OK;
1072
1073 /* If the pattern starts with "@@" we have a split lookup, where the domain is
1074 looked up to obtain a list of local parts. If the subject's local part is just
1075 "*" (called from retry) the match always fails. */
1076
1077 if (pattern[0] == '@' && pattern[1] == '@')
1078   {
1079   int watchdog = 50;
1080   uschar *list, *ss;
1081
1082   if (sdomain == subject + 1 && *subject == '*') return FAIL;
1083
1084   /* Loop for handling chains. The last item in any list may be of the form
1085   ">name" in order to chain on to another list. */
1086
1087   for (const uschar * key = sdomain + 1; key && watchdog-- > 0; )
1088     {
1089     int sep = 0;
1090
1091     if ((rc = match_check_string(key, pattern + 2, -1, MCS_PARTIAL, CUSS &list))
1092         != OK)
1093       return rc;
1094
1095     /* Check for chaining from the last item; set up the next key if one
1096     is found. */
1097
1098     ss = Ustrrchr(list, ':');
1099     if (!ss) ss = list; else ss++;
1100     Uskip_whitespace(&ss);
1101     if (*ss == '>')
1102       {
1103       *ss++ = 0;
1104       Uskip_whitespace(&ss);
1105       key = string_copy(ss);
1106       }
1107     else key = NULL;
1108
1109     /* Look up the local parts provided by the list; negation is permitted.
1110     If a local part has to begin with !, a regex can be used. */
1111
1112     while ((ss = string_nextinlist(CUSS &list, &sep, NULL, 0)))
1113       {
1114       int local_yield;
1115
1116       if (*ss == '!')
1117         {
1118         local_yield = FAIL;
1119         while (isspace((*(++ss))));
1120         }
1121       else local_yield = OK;
1122
1123       *sdomain = 0;
1124       rc = match_check_string(subject, ss, -1, cb->flags + MCS_PARTIAL, valueptr);
1125       *sdomain = '@';
1126
1127       switch(rc)
1128         {
1129         case OK:
1130         return local_yield;
1131
1132         case DEFER:
1133         return DEFER;
1134         }
1135       }
1136     }
1137
1138   /* End of chain loop; panic if too many times */
1139
1140   if (watchdog <= 0)
1141     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Loop detected in lookup of "
1142       "local part of %s in %s", subject, pattern);
1143
1144   /* Otherwise the local part check has failed, so the whole match
1145   fails. */
1146
1147   return FAIL;
1148   }
1149
1150
1151 /* We get here if the pattern is not a lookup or a regular expression. If it
1152 contains an @ there is both a local part and a domain. */
1153
1154 if ((pdomain = Ustrrchr(pattern, '@')))
1155   {
1156   int pllen, sllen;
1157
1158   /* If the domain in the pattern is empty or one of the special cases [] or
1159   mx_{any,primary,secondary}, and the local part in the pattern ends in "@",
1160   we have a pattern of the form <something>@@, <something>@@[], or
1161   <something>@@mx_{any,primary,secondary}. These magic "domains" are
1162   automatically interpreted in match_check_string. We just need to arrange that
1163   the leading @ is included in the domain. */
1164
1165   if (pdomain > pattern && pdomain[-1] == '@' &&
1166        (pdomain[1] == 0 ||
1167         Ustrcmp(pdomain+1, "[]") == 0 ||
1168         Ustrcmp(pdomain+1, "mx_any") == 0 ||
1169         Ustrcmp(pdomain+1, "mx_primary") == 0 ||
1170         Ustrcmp(pdomain+1, "mx_secondary") == 0))
1171     pdomain--;
1172
1173   pllen = pdomain - pattern;
1174   sllen = sdomain - subject;
1175
1176   /* Compare the local parts in the subject and the pattern */
1177
1178   if (*pattern == '*')
1179     {
1180     int cllen = pllen - 1;
1181     if (sllen < cllen) return FAIL;
1182     if (cb->flags & MCS_CASELESS
1183         ? strncmpic(subject+sllen-cllen, pattern + 1, cllen) != 0
1184         : Ustrncmp(subject+sllen-cllen, pattern + 1, cllen) != 0)
1185         return FAIL;
1186     if (cb->expand_setup > 0)
1187       {
1188       expand_nstring[cb->expand_setup] = subject;
1189       expand_nlength[cb->expand_setup] = sllen - cllen;
1190       expand_inc = 1;
1191       }
1192     value = string_copyn(pattern + 1, cllen);
1193     }
1194   else
1195     {
1196     if (sllen != pllen) return FAIL;
1197     if (cb->flags & MCS_CASELESS
1198         ? strncmpic(subject, pattern, sllen) != 0
1199         : Ustrncmp(subject, pattern, sllen) != 0) return FAIL;
1200     }
1201     value = string_copyn(pattern, sllen);
1202   }
1203
1204 /* If the local part matched, or was not being checked, check the domain using
1205 the generalized function, which supports file lookups (which may defer). The
1206 original code read as follows:
1207
1208   return match_check_string(sdomain + 1,
1209       pdomain ? pdomain + 1 : pattern,
1210       cb->expand_setup + expand_inc, cb->flags, NULL);
1211
1212 This supported only literal domains and *.x.y patterns. In order to allow for
1213 named domain lists (so that you can write, for example, "senders=+xxxx"), it
1214 was changed to use the list scanning function. */
1215
1216 csb.origsubject = sdomain + 1;
1217 csb.subject = cb->flags & MCS_CASELESS
1218   ? string_copylc(sdomain+1) : string_copy(sdomain+1);
1219 csb.expand_setup = cb->expand_setup + expand_inc;
1220 csb.flags = MCS_PARTIAL | MCS_AT_SPECIAL | cb->flags & MCS_CASELESS;
1221
1222 listptr = pdomain ? pdomain + 1 : pattern;
1223 if (valueptr) *valueptr = NULL;
1224
1225   {
1226   const uschar * dvalue = NULL;
1227   rc = match_check_list(
1228     &listptr,                  /* list of one item */
1229     UCHAR_MAX+1,               /* impossible separator; single item */
1230     &domainlist_anchor,        /* it's a domain list */
1231     &null,                     /* ptr to NULL means no caching */
1232     check_string,              /* the function to do one test */
1233     &csb,                      /* its data */
1234     MCL_DOMAIN + MCL_NOEXPAND, /* domain list; don't expand */
1235     csb.subject,               /* string for messages */
1236     &dvalue);                       /* where to pass back lookup data */
1237   if (valueptr && (value || dvalue))
1238     *valueptr = string_sprintf("%s@%s",
1239                   value ? value : US"", dvalue ? dvalue : US"");
1240   }
1241 return rc;
1242 }
1243
1244
1245
1246
1247 /*************************************************
1248 *    Test whether address matches address list   *
1249 *************************************************/
1250
1251 /* This function is given an address and a list of things to match it against.
1252 The list may contain individual addresses, regular expressions, lookup
1253 specifications, and indirection via bare files. Negation is supported. The
1254 address to check can consist of just a domain, which will then match only
1255 domain items or items specified as *@domain.
1256
1257 Domains are always lower cased before the match. Local parts are also lower
1258 cased unless "caseless" is false. The work of actually scanning the list is
1259 done by match_check_list(), with an appropriate block of arguments and a
1260 callback to check_address(). During caseless matching, it will recognize
1261 +caseful and revert to caseful matching.
1262
1263 Arguments:
1264   address         address to test
1265   caseless        TRUE to start in caseless state
1266   expand          TRUE to allow list expansion
1267   listptr         list to check against
1268   cache_bits      points to cache bits for named address lists, or NULL
1269   expand_setup    controls setting up of $n variables - passed through
1270                   to check_address (q.v.)
1271   sep             separator character for the list;
1272                   may be 0 to get separator from the list;
1273                   may be UCHAR_MAX+1 for one-item list
1274   valueptr        where to return a lookup value, or NULL
1275
1276 Returns:          OK    for a positive match, or end list after a negation;
1277                   FAIL  for a negative match, or end list after non-negation;
1278                   DEFER if a lookup deferred
1279 */
1280
1281 int
1282 match_address_list(const uschar *address, BOOL caseless, BOOL expand,
1283   const uschar **listptr, unsigned int *cache_bits, int expand_setup, int sep,
1284   const uschar **valueptr)
1285 {
1286 check_address_block ab;
1287 unsigned int *local_cache_bits = cache_bits;
1288 int len;
1289
1290 /* RFC 2505 recommends that for spam checking, local parts should be caselessly
1291 compared. Therefore, Exim now forces the entire address into lower case here,
1292 provided that "caseless" is set. (It is FALSE for calls for matching rewriting
1293 patterns.) Otherwise just the domain is lower cases. A magic item "+caseful" in
1294 the list can be used to restore a caseful copy of the local part from the
1295 original address.
1296 Limit the subject address size to avoid mem-exhaustion attacks.  The size chosen
1297 is historical (we used to use big_buffer here). */
1298
1299 if ((len = Ustrlen(address)) > BIG_BUFFER_SIZE) len = BIG_BUFFER_SIZE;
1300 ab.address = string_copyn(address, len);
1301
1302 for (uschar * p = ab.address + len - 1; p >= ab.address; p--)
1303   {
1304   if (!caseless && *p == '@') break;
1305   *p = tolower(*p);
1306   }
1307
1308 /* If expand_setup is zero, we need to set up $0 to the whole thing, in
1309 case there is a match. Can't use the built-in facilities of match_check_string
1310 (via check_address), as we may just be calling that for part of the address
1311 (the domain). */
1312
1313 if (expand_setup == 0)
1314   {
1315   expand_nstring[0] = string_copy(address);
1316   expand_nlength[0] = Ustrlen(address);
1317   expand_setup++;
1318   }
1319
1320 /* Set up the data to be passed ultimately to check_address. */
1321
1322 ab.origaddress = address;
1323 /* ab.address is above */
1324 ab.expand_setup = expand_setup;
1325 ab.flags = caseless ? MCS_CASELESS : 0;
1326
1327 return match_check_list(listptr, sep, &addresslist_anchor, &local_cache_bits,
1328   check_address, &ab, MCL_ADDRESS + (expand ? 0 : MCL_NOEXPAND), address,
1329     valueptr);
1330 }
1331
1332 /* Simpler version of match_address_list; always caseless, expanding,
1333 no cache bits, no value-return.
1334
1335 Arguments:
1336   address         address to test
1337   listptr         list to check against
1338   sep             separator character for the list;
1339                   may be 0 to get separator from the list;
1340                   may be UCHAR_MAX+1 for one-item list
1341
1342 Returns:          OK    for a positive match, or end list after a negation;
1343                   FAIL  for a negative match, or end list after non-negation;
1344                   DEFER if a lookup deferred
1345 */
1346
1347 int
1348 match_address_list_basic(const uschar *address, const uschar **listptr, int sep)
1349 {
1350 return match_address_list(address, TRUE, TRUE, listptr, NULL, -1, sep, NULL);
1351 }
1352
1353 /* End of match.c */