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