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