Cleanup logging.
[apps/pfixtools.git] / postlicyd / rbl.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 © 2007 Pierre Habouzit
34  * Copyright © 2008 Florent Bruneau
35  */
36
37 #include <arpa/inet.h>
38 #include <netinet/in.h>
39 #include <sys/mman.h>
40
41 #include "common.h"
42 #include "rbl.h"
43 #include "str.h"
44 #include "file.h"
45 #include "array.h"
46
47 #define IPv4_BITS        5
48 #define IPv4_PREFIX(ip)  ((uint32_t)(ip) >> IPv4_BITS)
49 #define IPv4_SUFFIX(ip)  ((uint32_t)(ip) & ((1 << IPv4_BITS) - 1))
50 #define NODE(db, i)      ((db)->tree + (i))
51 #ifndef DEBUG
52 #define DEBUG(...)
53 #endif
54
55 /* Implementation */
56
57 enum {
58     BALANCED    = 0,
59     LEFT_HEAVY  = 1,
60     RIGHT_HEAVY = 2,
61 };
62
63 struct rbldb_t {
64     A(uint32_t) ips;
65 };
66 ARRAY(rbldb_t)
67
68 static int get_o(const char *s, const char **out)
69 {
70     int res = 0;
71
72     if (*s < '0' || *s > '9')
73         return -1;
74
75     res = *s++ - '0';
76     if (*s < '0' || *s > '9')
77         goto ok;
78
79     res = res * 10 + *s++ - '0';
80     if (*s < '0' || *s > '9')
81         goto ok;
82
83     res = res * 10 + *s++ - '0';
84     if (!(*s < '0' || *s > '9') || res < 100)
85         return -1;
86
87   ok:
88     *out = s;
89     return res;
90 }
91
92 static int parse_ipv4(const char *s, const char **out, uint32_t *ip)
93 {
94     int o;
95
96     o = get_o(s, &s);
97     if ((o & ~0xff) || *s++ != '.')
98         return -1;
99     *ip = o << 24;
100
101     o = get_o(s, &s);
102     if ((o & ~0xff) || *s++ != '.')
103         return -1;
104     *ip |= o << 16;
105
106     o = get_o(s, &s);
107     if ((o & ~0xff) || *s++ != '.')
108         return -1;
109     *ip |= o << 8;
110
111     o = get_o(s, &s);
112     if (o & ~0xff)
113         return -1;
114     *ip |= o;
115
116     *out = s;
117     return 0;
118 }
119
120 rbldb_t *rbldb_create(const char *file, bool lock)
121 {
122     rbldb_t *db;
123     file_map_t map;
124     const char *p, *end;
125
126     if (!file_map_open(&map, file, false)) {
127         return NULL;
128     }
129
130     p   = map.map;
131     end = map.end;
132     while (end > p && end[-1] != '\n') {
133         --end;
134     }
135     if (end != map.end) {
136         warn("file %s miss a final \\n, ignoring last line",
137              file);
138     }
139
140     db = p_new(rbldb_t, 1);
141     while (p < end) {
142         uint32_t ip;
143
144         while (*p == ' ' || *p == '\t' || *p == '\r')
145             p++;
146
147         if (parse_ipv4(p, &p, &ip) < 0) {
148             p = (char *)memchr(p, '\n', end - p) + 1;
149         } else {
150             array_add(db->ips, ip);
151         }
152     }
153     file_map_close(&map);
154
155     /* Lookup may perform serveral I/O, so avoid swap.
156      */
157     array_adjust(db->ips);
158     if (lock && !array_lock(db->ips)) {
159         UNIXERR("mlock");
160     }
161
162     if (db->ips.len) {
163 #       define QSORT_TYPE uint32_t
164 #       define QSORT_BASE db->ips.data
165 #       define QSORT_NELT db->ips.len
166 #       define QSORT_LT(a,b) *a < *b
167 #       include "qsort.c"
168     }
169
170     info("rbl %s loaded, %d IPs", file, db->ips.len);
171     return db;
172 }
173
174 static void rbldb_wipe(rbldb_t *db)
175 {
176     array_wipe(db->ips);
177 }
178
179 void rbldb_delete(rbldb_t **db)
180 {
181     if (*db) {
182         rbldb_wipe(*db);
183         p_delete(&(*db));
184     }
185 }
186
187 uint32_t rbldb_stats(const rbldb_t *rbl)
188 {
189     return rbl->ips.len;
190 }
191
192 bool rbldb_ipv4_lookup(const rbldb_t *db, uint32_t ip)
193 {
194     int l = 0, r = db->ips.len;
195
196     while (l < r) {
197         int i = (r + l) / 2;
198
199         if (array_elt(db->ips, i) == ip)
200             return true;
201
202         if (ip < array_elt(db->ips, i)) {
203             r = i;
204         } else {
205             l = i + 1;
206         }
207     }
208     return false;
209 }
210
211
212 /* postlicyd filter declaration */
213
214 #include "filter.h"
215
216 typedef struct rbl_filter_t {
217     PA(rbldb_t) rbls;
218     A(int)      weights;
219
220     int32_t     hard_threshold;
221     int32_t     soft_threshold;
222 } rbl_filter_t;
223
224 static rbl_filter_t *rbl_filter_new(void)
225 {
226     return p_new(rbl_filter_t, 1);
227 }
228
229 static void rbl_filter_delete(rbl_filter_t **rbl)
230 {
231     if (*rbl) {
232         array_deep_wipe((*rbl)->rbls, rbldb_delete);
233         array_wipe((*rbl)->weights);
234         p_delete(rbl);
235     }
236 }
237
238
239 static bool rbl_filter_constructor(filter_t *filter)
240 {
241     rbl_filter_t *data = rbl_filter_new();
242
243 #define PARSE_CHECK(Expr, Str, ...)                                            \
244     if (!(Expr)) {                                                             \
245         err(Str, ##__VA_ARGS__);                                               \
246         rbl_filter_delete(&data);                                              \
247         return false;                                                          \
248     }
249
250     data->hard_threshold = 1;
251     data->soft_threshold = 1;
252     foreach (filter_param_t *param, filter->params) {
253         switch (param->type) {
254           /* file parameter is:
255            *  [no]lock:weight:filename
256            *  valid options are:
257            *    - lock:   memlock the database in memory.
258            *    - nolock: don't memlock the database in memory [default].
259            *    - \d+:    a number describing the weight to give to the match
260            *              the given list [mandatory]
261            *  the file pointed by filename MUST be a valid ip list issued from
262            *  the rsync (or equivalent) service of a (r)bl.
263            */
264           case ATK_FILE: {
265             bool lock = false;
266             int  weight = 0;
267             rbldb_t *rbl = NULL;
268             const char *current = param->value;
269             const char *p = m_strchrnul(param->value, ':');
270             char *next = NULL;
271             for (int i = 0 ; i < 3 ; ++i) {
272                 PARSE_CHECK(i == 2 || *p,
273                             "file parameter must contains a locking state "
274                             "and a weight option");
275                 switch (i) {
276                   case 0:
277                     if ((p - current) == 4 && strncmp(current, "lock", 4) == 0) {
278                         lock = true;
279                     } else if ((p - current) == 6
280                                && strncmp(current, "nolock", 6) == 0) {
281                         lock = false;
282                     } else {
283                         PARSE_CHECK(false, "illegal locking state %.*s",
284                                     p - current, current);
285                     }
286                     break;
287
288                   case 1:
289                     weight = strtol(current, &next, 10);
290                     PARSE_CHECK(next == p && weight >= 0 && weight <= 1024,
291                                 "illegal weight value %.*s",
292                                 (p - current), current);
293                     break;
294
295                   case 2:
296                     rbl = rbldb_create(current, lock);
297                     PARSE_CHECK(rbl != NULL,
298                                 "cannot load rbl db from %s", current);
299                     array_add(data->rbls, rbl);
300                     array_add(data->weights, weight);
301                     break;
302                 }
303                 if (i != 2) {
304                     current = p + 1;
305                     p = m_strchrnul(current, ':');
306                 }
307             }
308           } break;
309
310           /* hard_threshold parameter is an integer.
311            *  If the matching score is greater or equal than this threshold,
312            *  the hook "hard_match" is called.
313            * hard_threshold = 1 means, that all matches are hard matches.
314            * default is 1;
315            */
316           FILTER_PARAM_PARSE_INT(HARD_THRESHOLD, data->hard_threshold);
317
318           /* soft_threshold parameter is an integer.
319            *  if the matching score is greater or equal than this threshold
320            *  and smaller or equal than the hard_threshold, the hook "soft_match"
321            *  is called.
322            * default is 1;
323            */
324           FILTER_PARAM_PARSE_INT(SOFT_THRESHOLD, data->soft_threshold);
325
326           default: break;
327         }
328     }}
329
330     PARSE_CHECK(data->rbls.len, 
331                 "no file parameter in the filter %s", filter->name);
332     filter->data = data;
333     return true;
334 }
335
336 static void rbl_filter_destructor(filter_t *filter)
337 {
338     rbl_filter_t *data = filter->data;
339     rbl_filter_delete(&data);
340     filter->data = data;
341 }
342
343 static filter_result_t rbl_filter(const filter_t *filter, const query_t *query)
344 {
345     uint32_t ip;
346     int32_t sum = 0;
347     const char *end = NULL;
348     const rbl_filter_t *data = filter->data;
349
350     if (parse_ipv4(query->client_address, &end, &ip) != 0) {
351         warn("invalid client address: %s, expected ipv4",
352              query->client_address);
353         return HTK_ERROR;
354     }
355     for (uint32_t i = 0 ; i < data->rbls.len ; ++i) {
356         const rbldb_t *rbl = array_elt(data->rbls, i);
357         int weight   = array_elt(data->weights, i);
358         if (rbldb_ipv4_lookup(rbl, ip)) {
359             sum += weight;
360         }
361     }
362     if (sum >= data->hard_threshold) {
363         return HTK_HARD_MATCH;
364     } else if (sum >= data->soft_threshold) {
365         return HTK_SOFT_MATCH;
366     } else {
367         return HTK_FAIL;
368     }
369 }
370
371 static int rbl_init(void)
372 {
373     filter_type_t type =  filter_register("iplist", rbl_filter_constructor,
374                                           rbl_filter_destructor, rbl_filter);
375     /* Hooks.
376      */
377     (void)filter_hook_register(type, "abort");
378     (void)filter_hook_register(type, "error");
379     (void)filter_hook_register(type, "fail");
380     (void)filter_hook_register(type, "hard_match");
381     (void)filter_hook_register(type, "soft_match");
382
383     /* Parameters.
384      */
385     (void)filter_param_register(type, "file");
386     (void)filter_param_register(type, "hard_threshold");
387     (void)filter_param_register(type, "soft_threshold");
388     return 0;
389 }
390 module_init(rbl_init);