ee2cfb3b837408bb8a5865825a7d63d0c9fad946
[oweals/gnunet.git] / src / util / gnunet-service-resolver.c
1 /*
2      This file is part of GNUnet.
3      (C) 2007, 2008, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/gnunet-service-resolver.c
23  * @brief code to do DNS resolution
24  * @author Christian Grothoff
25  */
26
27 #include <stdlib.h>
28 #include "platform.h"
29 #include "gnunet_disk_lib.h"
30 #include "gnunet_getopt_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_service_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_strings_lib.h"
35 #include "gnunet_time_lib.h"
36 #include "resolver.h"
37
38 /**
39  * A cached DNS lookup result.
40  */
41 struct IPCache
42 {
43   /**
44    * This is a linked list.
45    */
46   struct IPCache *next;
47
48   /**
49    * Hostname in human-readable form.
50    */
51   char *addr;
52
53   /**
54    * Hostname in binary format.
55    */
56   struct sockaddr *sa;
57
58   /**
59    * Last time this entry was updated.
60    */
61   struct GNUNET_TIME_Absolute last_refresh;
62
63   /**
64    * Last time this entry was requested.
65    */
66   struct GNUNET_TIME_Absolute last_request;
67
68   /**
69    * Number of bytes in sa.
70    */
71   socklen_t salen;
72 };
73
74
75 /**
76  * Start of the linked list of cached DNS lookup results.
77  */
78 static struct IPCache *head;
79
80
81 #if HAVE_GETNAMEINFO
82 /**
83  * Resolve the given request using getnameinfo
84  *
85  * @param cache the request to resolve (and where to store the result)
86  */
87 static void
88 getnameinfo_resolve (struct IPCache *cache)
89 {
90   char hostname[256];
91
92   if (0 == getnameinfo (cache->sa,
93                         cache->salen,
94                         hostname, sizeof (hostname), NULL, 0, 0))
95     cache->addr = GNUNET_strdup (hostname);
96 }
97 #endif
98
99
100 #if HAVE_GETHOSTBYADDR
101 /**
102  * Resolve the given request using gethostbyaddr
103  *
104  * @param cache the request to resolve (and where to store the result)
105  */
106 static void
107 gethostbyaddr_resolve (struct IPCache *cache)
108 {
109   struct hostent *ent;
110
111   switch (cache->sa->sa_family)
112     {
113     case AF_INET:
114       ent = gethostbyaddr (&((struct sockaddr_in *) cache->sa)->sin_addr,
115                            sizeof (struct in_addr), AF_INET);
116       break;
117     case AF_INET6:
118       ent = gethostbyaddr (&((struct sockaddr_in6 *) cache->sa)->sin6_addr,
119                            sizeof (struct in6_addr), AF_INET6);
120       break;
121     default:
122       ent = NULL;
123     }
124   if (ent != NULL)
125     cache->addr = GNUNET_strdup (ent->h_name);
126 }
127 #endif
128
129 /**
130  * Resolve the given request using the available methods.
131  *
132  * @param cache the request to resolve (and where to store the result)
133  */
134 static void
135 cache_resolve (struct IPCache *cache)
136 {
137 #if HAVE_GETNAMEINFO
138   if (cache->addr == NULL)
139     getnameinfo_resolve (cache);
140 #endif
141 #if HAVE_GETHOSTBYADDR
142   if (cache->addr == NULL)
143     gethostbyaddr_resolve (cache);
144 #endif
145 }
146
147
148
149 /**
150  * Get an IP address as a string (works for both IPv4 and IPv6).  Note
151  * that the resolution happens asynchronously and that the first call
152  * may not immediately result in the FQN (but instead in a
153  * human-readable IP address).
154  *
155  * @param client handle to the client making the request (for sending the reply)
156  * @param sa should be of type "struct sockaddr*"
157  * @param salen number of bytes in sa
158  */
159 static void
160 get_ip_as_string (struct GNUNET_SERVER_Client *client,
161                   const struct sockaddr *sa, socklen_t salen)
162 {
163   struct IPCache *cache;
164   struct IPCache *prev;
165   struct GNUNET_TIME_Absolute now;
166   struct GNUNET_SERVER_TransmitContext *tc;
167
168   if (salen < sizeof (struct sockaddr))
169     {
170       GNUNET_break (0);
171       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
172       return;
173     }
174   now = GNUNET_TIME_absolute_get ();
175   cache = head;
176   prev = NULL;
177   while ((cache != NULL) &&
178          ((cache->salen != salen) || (0 != memcmp (cache->sa, sa, salen))))
179     {
180       if (GNUNET_TIME_absolute_get_duration (cache->last_request).rel_value <
181           60 * 60 * 1000)
182         {
183           if (prev != NULL)
184             {
185               prev->next = cache->next;
186               GNUNET_free_non_null (cache->addr);
187               GNUNET_free (cache->sa);
188               GNUNET_free (cache);
189               cache = prev->next;
190             }
191           else
192             {
193               head = cache->next;
194               GNUNET_free_non_null (cache->addr);
195               GNUNET_free (cache->sa);
196               GNUNET_free (cache);
197               cache = head;
198             }
199           continue;
200         }
201       prev = cache;
202       cache = cache->next;
203     }
204   if (cache != NULL)
205     {
206       cache->last_request = now;
207       if (GNUNET_TIME_absolute_get_duration (cache->last_request).rel_value <
208           60 * 60 * 1000)
209         {
210           GNUNET_free_non_null (cache->addr);
211           cache->addr = NULL;
212           cache->salen = 0;
213           cache_resolve (cache);
214         }
215     }
216   else
217     {
218       cache = GNUNET_malloc (sizeof (struct IPCache));
219       cache->next = head;
220       cache->salen = salen;
221       cache->sa = GNUNET_malloc (salen);
222       memcpy (cache->sa, sa, salen);
223       cache->last_request = GNUNET_TIME_absolute_get ();
224       cache->last_refresh = GNUNET_TIME_absolute_get ();
225       cache->addr = NULL;
226       cache_resolve (cache);
227       head = cache;
228     }
229   tc = GNUNET_SERVER_transmit_context_create (client);
230   if (cache->addr != NULL)
231     GNUNET_SERVER_transmit_context_append_data (tc,
232                                                 cache->addr,
233                                                 strlen (cache->addr) + 1,
234                                                 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
235   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
236                                               GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
237   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
238 }
239
240
241 #if HAVE_GETADDRINFO
242 static int
243 getaddrinfo_resolve (struct GNUNET_SERVER_TransmitContext *tc,
244                      const char *hostname, int domain)
245 {
246   int s;
247   struct addrinfo hints;
248   struct addrinfo *result;
249   struct addrinfo *pos;
250
251   memset (&hints, 0, sizeof (struct addrinfo));
252 // FIXME in PlibC
253 #ifndef MINGW
254   hints.ai_family = domain;
255 #else
256   hints.ai_family = AF_INET;
257 #endif
258   hints.ai_socktype = SOCK_STREAM;      /* go for TCP */
259
260   if (0 != (s = getaddrinfo (hostname, NULL, &hints, &result)))
261     {
262       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
263                   _("Could not resolve `%s' (%s): %s\n"), hostname,
264                   (domain ==
265                    AF_INET) ? "IPv4" : ((domain ==
266                                          AF_INET6) ? "IPv6" : "any"),
267                   gai_strerror (s));
268       if ((s == EAI_BADFLAGS) || (s == EAI_MEMORY) 
269 #ifndef MINGW
270           || (s == EAI_SYSTEM)
271 #else
272           // FIXME NILS
273           || 1
274 #endif
275         )
276         return GNUNET_NO;       /* other function may still succeed */
277       return GNUNET_SYSERR;
278     }
279   if (result == NULL)
280     return GNUNET_SYSERR;
281   pos = result;
282   while (pos != NULL)
283     {
284       GNUNET_SERVER_transmit_context_append_data (tc,
285                                                   pos->ai_addr,
286                                                   pos->ai_addrlen,
287                                                   GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
288       pos = pos->ai_next;
289     }
290   freeaddrinfo (result);
291   return GNUNET_OK;
292 }
293 #endif
294
295 #if HAVE_GETHOSTBYNAME2
296 static int
297 gethostbyname2_resolve (struct GNUNET_SERVER_TransmitContext *tc,
298                         const char *hostname, int domain)
299 {
300   struct hostent *hp;
301   struct sockaddr_in a4;
302   struct sockaddr_in6 a6;
303   int ret1;
304   int ret2;
305
306   if (domain == AF_UNSPEC)
307     {
308       ret1 = gethostbyname2_resolve (tc, hostname, AF_INET);
309       ret2 = gethostbyname2_resolve (tc, hostname, AF_INET6);
310       if ((ret1 == GNUNET_OK) || (ret2 == GNUNET_OK))
311         return GNUNET_OK;
312       if ((ret1 == GNUNET_SYSERR) || (ret2 == GNUNET_SYSERR))
313         return GNUNET_SYSERR;
314       return GNUNET_NO;
315     }
316   hp = gethostbyname2 (hostname, domain);
317   if (hp == NULL)
318     {
319       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
320                   _("Could not find IP of host `%s': %s\n"),
321                   hostname, hstrerror (h_errno));
322       return GNUNET_SYSERR;
323     }
324   GNUNET_assert (hp->h_addrtype == domain);
325   if (domain == AF_INET)
326     {
327       GNUNET_assert (hp->h_length == sizeof (struct in_addr));
328       memset (&a4, 0, sizeof (a4));
329       a4.sin_family = AF_INET;
330 #if HAVE_SOCKADDR_IN_SIN_LEN
331       a4.sin_len = (u_char) sizeof (struct sockaddr_in);
332 #endif
333       memcpy (&a4.sin_addr, hp->h_addr_list[0], hp->h_length);
334       GNUNET_SERVER_transmit_context_append_data (tc,
335                                                   &a4,
336                                                   sizeof (a4),
337                                                   GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
338     }
339   else
340     {
341       GNUNET_assert (hp->h_length == sizeof (struct in6_addr));
342       memset (&a6, 0, sizeof (a6));
343       a6.sin6_family = AF_INET6;
344 #if HAVE_SOCKADDR_IN_SIN_LEN
345       a6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
346 #endif
347       memcpy (&a6.sin6_addr, hp->h_addr_list[0], hp->h_length);
348       GNUNET_SERVER_transmit_context_append_data (tc,
349                                                   &a6,
350                                                   sizeof (a6),
351                                                   GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
352     }
353   return GNUNET_OK;
354 }
355 #endif
356
357 #if HAVE_GETHOSTBYNAME
358 static int
359 gethostbyname_resolve (struct GNUNET_SERVER_TransmitContext *tc,
360                        const char *hostname)
361 {
362   struct hostent *hp;
363   struct sockaddr_in addr;
364
365   hp = GETHOSTBYNAME (hostname);
366   if (hp == NULL)
367     {
368       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
369                   _("Could not find IP of host `%s': %s\n"),
370                   hostname, hstrerror (h_errno));
371       return GNUNET_SYSERR;
372     }
373   if (hp->h_addrtype != AF_INET)
374     {
375       GNUNET_break (0);
376       return GNUNET_SYSERR;
377     }
378   GNUNET_assert (hp->h_length == sizeof (struct in_addr));
379   memset (&addr, 0, sizeof (addr));
380   addr.sin_family = AF_INET;
381 #if HAVE_SOCKADDR_IN_SIN_LEN
382   addr.sin_len = (u_char) sizeof (struct sockaddr_in);
383 #endif
384   memcpy (&addr.sin_addr, hp->h_addr_list[0], hp->h_length);
385   GNUNET_SERVER_transmit_context_append_data (tc,
386                                               &addr,
387                                               sizeof (addr),
388                                               GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
389   return GNUNET_OK;
390 }
391 #endif
392
393
394 /**
395  * Convert a string to an IP address.
396  *
397  * @param client where to send the IP address
398  * @param hostname the hostname to resolve
399  * @param domain AF_INET or AF_INET6; use AF_UNSPEC for "any"
400  */
401 static void
402 get_ip_from_hostname (struct GNUNET_SERVER_Client *client,
403                       const char *hostname, int domain)
404 {
405   int ret;
406   struct GNUNET_SERVER_TransmitContext *tc;
407
408   tc = GNUNET_SERVER_transmit_context_create (client);
409   ret = GNUNET_NO;
410 #if HAVE_GETADDRINFO
411   if (ret == GNUNET_NO)
412     ret = getaddrinfo_resolve (tc, hostname, domain);
413 #endif
414 #if HAVE_GETHOSTBYNAME2
415   if (ret == GNUNET_NO)
416     ret = gethostbyname2_resolve (tc, hostname, domain);
417 #endif
418 #if HAVE_GETHOSTBYNAME
419   if ((ret == GNUNET_NO) && ((domain == AF_UNSPEC) || (domain == PF_INET)))
420     gethostbyname_resolve (tc, hostname);
421 #endif
422   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
423                                               GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
424   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
425 }
426
427
428 /**
429  * Handle GET-message.
430  *
431  * @param cls closure
432  * @param client identification of the client
433  * @param message the actual message
434  */
435 static void
436 handle_get (void *cls,
437             struct GNUNET_SERVER_Client *client,
438             const struct GNUNET_MessageHeader *message)
439 {
440   uint16_t msize;
441   const struct GNUNET_RESOLVER_GetMessage *msg;
442   const char *hostname;
443   uint16_t size;
444   int direction;
445   int domain;
446
447   msize = ntohs (message->size);
448   if (msize < sizeof (struct GNUNET_RESOLVER_GetMessage))
449     {
450       GNUNET_break (0);
451       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
452       return;
453     }
454   msg = (const struct GNUNET_RESOLVER_GetMessage *) message;
455   size = msize - sizeof (struct GNUNET_RESOLVER_GetMessage);
456   direction = ntohl (msg->direction);
457   domain = ntohl (msg->domain);
458   if (direction == GNUNET_NO)
459     {
460       /* IP from hostname */
461       hostname = (const char *) &msg[1];
462       if (hostname[size - 1] != '\0')
463         {
464           GNUNET_break (0);
465           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
466           return;
467         }
468 #if DEBUG_RESOLVER
469       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
470                   _("Resolver asked to look up `%s'.\n"), hostname);
471 #endif
472       get_ip_from_hostname (client, hostname, domain);
473     }
474   else
475     {
476 #if DEBUG_RESOLVER
477       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
478                   _("Resolver asked to look up IP address.\n"));
479 #endif
480       get_ip_as_string (client, (const struct sockaddr *) &msg[1], size);
481     }
482 }
483
484
485 /**
486  * Process resolver requests.
487  *
488  * @param cls closure
489  * @param server the initialized server
490  * @param cfg configuration to use
491  */
492 static void
493 run (void *cls,
494      struct GNUNET_SERVER_Handle *server,
495      const struct GNUNET_CONFIGURATION_Handle *cfg)
496 {
497   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
498     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST, 0},
499     {NULL, NULL, 0, 0}
500   };
501   GNUNET_SERVER_add_handlers (server, handlers);
502 }
503
504
505 /**
506  * The main function for the resolver service.
507  *
508  * @param argc number of arguments from the command line
509  * @param argv command line arguments
510  * @return 0 ok, 1 on error
511  */
512 int
513 main (int argc, char *const *argv)
514 {
515   int ret;
516   struct IPCache *pos;
517
518   ret = (GNUNET_OK ==
519          GNUNET_SERVICE_run (argc,
520                              argv,
521                              "resolver", GNUNET_SERVICE_OPTION_NONE,
522                              &run, NULL)) ? 0 : 1;
523
524   while (head != NULL)
525     {
526       pos = head->next;
527       GNUNET_free_non_null (head->addr);
528       GNUNET_free (head->sa);
529       GNUNET_free (head);
530       head = pos;
531     }
532   return ret;
533 }
534
535 /* end of gnunet-service-resolver.c */