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