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