]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/resolve.c
5839c19498cde0d8b9939d449bc947537eb678cf
[ngircd-alex.git] / src / ngircd / resolve.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2009 by Alexander Barton (alex@barton.de)
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  *
11  * Asynchronous resolver
12  */
13
14
15 #define RESOLVER_TIMEOUT (Conf_PongTimeout*3)/4
16
17 #include "portab.h"
18
19 #include "imp.h"
20 #include <assert.h>
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <netdb.h>
28 #include <signal.h>
29
30 #ifdef IDENTAUTH
31 #ifdef HAVE_IDENT_H
32 #include <ident.h>
33 #endif
34 #endif
35
36 #include "array.h"
37 #include "conn.h"
38 #include "conf.h"
39 #include "defines.h"
40 #include "log.h"
41 #include "ng_ipaddr.h"
42
43 #include "exp.h"
44 #include "resolve.h"
45 #include "io.h"
46
47
48 static void Do_ResolveAddr PARAMS(( const ng_ipaddr_t *Addr, int Sock, int w_fd ));
49 static void Do_ResolveName PARAMS(( const char *Host, int w_fd ));
50
51 #ifdef WANT_IPV6
52 extern bool Conf_ConnectIPv4;
53 extern bool Conf_ConnectIPv6;
54 #endif
55
56
57 /**
58  * Resolve IP (asynchronous!).
59  */
60 GLOBAL bool
61 Resolve_Addr(PROC_STAT * s, const ng_ipaddr_t *Addr, int identsock,
62              void (*cbfunc) (int, short))
63 {
64         int pipefd[2];
65         pid_t pid;
66
67         assert(s != NULL);
68
69         pid = Proc_Fork(s, pipefd, cbfunc, RESOLVER_TIMEOUT);
70         if (pid > 0) {
71                 LogDebug("Resolver for %s created (PID %d).", ng_ipaddr_tostr(Addr), pid);
72                 return true;
73         } else if( pid == 0 ) {
74                 /* Sub process */
75                 Log_Init_Subprocess("Resolver");
76                 Do_ResolveAddr( Addr, identsock, pipefd[1]);
77                 Log_Exit_Subprocess("Resolver");
78                 exit(0);
79         }
80         return false;
81 } /* Resolve_Addr */
82
83
84 /**
85  * Resolve hostname (asynchronous!).
86  */
87 GLOBAL bool
88 Resolve_Name( PROC_STAT *s, const char *Host, void (*cbfunc)(int, short))
89 {
90         int pipefd[2];
91         pid_t pid;
92
93         assert(s != NULL);
94
95         pid = Proc_Fork(s, pipefd, cbfunc, RESOLVER_TIMEOUT);
96         if (pid > 0) {
97                 /* Main process */
98 #ifdef DEBUG
99                 Log( LOG_DEBUG, "Resolver for \"%s\" created (PID %d).", Host, pid );
100 #endif
101                 return true;
102         } else if( pid == 0 ) {
103                 /* Sub process */
104                 Log_Init_Subprocess("Resolver");
105                 Do_ResolveName(Host, pipefd[1]);
106                 Log_Exit_Subprocess("Resolver");
107                 exit(0);
108         }
109         return false;
110 } /* Resolve_Name */
111
112
113 #if !defined(HAVE_GETADDRINFO) || !defined(HAVE_GETNAMEINFO)
114 #if !defined(WANT_IPV6) && defined(h_errno)
115 static char *
116 Get_Error( int H_Error )
117 {
118         /* Get error message for H_Error */
119         switch( H_Error ) {
120         case HOST_NOT_FOUND:
121                 return "host not found";
122         case NO_DATA:
123                 return "name valid but no IP address defined";
124         case NO_RECOVERY:
125                 return "name server error";
126         case TRY_AGAIN:
127                 return "name server temporary not available";
128         }
129         return "unknown error";
130 }
131 #endif
132 #endif
133
134
135 /* Do "IDENT" (aka "AUTH") lookup and append result to resolved_addr array */
136 static void
137 Do_IdentQuery(int identsock, array *resolved_addr)
138 {
139 #ifdef IDENTAUTH
140         char *res;
141
142         if (identsock < 0)
143                 return;
144
145 #ifdef DEBUG
146         Log_Subprocess(LOG_DEBUG, "Doing IDENT lookup on socket %d ...",
147                        identsock);
148 #endif
149         res = ident_id( identsock, 10 );
150 #ifdef DEBUG
151         Log_Subprocess(LOG_DEBUG, "Ok, IDENT lookup on socket %d done: \"%s\"",
152                        identsock, res ? res : "(NULL)");
153 #endif
154         if (!res) /* no result */
155                 return;
156         if (!array_cats(resolved_addr, res))
157                 Log_Subprocess(LOG_WARNING,
158                                "Resolver: Cannot copy IDENT result: %s!",
159                                strerror(errno));
160
161         free(res);
162 #else
163         (void) identsock;
164         (void) resolved_addr;
165 #endif
166 }
167
168
169 /**
170  * perform reverse DNS lookup and put result string into resbuf.
171  * If no hostname could be obtained, this function stores the string representation of
172  * the IP address in resbuf and returns false.
173  * @param IpAddr ip address to resolve
174  * @param resbuf result buffer to store DNS name/string representation of ip address
175  * @param reslen size of result buffer (must be >= NGT_INET_ADDRSTRLEN)
176  * @return true if reverse lookup successful, false otherwise
177  */
178 static bool
179 ReverseLookup(const ng_ipaddr_t *IpAddr, char *resbuf, size_t reslen)
180 {
181         char tmp_ip_str[NG_INET_ADDRSTRLEN];
182         const char *errmsg;
183 #ifdef HAVE_GETNAMEINFO
184         static const char funcname[]="getnameinfo";
185         int res;
186
187         *resbuf = 0;
188
189         res = getnameinfo((struct sockaddr *) IpAddr, ng_ipaddr_salen(IpAddr),
190                           resbuf, (socklen_t)reslen, NULL, 0, NI_NAMEREQD);
191         if (res == 0)
192                 return true;
193
194         if (res == EAI_SYSTEM)
195                 errmsg = strerror(errno);
196         else
197                 errmsg = gai_strerror(res);
198 #else
199         const struct sockaddr_in *Addr = (const struct sockaddr_in *) IpAddr;
200         struct hostent *h;
201         static const char funcname[]="gethostbyaddr";
202
203         h = gethostbyaddr((char *)&Addr->sin_addr, sizeof(Addr->sin_addr), AF_INET);
204         if (h) {
205                 if (strlcpy(resbuf, h->h_name, reslen) < reslen)
206                         return true;
207                 errmsg = "hostname too long";
208         } else {
209 # ifdef h_errno
210                 errmsg = Get_Error(h_errno);
211 # else
212                 errmsg = "unknown error";
213 # endif /* h_errno */
214         }
215 #endif  /* HAVE_GETNAMEINFO */
216
217         assert(errmsg);
218         assert(reslen >= NG_INET_ADDRSTRLEN);
219         ng_ipaddr_tostr_r(IpAddr, tmp_ip_str);
220
221         Log_Subprocess(LOG_WARNING, "%s: Can't resolve address \"%s\": %s",
222                                 funcname, tmp_ip_str, errmsg);
223         strlcpy(resbuf, tmp_ip_str, reslen);
224         return false;
225 }
226
227
228 /**
229  * perform DNS lookup of given host name and fill IpAddr with a list of
230  * ip addresses associated with that name.
231  * ip addresses found are stored in the "array *IpAddr" argument (type ng_ipaddr_t)
232  * @param hostname The domain name to look up.
233  * @param IpAddr pointer to empty and initialized array to store results
234  * @return true if lookup successful, false if domain name not found
235  */
236 static bool
237 ForwardLookup(const char *hostname, array *IpAddr)
238 {
239         ng_ipaddr_t addr;
240
241 #ifdef HAVE_GETADDRINFO
242         int res;
243         struct addrinfo *a, *ai_results;
244         static struct addrinfo hints;
245
246 #ifndef WANT_IPV6
247         hints.ai_family = AF_INET;
248 #endif
249 #ifdef AI_ADDRCONFIG    /* glibc has this, but not e.g. netbsd 4.0 */
250         hints.ai_flags = AI_ADDRCONFIG;
251 #endif
252         hints.ai_socktype = SOCK_STREAM;
253         hints.ai_protocol = IPPROTO_TCP;
254
255 #ifdef WANT_IPV6
256         assert(Conf_ConnectIPv6 || Conf_ConnectIPv4);
257
258         if (!Conf_ConnectIPv6)
259                 hints.ai_family = AF_INET;
260         if (!Conf_ConnectIPv4)
261                 hints.ai_family = AF_INET6;
262 #endif
263         memset(&addr, 0, sizeof(addr));
264
265         res = getaddrinfo(hostname, NULL, &hints, &ai_results);
266         switch (res) {
267         case 0: break;
268         case EAI_SYSTEM:
269                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, strerror(errno));
270                 return false;
271         default:
272                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, gai_strerror(res));
273                 return false;
274         }
275
276         for (a = ai_results; a != NULL; a = a->ai_next) {
277                 assert(a->ai_addrlen <= sizeof(addr));
278
279                 if (a->ai_addrlen > sizeof(addr))
280                         continue;
281
282                 memcpy(&addr, a->ai_addr, a->ai_addrlen);
283
284                 if (!array_catb(IpAddr, (char *)&addr, sizeof(addr)))
285                         break;
286         }
287
288         freeaddrinfo(ai_results);
289         return a == NULL;
290 #else
291         struct hostent *h = gethostbyname(hostname);
292
293         if (!h) {
294 #ifdef h_errno
295                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s",
296                                hostname, Get_Error(h_errno));
297 #else
298                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\"", hostname);
299 #endif
300                 return false;
301         }
302         memset(&addr, 0, sizeof(addr));
303
304         addr.sin4.sin_family = AF_INET;
305         memcpy(&addr.sin4.sin_addr, h->h_addr, sizeof(struct in_addr));
306
307         return array_copyb(IpAddr, (char *)&addr, sizeof(addr));
308 #endif /* HAVE_GETADDRINFO */
309 }
310
311
312 static bool
313 Addr_in_list(const array *resolved_addr, const ng_ipaddr_t *Addr)
314 {
315         char tmp_ip_str[NG_INET_ADDRSTRLEN];
316         const ng_ipaddr_t *tmpAddrs = array_start(resolved_addr);
317         size_t len = array_length(resolved_addr, sizeof(*tmpAddrs));
318
319         assert(len > 0);
320         assert(tmpAddrs);
321
322         while (len > 0) {
323                 if (ng_ipaddr_ipequal(Addr, tmpAddrs))
324                         return true;
325                 tmpAddrs++;
326                 len--;
327         }
328         /* failed; print list of addresses */
329         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
330         len = array_length(resolved_addr, sizeof(*tmpAddrs));
331         tmpAddrs = array_start(resolved_addr);
332
333         while (len > 0) {
334                 Log_Subprocess(LOG_WARNING, "Address mismatch: %s != %s",
335                         tmp_ip_str, ng_ipaddr_tostr(tmpAddrs));
336                 tmpAddrs++;
337                 len--;
338         }
339
340         return false;
341 }
342
343
344 static void
345 Log_Forgery_NoIP(const char *ip, const char *host)
346 {
347         Log_Subprocess(LOG_WARNING,
348                 "Possible forgery: %s resolved to %s (which has no ip address)", ip, host);
349 }
350
351 static void
352 Log_Forgery_WrongIP(const char *ip, const char *host)
353 {
354         Log_Subprocess(LOG_WARNING,
355                 "Possible forgery: %s resolved to %s (which points to different address)", ip, host);
356 }
357
358
359 static void
360 ArrayWrite(int fd, const array *a)
361 {
362         size_t len = array_bytes(a);
363         const char *data = array_start(a);
364
365         assert(data);
366
367         if( (size_t)write(fd, data, len) != len )
368                 Log_Subprocess( LOG_CRIT, "Resolver: Can't write to parent: %s!",
369                                                         strerror(errno));
370 }
371
372
373 static void
374 Do_ResolveAddr(const ng_ipaddr_t *Addr, int identsock, int w_fd)
375 {
376         /* Resolver sub-process: resolve IP address and write result into
377          * pipe to parent. */
378         char hostname[CLIENT_HOST_LEN];
379         char tmp_ip_str[NG_INET_ADDRSTRLEN];
380         size_t len;
381         array resolved_addr;
382
383         array_init(&resolved_addr);
384         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
385 #ifdef DEBUG
386         Log_Subprocess(LOG_DEBUG, "Now resolving %s ...", tmp_ip_str);
387 #endif
388         if (!ReverseLookup(Addr, hostname, sizeof(hostname)))
389                 goto dns_done;
390
391         if (ForwardLookup(hostname, &resolved_addr)) {
392                 if (!Addr_in_list(&resolved_addr, Addr)) {
393                         Log_Forgery_WrongIP(tmp_ip_str, hostname);
394                         strlcpy(hostname, tmp_ip_str, sizeof(hostname));
395                 }
396         } else {
397                 Log_Forgery_NoIP(tmp_ip_str, hostname);
398                 strlcpy(hostname, tmp_ip_str, sizeof(hostname));
399         }
400 #ifdef DEBUG
401         Log_Subprocess(LOG_DEBUG, "Ok, translated %s to \"%s\".", tmp_ip_str, hostname);
402 #endif
403  dns_done:
404         len = strlen(hostname);
405         hostname[len] = '\n';
406         if (!array_copyb(&resolved_addr, hostname, ++len)) {
407                 Log_Subprocess(LOG_CRIT,
408                                "Resolver: Can't copy resolved name: %s!",
409                                strerror(errno));
410                 array_free(&resolved_addr);
411                 return;
412         }
413
414         Do_IdentQuery(identsock, &resolved_addr);
415
416         ArrayWrite(w_fd, &resolved_addr);
417
418         array_free(&resolved_addr);
419 } /* Do_ResolveAddr */
420
421
422 static void
423 Do_ResolveName( const char *Host, int w_fd )
424 {
425         /* Resolver sub-process: resolve name and write result into pipe
426          * to parent. */
427         array IpAddrs;
428 #ifdef DEBUG
429         ng_ipaddr_t *addr;
430         size_t len;
431 #endif
432         Log_Subprocess(LOG_DEBUG, "Now resolving \"%s\" ...", Host);
433
434         array_init(&IpAddrs);
435         /* Resolve hostname */
436         if (!ForwardLookup(Host, &IpAddrs)) {
437                 close(w_fd);
438                 return;
439         }
440 #ifdef DEBUG
441         len = array_length(&IpAddrs, sizeof(*addr));
442         assert(len > 0);
443         addr = array_start(&IpAddrs);
444         assert(addr);
445         for (; len > 0; --len,addr++) {
446                 Log_Subprocess(LOG_DEBUG, "translated \"%s\" to %s.",
447                                         Host, ng_ipaddr_tostr(addr));
448         }
449 #endif
450         /* Write result into pipe to parent */
451         ArrayWrite(w_fd, &IpAddrs);
452
453         array_free(&IpAddrs);
454 } /* Do_ResolveName */
455
456
457 /* -eof- */