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