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