64bits fixes.
[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     char *value;
53     ssize_t value_len;
54 } match_condition_t;
55 ARRAY(match_condition_t)
56
57 static const char *condition_names[] = {
58   "unknown",
59   "equals to",
60   "differs from",
61   "contains",
62   "is contained",
63   "is empty"
64 };
65
66 #define CONDITION_INIT { PTK_UNKNOWN, false, MATCH_UNKNOWN, NULL, 0 }
67
68 typedef struct match_config_t {
69     A(match_condition_t) conditions;
70     bool match_all;
71 } match_config_t;
72
73 static match_config_t *match_config_new(void)
74 {
75     return p_new(match_config_t, 1);
76 }
77
78 static inline void match_condition_wipe(match_condition_t *condition)
79 {
80     p_delete(&condition->value);
81     condition->value_len = 0;
82 }
83
84 static void match_config_delete(match_config_t **config)
85 {
86     if (*config) {
87         array_deep_wipe((*config)->conditions, match_condition_wipe);
88         p_delete(config);
89     }
90 }
91
92 static bool match_filter_constructor(filter_t *filter)
93 {
94     match_config_t *config = match_config_new();
95
96 #define PARSE_CHECK(Expr, Str, ...)                                            \
97     if (!(Expr)) {                                                             \
98         err(Str, ##__VA_ARGS__);                                               \
99         match_config_delete(&config);                                          \
100         return false;                                                          \
101     }
102
103     foreach (filter_param_t *param, filter->params) {
104         switch (param->type) {
105           FILTER_PARAM_PARSE_BOOLEAN(MATCH_ALL, config->match_all);
106
107           /* condition parameter is:
108            *  field_name OPERATOR value.
109            *  valid operators are:
110            *    == field_name is strictly equal to
111            *    =i field_name is case insensitively equal to
112            *    != field_name is not equal to
113            *    !i field_name is not case insensitively equal to
114            *    >= field_name contains
115            *    >i field_name contains case insensitively
116            *    <= field_name is contained
117            *    <i field_name is contained case insensitively
118            *    #= field_name is empty or not set
119            *    #i field_name is not empty
120            */
121           case ATK_CONDITION: {
122 #define     IS_OP_START(N)                                                        \
123               ((N) == '=' || (N) == '!' || (N) == '>' || (N) == '<' || (N) == '#')
124 #define     IS_OP_END(N)                                                          \
125               ((N) == '=' || (N) == 'i')
126             match_condition_t condition = CONDITION_INIT;
127             const char *p = skipspaces(param->value);
128             const char *n = p + 1;
129             PARSE_CHECK(isalnum(*p), "invalid field name");
130             for (n = p + 1 ; *n && (isalnum(*n) || *n == '_') ; ++n);
131             PARSE_CHECK(*n && (isspace(*n) || IS_OP_START(*n)),
132                         "invalid condition, expected operator after field name");
133             condition.field = policy_tokenize(p, n - p);
134             PARSE_CHECK(condition.field >= PTK_HELO_NAME
135                         && condition.field < PTK_SMTPD_ACCESS_POLICY,
136                         "invalid field name %.*s", (int)(n - p), p);
137             p = skipspaces(n);
138             n = p + 1;
139             PARSE_CHECK(IS_OP_START(*p) && IS_OP_END(*n),
140                         "invalid operator %2s", p);
141             switch (*p) {
142 #define       CASE_OP(C, Value)                                                         \
143               case C:                                                                   \
144                 condition.condition = MATCH_ ## Value;                                  \
145                 PARSE_CHECK(*n == '=' || *n == 'i', "invalid operator modifier %c", *n);\
146                 condition.case_sensitive = !!(*n == '=');                               \
147                 break;
148               CASE_OP('=', EQUAL);
149               CASE_OP('!', DIFFER);
150               CASE_OP('>', CONTAINS);
151               CASE_OP('<', CONTAINED);
152               CASE_OP('#', EMPTY);
153 #undef        CASE_OP
154             }
155             PARSE_CHECK(condition.condition != MATCH_UNKNOWN,
156                         "invalid operator");
157             if (condition.condition != MATCH_EMPTY) {
158                 p = skipspaces(n + 1);
159                 PARSE_CHECK(*p, "no value defined to check the condition");
160                 condition.value_len = param->value_len - (p - param->value);
161                 condition.value     = p_dupstr(p, condition.value_len);
162             }
163             array_add(config->conditions, condition);
164           } break;
165
166           default: break;
167         }
168     }}
169
170     PARSE_CHECK(config->conditions.len > 0,
171                 "no condition defined");
172     filter->data = config;
173     return true;
174 }
175
176 static void match_filter_destructor(filter_t *filter)
177 {
178     match_config_t *config = filter->data;
179     match_config_delete(&config);
180     filter->data = config;
181 }
182
183 static inline bool match_condition(const match_condition_t *cond, const query_t *query)
184 {
185     const char *field = NULL;
186     switch (cond->field) {
187 #define CASE(Up, Low)                                                          \
188       case PTK_ ## Up: field = query->Low; break;
189       CASE(HELO_NAME, helo_name)
190       CASE(QUEUE_ID, queue_id)
191       CASE(SENDER, sender)
192       CASE(SENDER_DOMAIN, sender_domain)
193       CASE(RECIPIENT, recipient)
194       CASE(RECIPIENT_DOMAIN, recipient_domain)
195       CASE(RECIPIENT_COUNT, recipient_count)
196       CASE(CLIENT_ADDRESS, client_address)
197       CASE(CLIENT_NAME, client_name)
198       CASE(REVERSE_CLIENT_NAME, reverse_client_name)
199       CASE(INSTANCE, instance)
200       CASE(SASL_METHOD, sasl_method)
201       CASE(SASL_USERNAME, sasl_username)
202       CASE(SASL_SENDER, sasl_sender)
203       CASE(SIZE, size)
204       CASE(CCERT_SUBJECT, ccert_subject)
205       CASE(CCERT_ISSUER, ccert_issuer)
206       CASE(CCERT_FINGERPRINT, ccert_fingerprint)
207       CASE(ENCRYPTION_PROTOCOL, encryption_protocol)
208       CASE(ENCRYPTION_CIPHER, encryption_cipher)
209       CASE(ENCRYPTION_KEYSIZE, encryption_keysize)
210       CASE(ETRN_DOMAIN, etrn_domain)
211       CASE(STRESS, stress)
212 #undef CASE
213       default: return false;
214     }
215     debug("running condition: \"%s\" %s %s\"%s\"",
216           field, condition_names[cond->condition],
217           cond->case_sensitive ? "" : "(alternative) ",
218           cond->value ? cond->value : "(none)");
219     switch (cond->condition) {
220       case MATCH_EQUAL:
221       case MATCH_DIFFER:
222         if (field == NULL) {
223             return cond->condition != MATCH_DIFFER;
224         }
225         if (cond->case_sensitive) {
226             return !!((strcmp(field, cond->value) == 0)
227                       ^ (cond->condition == MATCH_DIFFER));
228         } else {
229             return !!((ascii_strcasecmp(field, cond->value) == 0)
230                       ^ (cond->condition == MATCH_DIFFER));
231         }
232         break;
233
234       case MATCH_CONTAINS:
235         if (field == NULL) {
236             return false;
237         }
238         if (cond->case_sensitive) {
239             return strstr(field, cond->value);
240         } else {
241             return m_stristrn(field, cond->value, cond->value_len);
242         }
243         break;
244
245       case MATCH_CONTAINED:
246         if (field == NULL) {
247             return false;
248         }
249         if (cond->case_sensitive) {
250             return strstr(cond->value, field);
251         } else {
252             return m_stristr(cond->value, field);
253         }
254         break;
255
256       case MATCH_EMPTY:
257         return !!((field == NULL || *field == '\0') ^ (!cond->case_sensitive));
258
259       default:
260         assert(false && "invalid condition type");
261     }
262     return true;
263 }
264
265 static filter_result_t match_filter(const filter_t *filter, const query_t *query)
266 {
267     const match_config_t *config = filter->data;
268     foreach (const match_condition_t *condition, config->conditions) {
269         bool r = match_condition(condition, query);
270         if (!r && config->match_all) {
271             debug("condition failed, match_all failed");
272             return HTK_FAIL;
273         } else if (r && !(config->match_all)) {
274             debug("condition succeed, not-match_all succeed");
275             return HTK_MATCH;
276         }
277     }}
278     if (config->match_all) {
279         debug("all conditions matched, match_all succeed");
280         return HTK_MATCH;
281     } else {
282         debug("no condition matched, not-match_all failed");
283         return HTK_FAIL;
284     }
285 }
286
287 static int match_init(void)
288 {
289     filter_type_t type =  filter_register("match", match_filter_constructor,
290                                           match_filter_destructor, match_filter);
291     /* Hooks.
292      */
293     (void)filter_hook_register(type, "abort");
294     (void)filter_hook_register(type, "error");
295     (void)filter_hook_register(type, "match");
296     (void)filter_hook_register(type, "fail");
297
298     /* Parameters.
299      */
300     (void)filter_param_register(type, "match_all");
301     (void)filter_param_register(type, "condition");
302     return 0;
303 }
304 module_init(match_init);