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