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