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