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