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