Regex compile cacheing
[exim.git] / src / src / regex_cache.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /*
6  * Copyright (c) The Exim Maintainers 2022
7  * License: GPL
8  */
9
10 /* Caching layers for compiled REs.  There is a local layer in the process,
11 implemented as a tree for inserts and lookup.  This cache is inherited from
12 the daemon, for the process tree deriving from there - but not by re-exec'd
13 proceses or commandline submission processes.
14
15 If the process has to compile, and is not the daemon or a re-exec'd exim,
16 it notifies the use of the RE to the daemon via a unix-domain socket.
17 This is a fire-and-forget send with no response, hence cheap from the point-of
18 view of the sender.  I have not measured the overall comms costs.  The
19 daemon also compiles the RE, and caches the result.
20
21 A second layer would be possible by asking the daemon via the notifier socket
22 (for a result from its cache, or a compile if it must).  The comms overhead
23 is significant, not only for the channel but also for de/serialisation of
24 the compiled object.  This makes it untenable for the primary use-case, the
25 transport process which has been re-exec'd to gain privs - and therefore does not
26 have the daemon-maintained cache.  Using shared-memory might reduce that cost
27 (the attach time for the memory segment will matter); the implimentation
28 would require suitable R/W locks.
29 */
30
31 #include "exim.h"
32
33 typedef struct re_req {
34   uschar        notifier_reqtype;
35   BOOL          caseless;
36   uschar        re[1];          /* extensible */
37 } re_req;
38
39 static tree_node * regex_cache = NULL;
40 static tree_node * regex_caseless_cache = NULL;
41
42 /******************************************************************************/
43
44 static void
45 regex_to_daemon(const uschar * key, BOOL caseless)
46 {
47 int klen = Ustrlen(key) + 1;
48 int rlen = sizeof(re_req) + klen;
49 re_req * req;
50 int fd, old_pool = store_pool;
51
52 DEBUG(D_expand|D_lists)
53   debug_printf_indent("sending RE '%s' to daemon\n", key);
54
55 store_pool = POOL_MAIN;
56   req = store_get(rlen, key);   /* maybe need a size limit */
57 store_pool = old_pool;;
58 req->notifier_reqtype = NOTIFY_REGEX;
59 req->caseless = caseless;
60 memcpy(req->re, key, klen);
61
62 if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) >= 0)
63   {
64   struct sockaddr_un sa_un = {.sun_family = AF_UNIX};
65   ssize_t len = daemon_notifier_sockname(&sa_un);
66
67   if (sendto(fd, req, rlen, 0, (struct sockaddr *)&sa_un, (socklen_t)len) < 0)
68     DEBUG(D_queue_run)
69       debug_printf("%s: sendto %s\n", __FUNCTION__, strerror(errno));
70   close(fd);
71   }
72 else DEBUG(D_queue_run) debug_printf(" socket: %s\n", strerror(errno));
73 }
74
75
76 static const pcre2_code *
77 regex_from_cache(const uschar * key, BOOL caseless)
78 {
79 tree_node * node  =
80   tree_search(caseless ? regex_caseless_cache : regex_cache, key);
81 DEBUG(D_expand|D_lists)
82   debug_printf_indent("compiled %sRE '%s' %sfound in local cache\n",
83                       caseless ? "caseless " : "", key, node ? "" : "not ");
84
85 return node ? node->data.ptr : NULL;
86 }
87
88
89 static void
90 regex_to_cache(const uschar * key, BOOL caseless, const pcre2_code * cre)
91 {
92 PCRE2_SIZE srelen;
93 uschar * sre;
94 tree_node * node;
95
96 node = store_get(sizeof(tree_node) + Ustrlen(key) + 1, key);    /* we are called with STORE_PERM */
97 Ustrcpy(node->name, key);
98 node->data.ptr = (void *)cre;
99
100 if (!tree_insertnode(caseless ? &regex_caseless_cache : &regex_cache, node))
101   { DEBUG(D_expand|D_lists) debug_printf_indent("duplicate key!\n"); }
102 else DEBUG(D_expand|D_lists)
103   debug_printf_indent("compiled RE '%s' saved in local cache\n", key);
104
105 /* Additionally, if not re-execed and not the daemon, tell the daemon of the RE
106 so it can add to the cache */
107
108 if (f.daemon_scion && !f.daemon_listen)
109   regex_to_daemon(key, caseless);
110
111 return;
112 }
113
114 /******************************************************************************/
115
116 /*************************************************
117 *  Compile regular expression and panic on fail  *
118 *************************************************/
119
120 /* This function is called when failure to compile a regular expression leads
121 to a panic exit. In other cases, pcre_compile() is called directly. In many
122 cases where this function is used, the results of the compilation are to be
123 placed in long-lived store, so we temporarily reset the store management
124 functions that PCRE uses if the use_malloc flag is set.
125
126 Argument:
127   pattern     the pattern to compile
128   flags
129    caseless    caseless matching is required
130    cacheable   use (writeback) cache
131   use_malloc  TRUE if compile into malloc store
132
133 Returns:      pointer to the compiled pattern
134 */
135
136 const pcre2_code *
137 regex_must_compile(const uschar * pattern, mcs_flags flags, BOOL use_malloc)
138 {
139 BOOL caseless = !!(flags & MCS_CASELESS);
140 size_t offset;
141 const pcre2_code * yield;
142 int old_pool = store_pool, err;
143
144 /* Optionall, check the cache and return if found */
145
146 if (  flags & MCS_CACHEABLE
147    && (yield = regex_from_cache(pattern, caseless)))
148   return yield;
149
150 store_pool = POOL_PERM;
151
152 if (!(yield = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED,
153   caseless ? PCRE_COPT|PCRE2_CASELESS : PCRE_COPT,
154   &err, &offset, use_malloc ? pcre_mlc_cmp_ctx : pcre_gen_cmp_ctx)))
155   {
156   uschar errbuf[128];
157   pcre2_get_error_message(err, errbuf, sizeof(errbuf));
158   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "regular expression error: "
159     "%s at offset %ld while compiling %s", errbuf, (long)offset, pattern);
160   }
161
162 if (use_malloc)
163   {
164   /*pcre2_general_context_free(gctx);*/
165   }
166
167 if (flags & MCS_CACHEABLE)
168   regex_to_cache(pattern, caseless, yield);
169
170 store_pool = old_pool;
171 return yield;
172 }
173
174
175
176
177 /* Wrapper for pcre2_compile() and error-message handling.
178
179 Arguments:      pattern         regex to compile
180                 flags
181                  caseless       flag for match variant
182                  cacheable      use (writeback) cache
183                 errstr          on error, filled in with error message
184                 cctx            compile-context for pcre2
185
186 Return:         NULL on error, with errstr set. Otherwise, the compiled RE object
187 */
188
189 const pcre2_code *
190 regex_compile(const uschar * pattern, mcs_flags flags, uschar ** errstr,
191   pcre2_compile_context * cctx)
192 {
193 const uschar * key = pattern;
194 BOOL caseless = !!(flags & MCS_CASELESS);
195 int err;
196 PCRE2_SIZE offset;
197 const pcre2_code * yield;
198 int old_pool = store_pool;
199
200 /* Optionally, check the cache and return if found */
201
202 if (  flags & MCS_CACHEABLE
203    && (yield = regex_from_cache(key, caseless)))
204   return yield;
205
206 DEBUG(D_expand|D_lists) debug_printf_indent("compiling %sRE '%s'\n",
207                                 caseless ? "caseless " : "", pattern);
208
209 store_pool = POOL_PERM;
210 if (!(yield = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED,
211                 caseless ? PCRE_COPT|PCRE2_CASELESS : PCRE_COPT,
212                 &err, &offset, cctx)))
213   {
214   uschar errbuf[128];
215   pcre2_get_error_message(err, errbuf, sizeof(errbuf));
216   store_pool = old_pool;
217   *errstr = string_sprintf("regular expression error in "
218             "\"%s\": %s at offset %ld", pattern, errbuf, (long)offset);
219   }
220 else if (flags & MCS_CACHEABLE)
221   regex_to_cache(key, caseless, yield);
222 store_pool = old_pool;
223
224 return yield;
225 }
226
227
228
229 /* Handle a regex notify arriving at the daemon.  We get sent the original RE;
230 compile it (again) and write to the cache.  Later forked procs will be able to
231 read from the cache, unless they re-execed.  Therefore, those latter never bother
232 sending us a notification. */
233
234 void
235 regex_at_daemon(const uschar * reqbuf)
236 {
237 const re_req * req = (const re_req *)reqbuf;
238 uschar * errstr;
239 const pcre2_code * cre = regex_compile(req->re,
240   req->caseless ? MCS_CASELESS | MCS_CACHEABLE : MCS_CACHEABLE,
241   &errstr, pcre_gen_cmp_ctx);
242
243 DEBUG(D_any) if (!cre) debug_printf("%s\n", errstr);
244 return;
245 }