efc3b8613ba178a9de653ed4e05cc06925476a8a
[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 "resources.h"
47 #include "rbl.h"
48
49 #define IPv4_BITS        5
50 #define IPv4_PREFIX(ip)  ((uint32_t)(ip) >> IPv4_BITS)
51 #define IPv4_SUFFIX(ip)  ((uint32_t)(ip) & ((1 << IPv4_BITS) - 1))
52 #define NODE(db, i)      ((db)->tree + (i))
53 #ifndef DEBUG
54 #define DEBUG(...)
55 #endif
56
57 /* Implementation */
58
59 enum {
60     BALANCED    = 0,
61     LEFT_HEAVY  = 1,
62     RIGHT_HEAVY = 2,
63 };
64
65 struct rbldb_t {
66     char        *filename;
67     A(uint16_t) *ips;
68 };
69 ARRAY(rbldb_t)
70
71 typedef struct rbldb_resource_t {
72     time_t mtime;
73     off_t  size;
74     A(uint16_t) ips[1 << 16];
75 } rbldb_resource_t;
76
77 static void rbldb_resource_wipe(rbldb_resource_t *res)
78 {
79     for (int i = 0 ; i < 1 << 16 ; ++i) {
80         array_wipe(res->ips[i]);
81     }
82     p_delete(&res);
83 }
84
85 static int get_o(const char *s, const char **out)
86 {
87     int res = 0;
88
89     if (*s < '0' || *s > '9')
90         return -1;
91
92     res = *s++ - '0';
93     if (*s < '0' || *s > '9')
94         goto ok;
95
96     res = res * 10 + *s++ - '0';
97     if (*s < '0' || *s > '9')
98         goto ok;
99
100     res = res * 10 + *s++ - '0';
101     if (!(*s < '0' || *s > '9') || res < 100)
102         return -1;
103
104   ok:
105     *out = s;
106     return res;
107 }
108
109 static int parse_ipv4(const char *s, const char **out, uint32_t *ip)
110 {
111     int o;
112
113     o = get_o(s, &s);
114     if ((o & ~0xff) || *s++ != '.')
115         return -1;
116     *ip = o << 24;
117
118     o = get_o(s, &s);
119     if ((o & ~0xff) || *s++ != '.')
120         return -1;
121     *ip |= o << 16;
122
123     o = get_o(s, &s);
124     if ((o & ~0xff) || *s++ != '.')
125         return -1;
126     *ip |= o << 8;
127
128     o = get_o(s, &s);
129     if (o & ~0xff)
130         return -1;
131     *ip |= o;
132
133     *out = s;
134     return 0;
135 }
136
137 rbldb_t *rbldb_create(const char *file, bool lock)
138 {
139     rbldb_t *db;
140     file_map_t map;
141     const char *p, *end;
142     uint32_t ips = 0;
143     time_t now = time(0);
144
145     if (!file_map_open(&map, file, false)) {
146         return NULL;
147     }
148
149     rbldb_resource_t *res = resource_get("iplist", file);
150     if (res == NULL) {
151         res = p_new(rbldb_resource_t, 1);
152         resource_set("iplist", file, res, (resource_destructor_t)rbldb_resource_wipe);
153     }
154
155     db = p_new(rbldb_t, 1);
156     db->filename = m_strdup(file);
157     db->ips = res->ips;
158     if (map.st.st_size == res->size && map.st.st_mtime == res->mtime) {
159         info("%s loaded: already up-to-date", file);
160         file_map_close(&map);
161         return db;
162     }
163     res->size  = map.st.st_size;
164     res->mtime = map.st.st_mtime;
165
166     p   = map.map;
167     end = map.end;
168     while (end > p && end[-1] != '\n') {
169         --end;
170     }
171     if (end != map.end) {
172         warn("%s: final \\n missing, ignoring last line", file);
173     }
174
175     while (p < end) {
176         uint32_t ip;
177
178         while (*p == ' ' || *p == '\t' || *p == '\r')
179             p++;
180
181         if (parse_ipv4(p, &p, &ip) < 0) {
182             p = (char *)memchr(p, '\n', end - p) + 1;
183         } else {
184             array_add(res->ips[ip >> 16], ip & 0xffff);
185             ++ips;
186         }
187     }
188     file_map_close(&map);
189
190     /* Lookup may perform serveral I/O, so avoid swap.
191      */
192     for (int i = 0 ; i < 1 << 16 ; ++i) {
193         array_adjust(res->ips[i]);
194         if (lock && !array_lock(res->ips[i])) {
195             UNIXERR("mlock");
196         }
197         if (res->ips[i].len) {
198 #       define QSORT_TYPE uint16_t
199 #       define QSORT_BASE res->ips[i].data
200 #       define QSORT_NELT res->ips[i].len
201 #       define QSORT_LT(a,b) *a < *b
202 #       include "qsort.c"
203         }
204     }
205
206     info("%s loaded: done in %us, %u IPs", file, (uint32_t)(time(0) - now), ips);
207     return db;
208 }
209
210 static void rbldb_wipe(rbldb_t *db)
211 {
212     resource_release("iplist", db->filename);
213     p_delete(&db->filename);
214     db->ips = NULL;
215 }
216
217 void rbldb_delete(rbldb_t **db)
218 {
219     if (*db) {
220         rbldb_wipe(*db);
221         p_delete(&(*db));
222     }
223 }
224
225 uint32_t rbldb_stats(const rbldb_t *rbl)
226 {
227     uint32_t ips = 0;
228     for (int i = 0 ; i < 1 << 16 ; ++i) {
229         ips += array_len(rbl->ips[i]);
230     }
231     return ips;
232 }
233
234 bool rbldb_ipv4_lookup(const rbldb_t *db, uint32_t ip)
235 {
236     const uint16_t hip = ip >> 16;
237     const uint16_t lip = ip & 0xffff;
238     int l = 0, r = db->ips[hip].len;
239
240     while (l < r) {
241         int i = (r + l) / 2;
242
243         if (array_elt(db->ips[hip], i) == lip)
244             return true;
245
246         if (lip < array_elt(db->ips[hip], i)) {
247             r = i;
248         } else {
249             l = i + 1;
250         }
251     }
252     return false;
253 }
254
255
256 /* postlicyd filter declaration */
257
258 #include "filter.h"
259
260 typedef struct iplist_filter_t {
261     PA(rbldb_t) rbls;
262     A(int)      weights;
263     A(char)     hosts;
264     A(int)      host_offsets;
265     A(int)      host_weights;
266
267     int32_t     hard_threshold;
268     int32_t     soft_threshold;
269 } iplist_filter_t;
270
271 typedef struct iplist_async_data_t {
272     A(rbl_result_t) results;
273     int awaited;
274     uint32_t sum;
275     bool error;
276 } iplist_async_data_t;
277
278 static filter_type_t filter_type = FTK_UNKNOWN;
279
280 static iplist_filter_t *iplist_filter_new(void)
281 {
282     return p_new(iplist_filter_t, 1);
283 }
284
285 static void iplist_filter_delete(iplist_filter_t **rbl)
286 {
287     if (*rbl) {
288         array_deep_wipe((*rbl)->rbls, rbldb_delete);
289         array_wipe((*rbl)->weights);
290         array_wipe((*rbl)->hosts);
291         array_wipe((*rbl)->host_offsets);
292         array_wipe((*rbl)->host_weights);
293         p_delete(rbl);
294     }
295 }
296
297
298 static bool iplist_filter_constructor(filter_t *filter)
299 {
300     iplist_filter_t *data = iplist_filter_new();
301
302 #define PARSE_CHECK(Expr, Str, ...)                                            \
303     if (!(Expr)) {                                                             \
304         err(Str, ##__VA_ARGS__);                                               \
305         iplist_filter_delete(&data);                                              \
306         return false;                                                          \
307     }
308
309     data->hard_threshold = 1;
310     data->soft_threshold = 1;
311     foreach (filter_param_t *param, filter->params) {
312         switch (param->type) {
313           /* file parameter is:
314            *  [no]lock:weight:filename
315            *  valid options are:
316            *    - lock:   memlock the database in memory.
317            *    - nolock: don't memlock the database in memory [default].
318            *    - \d+:    a number describing the weight to give to the match
319            *              the given list [mandatory]
320            *  the file pointed by filename MUST be a valid ip list issued from
321            *  the rsync (or equivalent) service of a (r)bl.
322            */
323           case ATK_FILE: case ATK_RBLDNS: {
324             bool lock = false;
325             int  weight = 0;
326             rbldb_t *rbl = NULL;
327             const char *current = param->value;
328             const char *p = m_strchrnul(param->value, ':');
329             char *next = NULL;
330             for (int i = 0 ; i < 3 ; ++i) {
331                 PARSE_CHECK(i == 2 || *p,
332                             "file parameter must contains a locking state "
333                             "and a weight option");
334                 switch (i) {
335                   case 0:
336                     if ((p - current) == 4 && strncmp(current, "lock", 4) == 0) {
337                         lock = true;
338                     } else if ((p - current) == 6
339                                && strncmp(current, "nolock", 6) == 0) {
340                         lock = false;
341                     } else {
342                         PARSE_CHECK(false, "illegal locking state %.*s",
343                                     (int)(p - current), current);
344                     }
345                     break;
346
347                   case 1:
348                     weight = strtol(current, &next, 10);
349                     PARSE_CHECK(next == p && weight >= 0 && weight <= 1024,
350                                 "illegal weight value %.*s",
351                                 (int)(p - current), current);
352                     break;
353
354                   case 2:
355                     rbl = rbldb_create(current, lock);
356                     PARSE_CHECK(rbl != NULL,
357                                 "cannot load rbl db from %s", current);
358                     array_add(data->rbls, rbl);
359                     array_add(data->weights, weight);
360                     break;
361                 }
362                 if (i != 2) {
363                     current = p + 1;
364                     p = m_strchrnul(current, ':');
365                 }
366             }
367           } break;
368
369           /* dns parameter.
370            *  weight:hostname.
371            * define a RBL to use through DNS resolution.
372            */
373           case ATK_DNS: {
374             int  weight = 0;
375             const char *current = param->value;
376             const char *p = m_strchrnul(param->value, ':');
377             char *next = NULL;
378             for (int i = 0 ; i < 2 ; ++i) {
379                 PARSE_CHECK(i == 1 || *p,
380                             "host parameter must contains a weight option");
381                 switch (i) {
382                   case 0:
383                     weight = strtol(current, &next, 10);
384                     PARSE_CHECK(next == p && weight >= 0 && weight <= 1024,
385                                 "illegal weight value %.*s",
386                                 (int)(p - current), current);
387                     break;
388
389                   case 1:
390                     array_add(data->host_offsets, array_len(data->hosts));
391                     array_append(data->hosts, current, strlen(current) + 1);
392                     array_add(data->host_weights, weight);
393                     break;
394                 }
395                 if (i != 1) {
396                     current = p + 1;
397                     p = m_strchrnul(current, ':');
398                 }
399             }
400           } break;
401
402           /* hard_threshold parameter is an integer.
403            *  If the matching score is greater or equal than this threshold,
404            *  the hook "hard_match" is called.
405            * hard_threshold = 1 means, that all matches are hard matches.
406            * default is 1;
407            */
408           FILTER_PARAM_PARSE_INT(HARD_THRESHOLD, data->hard_threshold);
409
410           /* soft_threshold parameter is an integer.
411            *  if the matching score is greater or equal than this threshold
412            *  and smaller or equal than the hard_threshold, the hook "soft_match"
413            *  is called.
414            * default is 1;
415            */
416           FILTER_PARAM_PARSE_INT(SOFT_THRESHOLD, data->soft_threshold);
417
418           default: break;
419         }
420     }}
421
422     PARSE_CHECK(data->rbls.len || data->host_offsets.len,
423                 "no file parameter in the filter %s", filter->name);
424     filter->data = data;
425     return true;
426 }
427
428 static void iplist_filter_destructor(filter_t *filter)
429 {
430     iplist_filter_t *data = filter->data;
431     iplist_filter_delete(&data);
432     filter->data = data;
433 }
434
435 static void iplist_filter_async(rbl_result_t *result, void *arg)
436 {
437     filter_context_t   *context = arg;
438     const filter_t      *filter = context->current_filter;
439     const iplist_filter_t *data = filter->data;
440     iplist_async_data_t  *async = context->contexts[filter_type];
441
442
443     if (*result != RBL_ERROR) {
444         async->error = false;
445     }
446     --async->awaited;
447
448     debug("got asynchronous request result for filter %s, rbl %d, still awaiting %d answers",
449           filter->name, (int)(result - array_ptr(async->results, 0)), async->awaited);
450
451     if (async->awaited == 0) {
452         filter_result_t res = HTK_FAIL;
453         if (async->error) {
454             res = HTK_ERROR;
455         } else {
456             for (uint32_t i = 0 ; i < array_len(data->host_offsets) ; ++i) {
457                 int weight = array_elt(data->host_weights, i);
458
459                 switch (array_elt(async->results, i)) {
460                   case RBL_ASYNC:
461                     crit("no more awaited answer but result is ASYNC");
462                     abort();
463                   case RBL_FOUND:
464                     async->sum += weight;
465                     break;
466                   default:
467                     break;
468                 }
469             }
470             if (async->sum >= (uint32_t)data->hard_threshold) {
471                 res = HTK_HARD_MATCH;
472             } else if (async->sum >= (uint32_t)data->soft_threshold) {
473                 res = HTK_SOFT_MATCH;
474             }
475         }
476         debug("answering to filter %s", filter->name);
477         filter_post_async_result(context, res);
478     }
479 }
480
481 static filter_result_t iplist_filter(const filter_t *filter, const query_t *query,
482                                      filter_context_t *context)
483 {
484     uint32_t ip;
485     int32_t sum = 0;
486     const char *end = NULL;
487     const iplist_filter_t *data = filter->data;
488     bool  error = true;
489
490     if (parse_ipv4(query->client_address.str, &end, &ip) != 0) {
491         if (strchr(query->client_address.str, ':')) {
492             /* iplist only works on IPv4 */
493             return HTK_FAIL;
494         }
495         warn("invalid client address: %s, expected ipv4",
496              query->client_address.str);
497         return HTK_ERROR;
498     }
499     for (uint32_t i = 0 ; i < data->rbls.len ; ++i) {
500         const rbldb_t *rbl = array_elt(data->rbls, i);
501         int weight   = array_elt(data->weights, i);
502         if (rbldb_ipv4_lookup(rbl, ip)) {
503             sum += weight;
504             if (sum >= data->hard_threshold) {
505                 return HTK_HARD_MATCH;
506             }
507         }
508         error = false;
509     }
510     if (array_len(data->host_offsets) > 0) {
511         iplist_async_data_t* async = context->contexts[filter_type];
512         array_ensure_exact_capacity(async->results, array_len(data->host_offsets));
513         async->sum = sum;
514         async->awaited = 0;
515         for (uint32_t i = 0 ; i < data->host_offsets.len ; ++i) {
516             const char *rbl = array_ptr(data->hosts, array_elt(data->host_offsets, i));
517             if (rbl_check(rbl, ip, array_ptr(async->results, i),
518                           iplist_filter_async, context)) {
519                 error = false;
520                 ++async->awaited;
521             }
522         }
523         debug("filter %s awaiting %d asynchronous queries", filter->name, async->awaited);
524         async->error = error;
525         return HTK_ASYNC;
526     }
527     if (error) {
528         err("filter %s: all the rbl returned an error", filter->name);
529         return HTK_ERROR;
530     }
531     if (sum >= data->hard_threshold) {
532         return HTK_HARD_MATCH;
533     } else if (sum >= data->soft_threshold) {
534         return HTK_SOFT_MATCH;
535     } else {
536         return HTK_FAIL;
537     }
538 }
539
540 static void *iplist_context_constructor(void)
541 {
542     return p_new(iplist_async_data_t, 1);
543 }
544
545 static void iplist_context_destructor(void *data)
546 {
547     iplist_async_data_t *ctx = data;
548     array_wipe(ctx->results);
549     p_delete(&ctx);
550 }
551
552 static int iplist_init(void)
553 {
554     filter_type =  filter_register("iplist", iplist_filter_constructor,
555                                    iplist_filter_destructor, iplist_filter,
556                                    iplist_context_constructor,
557                                    iplist_context_destructor);
558     /* Hooks.
559      */
560     (void)filter_hook_register(filter_type, "abort");
561     (void)filter_hook_register(filter_type, "error");
562     (void)filter_hook_register(filter_type, "fail");
563     (void)filter_hook_register(filter_type, "hard_match");
564     (void)filter_hook_register(filter_type, "soft_match");
565     (void)filter_hook_register(filter_type, "async");
566
567     /* Parameters.
568      */
569     (void)filter_param_register(filter_type, "file");
570     (void)filter_param_register(filter_type, "rbldns");
571     (void)filter_param_register(filter_type, "dns");
572     (void)filter_param_register(filter_type, "hard_threshold");
573     (void)filter_param_register(filter_type, "soft_threshold");
574     return 0;
575 }
576 module_init(iplist_init);