1 /******************************************************************************/
2 /* pfixtools: a collection of postfix related tools */
4 /* ________________________________________________________________________ */
6 /* Redistribution and use in source and binary forms, with or without */
7 /* modification, are permitted provided that the following conditions */
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 */
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 /******************************************************************************/
33 * Copyright © 2007 Pierre Habouzit
34 * Copyright © 2008 Florent Bruneau
37 #include <arpa/inet.h>
38 #include <netinet/in.h>
46 #include "resources.h"
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))
71 typedef struct rbldb_resource_t {
74 A(uint16_t) ips[1 << 16];
77 static void rbldb_resource_wipe(rbldb_resource_t *res)
79 for (int i = 0 ; i < 1 << 16 ; ++i) {
80 array_wipe(res->ips[i]);
85 static int get_o(const char *s, const char **out)
89 if (*s < '0' || *s > '9')
93 if (*s < '0' || *s > '9')
96 res = res * 10 + *s++ - '0';
97 if (*s < '0' || *s > '9')
100 res = res * 10 + *s++ - '0';
101 if (!(*s < '0' || *s > '9') || res < 100)
109 static int parse_ipv4(const char *s, const char **out, uint32_t *ip)
114 if ((o & ~0xff) || *s++ != '.')
119 if ((o & ~0xff) || *s++ != '.')
124 if ((o & ~0xff) || *s++ != '.')
137 rbldb_t *rbldb_create(const char *file, bool lock)
143 time_t now = time(0);
145 if (!file_map_open(&map, file, false)) {
149 rbldb_resource_t *res = resource_get("iplist", file);
151 res = p_new(rbldb_resource_t, 1);
152 resource_set("iplist", file, res, (resource_destructor_t)rbldb_resource_wipe);
155 db = p_new(rbldb_t, 1);
156 db->filename = m_strdup(file);
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);
163 res->size = map.st.st_size;
164 res->mtime = map.st.st_mtime;
168 while (end > p && end[-1] != '\n') {
171 if (end != map.end) {
172 warn("%s: final \\n missing, ignoring last line", file);
178 while (*p == ' ' || *p == '\t' || *p == '\r')
181 if (parse_ipv4(p, &p, &ip) < 0) {
182 p = (char *)memchr(p, '\n', end - p) + 1;
184 array_add(res->ips[ip >> 16], ip & 0xffff);
188 file_map_close(&map);
190 /* Lookup may perform serveral I/O, so avoid swap.
192 for (int i = 0 ; i < 1 << 16 ; ++i) {
193 array_adjust(res->ips[i]);
194 if (lock && !array_lock(res->ips[i])) {
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
206 info("%s loaded: done in %us, %u IPs", file, (uint32_t)(time(0) - now), ips);
210 static void rbldb_wipe(rbldb_t *db)
212 resource_release("iplist", db->filename);
213 p_delete(&db->filename);
217 void rbldb_delete(rbldb_t **db)
225 uint32_t rbldb_stats(const rbldb_t *rbl)
228 for (int i = 0 ; i < 1 << 16 ; ++i) {
229 ips += array_len(rbl->ips[i]);
234 bool rbldb_ipv4_lookup(const rbldb_t *db, uint32_t ip)
236 const uint16_t hip = ip >> 16;
237 const uint16_t lip = ip & 0xffff;
238 int l = 0, r = db->ips[hip].len;
243 if (array_elt(db->ips[hip], i) == lip)
246 if (lip < array_elt(db->ips[hip], i)) {
256 /* postlicyd filter declaration */
260 typedef struct iplist_filter_t {
267 int32_t hard_threshold;
268 int32_t soft_threshold;
271 typedef struct iplist_async_data_t {
272 A(rbl_result_t) results;
276 } iplist_async_data_t;
278 static filter_type_t filter_type = FTK_UNKNOWN;
280 static iplist_filter_t *iplist_filter_new(void)
282 return p_new(iplist_filter_t, 1);
285 static void iplist_filter_delete(iplist_filter_t **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);
298 static bool iplist_filter_constructor(filter_t *filter)
300 iplist_filter_t *data = iplist_filter_new();
302 #define PARSE_CHECK(Expr, Str, ...) \
304 err(Str, ##__VA_ARGS__); \
305 iplist_filter_delete(&data); \
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
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.
323 case ATK_FILE: case ATK_RBLDNS: {
327 const char *current = param->value;
328 const char *p = m_strchrnul(param->value, ':');
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");
336 if ((p - current) == 4 && strncmp(current, "lock", 4) == 0) {
338 } else if ((p - current) == 6
339 && strncmp(current, "nolock", 6) == 0) {
342 PARSE_CHECK(false, "illegal locking state %.*s",
343 (int)(p - current), current);
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);
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);
364 p = m_strchrnul(current, ':');
371 * define a RBL to use through DNS resolution.
375 const char *current = param->value;
376 const char *p = m_strchrnul(param->value, ':');
378 for (int i = 0 ; i < 2 ; ++i) {
379 PARSE_CHECK(i == 1 || *p,
380 "host parameter must contains a weight option");
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);
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);
397 p = m_strchrnul(current, ':');
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.
408 FILTER_PARAM_PARSE_INT(HARD_THRESHOLD, data->hard_threshold);
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"
416 FILTER_PARAM_PARSE_INT(SOFT_THRESHOLD, data->soft_threshold);
422 PARSE_CHECK(data->rbls.len || data->host_offsets.len,
423 "no file parameter in the filter %s", filter->name);
428 static void iplist_filter_destructor(filter_t *filter)
430 iplist_filter_t *data = filter->data;
431 iplist_filter_delete(&data);
435 static void iplist_filter_async(rbl_result_t *result, void *arg)
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];
443 if (*result != RBL_ERROR) {
444 async->error = false;
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);
451 if (async->awaited == 0) {
452 filter_result_t res = HTK_FAIL;
456 for (uint32_t i = 0 ; i < array_len(data->host_offsets) ; ++i) {
457 int weight = array_elt(data->host_weights, i);
459 switch (array_elt(async->results, i)) {
461 crit("no more awaited answer but result is ASYNC");
464 async->sum += weight;
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;
476 debug("answering to filter %s", filter->name);
477 filter_post_async_result(context, res);
481 static filter_result_t iplist_filter(const filter_t *filter, const query_t *query,
482 filter_context_t *context)
486 const char *end = NULL;
487 const iplist_filter_t *data = filter->data;
490 if (parse_ipv4(query->client_address.str, &end, &ip) != 0) {
491 if (strchr(query->client_address.str, ':')) {
492 /* iplist only works on IPv4 */
495 warn("invalid client address: %s, expected ipv4",
496 query->client_address.str);
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)) {
504 if (sum >= data->hard_threshold) {
505 return HTK_HARD_MATCH;
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));
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)) {
523 debug("filter %s awaiting %d asynchronous queries", filter->name, async->awaited);
524 async->error = error;
528 err("filter %s: all the rbl returned an error", filter->name);
531 if (sum >= data->hard_threshold) {
532 return HTK_HARD_MATCH;
533 } else if (sum >= data->soft_threshold) {
534 return HTK_SOFT_MATCH;
540 static void *iplist_context_constructor(void)
542 return p_new(iplist_async_data_t, 1);
545 static void iplist_context_destructor(void *data)
547 iplist_async_data_t *ctx = data;
548 array_wipe(ctx->results);
552 static int iplist_init(void)
554 filter_type = filter_register("iplist", iplist_filter_constructor,
555 iplist_filter_destructor, iplist_filter,
556 iplist_context_constructor,
557 iplist_context_destructor);
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");
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");
576 module_init(iplist_init);