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