pfix-srsd: add a -I option
[apps/pfixtools.git] / postlicyd / match.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 "filter.h"
40 #include "str.h"
41 #include "policy_tokens.h"
42
43 typedef struct match_condition_t {
44     postlicyd_token field;
45     bool case_sensitive;
46     enum {
47         MATCH_UNKNOWN  = 0,
48         MATCH_EQUAL,
49         MATCH_DIFFER,
50         MATCH_CONTAINS,
51         MATCH_CONTAINED,
52         MATCH_EMPTY,
53     } condition;
54
55     static_str_t value;
56 } match_condition_t;
57 ARRAY(match_condition_t)
58
59 static const char *condition_names[] = {
60   "unknown",
61   "equals to",
62   "differs from",
63   "contains",
64   "is contained",
65   "is empty"
66 };
67
68 #define CONDITION_INIT { PTK_UNKNOWN, false, MATCH_UNKNOWN, { NULL, 0 } }
69
70 typedef struct match_config_t {
71     A(match_condition_t) conditions;
72     bool match_all;
73 } match_config_t;
74
75 static match_config_t *match_config_new(void)
76 {
77     return p_new(match_config_t, 1);
78 }
79
80 static inline void match_condition_wipe(match_condition_t *condition)
81 {
82     char *str = (char*)condition->value.str;
83     p_delete(&str);
84     condition->value.str = NULL;
85     condition->value.len = 0;
86 }
87
88 static void match_config_delete(match_config_t **config)
89 {
90     if (*config) {
91         array_deep_wipe((*config)->conditions, match_condition_wipe);
92         p_delete(config);
93     }
94 }
95
96 static bool match_filter_constructor(filter_t *filter)
97 {
98     match_config_t *config = match_config_new();
99
100 #define PARSE_CHECK(Expr, Str, ...)                                            \
101     if (!(Expr)) {                                                             \
102         err(Str, ##__VA_ARGS__);                                               \
103         match_config_delete(&config);                                          \
104         return false;                                                          \
105     }
106
107     foreach (filter_param_t *param, filter->params) {
108         switch (param->type) {
109           FILTER_PARAM_PARSE_BOOLEAN(MATCH_ALL, config->match_all);
110
111           /* condition parameter is:
112            *  field_name OPERATOR value.
113            *  valid operators are:
114            *    == field_name is strictly equal to
115            *    =i field_name is case insensitively equal to
116            *    != field_name is not equal to
117            *    !i field_name is not case insensitively equal to
118            *    >= field_name contains
119            *    >i field_name contains case insensitively
120            *    <= field_name is contained
121            *    <i field_name is contained case insensitively
122            *    #= field_name is empty or not set
123            *    #i field_name is not empty
124            */
125           case ATK_CONDITION: {
126 #define     IS_OP_START(N)                                                        \
127               ((N) == '=' || (N) == '!' || (N) == '>' || (N) == '<' || (N) == '#')
128 #define     IS_OP_END(N)                                                          \
129               ((N) == '=' || (N) == 'i')
130             match_condition_t condition = CONDITION_INIT;
131             const char *p = skipspaces(param->value);
132             const char *n = p + 1;
133             PARSE_CHECK(isalnum(*p), "invalid field name");
134             for (n = p + 1 ; *n && (isalnum(*n) || *n == '_') ; ++n);
135             PARSE_CHECK(*n && (isspace(*n) || IS_OP_START(*n)),
136                         "invalid condition, expected operator after field name");
137             condition.field = policy_tokenize(p, n - p);
138             PARSE_CHECK(condition.field >= PTK_HELO_NAME
139                         && condition.field < PTK_SMTPD_ACCESS_POLICY,
140                         "invalid field name %.*s", (int)(n - p), p);
141             p = skipspaces(n);
142             n = p + 1;
143             PARSE_CHECK(IS_OP_START(*p) && IS_OP_END(*n),
144                         "invalid operator %2s", p);
145             switch (*p) {
146 #define       CASE_OP(C, Value)                                                         \
147               case C:                                                                   \
148                 condition.condition = MATCH_ ## Value;                                  \
149                 PARSE_CHECK(*n == '=' || *n == 'i', "invalid operator modifier %c", *n);\
150                 condition.case_sensitive = !!(*n == '=');                               \
151                 break;
152               CASE_OP('=', EQUAL);
153               CASE_OP('!', DIFFER);
154               CASE_OP('>', CONTAINS);
155               CASE_OP('<', CONTAINED);
156               CASE_OP('#', EMPTY);
157 #undef        CASE_OP
158             }
159             PARSE_CHECK(condition.condition != MATCH_UNKNOWN,
160                         "invalid operator");
161             if (condition.condition != MATCH_EMPTY) {
162                 p = skipspaces(n + 1);
163                 PARSE_CHECK(*p, "no value defined to check the condition");
164                 condition.value.len = param->value_len - (p - param->value);
165                 condition.value.str = p_dupstr(p, condition.value.len);
166             }
167             array_add(config->conditions, condition);
168           } break;
169
170           default: break;
171         }
172     }}
173
174     PARSE_CHECK(config->conditions.len > 0,
175                 "no condition defined");
176     filter->data = config;
177     return true;
178 }
179
180 static void match_filter_destructor(filter_t *filter)
181 {
182     match_config_t *config = filter->data;
183     match_config_delete(&config);
184     filter->data = config;
185 }
186
187 static inline bool match_condition(const match_condition_t *cond, const query_t *query)
188 {
189     const static_str_t *field = query_field_for_id(query, cond->field);
190     debug("running condition: \"%s\" %s %s\"%s\"",
191           field->str, condition_names[cond->condition],
192           cond->case_sensitive ? "" : "(alternative) ",
193           cond->value.str ? cond->value.str : "(none)");
194     switch (cond->condition) {
195       case MATCH_EQUAL:
196       case MATCH_DIFFER:
197         if (field == NULL || field->str == NULL) {
198             return cond->condition != MATCH_DIFFER;
199         }
200         if (cond->case_sensitive) {
201             return !!((strcmp(field->str, cond->value.str) == 0)
202                       ^ (cond->condition == MATCH_DIFFER));
203         } else {
204             return !!((ascii_strcasecmp(field->str, cond->value.str) == 0)
205                       ^ (cond->condition == MATCH_DIFFER));
206         }
207         break;
208
209       case MATCH_CONTAINS:
210         if (field == NULL || field->str == NULL) {
211             return false;
212         }
213         if (cond->case_sensitive) {
214             return strstr(field->str, cond->value.str);
215         } else {
216             return m_stristrn(field->str, cond->value.str, cond->value.len);
217         }
218         break;
219
220       case MATCH_CONTAINED:
221         if (field == NULL || field->str == NULL) {
222             return false;
223         }
224         if (cond->case_sensitive) {
225             return strstr(cond->value.str, field->str);
226         } else {
227             return m_stristr(cond->value.str, field->str);
228         }
229         break;
230
231       case MATCH_EMPTY:
232         return !!((field == NULL || field->len == 0) ^ (!cond->case_sensitive));
233
234       default:
235         assert(false && "invalid condition type");
236     }
237     return true;
238 }
239
240 static filter_result_t match_filter(const filter_t *filter, const query_t *query,
241                                     filter_context_t *context)
242 {
243     const match_config_t *config = filter->data;
244     foreach (const match_condition_t *condition, config->conditions) {
245         bool r = match_condition(condition, query);
246         if (!r && config->match_all) {
247             debug("condition failed, match_all failed");
248             return HTK_FAIL;
249         } else if (r && !(config->match_all)) {
250             debug("condition succeed, not-match_all succeed");
251             return HTK_MATCH;
252         }
253     }}
254     if (config->match_all) {
255         debug("all conditions matched, match_all succeed");
256         return HTK_MATCH;
257     } else {
258         debug("no condition matched, not-match_all failed");
259         return HTK_FAIL;
260     }
261 }
262
263 static int match_init(void)
264 {
265     filter_type_t type =  filter_register("match", match_filter_constructor,
266                                           match_filter_destructor, match_filter,
267                                           NULL, NULL);
268     /* Hooks.
269      */
270     (void)filter_hook_register(type, "abort");
271     (void)filter_hook_register(type, "error");
272     (void)filter_hook_register(type, "match");
273     (void)filter_hook_register(type, "fail");
274
275     /* Parameters.
276      */
277     (void)filter_param_register(type, "match_all");
278     (void)filter_param_register(type, "condition");
279     return 0;
280 }
281 module_init(match_init);