]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/resolve.c
resolve.c: fix valgrind 'uninitialized memory' warning
[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 "conn.h"
34 #include "defines.h"
35 #include "log.h"
36
37 #include "exp.h"
38 #include "resolve.h"
39 #include "io.h"
40
41
42 static void Do_ResolveAddr PARAMS(( const ng_ipaddr_t *Addr, int Sock, int w_fd ));
43 static void Do_ResolveName PARAMS(( const char *Host, int w_fd ));
44 static bool register_callback PARAMS((RES_STAT *s, void (*cbfunc)(int, short)));
45
46 #ifdef WANT_IPV6
47 extern bool Conf_ConnectIPv4;
48 extern bool Conf_ConnectIPv6;
49 #endif
50
51 static pid_t
52 Resolver_fork(int *pipefds)
53 {
54         pid_t pid;
55
56         if (pipe(pipefds) != 0) {
57                 Log( LOG_ALERT, "Resolver: Can't create output pipe: %s!", strerror( errno ));
58                 return -1;
59         }
60
61         pid = fork();
62         switch(pid) {
63                 case -1:
64                         Log( LOG_CRIT, "Resolver: Can't fork: %s!", strerror( errno ));
65                         close(pipefds[0]);
66                         close(pipefds[1]);
67                         return -1;
68                 case 0: /* child */
69                         close(pipefds[0]);
70                         Log_Init_Resolver( );
71                         return 0;
72         }
73         /* parent */
74         close(pipefds[1]);
75         return pid; 
76 }
77
78
79 /**
80  * Resolve IP (asynchronous!).
81  */
82 GLOBAL bool
83 Resolve_Addr(RES_STAT * s, const ng_ipaddr_t *Addr, int identsock,
84              void (*cbfunc) (int, short))
85 {
86         int pipefd[2];
87         pid_t pid;
88
89         assert(s != NULL);
90
91         pid = Resolver_fork(pipefd);
92         if (pid > 0) {
93                 LogDebug("Resolver for %s created (PID %d).", ng_ipaddr_tostr(Addr), pid);
94
95                 s->pid = pid;
96                 s->resolver_fd = pipefd[0];
97                 return register_callback(s, cbfunc);
98         } else if( pid == 0 ) {
99                 /* Sub process */
100                 Do_ResolveAddr( Addr, identsock, pipefd[1]);
101                 Log_Exit_Resolver( );
102                 exit(0);
103         }
104         return false;
105 } /* Resolve_Addr */
106
107
108 /**
109  * Resolve hostname (asynchronous!).
110  */
111 GLOBAL bool
112 Resolve_Name( RES_STAT *s, const char *Host, void (*cbfunc)(int, short))
113 {
114         int pipefd[2];
115         pid_t pid;
116
117         assert(s != NULL);
118
119         pid = Resolver_fork(pipefd);
120         if (pid > 0) {
121                 /* Main process */
122 #ifdef DEBUG
123                 Log( LOG_DEBUG, "Resolver for \"%s\" created (PID %d).", Host, pid );
124 #endif
125                 s->pid = pid;
126                 s->resolver_fd = pipefd[0];
127                 return register_callback(s, cbfunc);
128         } else if( pid == 0 ) {
129                 /* Sub process */
130                 Do_ResolveName(Host, pipefd[1]);
131                 Log_Exit_Resolver( );
132                 exit(0);
133         }
134         return false;
135 } /* Resolve_Name */
136
137
138 GLOBAL void
139 Resolve_Init(RES_STAT *s)
140 {
141         assert(s != NULL);
142         s->resolver_fd = -1;
143         s->pid = 0;
144 }
145
146
147 #ifndef WANT_IPV6
148 #ifdef h_errno
149 static char *
150 Get_Error( int H_Error )
151 {
152         /* Get error message for H_Error */
153         switch( H_Error ) {
154         case HOST_NOT_FOUND:
155                 return "host not found";
156         case NO_DATA:
157                 return "name valid but no IP address defined";
158         case NO_RECOVERY:
159                 return "name server error";
160         case TRY_AGAIN:
161                 return "name server temporary not available";
162         }
163         return "unknown error";
164 }
165 #endif /* h_errno */
166 #endif /* WANT_IPV6 */
167
168
169 /* Do "IDENT" (aka "AUTH") lookup and append result to resolved_addr array */
170 static void
171 Do_IdentQuery(int identsock, array *resolved_addr)
172 {
173 #ifdef IDENTAUTH
174         char *res;
175
176         if (identsock < 0)
177                 return;
178
179 #ifdef DEBUG
180         Log_Resolver(LOG_DEBUG, "Doing IDENT lookup on socket %d ...", identsock);
181 #endif
182         res = ident_id( identsock, 10 );
183 #ifdef DEBUG
184         Log_Resolver(LOG_DEBUG, "Ok, IDENT lookup on socket %d done: \"%s\"",
185                                                 identsock, res ? res : "(NULL)" );
186 #endif
187         if (!res) /* no result */
188                 return;
189         if (!array_cats(resolved_addr, res))
190                 Log_Resolver(LOG_WARNING, "Resolver: Cannot copy IDENT result: %s!", strerror(errno));
191
192         free(res);
193 #else
194         (void) identsock;
195         (void) resolved_addr;
196 #endif
197 }
198
199
200 /**
201  * perform reverse DNS lookup and put result string into resbuf.
202  * If no hostname could be obtained, this function stores the string representation of
203  * the IP address in resbuf and returns false.
204  * @param IpAddr ip address to resolve
205  * @param resbuf result buffer to store DNS name/string representation of ip address
206  * @reslen size of result buffer (must be >= NGT_INET_ADDRSTRLEN)
207  * @return true if reverse lookup successful, false otherwise
208  */
209 static bool
210 ReverseLookup(const ng_ipaddr_t *IpAddr, char *resbuf, size_t reslen)
211 {
212         char tmp_ip_str[NG_INET_ADDRSTRLEN];
213         const char *errmsg;
214 #ifdef HAVE_GETNAMEINFO
215         static const char funcname[]="getnameinfo";
216         int res;
217
218         *resbuf = 0;
219
220         res = getnameinfo((struct sockaddr *) IpAddr, ng_ipaddr_salen(IpAddr),
221                           resbuf, (socklen_t)reslen, NULL, 0, NI_NAMEREQD);
222         if (res == 0)
223                 return true;
224
225         if (res == EAI_SYSTEM)
226                 errmsg = strerror(errno);
227         else
228                 errmsg = gai_strerror(res);
229 #else
230         const struct sockaddr_in *Addr = (const struct sockaddr_in *) IpAddr;
231         struct hostent *h;
232         static const char funcname[]="gethostbyaddr";
233
234         h = gethostbyaddr((char *)&Addr->sin_addr, sizeof(Addr->sin_addr), AF_INET);
235         if (h) {
236                 if (strlcpy(resbuf, h->h_name, reslen) < reslen)
237                         return true;
238                 errmsg = "hostname too long";
239         } else {
240 # ifdef h_errno
241                 errmsg = Get_Error(h_errno);
242 # else
243                 errmsg = "unknown error";
244 # endif /* h_errno */
245         }
246 #endif  /* HAVE_GETNAMEINFO */
247
248         assert(errmsg);
249         assert(reslen >= NG_INET_ADDRSTRLEN);
250         ng_ipaddr_tostr_r(IpAddr, tmp_ip_str);
251
252         Log_Resolver(LOG_WARNING, "%s: Can't resolve address \"%s\": %s",
253                                 funcname, tmp_ip_str, errmsg);
254         strlcpy(resbuf, tmp_ip_str, reslen);
255         return false;
256 }
257
258
259 /**
260  * perform DNS lookup of given host name and fill IpAddr with a list of
261  * ip addresses associated with that name.
262  * ip addresses found are stored in the "array *IpAddr" argument (type ng_ipaddr_t)
263  * @param hostname The domain name to look up.
264  * @param IpAddr pointer to empty and initialized array to store results
265  * @return true if lookup successful, false if domain name not found
266  */
267 static bool
268 ForwardLookup(const char *hostname, array *IpAddr)
269 {
270         ng_ipaddr_t addr;
271
272 #ifdef HAVE_GETADDRINFO
273         int res;
274         struct addrinfo *a, *ai_results;
275         static struct addrinfo hints;
276
277 #ifndef WANT_IPV6
278         hints.ai_family = AF_INET;
279 #endif
280 #ifdef AI_ADDRCONFIG    /* glibc has this, but not e.g. netbsd 4.0 */
281         hints.ai_flags = AI_ADDRCONFIG;
282 #endif
283         hints.ai_socktype = SOCK_STREAM;
284         hints.ai_protocol = IPPROTO_TCP;
285
286 #ifdef WANT_IPV6
287         assert(Conf_ConnectIPv6 || Conf_ConnectIPv4);
288
289         if (!Conf_ConnectIPv6)
290                 hints.ai_family = AF_INET;
291         if (!Conf_ConnectIPv4)
292                 hints.ai_family = AF_INET6;
293 #endif
294         memset(&addr, 0, sizeof(addr));
295
296         res = getaddrinfo(hostname, NULL, &hints, &ai_results);
297         switch (res) {
298         case 0: break;
299         case EAI_SYSTEM:
300                 Log_Resolver(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, strerror(errno));
301                 return false;
302         default:
303                 Log_Resolver(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, gai_strerror(res));
304                 return false;
305         }
306
307         for (a = ai_results; a != NULL; a = a->ai_next) {
308                 assert(a->ai_addrlen <= sizeof(addr));
309
310                 if (a->ai_addrlen > sizeof(addr))
311                         continue;
312
313                 memcpy(&addr, a->ai_addr, a->ai_addrlen);
314
315                 if (!array_catb(IpAddr, (char *)&addr, sizeof(addr)))
316                         break;
317         }
318
319         freeaddrinfo(ai_results);
320         return a == NULL;
321 #else
322         struct hostent *h = gethostbyname(hostname);
323
324         if (!h) {
325 #ifdef h_errno
326                 Log_Resolver(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, Get_Error(h_errno));
327 #else
328                 Log_Resolver(LOG_WARNING, "Can't resolve \"%s\"", hostname);
329 #endif
330                 return false;
331         }
332         memset(&addr, 0, sizeof(addr));
333
334         addr.sin4.sin_family = AF_INET;
335         memcpy(&addr.sin4.sin_addr, h->h_addr, sizeof(struct in_addr));
336
337         return array_copyb(IpAddr, (char *)&addr, sizeof(addr));
338 #endif /* HAVE_GETADDRINFO */
339 }
340
341
342 static bool
343 Addr_in_list(const array *resolved_addr, const ng_ipaddr_t *Addr)
344 {
345         char tmp_ip_str[NG_INET_ADDRSTRLEN];
346         const ng_ipaddr_t *tmpAddrs = array_start(resolved_addr);
347         size_t len = array_length(resolved_addr, sizeof(*tmpAddrs));
348
349         assert(len > 0);
350         assert(tmpAddrs);
351
352         while (len > 0) {
353                 if (ng_ipaddr_ipequal(Addr, tmpAddrs))
354                         return true;
355                 tmpAddrs++;
356                 len--;
357         }
358         /* failed; print list of addresses */
359         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
360         len = array_length(resolved_addr, sizeof(*tmpAddrs));
361         tmpAddrs = array_start(resolved_addr);
362
363         while (len > 0) {
364                 Log_Resolver(LOG_WARNING, "Address mismatch: %s != %s",
365                         tmp_ip_str, ng_ipaddr_tostr(tmpAddrs));
366                 tmpAddrs++;
367                 len--;
368         }
369
370         return false;
371 }
372
373
374 static void
375 Log_Forgery_NoIP(const char *ip, const char *host)
376 {
377         Log_Resolver(LOG_WARNING, "Possible forgery: %s resolved to %s "
378                 "(which has no ip address)", ip, host);
379 }
380
381 static void
382 Log_Forgery_WrongIP(const char *ip, const char *host)
383 {
384         Log_Resolver(LOG_WARNING,"Possible forgery: %s resolved to %s "
385                 "(which points to different address)", ip, host);
386 }
387
388
389 static void
390 ArrayWrite(int fd, const array *a)
391 {
392         size_t len = array_bytes(a);
393         const char *data = array_start(a);
394
395         assert(data);
396
397         if( (size_t)write(fd, data, len) != len )
398                 Log_Resolver( LOG_CRIT, "Resolver: Can't write to parent: %s!",
399                                                         strerror(errno));
400 }
401
402
403 static void
404 Do_ResolveAddr(const ng_ipaddr_t *Addr, int identsock, int w_fd)
405 {
406         /* Resolver sub-process: resolve IP address and write result into
407          * pipe to parent. */
408         char hostname[CLIENT_HOST_LEN];
409         char tmp_ip_str[NG_INET_ADDRSTRLEN];
410         size_t len;
411         array resolved_addr;
412
413         array_init(&resolved_addr);
414         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
415 #ifdef DEBUG
416         Log_Resolver(LOG_DEBUG, "Now resolving %s ...", tmp_ip_str);
417 #endif
418         if (!ReverseLookup(Addr, hostname, sizeof(hostname)))
419                 goto dns_done;
420
421         if (ForwardLookup(hostname, &resolved_addr)) {
422                 if (!Addr_in_list(&resolved_addr, Addr)) {
423                         Log_Forgery_WrongIP(tmp_ip_str, hostname);
424                         strlcpy(hostname, tmp_ip_str, sizeof(hostname));
425                 }
426         } else {
427                 Log_Forgery_NoIP(tmp_ip_str, hostname);
428                 strlcpy(hostname, tmp_ip_str, sizeof(hostname));
429         }
430 #ifdef DEBUG
431         Log_Resolver(LOG_DEBUG, "Ok, translated %s to \"%s\".", tmp_ip_str, hostname);
432 #endif
433  dns_done:
434         len = strlen(hostname);
435         hostname[len] = '\n';
436         if (!array_copyb(&resolved_addr, hostname, ++len)) {
437                 Log_Resolver(LOG_CRIT, "Resolver: Can't copy resolved name: %s!", strerror(errno));
438                 array_free(&resolved_addr);
439                 return;
440         }
441
442         Do_IdentQuery(identsock, &resolved_addr);
443
444         ArrayWrite(w_fd, &resolved_addr);
445
446         array_free(&resolved_addr);
447 } /* Do_ResolveAddr */
448
449
450 static void
451 Do_ResolveName( const char *Host, int w_fd )
452 {
453         /* Resolver sub-process: resolve name and write result into pipe
454          * to parent. */
455         array IpAddrs;
456 #ifdef DEBUG
457         ng_ipaddr_t *addr;
458         size_t len;
459 #endif
460         Log_Resolver(LOG_DEBUG, "Now resolving \"%s\" ...", Host);
461
462         array_init(&IpAddrs);
463         /* Resolve hostname */
464         if (!ForwardLookup(Host, &IpAddrs)) {
465                 close(w_fd);
466                 return;
467         }
468 #ifdef DEBUG
469         len = array_length(&IpAddrs, sizeof(*addr));
470         assert(len > 0);
471         addr = array_start(&IpAddrs);
472         assert(addr);
473         for (; len > 0; --len,addr++) {
474                 Log_Resolver(LOG_DEBUG, "translated \"%s\" to %s.",
475                                         Host, ng_ipaddr_tostr(addr));
476         }
477 #endif
478         /* Write result into pipe to parent */
479         ArrayWrite(w_fd, &IpAddrs);
480
481         array_free(&IpAddrs);
482 } /* Do_ResolveName */
483
484
485 static bool
486 register_callback( RES_STAT *s, void (*cbfunc)(int, short))
487 {
488         assert(cbfunc != NULL);
489         assert(s != NULL);
490         assert(s->resolver_fd >= 0);
491
492         if (io_setnonblock(s->resolver_fd) &&
493                 io_event_create(s->resolver_fd, IO_WANTREAD, cbfunc))
494                         return true;
495
496         Log( LOG_CRIT, "Resolver: Could not register callback function: %s!", strerror(errno));
497         close(s->resolver_fd);
498         Resolve_Init(s);
499         return false;
500 }
501
502
503 GLOBAL bool
504 Resolve_Shutdown( RES_STAT *s)
505 {
506         bool ret = false;
507
508         assert(s != NULL);
509         assert(s->resolver_fd >= 0);
510
511         if (s->resolver_fd >= 0)
512                 ret = io_close(s->resolver_fd);
513
514         Resolve_Init(s);
515         return ret;
516 }
517
518
519 /**
520  * Read result of resolver sub-process from pipe
521  */
522 GLOBAL size_t
523 Resolve_Read( RES_STAT *s, void* readbuf, size_t buflen)
524 {
525         ssize_t bytes_read;
526
527         assert(buflen > 0);
528
529         /* Read result from pipe */
530         bytes_read = read(s->resolver_fd, readbuf, buflen);
531         if (bytes_read < 0) {
532                 if (errno == EAGAIN)
533                         return 0;
534
535                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror(errno));
536                 bytes_read = 0;
537         }
538 #ifdef DEBUG
539         else if (bytes_read == 0)
540                 Log( LOG_DEBUG, "Resolver: Can't read result: EOF");
541 #endif
542         Resolve_Shutdown(s);
543         return (size_t)bytes_read;
544 }
545
546
547 /* -eof- */