cf1d7344fb6d674f190e2cc3ccce38b03ea94760
[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 <fcntl.h>
39 #include <netinet/in.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42
43 #include "common.h"
44 #include "rbl.h"
45 #include "str.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 enum {
56     BALANCED    = 0,
57     LEFT_HEAVY  = 1,
58     RIGHT_HEAVY = 2,
59 };
60
61 struct rbldb_t {
62     uint32_t len, size;
63     uint32_t *ips;
64     bool     locked;
65 };
66
67 static int get_o(const char *s, const char **out)
68 {
69     int res = 0;
70
71     if (*s < '0' || *s > '9')
72         return -1;
73
74     res = *s++ - '0';
75     if (*s < '0' || *s > '9')
76         goto ok;
77
78     res = res * 10 + *s++ - '0';
79     if (*s < '0' || *s > '9')
80         goto ok;
81
82     res = res * 10 + *s++ - '0';
83     if (!(*s < '0' || *s > '9') || res < 100)
84         return -1;
85
86   ok:
87     *out = s;
88     return res;
89 }
90
91 static int parse_ipv4(const char *s, const char **out, uint32_t *ip)
92 {
93     int o;
94
95     o = get_o(s, &s);
96     if ((o & ~0xff) || *s++ != '.')
97         return -1;
98     *ip = o << 24;
99
100     o = get_o(s, &s);
101     if ((o & ~0xff) || *s++ != '.')
102         return -1;
103     *ip |= o << 16;
104
105     o = get_o(s, &s);
106     if ((o & ~0xff) || *s++ != '.')
107         return -1;
108     *ip |= o << 8;
109
110     o = get_o(s, &s);
111     if (o & ~0xff)
112         return -1;
113     *ip |= o;
114
115     *out = s;
116     return 0;
117 }
118
119 rbldb_t *rbldb_create(const char *file, bool lock)
120 {
121     rbldb_t *db;
122     const char *map, *p, *end;
123     struct stat st;
124     int fd;
125
126     fd = open(file, O_RDONLY, 0000);
127     if (fd < 0) {
128         UNIXERR("open");
129         return NULL;
130     }
131
132     if (fstat(fd, &st) < 0) {
133         UNIXERR("fstat");
134         close(fd);
135         return NULL;
136     }
137
138     p = map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
139     if (map == MAP_FAILED) {
140         UNIXERR("mmap");
141         close(fd);
142         return NULL;
143     }
144     close(fd);
145
146     end = map + st.st_size;
147     while (end > map && end[-1] != '\n') {
148         --end;
149     }
150     if (end != map + st.st_size) {
151         syslog(LOG_WARNING, "file %s miss a final \\n, ignoring last line",
152                file);
153     }
154
155     db = p_new(rbldb_t, 1);
156     while (p < end) {
157         uint32_t ip;
158
159         while (*p == ' ' || *p == '\t' || *p == '\r')
160             p++;
161
162         if (parse_ipv4(p, &p, &ip) < 0) {
163             p = (char *)memchr(p, '\n', end - p) + 1;
164         } else {
165             if (db->len >= db->size) {
166                 db->size += 64 * 1024;
167                 p_realloc(&db->ips, db->size);
168             }
169             db->ips[db->len++] = ip;
170         }
171     }
172     munmap((void*)map, st.st_size);
173
174     /* Lookup may perform serveral I/O, so avoid swap.
175      */
176     db->locked = lock && mlock(db->ips, db->len * sizeof(*(db->ips))) == 0;
177     if (lock && !db->locked) {
178         UNIXERR("mlock");
179     }
180
181     if (db->len) {
182 #       define QSORT_TYPE uint32_t
183 #       define QSORT_BASE db->ips
184 #       define QSORT_NELT db->len
185 #       define QSORT_LT(a,b) *a < *b
186 #       include "qsort.c"
187     }
188
189     syslog(LOG_INFO, "rbl %s loaded, %d IPs", file, db->len);
190     return db;
191 }
192
193 void rbldb_delete(rbldb_t **db)
194 {
195     if (*db) {
196         if ((*db)->locked) {
197             (void)munlock((*db)->ips, (*db)->len * sizeof(*(*db)->ips));
198         }
199         p_delete(&(*db)->ips);
200         p_delete(&(*db));
201     }
202 }
203
204 uint32_t rbldb_stats(rbldb_t *rbl)
205 {
206     return rbl->len;
207 }
208
209 bool rbldb_ipv4_lookup(rbldb_t *db, uint32_t ip)
210 {
211     int l = 0, r = db->len;
212
213     while (l < r) {
214         int i = (r + l) / 2;
215
216         if (db->ips[i] == ip)
217             return true;
218
219         if (ip < db->ips[i]) {
220             r = i;
221         } else {
222             l = i + 1;
223         }
224     }
225     return false;
226 }