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