* Support IPv6 RBL as described in http://tools.ietf.org/html/draft-irtf-asrg-dnsbl-08
[citadel.git] / citadel / locate_host.c
1 /*
2  * $Id$
3  *
4  * Functions which handle hostname/address lookups and resolution
5  *
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <ctype.h>
13 #include <signal.h>
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <netinet/in.h>
17 #include <arpa/inet.h>
18 #include <limits.h>
19 #include <netdb.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <libcitadel.h>
23 #include "citadel.h"
24 #include "server.h"
25 #include "locate_host.h"
26 #include "sysdep_decls.h"
27 #include "config.h"
28 #include "domain.h"
29 #include "context.h"
30 #include "ctdl_module.h"
31
32 #ifdef HAVE_RESOLV_H
33 #include <arpa/nameser.h>
34 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
35 #include <arpa/nameser_compat.h>
36 #endif
37 #include <resolv.h>
38 #endif
39
40
41 /*
42  * Given an open client socket, return the host name and IP address at the other end.
43  * (IPv4 and IPv6 compatible)
44  */
45 void locate_host(char *tbuf, size_t n, char *abuf, size_t na, int client_socket)
46 {
47         struct sockaddr_in6 clientaddr;
48         unsigned int addrlen = sizeof(clientaddr);
49
50         tbuf[0] = 0;
51         abuf[0] = 0;
52
53         getpeername(client_socket, (struct sockaddr *)&clientaddr, &addrlen);
54         getnameinfo((struct sockaddr *)&clientaddr, addrlen, tbuf, n, NULL, 0, 0);
55         getnameinfo((struct sockaddr *)&clientaddr, addrlen, abuf, na, NULL, 0, NI_NUMERICHOST);
56
57         /* Convert IPv6-mapped IPv4 addresses back to traditional dotted quad.
58          *
59          * Other code here, such as the RBL check, will expect IPv4 addresses to be represented
60          * as dotted-quad, even if they come in over a hybrid IPv6/IPv4 socket.
61          */
62         if ( (strlen(abuf) > 7) && (!strncasecmp(abuf, "::ffff:", 7)) ) {
63                 strcpy(abuf, &abuf[7]);
64         }
65 }
66
67
68 /*
69  * RBL check written by Edward S. Marshall [http://rblcheck.sourceforge.net]
70  */
71 #define RESULT_SIZE 4096 /* What is the longest result text we support? */
72 int rblcheck_backend(char *domain, char *txtbuf, int txtbufsize) {
73         int a, b, c;
74         char *result = NULL;
75         u_char fixedans[ PACKETSZ ];
76         u_char *answer;
77         int need_to_free_answer = 0;
78         const u_char *cp;
79         u_char *rp;
80         const u_char *cend;
81         const u_char *rend;
82         int len;
83         char *p = NULL;
84         static int res_initted = 0;
85
86         if (!res_initted) {             /* only have to do this once */
87                 res_init();
88                 res_initted = 1;
89         }
90
91         /* Make our DNS query. */
92         answer = fixedans;
93         if (CtdlThreadCheckStop())
94         {
95                 if (txtbuf != NULL) {
96                         snprintf(txtbuf, txtbufsize, "System shutting down");
97                 }
98                 return (1);
99         }
100         len = res_query(domain, C_IN, T_A, answer, PACKETSZ);
101
102         /* Was there a problem? If so, the domain doesn't exist. */
103         if (len == -1) {
104                 if (txtbuf != NULL) {
105                         strcpy(txtbuf, "");
106                 }
107                 return(0);
108         }
109
110         if( len > PACKETSZ )
111         {
112                 answer = malloc(len);
113                 need_to_free_answer = 1;
114                 len = res_query(domain, C_IN, T_A, answer, len);
115                 if( len == -1 ) {
116                         if (txtbuf != NULL) {
117                                 snprintf(txtbuf, txtbufsize,
118                                         "Message rejected due to known spammer source IP address");
119                         }
120                         if (need_to_free_answer) free(answer);
121                         return(1);
122                 }
123         }
124         if (CtdlThreadCheckStop())
125         {
126                 if (txtbuf != NULL)
127                         snprintf(txtbuf, txtbufsize, "System shutting down");
128                 if (need_to_free_answer) free(answer);
129                 return (1);
130         }
131
132         result = (char *) malloc(RESULT_SIZE);
133         result[ 0 ] = '\0';
134
135
136         /* Make another DNS query for textual data; this shouldn't
137          * be a performance hit, since it'll now be cached at the
138          * nameserver we're using.
139          */
140         len = res_query(domain, C_IN, T_TXT, answer, PACKETSZ);
141         if (CtdlThreadCheckStop())
142         {
143                 if (txtbuf != NULL) {
144                         snprintf(txtbuf, txtbufsize, "System shutting down");
145                 }
146                 if (need_to_free_answer) free(answer);
147                 free(result);
148                 return (1);
149         }
150
151         /* Just in case there's no TXT record... */
152         if (len ==(-1))
153         {
154                 if (txtbuf != NULL) {
155                         snprintf(txtbuf, txtbufsize,
156                                 "Message rejected due to known spammer source IP address");
157                 }
158                 if (need_to_free_answer) free(answer);
159                 free(result);
160                 return(1);
161         }
162
163         /* Skip the header and the address we queried. */
164         cp = answer + sizeof( HEADER );
165         while( *cp != '\0' )
166         {
167                 a = *cp++;
168                 while( a-- )
169                         cp++;
170         }
171
172         /* This seems to be a bit of magic data that we need to
173          * skip. I wish there were good online documentation
174          * for programming for libresolv, so I'd know what I'm
175          * skipping here. Anyone reading this, feel free to
176          * enlighten me.
177          */
178         cp += 1 + NS_INT16SZ + NS_INT32SZ;
179
180         /* Skip the type, class and ttl. */
181         cp += (NS_INT16SZ * 2) + NS_INT32SZ;
182
183         /* Get the length and end of the buffer. */
184         NS_GET16(c, cp);
185         cend = cp + c;
186
187         /* Iterate over any multiple answers we might have. In
188          * this context, it's unlikely, but anyway.
189          */
190         rp = (u_char *) result;
191         rend = (u_char *) result + RESULT_SIZE - 1;
192         while (cp < cend && rp < rend)
193         {
194                 a = *cp++;
195                 if( a != 0 )
196                         for (b = a; b > 0 && cp < cend && rp < rend; b--)
197                         {
198                                 if (*cp == '\n' || *cp == '"' || *cp == '\\')
199                                 {
200                                         *rp++ = '\\';
201                                 }
202                                 *rp++ = *cp++;
203                         }
204         }
205         *rp = '\0';
206         if (txtbuf != NULL) {
207                 snprintf(txtbuf, txtbufsize, "%s", result);
208         }
209         /* Remove nonprintable characters */
210         for (p=txtbuf; *p; ++p) {
211                 if (!isprint(*p)) strcpy(p, p+1);
212         }
213         if (need_to_free_answer) free(answer);
214         free(result);
215         return(1);
216 }
217
218
219 /*
220  * Check to see if the client host is on some sort of spam list (RBL)
221  * If spammer, returns nonzero and places reason in 'message_to_spammer'
222  */
223 int rbl_check(char *message_to_spammer)
224 {
225         char tbuf[256] = "";
226         int suffix_pos = 0;
227         int rbl;
228         int num_rbl;
229         char rbl_domains[SIZ];
230         char txt_answer[1024];
231         int ip_version = 4;
232
233         strcpy(message_to_spammer, "ok");
234
235         if ((strchr(CC->cs_addr, '.')) && (!strchr(CC->cs_addr, ':'))) {
236                 int a1, a2, a3, a4;
237                 ip_version = 4;
238
239                 sscanf(CC->cs_addr, "%d.%d.%d.%d", &a1, &a2, &a3, &a4);
240                 snprintf(tbuf, sizeof tbuf, "%d.%d.%d.%d.", a4, a3, a2, a1);
241                 suffix_pos = strlen(tbuf);
242         }
243         else if ((!strchr(CC->cs_addr, '.')) && (strchr(CC->cs_addr, ':'))) {
244                 int num_colons = 0;
245                 int i = 0;
246                 char workbuf[sizeof tbuf];
247                 char *ptr;
248
249                 ip_version = 6;
250
251                 /* tedious code to expand and reverse an IPv6 address */
252                 safestrncpy(tbuf, CC->cs_addr, sizeof tbuf);
253                 num_colons = haschar(tbuf, ':');
254                 if ((num_colons < 2) || (num_colons > 7)) return(0);    /* badly formed address */
255
256                 /* expand the "::" shorthand */
257                 while (num_colons < 7) {
258                         ptr = strstr(tbuf, "::");
259                         if (!ptr) return(0);                            /* badly formed address */
260                         ++ptr;
261                         strcpy(workbuf, ptr);
262                         strcpy(ptr, ":");
263                         strcat(ptr, workbuf);
264                         ++num_colons;
265                 }
266
267                 /* expand to 32 hex characters with no colons */
268                 strcpy(workbuf, tbuf);
269                 strcpy(tbuf, "00000000000000000000000000000000");
270                 for (i=0; i<8; ++i) {
271                         char tokbuf[5];
272                         extract_token(tokbuf, workbuf, i, ':', sizeof tokbuf);
273
274                         memcpy(&tbuf[ (i*4) + (4-strlen(tokbuf)) ], tokbuf, strlen(tokbuf) );
275                 }
276                 if (strlen(tbuf) != 32) return(0);
277
278                 /* now reverse it and add dots */
279                 strcpy(workbuf, tbuf);
280                 for (i=0; i<32; ++i) {
281                         tbuf[i*2] = workbuf[31-i];
282                         tbuf[(i*2)+1] = '.';
283                 }
284                 tbuf[64] = 0;
285                 suffix_pos = 64;
286         }
287         else {
288                 return(0);      /* unknown address format */
289         }
290
291         /* See if we have any RBL domains configured */
292         num_rbl = get_hosts(rbl_domains, "rbl");
293         if (num_rbl < 1) return(0);
294
295         /* Try all configured RBL's */
296         for (rbl=0; rbl<num_rbl; ++rbl) {
297                 extract_token(&tbuf[suffix_pos], rbl_domains, rbl, '|', (sizeof tbuf - suffix_pos));
298
299                 if (rblcheck_backend(tbuf, txt_answer, sizeof txt_answer)) {
300                         strcpy(message_to_spammer, txt_answer);
301                         CtdlLogPrintf(CTDL_INFO, "RBL: %s\n", txt_answer);
302                         return(1);
303                 }
304         }
305
306         return(0);
307 }
308                         
309
310 /*
311  * Convert a host name to a dotted quad address. 
312  * Returns zero on success or nonzero on failure.
313  *
314  * FIXME this is obviously not IPv6 compatible.
315  */
316 int hostname_to_dotted_quad(char *addr, char *host) {
317         struct hostent *ch;
318         const char *i;
319         int a1, a2, a3, a4;
320
321         ch = gethostbyname(host);
322         if (ch == NULL) {
323                 strcpy(addr, "0.0.0.0");
324                 return(1);
325         }
326
327         i = (const char *) ch->h_addr_list[0];
328         a1 = ((*i++) & 0xff);
329         a2 = ((*i++) & 0xff);
330         a3 = ((*i++) & 0xff);
331         a4 = ((*i++) & 0xff);
332         sprintf(addr, "%d.%d.%d.%d", a1, a2, a3, a4);
333         return(0);
334 }