SPDX: license tags (mostly by guesswork)
[exim.git] / src / src / lookups / lsearch.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 /* SPDX-License-Identifier: GPL-2.0-only */
9
10 #include "../exim.h"
11 #include "lf_functions.h"
12
13 /* Codes for the different kinds of lsearch that are supported */
14
15 enum {
16   LSEARCH_PLAIN,        /* Literal keys */
17   LSEARCH_WILD,         /* Wild card keys, expanded */
18   LSEARCH_NWILD,        /* Wild card keys, not expanded */
19   LSEARCH_IP            /* IP addresses and networks */
20 };
21
22
23
24 /*************************************************
25 *              Open entry point                  *
26 *************************************************/
27
28 /* See local README for interface description */
29
30 static void *
31 lsearch_open(const uschar * filename, uschar ** errmsg)
32 {
33 FILE * f = Ufopen(filename, "rb");
34 if (!f)
35   *errmsg = string_open_failed("%s for linear search", filename);
36 return f;
37 }
38
39
40
41 /*************************************************
42 *             Check entry point                  *
43 *************************************************/
44
45 static BOOL
46 lsearch_check(void *handle, const uschar *filename, int modemask, uid_t *owners,
47   gid_t *owngroups, uschar **errmsg)
48 {
49 return lf_check_file(fileno((FILE *)handle), filename, S_IFREG, modemask,
50   owners, owngroups, "lsearch", errmsg) == 0;
51 }
52
53
54
55 /*************************************************
56 *  Internal function for the various lsearches   *
57 *************************************************/
58
59 /* See local README for interface description, plus:
60
61 Extra argument:
62
63   type     one of the values LSEARCH_PLAIN, LSEARCH_WILD, LSEARCH_NWILD, or
64            LSEARCH_IP
65
66 There is some messy logic in here to cope with very long data lines that do not
67 fit into the fixed sized buffer. Most of the time this will never be exercised,
68 but people do occasionally do weird things. */
69
70 static int
71 internal_lsearch_find(void * handle, const uschar * filename,
72   const uschar * keystring, int length, uschar ** result, uschar ** errmsg,
73   int type, const uschar * opts)
74 {
75 FILE *f = handle;
76 BOOL ret_full = FALSE;
77 int old_pool = store_pool;
78 rmark reset_point = NULL;
79 uschar buffer[4096];
80
81 if (opts)
82   {
83   int sep = ',';
84   uschar * ele;
85
86   while ((ele = string_nextinlist(&opts, &sep, NULL, 0)))
87     if (Ustrcmp(ele, "ret=full") == 0)
88       { ret_full = TRUE; break; }
89   }
90
91 /* Wildcard searches may use up some store, because of expansions. We don't
92 want them to fill up our search store. What we do is set the pool to the main
93 pool and get a point to reset to later. Wildcard searches could also issue
94 lookups, but internal_search_find will take care of that, and the cache will be
95 safely stored in the search pool again. */
96
97 if (type == LSEARCH_WILD || type == LSEARCH_NWILD)
98   {
99   store_pool = POOL_MAIN;
100   reset_point = store_mark();
101   }
102
103 rewind(f);
104 for (BOOL this_is_eol, last_was_eol = TRUE;
105      Ufgets(buffer, sizeof(buffer), f) != NULL;
106      last_was_eol = this_is_eol)
107   {
108   int p = Ustrlen(buffer);
109   int linekeylength;
110   BOOL this_is_comment;
111   gstring * yield;
112   uschar *s = buffer;
113
114   /* Check whether this the final segment of a line. If it follows an
115   incomplete part-line, skip it. */
116
117   this_is_eol = p > 0 && buffer[p-1] == '\n';
118   if (!last_was_eol) continue;
119
120   /* We now have the start of a physical line. If this is a final line segment,
121   remove trailing white space. */
122
123   if (this_is_eol)
124     {
125     while (p > 0 && isspace((uschar)buffer[p-1])) p--;
126     buffer[p] = 0;
127     }
128
129   /* If the buffer is empty it might be (a) a complete empty line, or (b) the
130   start of a line that begins with so much white space that it doesn't all fit
131   in the buffer. In both cases we want to skip the entire physical line.
132
133   If the buffer begins with # it is a comment line; if it begins with white
134   space it is a logical continuation; again, we want to skip the entire
135   physical line. */
136
137   if (buffer[0] == 0 || buffer[0] == '#' || isspace(buffer[0])) continue;
138
139   /* We assume that they key will fit in the buffer. If the key starts with ",
140   read it as a quoted string. We don't use string_dequote() because that uses
141   new store for the result, and we may be doing this many times in a long file.
142   We know that the dequoted string must be shorter than the original, because
143   we are removing the quotes, and also any escape sequences always turn two or
144   more characters into one character. Therefore, we can store the new string in
145   the same buffer. */
146
147   if (*s == '\"')
148     {
149     uschar *t = s++;
150     while (*s && *s != '\"')
151       {
152       *t++ = *s == '\\' ? string_interpret_escape(CUSS &s) : *s;
153       s++;
154       }
155     linekeylength = t - buffer;
156     if (*s) s++;                        /* Past terminating " */
157     if (ret_full)
158       memmove(t, s, Ustrlen(s)+1);      /* copy the rest of line also */
159     }
160
161   /* Otherwise it is terminated by a colon or white space */
162
163   else
164     {
165     while (*s && *s != ':' && !isspace(*s)) s++;
166     linekeylength = s - buffer;
167     }
168
169   /* The matching test depends on which kind of lsearch we are doing */
170
171   switch(type)
172     {
173     /* A plain lsearch treats each key as a literal */
174
175     case LSEARCH_PLAIN:
176       if (linekeylength != length || strncmpic(buffer, keystring, length) != 0)
177         continue;
178       break;      /* Key matched */
179
180     /* A wild lsearch treats each key as a possible wildcarded string; no
181     expansion is done for nwildlsearch. */
182
183     case LSEARCH_WILD:
184     case LSEARCH_NWILD:
185       {
186       int rc;
187       int save = buffer[linekeylength];
188       const uschar *list = buffer;
189       buffer[linekeylength] = 0;
190       rc = match_isinlist(keystring,
191         &list,
192         UCHAR_MAX+1,              /* Single-item list */
193         NULL,                     /* No anchor */
194         NULL,                     /* No caching */
195         MCL_STRING + (type == LSEARCH_WILD ? 0 : MCL_NOEXPAND),
196         TRUE,                     /* Caseless */
197         NULL);
198       buffer[linekeylength] = save;
199       if (rc == FAIL) continue;
200       if (rc == DEFER) return DEFER;
201       }
202
203       /* The key has matched. If the search involved a regular expression, it
204       might have caused numerical variables to be set. However, their values will
205       be in the wrong storage pool for external use. Copying them to the standard
206       pool is not feasible because of the caching of lookup results - a repeated
207       lookup will not match the regular expression again. Therefore, we drop
208       all numeric variables at this point. */
209
210       expand_nmax = -1;
211       break;
212
213     /* Compare an ip address against a list of network/ip addresses. We have to
214     allow for the "*" case specially. */
215
216     case LSEARCH_IP:
217       if (linekeylength == 1 && buffer[0] == '*')
218         {
219         if (length != 1 || keystring[0] != '*') continue;
220         }
221       else if (length == 1 && keystring[0] == '*') continue;
222       else
223         {
224         int maskoffset;
225         int save = buffer[linekeylength];
226         buffer[linekeylength] = 0;
227         if (string_is_ip_address(buffer, &maskoffset) == 0 ||
228             !host_is_in_net(keystring, buffer, maskoffset)) continue;
229         buffer[linekeylength] = save;
230         }
231       break;      /* Key matched */
232     }
233
234   /* The key has matched. Skip spaces after the key, and allow an optional
235   colon after the spaces. This is an odd specification, but it's for
236   compatibility. */
237
238   if (!ret_full)
239     if (Uskip_whitespace(&s) == ':')
240       {
241       s++;
242       Uskip_whitespace(&s);
243       }
244
245   /* Reset dynamic store, if we need to, and revert to the search pool */
246
247   if (reset_point)
248     {
249     reset_point = store_reset(reset_point);
250     store_pool = old_pool;
251     }
252
253   /* Now we want to build the result string to contain the data. There can be
254   two kinds of continuation: (a) the physical line may not all have fitted into
255   the buffer, and (b) there may be logical continuation lines, for which we
256   must convert all leading white space into a single blank.
257
258   Initialize, and copy the first segment of data. */
259
260   this_is_comment = FALSE;
261   yield = string_get(100);
262   if (ret_full)
263     yield = string_cat(yield, buffer);
264   else if (*s)
265     yield = string_cat(yield, s);
266
267   /* Now handle continuations */
268
269   for (last_was_eol = this_is_eol;
270        Ufgets(buffer, sizeof(buffer), f) != NULL;
271        last_was_eol = this_is_eol)
272     {
273     s = buffer;
274     p = Ustrlen(buffer);
275     this_is_eol = p > 0 && buffer[p-1] == '\n';
276
277     /* Remove trailing white space from a physical line end */
278
279     if (this_is_eol)
280       {
281       while (p > 0 && isspace((uschar)buffer[p-1])) p--;
282       buffer[p] = 0;
283       }
284
285     /* If this is not a physical line continuation, skip it entirely if it's
286     empty or starts with #. Otherwise, break the loop if it doesn't start with
287     white space. Otherwise, replace leading white space with a single blank. */
288
289     if (last_was_eol)
290       {
291       this_is_comment = (this_is_comment || (buffer[0] == 0 || buffer[0] == '#'));
292       if (this_is_comment) continue;
293       if (!isspace((uschar)buffer[0])) break;
294       while (isspace((uschar)*s)) s++;
295       *(--s) = ' ';
296       }
297     if (this_is_comment) continue;
298
299     /* Join a physical or logical line continuation onto the result string. */
300
301     yield = string_cat(yield, s);
302     }
303
304   gstring_release_unused(yield);
305   *result = string_from_gstring(yield);
306   return OK;
307   }
308
309 /* Reset dynamic store, if we need to */
310
311 if (reset_point)
312   {
313   store_reset(reset_point);
314   store_pool = old_pool;
315   }
316
317 return FAIL;
318 }
319
320
321 /*************************************************
322 *         Find entry point for lsearch           *
323 *************************************************/
324
325 /* See local README for interface description */
326
327 static int
328 lsearch_find(void * handle, const uschar * filename, const uschar * keystring,
329   int length, uschar ** result, uschar ** errmsg, uint * do_cache,
330   const uschar * opts)
331 {
332 return internal_lsearch_find(handle, filename, keystring, length, result,
333   errmsg, LSEARCH_PLAIN, opts);
334 }
335
336
337
338 /*************************************************
339 *      Find entry point for wildlsearch          *
340 *************************************************/
341
342 /* See local README for interface description */
343
344 static int
345 wildlsearch_find(void * handle, const uschar * filename, const uschar * keystring,
346   int length, uschar ** result, uschar ** errmsg, uint * do_cache,
347   const uschar * opts)
348 {
349 return internal_lsearch_find(handle, filename, keystring, length, result,
350   errmsg, LSEARCH_WILD, opts);
351 }
352
353
354
355 /*************************************************
356 *      Find entry point for nwildlsearch         *
357 *************************************************/
358
359 /* See local README for interface description */
360
361 static int
362 nwildlsearch_find(void * handle, const uschar * filename, const uschar * keystring,
363   int length, uschar ** result, uschar ** errmsg, uint * do_cache,
364   const uschar * opts)
365 {
366 return internal_lsearch_find(handle, filename, keystring, length, result,
367   errmsg, LSEARCH_NWILD, opts);
368 }
369
370
371
372
373 /*************************************************
374 *      Find entry point for iplsearch            *
375 *************************************************/
376
377 /* See local README for interface description */
378
379 static int
380 iplsearch_find(void * handle, uschar const * filename, const uschar * keystring,
381   int length, uschar ** result, uschar ** errmsg, uint * do_cache,
382   const uschar * opts)
383 {
384 if ((length == 1 && keystring[0] == '*') ||
385     string_is_ip_address(keystring, NULL) != 0)
386   return internal_lsearch_find(handle, filename, keystring, length, result,
387     errmsg, LSEARCH_IP, opts);
388
389 *errmsg = string_sprintf("\"%s\" is not a valid iplsearch key (an IP "
390 "address, with optional CIDR mask, is wanted): "
391 "in a host list, use net-iplsearch as the search type", keystring);
392 return DEFER;
393 }
394
395
396
397
398 /*************************************************
399 *              Close entry point                 *
400 *************************************************/
401
402 /* See local README for interface description */
403
404 static void
405 lsearch_close(void *handle)
406 {
407 (void)fclose((FILE *)handle);
408 }
409
410
411
412 /*************************************************
413 *         Version reporting entry point          *
414 *************************************************/
415
416 /* See local README for interface description. */
417
418 #include "../version.h"
419
420 gstring *
421 lsearch_version_report(gstring * g)
422 {
423 #ifdef DYNLOOKUP
424 g = string_fmt_append(g, "Library version: lsearch: Exim version %s\n", EXIM_VERSION_STR));
425 #endif
426 return g;
427 }
428
429
430 static lookup_info iplsearch_lookup_info = {
431   .name = US"iplsearch",                /* lookup name */
432   .type = lookup_absfile,               /* uses absolute file name */
433   .open = lsearch_open,                 /* open function */
434   .check = lsearch_check,               /* check function */
435   .find = iplsearch_find,               /* find function */
436   .close = lsearch_close,               /* close function */
437   .tidy = NULL,                         /* no tidy function */
438   .quote = NULL,                        /* no quoting function */
439   .version_report = NULL                           /* no version reporting (redundant) */
440 };
441
442 static lookup_info lsearch_lookup_info = {
443   .name = US"lsearch",                  /* lookup name */
444   .type = lookup_absfile,               /* uses absolute file name */
445   .open = lsearch_open,                 /* open function */
446   .check = lsearch_check,               /* check function */
447   .find = lsearch_find,                 /* find function */
448   .close = lsearch_close,               /* close function */
449   .tidy = NULL,                         /* no tidy function */
450   .quote = NULL,                        /* no quoting function */
451   .version_report = lsearch_version_report         /* version reporting */
452 };
453
454 static lookup_info nwildlsearch_lookup_info = {
455   .name = US"nwildlsearch",             /* lookup name */
456   .type = lookup_absfile,               /* uses absolute file name */
457   .open = lsearch_open,                 /* open function */
458   .check = lsearch_check,               /* check function */
459   .find = nwildlsearch_find,            /* find function */
460   .close = lsearch_close,               /* close function */
461   .tidy = NULL,                         /* no tidy function */
462   .quote = NULL,                        /* no quoting function */
463   .version_report = NULL                           /* no version reporting (redundant) */
464 };
465
466 static lookup_info wildlsearch_lookup_info = {
467   .name = US"wildlsearch",              /* lookup name */
468   .type = lookup_absfile,               /* uses absolute file name */
469   .open = lsearch_open,                 /* open function */
470   .check = lsearch_check,               /* check function */
471   .find = wildlsearch_find,             /* find function */
472   .close = lsearch_close,               /* close function */
473   .tidy = NULL,                         /* no tidy function */
474   .quote = NULL,                        /* no quoting function */
475   .version_report = NULL                           /* no version reporting (redundant) */
476 };
477
478 #ifdef DYNLOOKUP
479 #define lsearch_lookup_module_info _lookup_module_info
480 #endif
481
482 static lookup_info *_lookup_list[] = { &iplsearch_lookup_info,
483                                        &lsearch_lookup_info,
484                                        &nwildlsearch_lookup_info,
485                                        &wildlsearch_lookup_info };
486 lookup_module_info lsearch_lookup_module_info = { LOOKUP_MODULE_INFO_MAGIC, _lookup_list, 4 };
487
488 /* End of lookups/lsearch.c */