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