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