]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/resolve.c
a8a163f0cf786c73ef34173ed3c3b90059e3fdd5
[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 #if !defined(HAVE_WORKING_GETADDRINFO) || !defined(HAVE_GETNAMEINFO)
112 #ifdef h_errno
113 static char *
114 Get_Error( int H_Error )
115 {
116         /* Get error message for H_Error */
117         switch( H_Error ) {
118         case HOST_NOT_FOUND:
119                 return "host not found";
120         case NO_DATA:
121                 return "name valid but no IP address defined";
122         case NO_RECOVERY:
123                 return "name server error";
124         case TRY_AGAIN:
125                 return "name server temporary not available";
126         }
127         return "unknown error";
128 }
129 #endif
130 #endif
131
132
133 /* Do "IDENT" (aka "AUTH") lookup and append result to resolved_addr array */
134 static void
135 Do_IdentQuery(int identsock, array *resolved_addr)
136 {
137 #ifdef IDENTAUTH
138         char *res;
139
140         if (identsock < 0)
141                 return;
142
143 #ifdef DEBUG
144         Log_Subprocess(LOG_DEBUG, "Doing IDENT lookup on socket %d ...",
145                        identsock);
146 #endif
147         res = ident_id( identsock, 10 );
148 #ifdef DEBUG
149         Log_Subprocess(LOG_DEBUG, "Ok, IDENT lookup on socket %d done: \"%s\"",
150                        identsock, res ? res : "(NULL)");
151 #endif
152         if (!res) /* no result */
153                 return;
154         if (!array_cats(resolved_addr, res))
155                 Log_Subprocess(LOG_WARNING,
156                                "Resolver: Cannot copy IDENT result: %s!",
157                                strerror(errno));
158
159         free(res);
160 #else
161         (void) identsock;
162         (void) resolved_addr;
163 #endif
164 }
165
166
167 /**
168  * perform reverse DNS lookup and put result string into resbuf.
169  * If no hostname could be obtained, this function stores the string representation of
170  * the IP address in resbuf and returns false.
171  * @param IpAddr ip address to resolve
172  * @param resbuf result buffer to store DNS name/string representation of ip address
173  * @param reslen size of result buffer (must be >= NGT_INET_ADDRSTRLEN)
174  * @return true if reverse lookup successful, false otherwise
175  */
176 static bool
177 ReverseLookup(const ng_ipaddr_t *IpAddr, char *resbuf, size_t reslen)
178 {
179         char tmp_ip_str[NG_INET_ADDRSTRLEN];
180         const char *errmsg;
181 #ifdef HAVE_GETNAMEINFO
182         static const char funcname[]="getnameinfo";
183         int res;
184
185         *resbuf = 0;
186
187         res = getnameinfo((struct sockaddr *) IpAddr, ng_ipaddr_salen(IpAddr),
188                           resbuf, (socklen_t)reslen, NULL, 0, NI_NAMEREQD);
189         if (res == 0)
190                 return true;
191
192         if (res == EAI_SYSTEM)
193                 errmsg = strerror(errno);
194         else
195                 errmsg = gai_strerror(res);
196 #else
197         const struct sockaddr_in *Addr = (const struct sockaddr_in *) IpAddr;
198         struct hostent *h;
199         static const char funcname[]="gethostbyaddr";
200
201         h = gethostbyaddr((char *)&Addr->sin_addr, sizeof(Addr->sin_addr), AF_INET);
202         if (h) {
203                 if (strlcpy(resbuf, h->h_name, reslen) < reslen)
204                         return true;
205                 errmsg = "hostname too long";
206         } else {
207 # ifdef h_errno
208                 errmsg = Get_Error(h_errno);
209 # else
210                 errmsg = "unknown error";
211 # endif /* h_errno */
212         }
213 #endif  /* HAVE_GETNAMEINFO */
214
215         assert(errmsg);
216         assert(reslen >= NG_INET_ADDRSTRLEN);
217         ng_ipaddr_tostr_r(IpAddr, tmp_ip_str);
218
219         Log_Subprocess(LOG_WARNING, "Can't resolve address \"%s\": %s [%s].",
220                        tmp_ip_str, errmsg, funcname);
221         strlcpy(resbuf, tmp_ip_str, reslen);
222         return false;
223 }
224
225
226 /**
227  * perform DNS lookup of given host name and fill IpAddr with a list of
228  * ip addresses associated with that name.
229  * ip addresses found are stored in the "array *IpAddr" argument (type ng_ipaddr_t)
230  * @param hostname The domain name to look up.
231  * @param IpAddr pointer to empty and initialized array to store results
232  * @return true if lookup successful, false if domain name not found
233  */
234 static bool
235 ForwardLookup(const char *hostname, array *IpAddr, int af)
236 {
237         ng_ipaddr_t addr;
238
239 #ifdef HAVE_WORKING_GETADDRINFO
240         int res;
241         struct addrinfo *a, *ai_results;
242         static struct addrinfo hints;
243
244 #ifdef AI_ADDRCONFIG    /* glibc has this, but not e.g. netbsd 4.0 */
245         hints.ai_flags = AI_ADDRCONFIG;
246 #endif
247         hints.ai_socktype = SOCK_STREAM;
248         hints.ai_protocol = IPPROTO_TCP;
249         hints.ai_family = af;
250
251         memset(&addr, 0, sizeof(addr));
252
253         res = getaddrinfo(hostname, NULL, &hints, &ai_results);
254         switch (res) {
255         case 0: break;
256         case EAI_SYSTEM:
257                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, strerror(errno));
258                 return false;
259         default:
260                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, gai_strerror(res));
261                 return false;
262         }
263
264         for (a = ai_results; a != NULL; a = a->ai_next) {
265                 assert((size_t)a->ai_addrlen <= sizeof(addr));
266
267                 if ((size_t)a->ai_addrlen > sizeof(addr))
268                         continue;
269
270                 memcpy(&addr, a->ai_addr, a->ai_addrlen);
271
272                 if (!array_catb(IpAddr, (char *)&addr, sizeof(addr)))
273                         break;
274         }
275
276         freeaddrinfo(ai_results);
277         return a == NULL;
278 #else
279         struct hostent *h = gethostbyname(hostname);
280
281         if (!h) {
282 #ifdef h_errno
283                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s",
284                                hostname, Get_Error(h_errno));
285 #else
286                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\"", hostname);
287 #endif
288                 return false;
289         }
290         memset(&addr, 0, sizeof(addr));
291
292         addr.sin4.sin_family = AF_INET;
293         memcpy(&addr.sin4.sin_addr, h->h_addr, sizeof(struct in_addr));
294
295         return array_copyb(IpAddr, (char *)&addr, sizeof(addr));
296 #endif /* HAVE_GETADDRINFO */
297 }
298
299
300 static bool
301 Addr_in_list(const array *resolved_addr, const ng_ipaddr_t *Addr)
302 {
303         char tmp_ip_str[NG_INET_ADDRSTRLEN];
304         const ng_ipaddr_t *tmpAddrs = array_start(resolved_addr);
305         size_t len = array_length(resolved_addr, sizeof(*tmpAddrs));
306
307         assert(len > 0);
308         assert(tmpAddrs);
309
310         while (len > 0) {
311                 if (ng_ipaddr_ipequal(Addr, tmpAddrs))
312                         return true;
313                 tmpAddrs++;
314                 len--;
315         }
316         /* failed; print list of addresses */
317         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
318         len = array_length(resolved_addr, sizeof(*tmpAddrs));
319         tmpAddrs = array_start(resolved_addr);
320
321         while (len > 0) {
322                 Log_Subprocess(LOG_WARNING, "Address mismatch: %s != %s",
323                         tmp_ip_str, ng_ipaddr_tostr(tmpAddrs));
324                 tmpAddrs++;
325                 len--;
326         }
327
328         return false;
329 }
330
331
332 static void
333 Log_Forgery_NoIP(const char *ip, const char *host)
334 {
335         Log_Subprocess(LOG_WARNING,
336                 "Possible forgery: %s resolved to \"%s\", which has no IP address!",
337                 ip, host);
338 }
339
340 static void
341 Log_Forgery_WrongIP(const char *ip, const char *host)
342 {
343         Log_Subprocess(LOG_WARNING,
344                 "Possible forgery: %s resolved to \"%s\", which points to a different address!",
345                 ip, host);
346 }
347
348
349 static void
350 ArrayWrite(int fd, const array *a)
351 {
352         size_t len = array_bytes(a);
353         const char *data = array_start(a);
354
355         assert(data);
356
357         if( (size_t)write(fd, data, len) != len )
358                 Log_Subprocess( LOG_CRIT, "Resolver: Can't write to parent: %s!",
359                                                         strerror(errno));
360 }
361
362
363 static void
364 Do_ResolveAddr(const ng_ipaddr_t *Addr, int identsock, int w_fd)
365 {
366         /* Resolver sub-process: resolve IP address and write result into
367          * pipe to parent. */
368         char hostname[CLIENT_HOST_LEN];
369         char tmp_ip_str[NG_INET_ADDRSTRLEN];
370         size_t len;
371         array resolved_addr;
372
373         array_init(&resolved_addr);
374         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
375 #ifdef DEBUG
376         Log_Subprocess(LOG_DEBUG, "Now resolving %s ...", tmp_ip_str);
377 #endif
378         if (!ReverseLookup(Addr, hostname, sizeof(hostname)))
379                 goto dns_done;
380
381         if (ForwardLookup(hostname, &resolved_addr, ng_ipaddr_af(Addr))) {
382                 if (!Addr_in_list(&resolved_addr, Addr)) {
383                         Log_Forgery_WrongIP(tmp_ip_str, hostname);
384                         strlcpy(hostname, tmp_ip_str, sizeof(hostname));
385                 }
386         } else {
387                 Log_Forgery_NoIP(tmp_ip_str, hostname);
388                 strlcpy(hostname, tmp_ip_str, sizeof(hostname));
389         }
390 #ifdef DEBUG
391         Log_Subprocess(LOG_DEBUG, "Ok, translated %s to \"%s\".", tmp_ip_str, hostname);
392 #endif
393  dns_done:
394         len = strlen(hostname);
395         hostname[len] = '\n';
396         if (!array_copyb(&resolved_addr, hostname, ++len)) {
397                 Log_Subprocess(LOG_CRIT,
398                                "Resolver: Can't copy resolved name: %s!",
399                                strerror(errno));
400                 array_free(&resolved_addr);
401                 return;
402         }
403
404         Do_IdentQuery(identsock, &resolved_addr);
405
406         ArrayWrite(w_fd, &resolved_addr);
407
408         array_free(&resolved_addr);
409 } /* Do_ResolveAddr */
410
411
412 static void
413 Do_ResolveName( const char *Host, int w_fd )
414 {
415         /* Resolver sub-process: resolve name and write result into pipe
416          * to parent. */
417         array IpAddrs;
418         int af;
419 #ifdef DEBUG
420         ng_ipaddr_t *addr;
421         size_t len;
422 #endif
423         Log_Subprocess(LOG_DEBUG, "Now resolving \"%s\" ...", Host);
424
425         array_init(&IpAddrs);
426
427 #ifdef WANT_IPV6
428         af = AF_UNSPEC;
429         assert(Conf_ConnectIPv6 || Conf_ConnectIPv4);
430
431         if (!Conf_ConnectIPv6)
432                 af = AF_INET;
433         if (!Conf_ConnectIPv4)
434                 af = AF_INET6;
435 #else
436         af = AF_INET;
437 #endif
438         if (!ForwardLookup(Host, &IpAddrs, af)) {
439                 close(w_fd);
440                 return;
441         }
442 #ifdef DEBUG
443         len = array_length(&IpAddrs, sizeof(*addr));
444         assert(len > 0);
445         addr = array_start(&IpAddrs);
446         assert(addr);
447         for (; len > 0; --len,addr++) {
448                 Log_Subprocess(LOG_DEBUG, "translated \"%s\" to %s.",
449                                         Host, ng_ipaddr_tostr(addr));
450         }
451 #endif
452         /* Write result into pipe to parent */
453         ArrayWrite(w_fd, &IpAddrs);
454
455         array_free(&IpAddrs);
456 } /* Do_ResolveName */
457
458
459 /* -eof- */