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