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