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