1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2020 - 2024 */
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 */
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.
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
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. */
29 /* Tree in which to cache open files until tidyup called. */
31 static tree_node *search_tree = NULL;
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. */
37 static tree_node *open_top = NULL;
38 static tree_node *open_bot = NULL;
40 /* Count of open databases that use real files */
42 static int open_filecount = 0;
44 /* Allow us to reset store used for lookups and lookup caching */
46 static rmark search_reset_point = NULL;
50 /*************************************************
51 * Validate a plain lookup type name *
52 *************************************************/
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
59 name lookup type name - not necessarily zero terminated (e.g. dbm*)
60 len length of the name
62 Returns: ptr to info struct for the lookup,
63 or NULL with message in search_error_message.
67 search_findtype(const uschar * name, int len)
69 const uschar * s = name[len] ? string_copyn(name, len) : name;
70 tree_node * t = tree_search(lookups_tree, s);
72 if (t) return t->data.ptr;
74 search_error_message = string_sprintf("unknown lookup type \"%s\"", s);
81 /*************************************************
82 * Validate a full lookup type name *
83 *************************************************/
85 /* This function recognizes the "partial-" prefix and also terminating * and *@
89 name the full lookup type name
90 ptypeptr where to put the partial type
91 after subtraction of 1024 or 2048:
92 negative => no partial matching
93 non-negative => minimum number of non-wild components
94 ptypeaff where to put a pointer to the affix
95 the affix is within name if supplied therein
96 otherwise it's a literal string
97 afflen the length of the affix
98 starflags where to put the SEARCH_STAR and SEARCH_STARAT flags
99 opts where to put the options
101 Returns: ptr to info struct for the lookup,
102 or NULL with message in search_error_message.
106 search_findtype_partial(const uschar *name, int *ptypeptr, const uschar **ptypeaff,
107 int *afflen, int *starflags, const uschar ** opts)
109 const lookup_info * li;
111 const uschar * ss = name, * t;
116 /* Check for a partial matching type. It must start with "partial", optionally
117 followed by a sequence of digits. If this is followed by "-", the affix is the
118 default "*." string. Otherwise we expect an affix in parentheses. Affixes are a
119 limited number of characters, not including parens. */
121 if (Ustrncmp(name, "partial", 7) == 0)
127 while (isdigit(*ss)) pv = pv*10 + *ss++ - '0';
129 else pv = 2; /* Default number of wild components */
134 while (ispunct(*ss) && *ss != ')') ss++;
135 if (*ss != ')') goto BAD_TYPE;
136 *afflen = ss++ - *ptypeaff;
138 else if (*ss++ == '-')
146 search_error_message = string_sprintf("format error in lookup type \"%s\"",
152 /* Now we are left with a lookup name, possibly followed by * or *@,
153 and then by options starting with a "," */
156 if ((t = Ustrchr(ss, '*')))
159 *starflags |= (t[1] == '@' ? SEARCH_STARAT : SEARCH_STAR);
164 if ((t = Ustrchr(t, ',')))
167 if (l < len) len = l;
168 *opts = string_copy(t+1);
173 /* Check for the individual search type. Only those that are actually in the
174 binary are valid. For query-style types, "partial" and default types are
177 li = search_findtype(ss, len);
178 if (li && mac_islookup(li, lookup_querystyle))
182 search_error_message = string_sprintf("\"partial\" is not permitted "
183 "for lookup type \"%s\"", ss);
186 if ((*starflags & (SEARCH_STAR|SEARCH_STARAT)) != 0)
188 search_error_message = string_sprintf("defaults using \"*\" or \"*@\" are "
189 "not permitted for lookup type \"%s\"", ss);
199 /* Set the parameters for the three different kinds of lookup.
201 li the info block for the search type
202 search the search-type string
203 query argument for the search; filename or query
204 fnamep pointer to return filename
207 Return: keyquery the search-type (for single-key) or query (for query-type)
210 search_args(const lookup_info * li, uschar * search, uschar * query, uschar ** fnamep,
213 Uskip_whitespace(&query);
214 if (mac_islookup(li, lookup_absfilequery))
215 { /* query-style but with file (sqlite) */
218 /* Check options first for new-style file spec */
219 if (opts) for (uschar * s; s = string_nextinlist(&opts, &sep, NULL, 0); )
220 if (Ustrncmp(s, "file=", 5) == 0)
226 /* If no filename from options, use old-tyle space-sep prefix on query */
230 Uskip_nonwhite(&query);
231 *fnamep = string_copyn(s, query - s);
232 Uskip_whitespace(&query);
236 return query; /* remainder after file skipped */
238 if (!mac_islookup(li, lookup_querystyle))
241 return search; /* modifiers important so use "keyquery" for them */
243 *fnamep = NULL; /* else query-style */
249 /*************************************************
250 * Release cached resources *
251 *************************************************/
253 /* When search_open is called it caches the "file" that it opens in
254 search_tree. The name of the tree node is a concatenation of the search type
255 with the file name. For query-style lookups, the file name is empty. Real files
256 are normally closed only when this tidyup routine is called, typically at the
257 end of sections of code where a number of lookups might occur. However, if too
258 many files are open simultaneously, some get closed beforehand. They can't be
259 removed from the tree. There is also a general tidyup function which is called
260 for the lookup driver, if it exists.
262 First, there is an internal, recursive subroutine.
264 Argument: a pointer to a search_openfile tree node
269 tidyup_subtree(tree_node *t)
271 search_cache * c = (search_cache *)t->data.ptr;
272 if (t->left) tidyup_subtree(t->left);
273 if (t->right) tidyup_subtree(t->right);
274 if (c && c->handle && c->li->close)
275 c->li->close(c->handle);
280 tidy_cb(uschar * name, uschar * ptr, void * ctx)
282 lookup_info * li = (lookup_info *)ptr;
283 if (li->tidy) (li->tidy)();
287 /* The external entry point
296 int old_pool = store_pool;
298 DEBUG(D_lookup) debug_printf_indent("search_tidyup called\n");
300 /* Close individually each cached open file. */
302 store_pool = POOL_SEARCH;
305 tidyup_subtree(search_tree);
308 open_top = open_bot = NULL;
311 /* Call the general tidyup entry for any drivers that have one. */
313 tree_walk(lookups_tree, tidy_cb, NULL);
315 if (search_reset_point) search_reset_point = store_reset(search_reset_point);
316 store_pool = old_pool;
322 /*************************************************
323 * Open search database *
324 *************************************************/
326 /* A mode, and lists of owners and groups, are passed over for checking in
327 the cases where the database is one or more files. Return NULL, with a message
328 pointed to by message, in cases of error.
330 For search types that use a file or files, check up on the mode after
331 opening. It is tempting to do a stat before opening the file, and use it as
332 an existence check. However, doing that opens a small security loophole in
333 that the status could be changed before the file is opened. Can't quite see
334 what problems this might lead to, but you can't be too careful where security
335 is concerned. Fstat() on an open file can normally be expected to succeed,
336 but there are some NFS states where it does not.
338 There are two styles of query: (1) in the "single-key+file" style, a single
339 key string and a file name are given, for example, for linear searches, DBM
340 files, or for NIS. (2) In the "query" style, no "filename" is given; instead
341 just a single query string is passed. This applies to multiple-key lookup
344 Before opening, scan the tree of cached files to see if this file is already
345 open for the correct search type. If so, return the saved handle. If not, put
346 the handle in the tree for possible subsequent use. See search_tidyup above for
347 closing all the cached files.
349 A count of open databases which use real files is maintained, and if this
350 gets too large, we have to close a cached file. Its entry remains in the tree,
351 but is marked closed.
354 filename the name of the file for single-key+file style lookups,
355 NULL for query-style lookups
356 li the info block for the type of search required
357 modemask if a real single file is used, this specifies mode bits that
358 must not be set; otherwise it is ignored
359 owners if a real single file is used, this specifies the possible
360 owners of the file; otherwise it is ignored
361 owngroups if a real single file is used, this specifies the possible
362 group owners of the file; otherwise it is ignored
364 Returns: an identifying handle for the open database;
365 this is the pointer to the tree block in the
366 cache of open files; return NULL on open failure, with
367 a message in search_error_message
371 search_open(const uschar * filename, const lookup_info * li, int modemask,
372 uid_t * owners, gid_t * owngroups)
377 uschar keybuffer[256];
378 int old_pool = store_pool;
380 if (filename && is_tainted(filename))
382 log_write(0, LOG_MAIN|LOG_PANIC,
383 "Tainted filename for search: '%s'", filename);
387 /* Change to the search store pool and remember our reset point */
389 store_pool = POOL_SEARCH;
390 if (!search_reset_point) search_reset_point = store_mark();
392 DEBUG(D_lookup) debug_printf_indent("search_open: %s \"%s\"\n", li->name,
393 filename ? filename : US"NULL");
395 /* See if we already have this open for this type of search, and if so,
396 pass back the tree block as the handle. The key for the tree node is the search
397 type plus '0' concatenated with the file name. There may be entries in the tree
398 with closed files if a lot of files have been opened. */
400 sprintf(CS keybuffer, "%c%.254s", li->acq_num+ '0',
401 filename ? filename : US"");
403 if ((t = tree_search(search_tree, keybuffer)))
405 if ((c = (search_cache *)t->data.ptr)->handle)
407 DEBUG(D_lookup) debug_printf_indent(" cached open\n");
408 store_pool = old_pool;
411 DEBUG(D_lookup) debug_printf_indent(" cached closed\n");
414 /* Otherwise, we need to open the file or database - each search type has its
415 own code, which is now split off into separately compiled modules. Before doing
416 this, if the search type is one that uses real files, check on the number that
417 we are holding open in the cache. If the limit is reached, close the least
418 recently used one. */
420 if (li->type == lookup_absfile && open_filecount >= lookup_open_max)
422 log_write(0, LOG_MAIN|LOG_PANIC, "too many lookups open, but can't find "
426 search_cache *c = (search_cache *)(open_bot->data.ptr);
427 DEBUG(D_lookup) debug_printf_indent("Too many lookup files open\n closing %s\n",
429 if ((open_bot = c->up))
430 ((search_cache *)(open_bot->data.ptr))->down = NULL;
433 ((c->li)->close)(c->handle);
438 /* If opening is successful, call the file-checking function if there is one,
439 and if all is still well, enter the open database into the tree. */
441 if (!(handle = (li->open)(filename, &search_error_message)))
443 store_pool = old_pool;
448 && !li->check(handle, filename, modemask, owners, owngroups,
449 &search_error_message))
452 store_pool = old_pool;
456 /* If this is a search type that uses real files, keep count. */
458 if (li->type == lookup_absfile) open_filecount++;
460 /* If we found a previously opened entry in the tree, re-use it; otherwise
461 insert a new entry. On re-use, leave any cached lookup data and the lookup
466 t = store_get(sizeof(tree_node) + Ustrlen(keybuffer), GET_UNTAINTED);
467 t->data.ptr = c = store_get(sizeof(search_cache), GET_UNTAINTED);
468 c->item_cache = NULL;
469 Ustrcpy(t->name, keybuffer);
470 tree_insertnode(&search_tree, t);
472 else c = t->data.ptr;
476 c->up = c->down = NULL;
478 store_pool = old_pool;
486 /*************************************************
487 * Internal function: Find one item in database *
488 *************************************************/
490 /* The answer is always put into dynamic store. The last lookup for each handle
494 handle the handle from search_open; points to tree node
495 filename the filename that was handed to search_open, or
496 NULL for query-style searches
497 keystring the keystring for single-key+file lookups, or
498 the querystring for query-style lookups
499 cache_rd FALSE to avoid lookup in cache layer
500 opts type-specific options
502 Returns: a pointer to a dynamic string containing the answer,
503 or NULL if the query failed or was deferred; in the
504 latter case, search_find_defer is set TRUE; after an unusual
505 failure, there may be a message in search_error_message.
509 internal_search_find(void * handle, const uschar * filename,
510 const uschar * keystring, BOOL cache_rd, const uschar * opts)
512 tree_node * t = (tree_node *)handle;
513 search_cache * c = (search_cache *)(t->data.ptr);
514 const lookup_info * li = c->li;
515 expiring_data * e = NULL; /* compiler quietening */
516 uschar * data = NULL;
517 int quoter_id = li->acq_num;
518 int old_pool = store_pool;
520 /* Lookups that return DEFER may not always set an error message. So that
521 the callers don't have to test for NULL, set an empty string. */
523 search_error_message = US"";
524 f.search_find_defer = FALSE;
526 DEBUG(D_lookup) debug_printf_indent("internal_search_find: file=\"%s\"\n "
527 "type=%s key=\"%s\" opts=%s%s%s\n", filename,
528 li->name, keystring, opts ? "\"" : "", opts, opts ? "\"" : "");
530 /* Insurance. If the keystring is empty, just fail. */
532 if (keystring[0] == 0) return NULL;
534 /* Use the special store pool for search data */
536 store_pool = POOL_SEARCH;
538 /* Look up the data for the key, unless it is already in the cache for this
539 file. No need to check c->item_cache for NULL, tree_search will do so. Check
540 whether we want to use the cache entry last so that we can always replace it. */
542 if ( (t = tree_search(c->item_cache, keystring))
543 && (!(e = t->data.ptr)->expiry || e->expiry > time(NULL))
544 && (!opts && !e->opts || opts && e->opts && Ustrcmp(opts, e->opts) == 0)
547 { /* Data was in the cache already; set the pointer from the tree node */
549 DEBUG(D_lookup) debug_printf_indent("cached data used for lookup of %s%s%s\n",
551 filename ? US"\n in " : US"", filename ? filename : US"");
555 uint do_cache = UINT_MAX;
556 int keylength = Ustrlen(keystring);
561 debug_printf_indent("cached data found but %s; ",
562 e->expiry && e->expiry <= time(NULL) ? "out-of-date"
563 : cache_rd ? "wrong opts" : "no_rd option set");
564 debug_printf_indent("%s lookup required for %s%s%s\n",
565 filename ? US"file" : US"database",
567 filename ? US"\n in " : US"", filename ? filename : US"");
568 if (!filename && is_tainted(keystring))
570 debug_printf_indent(" ");
571 debug_print_taint(keystring);
575 /* Check that the query, for query-style lookups,
576 is either untainted or properly quoted for the lookup type.
578 XXX Should we this move into lf_sqlperform() ? The server-taint check is there.
579 Also it already knows about looking for a "servers" spec in the query string.
580 Passing quoter_id down that far is an issue.
583 if ( !filename && li->quote
584 && is_tainted(keystring) && !is_quoted_like(keystring, quoter_id))
586 const uschar * ks = keystring;
587 uschar * loc = acl_current_verb();
588 if (!loc) loc = authenticator_current_name(); /* must be before transport */
589 if (!loc) loc = transport_current_name(); /* must be before router */
590 if (!loc) loc = router_current_name(); /* GCC ?: would be good, but not in clang */
591 if (!loc) loc = US"";
593 if (Ustrncmp(ks, "servers", 7) == 0) /* Avoid logging server/password */
594 if ((ks = Ustrchr(keystring, ';')))
595 while (isspace(*++ks))
600 #ifdef enforce_quote_protection_notyet
601 search_error_message = string_sprintf(
602 "tainted search query is not properly quoted%s: %s%s",
604 f.search_find_defer = TRUE;
607 /* If we're called from a transport, no privs to open the paniclog;
608 the logging punts to using stderr - and that seems to stop the debug
611 transport_name ? LOG_MAIN : LOG_MAIN|LOG_PANIC,
612 "tainted search query is not properly quoted%s: %s", loc, ks);
616 int q = quoter_for_address(ks);
617 const lookup_info * qli = lookup_with_acq_num(q);
619 debug_printf_indent("quoter_id %d (%s) quoting %d (%s)\n",
622 is_real_quoter(q) ? qli ? qli->name : US"???" : US"none");
627 /* Call the code for the different kinds of search. DEFER is handled
628 like FAIL, except that search_find_defer is set so the caller can
629 distinguish if necessary. */
631 if (li->find(c->handle, filename, keystring, keylength,
632 &data, &search_error_message, &do_cache, opts) == DEFER)
633 f.search_find_defer = TRUE;
635 /* A record that has been found is now in data, which is either NULL
636 or points to a bit of dynamic store. Cache the result of the lookup if
637 caching is permitted. Lookups can disable caching, when they did something
638 that changes their data. The mysql and pgsql lookups do this when an
639 UPDATE/INSERT query was executed. Lookups can also set a TTL for the
640 cache entry; the dnsdb lookup does.
641 Finally, the caller can request no caching by setting an option. */
645 DEBUG(D_lookup) debug_printf_indent("%s cache entry\n",
646 t ? "replacing old" : "creating new");
647 if (!t) /* No existing entry. Create new one. */
649 int len = keylength + 1;
650 /* The cache node value should never be expanded so use tainted mem */
651 e = store_get(sizeof(expiring_data) + sizeof(tree_node) + len, GET_TAINTED);
652 t = (tree_node *)(e+1);
653 memcpy(t->name, keystring, len);
655 tree_insertnode(&c->item_cache, t);
657 /* Else previous, out-of-date cache entry. Update with the */
658 /* new result and forget the old one */
659 e->expiry = do_cache == UINT_MAX ? 0 : time(NULL)+do_cache;
660 e->opts = opts ? string_copy(opts) : NULL;
664 /* If caching was disabled, empty the cache tree. We just set the cache
665 pointer to NULL here, because we cannot release the store at this stage. */
669 DEBUG(D_lookup) debug_printf_indent("lookup forced cache cleanup\n");
670 c->item_cache = NULL; /* forget all lookups on this connection */
678 debug_printf_indent("lookup yielded: %W\n", data);
679 else if (f.search_find_defer)
680 debug_printf_indent("lookup deferred: %s\n", search_error_message);
681 else debug_printf_indent("lookup failed\n");
684 /* Return it in new dynamic store in the regular pool */
686 store_pool = old_pool;
687 return data ? string_copy(data) : NULL;
693 /*************************************************
694 * Find one item in database, possibly wildcarded *
695 *************************************************/
697 /* This function calls the internal function above; once only if there
698 is no partial matching, but repeatedly when partial matching is requested.
701 handle the handle from search_open
702 filename the filename that was handed to search_open, or
703 NULL for query-style searches
704 keystring the keystring for single-key+file lookups, or
705 the querystring for query-style lookups
706 partial -1 means no partial matching;
707 otherwise it's the minimum number of components;
708 affix the affix string for partial matching
709 affixlen the length of the affix string
710 starflags SEARCH_STAR and SEARCH_STARAT flags
711 expand_setup pointer to offset for setting up expansion strings;
713 opts type-specific options
715 Returns: a pointer to a dynamic string containing the answer,
716 or NULL if the query failed or was deferred; in the
717 latter case, search_find_defer is set TRUE
721 search_find(void * handle, const uschar * filename, const uschar * keystring,
722 int partial, const uschar * affix, int affixlen, int starflags,
723 int * expand_setup, const uschar * opts)
725 tree_node * t = (tree_node *)handle;
726 BOOL set_null_wild = FALSE, cache_rd = TRUE, ret_key = FALSE;
731 if (partial < 0) affixlen = 99; /* So that "NULL" prints */
732 debug_printf_indent("search_find: file=\"%s\"\n key=\"%s\" "
733 "partial=%d affix=%.*s starflags=%x opts=%s%s%s\n",
734 filename ? filename : US"NULL",
735 keystring, partial, affixlen, affix, starflags,
736 opts ? "\"" : "", opts, opts ? "\"" : "");
740 /* Parse global lookup options. Also, create a new options list with
741 the global options dropped so that the cache-modifiers are not
742 used in the cache key. */
749 for (uschar * ele; ele = string_nextinlist(&opts, &sep, NULL, 0); )
750 if (Ustrcmp(ele, "ret=key") == 0) ret_key = TRUE;
751 else if (Ustrcmp(ele, "cache=no_rd") == 0) cache_rd = FALSE;
752 else g = string_append_listele(g, ',', ele);
754 opts = string_from_gstring(g);
757 /* Arrange to put this database at the top of the LRU chain if it is a type
758 that opens real files. */
760 if (open_top != (tree_node *)handle)
762 const lookup_info * li = lookup_with_acq_num(t->name[0]-'0');
763 if (li && li->type == lookup_absfile)
765 search_cache *c = (search_cache *)(t->data.ptr);
766 tree_node *up = c->up;
767 tree_node *down = c->down;
769 /* Cut it out of the list. A newly opened file will a NULL up pointer.
770 Otherwise there will be a non-NULL up pointer, since we checked above that
771 this block isn't already at the top of the list. */
775 ((search_cache *)(up->data.ptr))->down = down;
777 ((search_cache *)(down->data.ptr))->up = up;
782 /* Now put it at the head of the list. */
786 if (!open_top) open_bot = t;
787 else ((search_cache *)(open_top->data.ptr))->up = t;
794 debug_printf_indent("LRU list:\n");
795 for (tree_node *t = open_top; t; )
797 search_cache *c = (search_cache *)(t->data.ptr);
798 debug_printf_indent(" %s\n", t->name);
799 if (t == open_bot) debug_printf_indent(" End\n");
804 /* First of all, try to match the key string verbatim. If matched a complete
805 entry but could have been partial, flag to set up variables. */
807 yield = internal_search_find(handle, filename, keystring, cache_rd, opts);
808 if (f.search_find_defer) return NULL;
810 if (yield) { if (partial >= 0) set_null_wild = TRUE; }
812 /* Not matched a complete entry; handle partial lookups, but only if the full
813 search didn't defer. Don't use string_sprintf() to construct the initial key,
814 just in case the original key is too long for the string_sprintf() buffer (it
815 *has* happened!). The case of a zero-length affix has to be treated specially.
818 else if (partial >= 0)
820 int len = Ustrlen(keystring);
823 /* Try with the affix on the front, except for a zero-length affix */
826 keystring2 = string_copy(keystring);
829 keystring2 = store_get(len + affixlen + 1,
830 is_tainted(keystring) || is_tainted(affix) ? GET_TAINTED : GET_UNTAINTED);
831 Ustrncpy(keystring2, affix, affixlen);
832 Ustrcpy(keystring2 + affixlen, keystring);
833 DEBUG(D_lookup) debug_printf_indent("trying partial match %s\n", keystring2);
834 yield = internal_search_find(handle, filename, CUS keystring2, cache_rd, opts);
835 if (f.search_find_defer) return NULL;
838 /* The key in its entirety did not match a wild entry; try chopping off
839 leading components. */
844 uschar * keystring3 = keystring2 + affixlen;
846 for(uschar * s = keystring3; *s; ) if (*s++ == '.') dotcount++;
848 while (dotcount-- >= partial)
850 while (*keystring3 && *keystring3 != '.') keystring3++;
852 /* If we get right to the end of the string (which will be the last time
853 through this loop), we've failed if the affix is null. Otherwise do one
854 last lookup for the affix itself, but if it is longer than 1 character,
855 remove the last character if it is ".". */
859 if (affixlen < 1) break;
860 if (affixlen > 1 && affix[affixlen-1] == '.') affixlen--;
861 Ustrncpy(keystring2, affix, affixlen);
862 keystring2[affixlen] = 0;
863 keystring3 = keystring2;
867 keystring3 -= affixlen - 1;
868 if (affixlen > 0) Ustrncpy(keystring3, affix, affixlen);
871 DEBUG(D_lookup) debug_printf_indent("trying partial match %s\n", keystring3);
872 yield = internal_search_find(handle, filename, CUS keystring3,
874 if (f.search_find_defer) return NULL;
877 /* First variable is the wild part; second is the fixed part. Take care
878 to get it right when keystring3 is just "*". Return a de-tainted version
879 of the fixed part, on the grounds it has been validated by the lookup. */
881 if (expand_setup && *expand_setup >= 0)
883 int fixedlength = Ustrlen(keystring3) - affixlen;
884 int wildlength = Ustrlen(keystring) - fixedlength - 1;
886 expand_nstring[*expand_setup] = keystring;
887 expand_nlength[*expand_setup] = wildlength;
889 if (fixedlength < 0) fixedlength = 0;
890 expand_nstring[*expand_setup] = string_copyn_taint(
891 keystring + wildlength + 1, fixedlength, GET_UNTAINTED);
892 expand_nlength[*expand_setup] = fixedlength;
896 keystring3 += affixlen;
900 else set_null_wild = TRUE; /* Matched a wild entry without any wild part */
903 /* If nothing has been matched, but the option to look for "*@" is set, try
904 replacing everything to the left of @ by *. After a match, the wild part
905 is set to the string to the left of the @. */
907 if (!yield && starflags & SEARCH_STARAT)
909 uschar *atat = Ustrrchr(keystring, '@');
910 if (atat && atat > keystring)
916 DEBUG(D_lookup) debug_printf_indent("trying default match %s\n", atat);
917 yield = internal_search_find(handle, filename, atat, cache_rd, opts);
919 if (f.search_find_defer) return NULL;
921 if (yield && expand_setup && *expand_setup >= 0)
924 expand_nstring[*expand_setup] = keystring;
925 expand_nlength[*expand_setup] = atat - keystring + 1;
927 expand_nstring[*expand_setup] = keystring;
928 expand_nlength[*expand_setup] = 0;
933 /* If we still haven't matched anything, and the option to look for "*" is set,
934 try that. If we do match, the first variable (the wild part) is the whole key,
935 and the second is empty. */
937 if (!yield && starflags & (SEARCH_STAR|SEARCH_STARAT))
939 DEBUG(D_lookup) debug_printf_indent("trying to match *\n");
940 yield = internal_search_find(handle, filename, US"*", cache_rd, opts);
941 if (yield && expand_setup && *expand_setup >= 0)
944 expand_nstring[*expand_setup] = keystring;
945 expand_nlength[*expand_setup] = Ustrlen(keystring);
947 expand_nstring[*expand_setup] = keystring;
948 expand_nlength[*expand_setup] = 0;
952 /* If this was a potentially partial lookup, and we matched either a
953 complete non-wild domain entry, or we matched a wild-carded entry without
954 chopping off any of the domain components, set up the expansion variables
955 (if required) so that the first one is empty, and the second one is the
956 fixed part of the domain. The set_null_wild flag is set only when yield is not
957 NULL. Return a de-tainted version of the fixed part, on the grounds it has been
958 validated by the lookup. */
960 if (set_null_wild && expand_setup && *expand_setup >= 0)
962 int fixedlength = Ustrlen(keystring);
964 expand_nstring[*expand_setup] = keystring;
965 expand_nlength[*expand_setup] = 0;
967 expand_nstring[*expand_setup] = string_copyn_taint(
968 keystring, fixedlength, GET_UNTAINTED);
969 expand_nlength[*expand_setup] = fixedlength;
972 /* If we have a result, check the options to see if the key was wanted rather
973 than the result. Return a de-tainted version of the key on the grounds that
974 it have been validated by the lookup. */
976 if (yield && ret_key)
978 yield = string_copy_taint(keystring, GET_UNTAINTED);
980 debug_printf_indent("lookup yield replace by key: %s\n", yield);
986 /* End of search.c */