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