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