Can remove the sender and/or the recipient from the key of the greylister.
[apps/pfixtools.git] / postlicyd / filter.c
1 /******************************************************************************/
2 /*          pfixtools: a collection of postfix related tools                  */
3 /*          ~~~~~~~~~                                                         */
4 /*  ________________________________________________________________________  */
5 /*                                                                            */
6 /*  Redistribution and use in source and binary forms, with or without        */
7 /*  modification, are permitted provided that the following conditions        */
8 /*  are met:                                                                  */
9 /*                                                                            */
10 /*  1. Redistributions of source code must retain the above copyright         */
11 /*     notice, this list of conditions and the following disclaimer.          */
12 /*  2. Redistributions in binary form must reproduce the above copyright      */
13 /*     notice, this list of conditions and the following disclaimer in the    */
14 /*     documentation and/or other materials provided with the distribution.   */
15 /*  3. The names of its contributors may not be used to endorse or promote    */
16 /*     products derived from this software without specific prior written     */
17 /*     permission.                                                            */
18 /*                                                                            */
19 /*  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND   */
20 /*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE     */
21 /*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR        */
22 /*  PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS    */
23 /*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR    */
24 /*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF      */
25 /*  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  */
26 /*  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN   */
27 /*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)   */
28 /*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF    */
29 /*  THE POSSIBILITY OF SUCH DAMAGE.                                           */
30 /******************************************************************************/
31
32 /*
33  * Copyright © 2008 Florent Bruneau
34  */
35
36 #include "str.h"
37 #include "buffer.h"
38 #include "filter.h"
39
40 static filter_runner_t      runners[FTK_count];
41 static filter_constructor_t constructors[FTK_count];
42 static filter_destructor_t  destructors[FTK_count];
43 static bool                 hooks[FTK_count][HTK_count];
44 static bool                 params[FTK_count][ATK_count];
45
46 static filter_context_constructor_t ctx_constructors[FTK_count];
47 static filter_context_destructor_t  ctx_destructors[FTK_count];
48 static filter_async_handler_t       async_handler = NULL;
49
50 static const filter_hook_t default_hook = {
51     .type      = 0,
52     .value     = (char*)"DUNNO",
53     .counter   = -1,
54     .cost      = 0,
55     .postfix   = true,
56     .async     = false,
57     .filter_id = 0
58 };
59
60 static const filter_hook_t async_hook = {
61     .type      = 0,
62     .value     = NULL,
63     .counter   = -1,
64     .cost      = 0,
65     .postfix   = false,
66     .async     = true,
67     .filter_id = 0
68 };
69
70 uint32_t filter_running = 0;
71
72 filter_type_t filter_register(const char *type, filter_constructor_t constructor,
73                               filter_destructor_t destructor, filter_runner_t runner,
74                               filter_context_constructor_t context_constructor,
75                               filter_context_destructor_t context_destructor)
76 {
77     filter_token tok = filter_tokenize(type, m_strlen(type));
78     CHECK_FILTER(tok);
79
80     runners[tok] = runner;
81     constructors[tok] = constructor;
82     destructors[tok] = destructor;
83
84     ctx_constructors[tok] = context_constructor;
85     ctx_destructors[tok]  = context_destructor;
86     return tok;
87 }
88
89 filter_result_t filter_hook_register(filter_type_t filter,
90                                      const char *name)
91 {
92     filter_result_t tok = hook_tokenize(name, m_strlen(name));
93     CHECK_FILTER(filter);
94     CHECK_HOOK(tok);
95
96     hooks[filter][tok] = true;
97     return tok;
98 }
99
100 filter_param_id_t filter_param_register(filter_type_t filter,
101                                         const char *name)
102 {
103     filter_param_id_t tok = param_tokenize(name, m_strlen(name));
104     CHECK_FILTER(filter);
105     CHECK_PARAM(tok);
106
107     params[filter][tok] = true;
108     return tok;
109 }
110
111 void filter_async_handler_register(filter_async_handler_t handler)
112 {
113     async_handler = handler;
114 }
115
116 bool filter_build(filter_t *filter)
117 {
118     bool ret = true;
119     if (filter->type == FTK_UNKNOWN || filter->name == NULL) {
120         return false;
121     }
122     if (filter->hooks.len > 0) {
123 #       define QSORT_TYPE filter_hook_t
124 #       define QSORT_BASE filter->hooks.data
125 #       define QSORT_NELT filter->hooks.len
126 #       define QSORT_LT(a,b) a->type < b->type
127 #       include "qsort.c"
128     }
129     filter_constructor_t constructor = constructors[filter->type];
130     if (constructor) {
131         ret = constructor(filter);
132     }
133     array_deep_wipe(filter->params, filter_params_wipe);
134     return ret;
135 }
136
137 bool filter_update_references(filter_t *filter, A(filter_t) *filter_list)
138 {
139     foreach (filter_hook_t *hook, filter->hooks) {
140         if (!hook->postfix) {
141             hook->filter_id = filter_find_with_name(filter_list, hook->value);
142             if (hook->filter_id == -1) {
143                 err("invalid filter name %s for hook %s",
144                     hook->value, htokens[hook->type]);
145                 return false;
146             }
147             p_delete(&hook->value);
148         }
149     }}
150     return true;
151 }
152
153 static inline bool filter_check_loop(filter_t *filter, A(filter_t) *array, int level)
154 {
155     if (filter->last_seen == level) {
156         return true;
157     }
158     filter->last_seen = level;
159     foreach (filter_hook_t *hook, filter->hooks) {
160         if (hook->postfix) {
161             continue;
162         }
163         if (hook->filter_id == level) {
164             return false;
165         }
166         if (!filter_check_loop(array_ptr(*array, hook->filter_id), array, level)) {
167             return false;
168         }
169     }}
170     return true;
171 }
172
173 bool filter_check_safety(A(filter_t) *array)
174 {
175     foreach (filter_t *filter, *array) {
176         if (!filter_check_loop(filter, array, __Ai)) {
177             err("the filter tree contains a loop");
178             return false;
179         }
180     }}
181     return true;
182 }
183
184 void filter_wipe(filter_t *filter)
185 {
186     filter_destructor_t destructor = destructors[filter->type];
187     if (destructor) {
188         destructor(filter);
189     }
190     array_deep_wipe(filter->hooks, filter_hook_wipe);
191     array_deep_wipe(filter->params, filter_params_wipe);
192     p_delete(&filter->name);
193 }
194
195 static inline const filter_hook_t *filter_hook_for_result(const filter_t *filter,
196                                                           filter_result_t res)
197 {
198     int start = 0;
199     int end   = filter->hooks.len;
200
201     if (res == HTK_ABORT) {
202         return NULL;
203     }
204     if (res == HTK_ASYNC) {
205         return &async_hook;
206     }
207
208     while (start < end) {
209         int mid = (start + end) / 2;
210         filter_hook_t *hook = array_ptr(filter->hooks, mid);
211         if (hook->type == res) {
212             debug("return hook of type %s, value %s",
213                   htokens[hook->type], hook->value);
214             return hook;
215         } else if (res < hook->type) {
216             end = mid;
217         } else {
218             start = mid + 1;
219         }
220     }
221     warn("missing hook %s for filter %s", htokens[res], filter->name);
222     return &default_hook;
223 }
224
225 const filter_hook_t *filter_run(const filter_t *filter, const query_t *query,
226                                 filter_context_t *context)
227 {
228     debug("running filter %s (%s)", filter->name, ftokens[filter->type]);
229     ++filter_running;
230     filter_result_t res = runners[filter->type](filter, query, context);
231
232     if (res == HTK_ASYNC) {
233         context->current_filter = filter;
234     } else {
235         --filter_running;
236         context->current_filter = NULL;
237     }
238
239     debug("filter run, result is %s", htokens[res]);
240     return filter_hook_for_result(filter, res);
241 }
242
243 bool filter_test(const filter_t *filter, const query_t *query,
244                  filter_context_t *context, filter_result_t result)
245 {
246     return !!(runners[filter->type](filter, query, context) == result);
247 }
248
249 void filter_set_name(filter_t *filter, const char *name, int len)
250 {
251     filter->name = p_dupstr(name, len);
252 }
253
254 bool filter_set_type(filter_t *filter, const char *type, int len)
255 {
256     filter->type = filter_tokenize(type, len);
257     return filter->type != FTK_UNKNOWN;
258 }
259
260 bool filter_add_param(filter_t *filter, const char *name, int name_len,
261                       const char *value, int value_len)
262 {
263     filter_param_t param;
264     param.type = param_tokenize(name, name_len);
265     if (param.type == ATK_UNKNOWN) {
266         err("unknown parameter %.*s", name_len, name);
267         return false;
268     }
269     if (!params[filter->type][param.type]) {
270         err("hook %s is not valid for filter %s",
271             atokens[param.type], ftokens[filter->type]);
272         return false;
273     }
274     param.value     = p_dupstr(value, value_len);
275     param.value_len = value_len;
276     array_add(filter->params, param);
277     return true;
278 }
279
280 bool filter_add_hook(filter_t *filter, const char *name, int name_len,
281                      const char *value, int value_len)
282 {
283     filter_hook_t hook;
284     hook.filter_id = -1;
285     hook.type  = hook_tokenize(name, name_len);
286     if (hook.type == HTK_UNKNOWN) {
287         err("unknown hook type %.*s", name_len, name);
288         return false;
289     }
290     if (!hooks[filter->type][hook.type] || hook.type == HTK_ABORT) {
291         err("hook %s not is valid for filter %s",
292             htokens[hook.type], ftokens[filter->type]);
293         return false;
294     }
295     hook.async   = false;
296
297     /* Value format is (counter:id:incr)?(postfix:reply|filter_name)
298      */
299     hook.value = NULL;
300     if (strncmp(value, "counter:", 8) == 0) {
301         char *end = NULL;
302         value += 8;
303         hook.counter = strtol(value, &end, 10);
304         if (end == value || *end != ':') {
305               err("hook %s, cannot read counter id", htokens[hook.type]);
306               return false;
307         } else if (hook.counter < 0 || hook.counter >= MAX_COUNTERS) {
308             err("hook %s, invalid counter id %d", htokens[hook.type], hook.counter);
309             return false;
310         }
311         value = end + 1;
312         hook.cost = strtol(value, &end, 10);
313         if (end == value || *end != ':') {
314             err("hook %s, cannot read counter increment", htokens[hook.type]);
315             return false;
316         } else if (hook.cost < 0) {
317             err("hook %s, invalid counter increment value %d", htokens[hook.type],
318                 hook.cost);
319             return false;
320         }
321         value = end + 1;
322     } else {
323         hook.counter = -1;
324         hook.cost    = 0;
325     }
326     hook.postfix = (strncmp(value, "postfix:", 8) == 0);
327     if (hook.postfix && query_format(NULL, 0, value + 8, NULL) == -1) {
328         err("invalid formatted text \"%s\"", value + 8);
329         return false;
330     }
331     hook.value = m_strdup(hook.postfix ? value + 8 : value);
332     array_add(filter->hooks, hook);
333     return true;
334 }
335
336 void filter_context_prepare(filter_context_t *context, void *qctx)
337 {
338     for (int i = 0 ; i < FTK_count ; ++i) {
339         if (ctx_constructors[i] != NULL) {
340             context->contexts[i] = ctx_constructors[i]();
341         }
342     }
343     context->current_filter = NULL;
344     context->data = qctx;
345 }
346
347 void filter_context_wipe(filter_context_t *context)
348 {
349     for (int i = 0 ; i < FTK_count ; ++i) {
350         if (ctx_destructors[i] != NULL) {
351             ctx_destructors[i](context->contexts[i]);
352         }
353     }
354 }
355
356 void filter_context_clean(filter_context_t *context)
357 {
358     p_clear(&context->counters, 1);
359     context->instance[0] = '\0';
360 }
361
362 void filter_post_async_result(filter_context_t *context, filter_result_t result)
363 {
364     const filter_t *filter = context->current_filter;
365     const filter_hook_t *hook = NULL;
366
367     if (result == HTK_ASYNC) {
368         return;
369     }
370     --filter_running;
371     hook = filter_hook_for_result(filter, result);
372     async_handler(context, hook);
373 }