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