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