SPDX: Mass-update to GPL-2.0-or-later
[exim.git] / src / src / search.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 - 2015 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10 /* A set of functions to search databases in various formats. An open
11 database is represented by a void * value which is returned from a lookup-
12 specific "open" function. These are now all held in individual modules in the
13 lookups subdirectory and the functions here form a generic interface.
14
15 Caching is used to improve performance. Open files are cached until a tidyup
16 function is called, and for each file the result of the last lookup is cached.
17 However, if too many files are opened, some of those that are not in use have
18 to be closed. Those open items that use real files are kept on a LRU chain to
19 help with this.
20
21 All the data is held in permanent store so as to be independent of the stacking
22 pool that is reset from time to time. In fact, we use malloc'd store so that it
23 can be freed when the caches are tidied up. It isn't actually clear whether
24 this is a benefit or not, to be honest. */
25
26 #include "exim.h"
27
28
29 /* Tree in which to cache open files until tidyup called. */
30
31 static tree_node *search_tree = NULL;
32
33 /* Two-way chain of open databases that use real files. This is maintained in
34 recently-used order for the purposes of closing the least recently used when
35 too many files are open. */
36
37 static tree_node *open_top = NULL;
38 static tree_node *open_bot = NULL;
39
40 /* Count of open databases that use real files */
41
42 static int open_filecount = 0;
43
44 /* Allow us to reset store used for lookups and lookup caching */
45
46 static rmark search_reset_point = NULL;
47
48
49
50 /*************************************************
51 *      Validate a plain lookup type name         *
52 *************************************************/
53
54 /* Only those names that are recognized and whose code is included in the
55 binary give an OK response. Use a binary chop search now that the list has got
56 so long.
57
58 Arguments:
59   name       lookup type name - not necessarily zero terminated (e.g. dbm*)
60   len        length of the name
61
62 Returns:     +ve => valid lookup name; value is offset in lookup_list
63              -ve => invalid name; message in search_error_message.
64 */
65
66 int
67 search_findtype(const uschar * name, int len)
68 {
69 for (int bot = 0, top = lookup_list_count; top > bot; )
70   {
71   int mid = (top + bot)/2;
72   int c = Ustrncmp(name, lookup_list[mid]->name, len);
73
74   /* If c == 0 we have matched the incoming name with the start of the search
75   type name. However, some search types are substrings of others (e.g. nis and
76   nisplus) so we need to check that the lengths are the same. The length of the
77   type name cannot be shorter (else c would not be 0); if it is not equal it
78   must be longer, and in that case, the incoming name comes before the name we
79   are testing. By leaving c == 0 when the lengths are different, and doing a
80   > 0 test below, this all falls out correctly. */
81
82   if (c == 0 && Ustrlen(lookup_list[mid]->name) == len)
83     {
84     if (lookup_list[mid]->find != NULL) return mid;
85     search_error_message  = string_sprintf("lookup type \"%.*s\" is not "
86       "available (not in the binary - check buildtime LOOKUP configuration)",
87       len, name);
88     return -1;
89     }
90
91   if (c > 0) bot = mid + 1; else top = mid;
92   }
93
94 search_error_message = string_sprintf("unknown lookup type \"%.*s\"", len, name);
95 return -1;
96 }
97
98
99
100 /*************************************************
101 *       Validate a full lookup type name         *
102 *************************************************/
103
104 /* This function recognizes the "partial-" prefix and also terminating * and *@
105 suffixes.
106
107 Arguments:
108   name         the full lookup type name
109   ptypeptr     where to put the partial type
110                  after subtraction of 1024 or 2048:
111                    negative     => no partial matching
112                    non-negative => minimum number of non-wild components
113   ptypeaff     where to put a pointer to the affix
114                  the affix is within name if supplied therein
115                  otherwise it's a literal string
116   afflen       the length of the affix
117   starflags    where to put the SEARCH_STAR and SEARCH_STARAT flags
118   opts         where to put the options
119
120 Returns:     +ve => valid lookup name; value is offset in lookup_list
121              -ve => invalid name; message in search_error_message.
122 */
123
124 int
125 search_findtype_partial(const uschar *name, int *ptypeptr, const uschar **ptypeaff,
126   int *afflen, int *starflags, const uschar ** opts)
127 {
128 int len, stype;
129 int pv = -1;
130 const uschar *ss = name;
131 const uschar * t;
132
133 *starflags = 0;
134 *ptypeaff = NULL;
135
136 /* Check for a partial matching type. It must start with "partial", optionally
137 followed by a sequence of digits. If this is followed by "-", the affix is the
138 default "*." string. Otherwise we expect an affix in parentheses. Affixes are a
139 limited number of characters, not including parens. */
140
141 if (Ustrncmp(name, "partial", 7) == 0)
142   {
143   ss += 7;
144   if (isdigit (*ss))
145     {
146     pv = 0;
147     while (isdigit(*ss)) pv = pv*10 + *ss++ - '0';
148     }
149   else pv = 2;         /* Default number of wild components */
150
151   if (*ss == '(')
152     {
153     *ptypeaff = ++ss;
154     while (ispunct(*ss) && *ss != ')') ss++;
155     if (*ss != ')') goto BAD_TYPE;
156     *afflen = ss++ - *ptypeaff;
157     }
158   else if (*ss++ == '-')
159     {
160     *ptypeaff = US "*.";
161     *afflen = 2;
162     }
163   else
164     {
165     BAD_TYPE:
166     search_error_message = string_sprintf("format error in lookup type \"%s\"",
167       name);
168     return -1;
169     }
170   }
171
172 /* Now we are left with a lookup name, possibly followed by * or *@,
173 and then by options starting with a "," */
174
175 len = Ustrlen(ss);
176 if ((t = Ustrchr(ss, '*')))
177   {
178   len = t - ss;
179   *starflags |= (t[1] == '@' ? SEARCH_STARAT : SEARCH_STAR);
180   }
181 else
182   t = ss;
183
184 if ((t = Ustrchr(t, ',')))
185   {
186   int l = t - ss;
187   if (l < len) len = l;
188   *opts = string_copy(t+1);
189   }
190 else
191   *opts = NULL;
192
193 /* Check for the individual search type. Only those that are actually in the
194 binary are valid. For query-style types, "partial" and default types are
195 erroneous. */
196
197 stype = search_findtype(ss, len);
198 if (stype >= 0 && mac_islookup(stype, lookup_querystyle))
199   {
200   if (pv >= 0)
201     {
202     search_error_message = string_sprintf("\"partial\" is not permitted "
203       "for lookup type \"%s\"", ss);
204     return -1;
205     }
206   if ((*starflags & (SEARCH_STAR|SEARCH_STARAT)) != 0)
207     {
208     search_error_message = string_sprintf("defaults using \"*\" or \"*@\" are "
209       "not permitted for lookup type \"%s\"", ss);
210     return -1;
211     }
212   }
213
214 *ptypeptr = pv;
215 return stype;
216 }
217
218
219 /* Set the parameters for the three different kinds of lookup.
220 Arguments:
221  search_type    the search-type code
222  search         the search-type string
223  query          argument for the search; filename or query
224  fnamep         pointer to return filename
225  opts           options
226
227 Return: keyquery        the search-type (for single-key) or query (for query-type)
228  */
229 uschar *
230 search_args(int search_type, uschar * search, uschar * query, uschar ** fnamep,
231   const uschar * opts)
232 {
233 Uskip_whitespace(&query);
234 if (mac_islookup(search_type, lookup_absfilequery))
235   {                                     /* query-style but with file (sqlite) */
236   int sep = ',';
237
238   /* Check options first for new-style file spec */
239   if (opts) for (uschar * s; s = string_nextinlist(&opts, &sep, NULL, 0); )
240     if (Ustrncmp(s, "file=", 5) == 0)
241       {
242       *fnamep = s+5;
243       return query;
244       }
245
246   /* If no filename from options, use old-tyle space-sep prefix on query */
247   if (*query == '/')
248     {
249     uschar * s = query;
250     while (*query && !isspace(*query)) query++;
251     *fnamep = string_copyn(s, query - s);
252     Uskip_whitespace(&query);
253     }
254   else
255     *fnamep = NULL;
256   return query;         /* remainder after file skipped */
257   }
258 if (!mac_islookup(search_type, lookup_querystyle))
259   {                                     /* single-key */
260   *fnamep = query;
261   return search;        /* modifiers important so use "keyquery" for them */
262   }
263 *fnamep = NULL;                         /* else query-style */
264 return query;
265 }
266
267
268
269 /*************************************************
270 *               Release cached resources         *
271 *************************************************/
272
273 /* When search_open is called it caches the "file" that it opens in
274 search_tree. The name of the tree node is a concatenation of the search type
275 with the file name. For query-style lookups, the file name is empty. Real files
276 are normally closed only when this tidyup routine is called, typically at the
277 end of sections of code where a number of lookups might occur. However, if too
278 many files are open simultaneously, some get closed beforehand. They can't be
279 removed from the tree. There is also a general tidyup function which is called
280 for the lookup driver, if it exists.
281
282 First, there is an internal, recursive subroutine.
283
284 Argument:    a pointer to a search_openfile tree node
285 Returns:     nothing
286 */
287
288 static void
289 tidyup_subtree(tree_node *t)
290 {
291 search_cache * c = (search_cache *)(t->data.ptr);
292 if (t->left)  tidyup_subtree(t->left);
293 if (t->right) tidyup_subtree(t->right);
294 if (c && c->handle && lookup_list[c->search_type]->close)
295   lookup_list[c->search_type]->close(c->handle);
296 }
297
298
299 /* The external entry point
300
301 Argument: none
302 Returns:  nothing
303 */
304
305 void
306 search_tidyup(void)
307 {
308 int old_pool = store_pool;
309
310 DEBUG(D_lookup) debug_printf_indent("search_tidyup called\n");
311
312 /* Close individually each cached open file. */
313
314 store_pool = POOL_SEARCH;
315 if (search_tree)
316   {
317   tidyup_subtree(search_tree);
318   search_tree = NULL;
319   }
320 open_top = open_bot = NULL;
321 open_filecount = 0;
322
323 /* Call the general tidyup entry for any drivers that have one. */
324
325 for (int i = 0; i < lookup_list_count; i++) if (lookup_list[i]->tidy)
326   (lookup_list[i]->tidy)();
327
328 if (search_reset_point) search_reset_point = store_reset(search_reset_point);
329 store_pool = old_pool;
330 }
331
332
333
334
335 /*************************************************
336 *             Open search database               *
337 *************************************************/
338
339 /* A mode, and lists of owners and groups, are passed over for checking in
340 the cases where the database is one or more files. Return NULL, with a message
341 pointed to by message, in cases of error.
342
343 For search types that use a file or files, check up on the mode after
344 opening. It is tempting to do a stat before opening the file, and use it as
345 an existence check. However, doing that opens a small security loophole in
346 that the status could be changed before the file is opened. Can't quite see
347 what problems this might lead to, but you can't be too careful where security
348 is concerned. Fstat() on an open file can normally be expected to succeed,
349 but there are some NFS states where it does not.
350
351 There are two styles of query: (1) in the "single-key+file" style, a single
352 key string and a file name are given, for example, for linear searches, DBM
353 files, or for NIS. (2) In the "query" style, no "filename" is given; instead
354 just a single query string is passed. This applies to multiple-key lookup
355 types such as NIS+.
356
357 Before opening, scan the tree of cached files to see if this file is already
358 open for the correct search type. If so, return the saved handle. If not, put
359 the handle in the tree for possible subsequent use. See search_tidyup above for
360 closing all the cached files.
361
362 A count of open databases which use real files is maintained, and if this
363 gets too large, we have to close a cached file. Its entry remains in the tree,
364 but is marked closed.
365
366 Arguments:
367   filename       the name of the file for single-key+file style lookups,
368                  NULL for query-style lookups
369   search_type    the type of search required
370   modemask       if a real single file is used, this specifies mode bits that
371                  must not be set; otherwise it is ignored
372   owners         if a real single file is used, this specifies the possible
373                  owners of the file; otherwise it is ignored
374   owngroups      if a real single file is used, this specifies the possible
375                  group owners of the file; otherwise it is ignored
376
377 Returns:         an identifying handle for the open database;
378                  this is the pointer to the tree block in the
379                  cache of open files; return NULL on open failure, with
380                  a message in search_error_message
381 */
382
383 void *
384 search_open(const uschar * filename, int search_type, int modemask,
385   uid_t * owners, gid_t * owngroups)
386 {
387 void *handle;
388 tree_node *t;
389 search_cache *c;
390 lookup_info *lk = lookup_list[search_type];
391 uschar keybuffer[256];
392 int old_pool = store_pool;
393
394 if (filename && is_tainted(filename))
395   {
396   log_write(0, LOG_MAIN|LOG_PANIC,
397     "Tainted filename for search: '%s'", filename);
398   return NULL;
399   }
400
401 /* Change to the search store pool and remember our reset point */
402
403 store_pool = POOL_SEARCH;
404 if (!search_reset_point) search_reset_point = store_mark();
405
406 DEBUG(D_lookup) debug_printf_indent("search_open: %s \"%s\"\n", lk->name,
407   filename ? filename : US"NULL");
408
409 /* See if we already have this open for this type of search, and if so,
410 pass back the tree block as the handle. The key for the tree node is the search
411 type plus '0' concatenated with the file name. There may be entries in the tree
412 with closed files if a lot of files have been opened. */
413
414 sprintf(CS keybuffer, "%c%.254s", search_type + '0',
415   filename ? filename : US"");
416
417 if ((t = tree_search(search_tree, keybuffer)))
418   {
419   if ((c = (search_cache *)t->data.ptr)->handle)
420     {
421     DEBUG(D_lookup) debug_printf_indent("  cached open\n");
422     store_pool = old_pool;
423     return t;
424     }
425   DEBUG(D_lookup) debug_printf_indent("  cached closed\n");
426   }
427
428 /* Otherwise, we need to open the file or database - each search type has its
429 own code, which is now split off into separately compiled modules. Before doing
430 this, if the search type is one that uses real files, check on the number that
431 we are holding open in the cache. If the limit is reached, close the least
432 recently used one. */
433
434 if (lk->type == lookup_absfile && open_filecount >= lookup_open_max)
435   if (!open_bot)
436     log_write(0, LOG_MAIN|LOG_PANIC, "too many lookups open, but can't find "
437       "one to close");
438   else
439     {
440     search_cache *c = (search_cache *)(open_bot->data.ptr);
441     DEBUG(D_lookup) debug_printf_indent("Too many lookup files open\n  closing %s\n",
442       open_bot->name);
443     if ((open_bot = c->up))
444       ((search_cache *)(open_bot->data.ptr))->down = NULL;
445     else
446       open_top = NULL;
447     ((lookup_list[c->search_type])->close)(c->handle);
448     c->handle = NULL;
449     open_filecount--;
450     }
451
452 /* If opening is successful, call the file-checking function if there is one,
453 and if all is still well, enter the open database into the tree. */
454
455 if (!(handle = (lk->open)(filename, &search_error_message)))
456   {
457   store_pool = old_pool;
458   return NULL;
459   }
460
461 if (  lk->check
462    && !lk->check(handle, filename, modemask, owners, owngroups,
463          &search_error_message))
464   {
465   lk->close(handle);
466   store_pool = old_pool;
467   return NULL;
468   }
469
470 /* If this is a search type that uses real files, keep count. */
471
472 if (lk->type == lookup_absfile) open_filecount++;
473
474 /* If we found a previously opened entry in the tree, re-use it; otherwise
475 insert a new entry. On re-use, leave any cached lookup data and the lookup
476 count alone. */
477
478 if (!t)
479   {
480   t = store_get(sizeof(tree_node) + Ustrlen(keybuffer), GET_UNTAINTED);
481   t->data.ptr = c = store_get(sizeof(search_cache), GET_UNTAINTED);
482   c->item_cache = NULL;
483   Ustrcpy(t->name, keybuffer);
484   tree_insertnode(&search_tree, t);
485   }
486 else c = t->data.ptr;
487
488 c->handle = handle;
489 c->search_type = search_type;
490 c->up = c->down = NULL;
491
492 store_pool = old_pool;
493 return t;
494 }
495
496
497
498
499
500 /*************************************************
501 *  Internal function: Find one item in database  *
502 *************************************************/
503
504 /* The answer is always put into dynamic store. The last lookup for each handle
505 is cached.
506
507 Arguments:
508   handle       the handle from search_open; points to tree node
509   filename     the filename that was handed to search_open, or
510                NULL for query-style searches
511   keystring    the keystring for single-key+file lookups, or
512                the querystring for query-style lookups
513   cache_rd     FALSE to avoid lookup in cache layer
514   opts         type-specific options
515
516 Returns:       a pointer to a dynamic string containing the answer,
517                or NULL if the query failed or was deferred; in the
518                latter case, search_find_defer is set TRUE; after an unusual
519                failure, there may be a message in search_error_message.
520 */
521
522 static uschar *
523 internal_search_find(void * handle, const uschar * filename, uschar * keystring,
524   BOOL cache_rd, const uschar * opts)
525 {
526 tree_node * t = (tree_node *)handle;
527 search_cache * c = (search_cache *)(t->data.ptr);
528 expiring_data * e = NULL;       /* compiler quietening */
529 uschar * data = NULL;
530 int search_type = t->name[0] - '0';
531 int old_pool = store_pool;
532
533 /* Lookups that return DEFER may not always set an error message. So that
534 the callers don't have to test for NULL, set an empty string. */
535
536 search_error_message = US"";
537 f.search_find_defer = FALSE;
538
539 DEBUG(D_lookup) debug_printf_indent("internal_search_find: file=\"%s\"\n  "
540   "type=%s key=\"%s\" opts=%s%s%s\n", filename,
541   lookup_list[search_type]->name, keystring,
542   opts ? "\"" : "", opts, opts ? "\"" : "");
543
544 /* Insurance. If the keystring is empty, just fail. */
545
546 if (keystring[0] == 0) return NULL;
547
548 /* Use the special store pool for search data */
549
550 store_pool = POOL_SEARCH;
551
552 /* Look up the data for the key, unless it is already in the cache for this
553 file. No need to check c->item_cache for NULL, tree_search will do so. Check
554 whether we want to use the cache entry last so that we can always replace it. */
555
556 if (  (t = tree_search(c->item_cache, keystring))
557    && (!(e = t->data.ptr)->expiry || e->expiry > time(NULL))
558    && (!opts && !e->opts  ||  opts && e->opts && Ustrcmp(opts, e->opts) == 0)
559    && cache_rd
560    )
561   { /* Data was in the cache already; set the pointer from the tree node */
562   data = e->data.ptr;
563   DEBUG(D_lookup) debug_printf_indent("cached data used for lookup of %s%s%s\n",
564     keystring,
565     filename ? US"\n  in " : US"", filename ? filename : US"");
566   }
567 else
568   {
569   uint do_cache = UINT_MAX;
570   int keylength = Ustrlen(keystring);
571
572   DEBUG(D_lookup)
573     {
574     if (t)
575       debug_printf_indent("cached data found but %s; ",
576         e->expiry && e->expiry <= time(NULL) ? "out-of-date"
577         : cache_rd ? "wrong opts" : "no_rd option set");
578     debug_printf_indent("%s lookup required for %s%s%s\n",
579       filename ? US"file" : US"database",
580       keystring,
581       filename ? US"\n  in " : US"", filename ? filename : US"");
582     if (!filename && is_tainted(keystring))
583       {
584       debug_printf_indent("                             ");
585       debug_print_taint(keystring);
586       }
587     }
588
589   /* Check that the query, for query-style lookups,
590   is either untainted or properly quoted for the lookup type.
591
592   XXX Should we this move into lf_sqlperform() ?  The server-taint check is there.
593   */
594
595   if (  !filename && lookup_list[search_type]->quote
596      && is_tainted(keystring) && !is_quoted_like(keystring, search_type))
597     {
598     uschar * s = acl_current_verb();
599     if (!s) s = authenticator_current_name();   /* must be before transport */
600     if (!s) s = transport_current_name();       /* must be before router */
601     if (!s) s = router_current_name();  /* GCC ?: would be good, but not in clang */
602     if (!s) s = US"";
603 #ifdef enforce_quote_protection_notyet
604     search_error_message = string_sprintf(
605       "tainted search query is not properly quoted%s: %s%s",
606       s, keystring);
607     f.search_find_defer = TRUE;
608 #else
609      {
610       int q = quoter_for_address(keystring);
611       /* If we're called from a transport, no privs to open the paniclog;
612       the logging punts to using stderr - and that seems to stop the debug
613       stream. */
614       log_write(0,
615         transport_name ? LOG_MAIN : LOG_MAIN|LOG_PANIC,
616         "tainted search query is not properly quoted%s: %s", s, keystring);
617
618       DEBUG(D_lookup) debug_printf_indent("search_type %d (%s) quoting %d (%s)\n",
619         search_type, lookup_list[search_type]->name,
620         q, is_real_quoter(q) ? lookup_list[q]->name : US"none");
621      }
622 #endif
623     }
624
625   /* Call the code for the different kinds of search. DEFER is handled
626   like FAIL, except that search_find_defer is set so the caller can
627   distinguish if necessary. */
628
629   if (lookup_list[search_type]->find(c->handle, filename, keystring, keylength,
630           &data, &search_error_message, &do_cache, opts) == DEFER)
631     f.search_find_defer = TRUE;
632
633   /* A record that has been found is now in data, which is either NULL
634   or points to a bit of dynamic store. Cache the result of the lookup if
635   caching is permitted. Lookups can disable caching, when they did something
636   that changes their data. The mysql and pgsql lookups do this when an
637   UPDATE/INSERT query was executed.  Lookups can also set a TTL for the
638   cache entry; the dnsdb lookup does.
639   Finally, the caller can request no caching by setting an option. */
640
641   else if (do_cache)
642     {
643     DEBUG(D_lookup) debug_printf_indent("%s cache entry\n",
644       t ? "replacing old" : "creating new");
645     if (!t)     /* No existing entry.  Create new one. */
646       {
647       int len = keylength + 1;
648       /* The cache node value should never be expanded so use tainted mem */
649       e = store_get(sizeof(expiring_data) + sizeof(tree_node) + len, GET_TAINTED);
650       t = (tree_node *)(e+1);
651       memcpy(t->name, keystring, len);
652       t->data.ptr = e;
653       tree_insertnode(&c->item_cache, t);
654       }
655       /* Else previous, out-of-date cache entry.  Update with the */
656       /* new result and forget the old one */
657     e->expiry = do_cache == UINT_MAX ? 0 : time(NULL)+do_cache;
658     e->opts = opts ? string_copy(opts) : NULL;
659     e->data.ptr = data;
660     }
661
662 /* If caching was disabled, empty the cache tree. We just set the cache
663 pointer to NULL here, because we cannot release the store at this stage. */
664
665   else
666     {
667     DEBUG(D_lookup) debug_printf_indent("lookup forced cache cleanup\n");
668     c->item_cache = NULL;       /* forget all lookups on this connection */
669     }
670   }
671
672 DEBUG(D_lookup)
673   {
674   if (data)
675     debug_printf_indent("lookup yielded: %s\n", data);
676   else if (f.search_find_defer)
677     debug_printf_indent("lookup deferred: %s\n", search_error_message);
678   else debug_printf_indent("lookup failed\n");
679   }
680
681 /* Return it in new dynamic store in the regular pool */
682
683 store_pool = old_pool;
684 return data ? string_copy(data) : NULL;
685 }
686
687
688
689
690 /*************************************************
691 * Find one item in database, possibly wildcarded *
692 *************************************************/
693
694 /* This function calls the internal function above; once only if there
695 is no partial matching, but repeatedly when partial matching is requested.
696
697 Arguments:
698   handle         the handle from search_open
699   filename       the filename that was handed to search_open, or
700                    NULL for query-style searches
701   keystring      the keystring for single-key+file lookups, or
702                    the querystring for query-style lookups
703   partial        -1 means no partial matching;
704                    otherwise it's the minimum number of components;
705   affix          the affix string for partial matching
706   affixlen       the length of the affix string
707   starflags      SEARCH_STAR and SEARCH_STARAT flags
708   expand_setup   pointer to offset for setting up expansion strings;
709                  don't do any if < 0
710   opts           type-specific options
711
712 Returns:         a pointer to a dynamic string containing the answer,
713                  or NULL if the query failed or was deferred; in the
714                  latter case, search_find_defer is set TRUE
715 */
716
717 uschar *
718 search_find(void * handle, const uschar * filename, uschar * keystring,
719   int partial, const uschar * affix, int affixlen, int starflags,
720   int * expand_setup, const uschar * opts)
721 {
722 tree_node * t = (tree_node *)handle;
723 BOOL set_null_wild = FALSE, cache_rd = TRUE, ret_key = FALSE;
724 uschar * yield;
725
726 DEBUG(D_lookup)
727   {
728   if (partial < 0) affixlen = 99;   /* So that "NULL" prints */
729   debug_printf_indent("search_find: file=\"%s\"\n  key=\"%s\" "
730     "partial=%d affix=%.*s starflags=%x opts=%s%s%s\n",
731     filename ? filename : US"NULL",
732     keystring, partial, affixlen, affix, starflags,
733     opts ? "\"" : "", opts, opts ? "\"" : "");
734
735   }
736
737 /* Parse global lookup options. Also, create a new options list with
738 the global options dropped so that the cache-modifiers are not
739 used in the cache key. */
740
741 if (opts)
742   {
743   int sep = ',';
744   gstring * g = NULL;
745
746   for (uschar * ele; ele = string_nextinlist(&opts, &sep, NULL, 0); )
747     if (Ustrcmp(ele, "ret=key") == 0) ret_key = TRUE;
748     else if (Ustrcmp(ele, "cache=no_rd") == 0) cache_rd = FALSE;
749     else g = string_append_listele(g, ',', ele);
750
751   opts = string_from_gstring(g);
752   }
753
754 /* Arrange to put this database at the top of the LRU chain if it is a type
755 that opens real files. */
756
757 if (  open_top != (tree_node *)handle 
758    && lookup_list[t->name[0]-'0']->type == lookup_absfile)
759   {
760   search_cache *c = (search_cache *)(t->data.ptr);
761   tree_node *up = c->up;
762   tree_node *down = c->down;
763
764   /* Cut it out of the list. A newly opened file will a NULL up pointer.
765   Otherwise there will be a non-NULL up pointer, since we checked above that
766   this block isn't already at the top of the list. */
767
768   if (up)
769     {
770     ((search_cache *)(up->data.ptr))->down = down;
771     if (down)
772       ((search_cache *)(down->data.ptr))->up = up;
773     else
774       open_bot = up;
775     }
776
777   /* Now put it at the head of the list. */
778
779   c->up = NULL;
780   c->down = open_top;
781   if (!open_top) open_bot = t;
782   else ((search_cache *)(open_top->data.ptr))->up = t;
783   open_top = t;
784   }
785
786 DEBUG(D_lookup)
787   {
788   debug_printf_indent("LRU list:\n");
789   for (tree_node *t = open_top; t; )
790     {
791     search_cache *c = (search_cache *)(t->data.ptr);
792     debug_printf_indent("  %s\n", t->name);
793     if (t == open_bot) debug_printf_indent("  End\n");
794     t = c->down;
795     }
796   }
797
798 /* First of all, try to match the key string verbatim. If matched a complete
799 entry but could have been partial, flag to set up variables. */
800
801 yield = internal_search_find(handle, filename, keystring, cache_rd, opts);
802 if (f.search_find_defer) return NULL;
803
804 if (yield) { if (partial >= 0) set_null_wild = TRUE; }
805
806 /* Not matched a complete entry; handle partial lookups, but only if the full
807 search didn't defer. Don't use string_sprintf() to construct the initial key,
808 just in case the original key is too long for the string_sprintf() buffer (it
809 *has* happened!). The case of a zero-length affix has to be treated specially.
810 */
811
812 else if (partial >= 0)
813   {
814   int len = Ustrlen(keystring);
815   uschar *keystring2;
816
817   /* Try with the affix on the front, except for a zero-length affix */
818
819   if (affixlen == 0) keystring2 = keystring; else
820     {
821     keystring2 = store_get(len + affixlen + 1,
822           is_tainted(keystring) || is_tainted(affix) ? GET_TAINTED : GET_UNTAINTED);
823     Ustrncpy(keystring2, affix, affixlen);
824     Ustrcpy(keystring2 + affixlen, keystring);
825     DEBUG(D_lookup) debug_printf_indent("trying partial match %s\n", keystring2);
826     yield = internal_search_find(handle, filename, keystring2, cache_rd, opts);
827     if (f.search_find_defer) return NULL;
828     }
829
830   /* The key in its entirety did not match a wild entry; try chopping off
831   leading components. */
832
833   if (!yield)
834     {
835     int dotcount = 0;
836     uschar *keystring3 = keystring2 + affixlen;
837     uschar *s = keystring3;
838     while (*s != 0) if (*s++ == '.') dotcount++;
839
840     while (dotcount-- >= partial)
841       {
842       while (*keystring3 != 0 && *keystring3 != '.') keystring3++;
843
844       /* If we get right to the end of the string (which will be the last time
845       through this loop), we've failed if the affix is null. Otherwise do one
846       last lookup for the affix itself, but if it is longer than 1 character,
847       remove the last character if it is ".". */
848
849       if (*keystring3 == 0)
850         {
851         if (affixlen < 1) break;
852         if (affixlen > 1 && affix[affixlen-1] == '.') affixlen--;
853         Ustrncpy(keystring2, affix, affixlen);
854         keystring2[affixlen] = 0;
855         keystring3 = keystring2;
856         }
857       else
858         {
859         keystring3 -= affixlen - 1;
860         if (affixlen > 0) Ustrncpy(keystring3, affix, affixlen);
861         }
862
863       DEBUG(D_lookup) debug_printf_indent("trying partial match %s\n", keystring3);
864       yield = internal_search_find(handle, filename, keystring3,
865                 cache_rd, opts);
866       if (f.search_find_defer) return NULL;
867       if (yield)
868         {
869         /* First variable is the wild part; second is the fixed part. Take care
870         to get it right when keystring3 is just "*". */
871
872         if (expand_setup && *expand_setup >= 0)
873           {
874           int fixedlength = Ustrlen(keystring3) - affixlen;
875           int wildlength = Ustrlen(keystring) - fixedlength - 1;
876           *expand_setup += 1;
877           expand_nstring[*expand_setup] = keystring;
878           expand_nlength[*expand_setup] = wildlength;
879           *expand_setup += 1;
880           expand_nstring[*expand_setup] = keystring + wildlength + 1;
881           expand_nlength[*expand_setup] = (fixedlength < 0)? 0 : fixedlength;
882           }
883         break;
884         }
885       keystring3 += affixlen;
886       }
887     }
888
889   else set_null_wild = TRUE; /* Matched a wild entry without any wild part */
890   }
891
892 /* If nothing has been matched, but the option to look for "*@" is set, try
893 replacing everything to the left of @ by *. After a match, the wild part
894 is set to the string to the left of the @. */
895
896 if (!yield  &&  starflags & SEARCH_STARAT)
897   {
898   uschar *atat = Ustrrchr(keystring, '@');
899   if (atat != NULL && atat > keystring)
900     {
901     int savechar;
902     savechar = *(--atat);
903     *atat = '*';
904
905     DEBUG(D_lookup) debug_printf_indent("trying default match %s\n", atat);
906     yield = internal_search_find(handle, filename, atat, cache_rd, opts);
907     *atat = savechar;
908     if (f.search_find_defer) return NULL;
909
910     if (yield && expand_setup && *expand_setup >= 0)
911       {
912       *expand_setup += 1;
913       expand_nstring[*expand_setup] = keystring;
914       expand_nlength[*expand_setup] = atat - keystring + 1;
915       *expand_setup += 1;
916       expand_nstring[*expand_setup] = keystring;
917       expand_nlength[*expand_setup] = 0;
918       }
919     }
920   }
921
922 /* If we still haven't matched anything, and the option to look for "*" is set,
923 try that. If we do match, the first variable (the wild part) is the whole key,
924 and the second is empty. */
925
926 if (!yield  &&  starflags & (SEARCH_STAR|SEARCH_STARAT))
927   {
928   DEBUG(D_lookup) debug_printf_indent("trying to match *\n");
929   yield = internal_search_find(handle, filename, US"*", cache_rd, opts);
930   if (yield && expand_setup && *expand_setup >= 0)
931     {
932     *expand_setup += 1;
933     expand_nstring[*expand_setup] = keystring;
934     expand_nlength[*expand_setup] = Ustrlen(keystring);
935     *expand_setup += 1;
936     expand_nstring[*expand_setup] = keystring;
937     expand_nlength[*expand_setup] = 0;
938     }
939   }
940
941 /* If this was a potentially partial lookup, and we matched either a
942 complete non-wild domain entry, or we matched a wild-carded entry without
943 chopping off any of the domain components, set up the expansion variables
944 (if required) so that the first one is empty, and the second one is the
945 fixed part of the domain. The set_null_wild flag is set only when yield is not
946 NULL. */
947
948 if (set_null_wild && expand_setup && *expand_setup >= 0)
949   {
950   *expand_setup += 1;
951   expand_nstring[*expand_setup] = keystring;
952   expand_nlength[*expand_setup] = 0;
953   *expand_setup += 1;
954   expand_nstring[*expand_setup] = keystring;
955   expand_nlength[*expand_setup] = Ustrlen(keystring);
956   }
957
958 /* If we have a result, check the options to see if the key was wanted rather
959 than the result.  Return a de-tainted version of the key on the grounds that
960 it have been validated by the lookup. */
961
962 if (yield && ret_key)
963   yield = string_copy_taint(keystring, GET_UNTAINTED);
964
965 return yield;
966 }
967
968 /* End of search.c */