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