]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/resolve.c
01e303ea33018c122ed6405a5b2bcb335202e83e
[ngircd-alex.git] / src / ngircd / resolve.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2014 Alexander Barton (alex@barton.de) and Contributors.
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
12 #define RESOLVER_TIMEOUT (Conf_PongTimeout*3)/4
13
14 #include "portab.h"
15
16 /**
17  * @file
18  * Asynchronous resolver
19  */
20
21 #include <assert.h>
22 #include <errno.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <netdb.h>
31
32 #ifdef IDENTAUTH
33 #ifdef HAVE_IDENT_H
34 #include <ident.h>
35 #endif
36 #endif
37
38 #include "conn.h"
39 #include "conf.h"
40 #include "log.h"
41 #include "ng_ipaddr.h"
42
43 static void Do_ResolveAddr PARAMS(( const ng_ipaddr_t *Addr, int Sock, int w_fd ));
44 static void Do_ResolveName PARAMS(( const char *Host, int w_fd ));
45
46 #ifdef WANT_IPV6
47 extern bool Conf_ConnectIPv4;
48 extern bool Conf_ConnectIPv6;
49 #endif
50
51
52 /**
53  * Resolve IP (asynchronous!).
54  */
55 GLOBAL bool
56 Resolve_Addr(PROC_STAT * s, const ng_ipaddr_t *Addr, int identsock,
57              void (*cbfunc) (int, short))
58 {
59         int pipefd[2];
60         pid_t pid;
61
62         assert(s != NULL);
63
64         pid = Proc_Fork(s, pipefd, cbfunc, RESOLVER_TIMEOUT);
65         if (pid > 0) {
66                 LogDebug("Resolver for %s created (PID %d).", ng_ipaddr_tostr(Addr), pid);
67                 return true;
68         } else if( pid == 0 ) {
69                 /* Sub process */
70                 Log_Init_Subprocess("Resolver");
71                 Conn_CloseAllSockets(identsock);
72                 Do_ResolveAddr(Addr, identsock, pipefd[1]);
73                 Log_Exit_Subprocess("Resolver");
74                 exit(0);
75         }
76         return false;
77 } /* Resolve_Addr */
78
79
80 /**
81  * Resolve hostname (asynchronous!).
82  */
83 GLOBAL bool
84 Resolve_Name( PROC_STAT *s, const char *Host, void (*cbfunc)(int, short))
85 {
86         int pipefd[2];
87         pid_t pid;
88
89         assert(s != NULL);
90
91         pid = Proc_Fork(s, pipefd, cbfunc, RESOLVER_TIMEOUT);
92         if (pid > 0) {
93                 /* Main process */
94 #ifdef DEBUG
95                 Log( LOG_DEBUG, "Resolver for \"%s\" created (PID %d).", Host, pid );
96 #endif
97                 return true;
98         } else if( pid == 0 ) {
99                 /* Sub process */
100                 Log_Init_Subprocess("Resolver");
101                 Conn_CloseAllSockets(NONE);
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, int af)
235 {
236         ng_ipaddr_t addr;
237
238 #ifdef HAVE_WORKING_GETADDRINFO
239         int res;
240         struct addrinfo *a, *ai_results;
241         static struct addrinfo hints;
242
243 #ifdef AI_ADDRCONFIG    /* glibc has this, but not e.g. netbsd 4.0 */
244         hints.ai_flags = AI_ADDRCONFIG;
245 #endif
246         hints.ai_socktype = SOCK_STREAM;
247         hints.ai_protocol = IPPROTO_TCP;
248         hints.ai_family = af;
249
250         memset(&addr, 0, sizeof(addr));
251
252         res = getaddrinfo(hostname, NULL, &hints, &ai_results);
253         switch (res) {
254         case 0: break;
255         case EAI_SYSTEM:
256                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, strerror(errno));
257                 return false;
258         default:
259                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, gai_strerror(res));
260                 return false;
261         }
262
263         for (a = ai_results; a != NULL; a = a->ai_next) {
264                 assert((size_t)a->ai_addrlen <= sizeof(addr));
265
266                 if ((size_t)a->ai_addrlen > sizeof(addr))
267                         continue;
268
269                 memcpy(&addr, a->ai_addr, a->ai_addrlen);
270
271                 if (!array_catb(IpAddr, (char *)&addr, sizeof(addr)))
272                         break;
273         }
274
275         freeaddrinfo(ai_results);
276         return a == NULL;
277 #else
278         struct hostent *h = gethostbyname(hostname);
279
280         if (!h) {
281 #ifdef h_errno
282                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s",
283                                hostname, Get_Error(h_errno));
284 #else
285                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\"", hostname);
286 #endif
287                 return false;
288         }
289         memset(&addr, 0, sizeof(addr));
290
291         addr.sin4.sin_family = AF_INET;
292         memcpy(&addr.sin4.sin_addr, h->h_addr, sizeof(struct in_addr));
293
294         return array_copyb(IpAddr, (char *)&addr, sizeof(addr));
295 #endif /* HAVE_GETADDRINFO */
296 }
297
298
299 static bool
300 Addr_in_list(const array *resolved_addr, const ng_ipaddr_t *Addr)
301 {
302         char tmp_ip_str[NG_INET_ADDRSTRLEN];
303         const ng_ipaddr_t *tmpAddrs = array_start(resolved_addr);
304         size_t len = array_length(resolved_addr, sizeof(*tmpAddrs));
305
306         assert(len > 0);
307         assert(tmpAddrs);
308
309         while (len > 0) {
310                 if (ng_ipaddr_ipequal(Addr, tmpAddrs))
311                         return true;
312                 tmpAddrs++;
313                 len--;
314         }
315         /* failed; print list of addresses */
316         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
317         len = array_length(resolved_addr, sizeof(*tmpAddrs));
318         tmpAddrs = array_start(resolved_addr);
319
320         while (len > 0) {
321                 Log_Subprocess(LOG_WARNING, "Address mismatch: %s != %s",
322                         tmp_ip_str, ng_ipaddr_tostr(tmpAddrs));
323                 tmpAddrs++;
324                 len--;
325         }
326
327         return false;
328 }
329
330
331 static void
332 Log_Forgery_NoIP(const char *ip, const char *host)
333 {
334         Log_Subprocess(LOG_WARNING,
335                 "Possible forgery: %s resolved to %s (which has no ip address)", ip, host);
336 }
337
338 static void
339 Log_Forgery_WrongIP(const char *ip, const char *host)
340 {
341         Log_Subprocess(LOG_WARNING,
342                 "Possible forgery: %s resolved to %s (which points to different address)", ip, host);
343 }
344
345
346 static void
347 ArrayWrite(int fd, const array *a)
348 {
349         size_t len = array_bytes(a);
350         const char *data = array_start(a);
351
352         assert(data);
353
354         if( (size_t)write(fd, data, len) != len )
355                 Log_Subprocess( LOG_CRIT, "Resolver: Can't write to parent: %s!",
356                                                         strerror(errno));
357 }
358
359
360 static void
361 Do_ResolveAddr(const ng_ipaddr_t *Addr, int identsock, int w_fd)
362 {
363         /* Resolver sub-process: resolve IP address and write result into
364          * pipe to parent. */
365         char hostname[CLIENT_HOST_LEN];
366         char tmp_ip_str[NG_INET_ADDRSTRLEN];
367         size_t len;
368         array resolved_addr;
369
370         array_init(&resolved_addr);
371         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
372 #ifdef DEBUG
373         Log_Subprocess(LOG_DEBUG, "Now resolving %s ...", tmp_ip_str);
374 #endif
375         if (!ReverseLookup(Addr, hostname, sizeof(hostname)))
376                 goto dns_done;
377
378         if (ForwardLookup(hostname, &resolved_addr, ng_ipaddr_af(Addr))) {
379                 if (!Addr_in_list(&resolved_addr, Addr)) {
380                         Log_Forgery_WrongIP(tmp_ip_str, hostname);
381                         strlcpy(hostname, tmp_ip_str, sizeof(hostname));
382                 }
383         } else {
384                 Log_Forgery_NoIP(tmp_ip_str, hostname);
385                 strlcpy(hostname, tmp_ip_str, sizeof(hostname));
386         }
387 #ifdef DEBUG
388         Log_Subprocess(LOG_DEBUG, "Ok, translated %s to \"%s\".", tmp_ip_str, hostname);
389 #endif
390  dns_done:
391         len = strlen(hostname);
392         hostname[len] = '\n';
393         if (!array_copyb(&resolved_addr, hostname, ++len)) {
394                 Log_Subprocess(LOG_CRIT,
395                                "Resolver: Can't copy resolved name: %s!",
396                                strerror(errno));
397                 array_free(&resolved_addr);
398                 return;
399         }
400
401         Do_IdentQuery(identsock, &resolved_addr);
402
403         ArrayWrite(w_fd, &resolved_addr);
404
405         array_free(&resolved_addr);
406 } /* Do_ResolveAddr */
407
408
409 static void
410 Do_ResolveName( const char *Host, int w_fd )
411 {
412         /* Resolver sub-process: resolve name and write result into pipe
413          * to parent. */
414         array IpAddrs;
415         int af;
416 #ifdef DEBUG
417         ng_ipaddr_t *addr;
418         size_t len;
419 #endif
420         Log_Subprocess(LOG_DEBUG, "Now resolving \"%s\" ...", Host);
421
422         array_init(&IpAddrs);
423
424 #ifdef WANT_IPV6
425         af = AF_UNSPEC;
426         assert(Conf_ConnectIPv6 || Conf_ConnectIPv4);
427
428         if (!Conf_ConnectIPv6)
429                 af = AF_INET;
430         if (!Conf_ConnectIPv4)
431                 af = AF_INET6;
432 #else
433         af = AF_INET;
434 #endif
435         if (!ForwardLookup(Host, &IpAddrs, af)) {
436                 close(w_fd);
437                 return;
438         }
439 #ifdef DEBUG
440         len = array_length(&IpAddrs, sizeof(*addr));
441         assert(len > 0);
442         addr = array_start(&IpAddrs);
443         assert(addr);
444         for (; len > 0; --len,addr++) {
445                 Log_Subprocess(LOG_DEBUG, "translated \"%s\" to %s.",
446                                         Host, ng_ipaddr_tostr(addr));
447         }
448 #endif
449         /* Write result into pipe to parent */
450         ArrayWrite(w_fd, &IpAddrs);
451
452         array_free(&IpAddrs);
453 } /* Do_ResolveName */
454
455
456 /* -eof- */