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