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