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