better comments
[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, 
95                         sizeof(hostname), 
96                         NULL, 0, 0))
97     cache->addr = GNUNET_strdup (hostname);
98 }
99 #endif
100
101
102 #if HAVE_GETHOSTBYADDR
103 /**
104  * Resolve the given request using gethostbyaddr
105  *
106  * @param cache the request to resolve (and where to store the result)
107  */
108 static void
109 gethostbyaddr_resolve (struct IPCache *cache)
110 {
111   struct hostent *ent;
112
113   switch (cache->sa->sa_family)
114     {
115     case AF_INET:
116       ent = gethostbyaddr (&((struct sockaddr_in *) cache->sa)->sin_addr,
117                            sizeof (struct in_addr), AF_INET);
118       break;
119     case AF_INET6:
120       ent = gethostbyaddr (&((struct sockaddr_in6 *) cache->sa)->sin6_addr,
121                            sizeof (struct in6_addr), AF_INET6);
122       break;
123     default:
124       ent = NULL;
125     }
126   if (ent != NULL)
127     cache->addr = GNUNET_strdup (ent->h_name);
128 }
129 #endif
130
131 /**
132  * Resolve the given request using the available methods.
133  *
134  * @param cache the request to resolve (and where to store the result)
135  */
136 static void
137 cache_resolve (struct IPCache *cache)
138 {
139 #if HAVE_GETNAMEINFO
140   if (cache->addr == NULL)
141     getnameinfo_resolve (cache);
142 #endif
143 #if HAVE_GETHOSTBYADDR
144   if (cache->addr == NULL)
145     gethostbyaddr_resolve (cache);
146 #endif
147 }
148
149
150
151 /**
152  * Get an IP address as a string (works for both IPv4 and IPv6).  Note
153  * that the resolution happens asynchronously and that the first call
154  * may not immediately result in the FQN (but instead in a
155  * human-readable IP address).
156  *
157  * @param client handle to the client making the request (for sending the reply)
158  * @param sa should be of type "struct sockaddr*"
159  * @param salen number of bytes in sa
160  */
161 static void
162 get_ip_as_string (struct GNUNET_SERVER_Client *client,
163                   const struct sockaddr *sa, socklen_t salen)
164 {
165   struct IPCache *cache;
166   struct IPCache *prev;
167   struct GNUNET_TIME_Absolute now;
168   struct GNUNET_SERVER_TransmitContext *tc;
169
170   if (salen < sizeof (struct sockaddr))
171     {
172       GNUNET_break (0);
173       return;
174     }
175   now = GNUNET_TIME_absolute_get ();
176   cache = head;
177   prev = NULL;
178   while ((cache != NULL) &&
179          ((cache->salen != salen) || (0 != memcmp (cache->sa, sa, salen))))
180     {
181       if (GNUNET_TIME_absolute_get_duration (cache->last_request).value <
182           60 * 60 * 1000)
183         {
184           if (prev != NULL)
185             {
186               prev->next = cache->next;
187               GNUNET_free_non_null (cache->addr);
188               GNUNET_free (cache->sa);
189               GNUNET_free (cache);
190               cache = prev->next;
191             }
192           else
193             {
194               head = cache->next;
195               GNUNET_free_non_null (cache->addr);
196               GNUNET_free (cache->sa);
197               GNUNET_free (cache);
198               cache = head;
199             }
200           continue;
201         }
202       prev = cache;
203       cache = cache->next;
204     }
205   if (cache != NULL)
206     {
207       cache->last_request = now;
208       if (GNUNET_TIME_absolute_get_duration (cache->last_request).value <
209           60 * 60 * 1000)
210         {
211           GNUNET_free_non_null (cache->addr);
212           cache->addr = NULL;
213           cache->salen = 0;
214           cache_resolve (cache);
215         }
216     }
217   else
218     {
219       cache = GNUNET_malloc (sizeof (struct IPCache));
220       cache->next = head;
221       cache->salen = salen;
222       cache->sa = GNUNET_malloc (salen);
223       memcpy (cache->sa, sa, salen);
224       cache->last_request = GNUNET_TIME_absolute_get ();
225       cache->last_refresh = GNUNET_TIME_absolute_get ();
226       cache->addr = NULL;
227       cache_resolve (cache);
228       head = cache;
229     }
230   tc = GNUNET_SERVER_transmit_context_create (client);
231   if (cache->addr != NULL)
232     GNUNET_SERVER_transmit_context_append (tc,
233                                            cache->addr,
234                                            strlen (cache->addr) + 1,
235                                            GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
236   GNUNET_SERVER_transmit_context_append (tc, NULL, 0,
237                                          GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
238   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
239 }
240
241
242 #if HAVE_GETADDRINFO
243 static int
244 getaddrinfo_resolve (struct GNUNET_SERVER_TransmitContext *tc,
245                      const char *hostname, int domain)
246 {
247   int s;
248   struct addrinfo hints;
249   struct addrinfo *result;
250   struct addrinfo *pos;
251
252   memset (&hints, 0, sizeof (struct addrinfo));
253 // FIXME in PlibC
254 #ifndef MINGW
255   hints.ai_family = domain;
256 #else
257   hints.ai_family = AF_INET;
258 #endif
259   hints.ai_socktype = SOCK_STREAM;      /* go for TCP */
260
261   if (0 != (s = getaddrinfo (hostname, NULL, &hints, &result)))
262     {
263       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
264                   _("Could not resolve `%s' (%s): %s\n"), hostname,
265                   (domain ==
266                    AF_INET) ? "IPv4" : ((domain ==
267                                          AF_INET6) ? "IPv6" : "any"),
268                   gai_strerror (s));
269       if ((s == EAI_BADFLAGS) || (s == EAI_MEMORY) ||
270 #ifndef MINGW
271           (s == EAI_SYSTEM)
272 #else
273           // FIXME NILS
274           1
275 #endif
276       )
277         return GNUNET_NO;       /* other function may still succeed */
278       return GNUNET_SYSERR;
279     }
280   if (result == NULL)
281     return GNUNET_SYSERR;
282   pos = result;
283   while (pos != NULL)
284     {
285       GNUNET_SERVER_transmit_context_append (tc,
286                                              result->ai_addr,
287                                              result->ai_addrlen,
288                                              GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
289       pos = pos->ai_next;
290     }
291   freeaddrinfo (result);
292   return GNUNET_OK;
293 }
294 #endif
295
296 #if HAVE_GETHOSTBYNAME2
297 static int
298 gethostbyname2_resolve (struct GNUNET_SERVER_TransmitContext *tc,
299                         const char *hostname, int domain)
300 {
301   struct hostent *hp;
302   struct sockaddr_in a4;
303   struct sockaddr_in6 a6;
304   int ret1;
305   int ret2;
306
307   if (domain == AF_UNSPEC)
308     {
309       ret1 = gethostbyname2_resolve (tc, hostname, AF_INET);
310       ret2 = gethostbyname2_resolve (tc, hostname, AF_INET6);
311       if ((ret1 == GNUNET_OK) || (ret2 == GNUNET_OK))
312         return GNUNET_OK;
313       if ((ret1 == GNUNET_SYSERR) || (ret2 == GNUNET_SYSERR))
314         return GNUNET_SYSERR;
315       return GNUNET_NO;
316     }
317   hp = gethostbyname2 (hostname, domain);
318   if (hp == NULL)
319     {
320       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
321                   _("Could not find IP of host `%s': %s\n"),
322                   hostname, hstrerror (h_errno));
323       return GNUNET_SYSERR;
324     }
325   GNUNET_assert (hp->h_addrtype == domain);
326   if (domain == AF_INET)
327     {
328       GNUNET_assert (hp->h_length == sizeof (struct in_addr));
329       memset (&a4, 0, sizeof (a4));
330       a4.sin_family = AF_INET;
331       memcpy (&a4.sin_addr, hp->h_addr_list[0], hp->h_length);
332       GNUNET_SERVER_transmit_context_append (tc,
333                                              &a4,
334                                              sizeof (a4),
335                                              GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
336     }
337   else
338     {
339       GNUNET_assert (hp->h_length == sizeof (struct in6_addr));
340       memset (&a6, 0, sizeof (a6));
341       a6.sin6_family = AF_INET6;
342       memcpy (&a6.sin6_addr, hp->h_addr_list[0], hp->h_length);
343       GNUNET_SERVER_transmit_context_append (tc,
344                                              &a6,
345                                              sizeof (a6),
346                                              GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
347     }
348   return GNUNET_OK;
349 }
350 #endif
351
352 #if HAVE_GETHOSTBYNAME
353 static int
354 gethostbyname_resolve (struct GNUNET_SERVER_TransmitContext *tc,
355                        const char *hostname)
356 {
357   struct hostent *hp;
358   struct sockaddr_in addr;
359
360   hp = GETHOSTBYNAME (hostname);
361   if (hp == NULL)
362     {
363       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
364                   _("Could not find IP of host `%s': %s\n"),
365                   hostname, hstrerror (h_errno));
366       return GNUNET_SYSERR;
367     }
368   if (hp->h_addrtype != AF_INET)
369     {
370       GNUNET_break (0);
371       return GNUNET_SYSERR;
372     }
373   GNUNET_assert (hp->h_length == sizeof (struct in_addr));
374   memset (&addr, 0, sizeof (addr));
375   addr.sin_family = AF_INET;
376   memcpy (&addr.sin_addr, hp->h_addr_list[0], hp->h_length);
377   GNUNET_SERVER_transmit_context_append (tc,
378                                          &addr,
379                                          sizeof (addr),
380                                          GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
381   return GNUNET_OK;
382 }
383 #endif
384
385
386 /**
387  * Convert a string to an IP address.
388  *
389  * @param client where to send the IP address
390  * @param hostname the hostname to resolve
391  * @param domain AF_INET or AF_INET6; use AF_UNSPEC for "any"
392  */
393 static void
394 get_ip_from_hostname (struct GNUNET_SERVER_Client *client,
395                       const char *hostname, int domain)
396 {
397   int ret;
398   struct GNUNET_SERVER_TransmitContext *tc;
399
400   tc = GNUNET_SERVER_transmit_context_create (client);
401   ret = GNUNET_NO;
402 #if HAVE_GETADDRINFO
403   if (ret == GNUNET_NO)
404     ret = getaddrinfo_resolve (tc, hostname, domain);
405 #endif
406 #if HAVE_GETHOSTBYNAME2
407   if (ret == GNUNET_NO)
408     ret = gethostbyname2_resolve (tc, hostname, domain);
409 #endif
410 #if HAVE_GETHOSTBYNAME
411   if ((ret == GNUNET_NO) && ((domain == AF_UNSPEC) || (domain == PF_INET)))
412     gethostbyname_resolve (tc, hostname);
413 #endif
414   GNUNET_SERVER_transmit_context_append (tc, NULL, 0,
415                                          GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
416   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
417 }
418
419
420 /**
421  * Handle GET-message.
422  *
423  * @param cls closure
424  * @param client identification of the client
425  * @param message the actual message
426  */
427 static void
428 handle_get (void *cls,
429             struct GNUNET_SERVER_Client *client,
430             const struct GNUNET_MessageHeader *message)
431 {
432   uint16_t msize;
433   const struct GNUNET_RESOLVER_GetMessage *msg;
434   const char *hostname;
435   uint16_t size;
436   int direction;
437   int domain;
438
439   msize = ntohs (message->size);
440   if (msize < sizeof (struct GNUNET_RESOLVER_GetMessage))
441     {
442       GNUNET_break (0);
443       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
444       return;
445     }
446   msg = (const struct GNUNET_RESOLVER_GetMessage *) message;
447   size = msize - sizeof (struct GNUNET_RESOLVER_GetMessage);
448   direction = ntohl (msg->direction);
449   domain = ntohl (msg->domain);
450   if (direction == GNUNET_NO)
451     {
452       /* IP from hostname */
453       hostname = (const char *) &msg[1];
454       if (hostname[size - 1] != '\0')
455         {
456           GNUNET_break (0);
457           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
458           return;
459         }
460 #if DEBUG_RESOLVER
461       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
462                   _("Resolver asked to look up `%s'.\n"), hostname);
463 #endif
464       get_ip_from_hostname (client, hostname, domain);
465     }
466   else
467     {
468 #if DEBUG_RESOLVER
469       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
470                   _("Resolver asked to look up IP address.\n"));
471 #endif
472       get_ip_as_string (client, (const struct sockaddr *) &msg[1], size);
473     }
474 }
475
476
477 /**
478  * List of handlers for the messages understood by this
479  * service.
480  */
481 static struct GNUNET_SERVER_MessageHandler handlers[] = {
482   {&handle_get, NULL, GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST, 0},
483   {NULL, NULL, 0, 0}
484 };
485
486
487 /**
488  * Process resolver requests.
489  *
490  * @param cls closure
491  * @param sched scheduler to use
492  * @param server the initialized server
493  * @param cfg configuration to use
494  */
495 static void
496 run (void *cls,
497      struct GNUNET_SCHEDULER_Handle *sched,
498      struct GNUNET_SERVER_Handle *server,
499      const struct GNUNET_CONFIGURATION_Handle *cfg)
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", &run, NULL, NULL, NULL)) ? 0 : 1;
522
523   while (head != NULL)
524     {
525       pos = head->next;
526       GNUNET_free_non_null (head->addr);
527       GNUNET_free (head->sa);
528       GNUNET_free (head);
529       head = pos;
530     }
531   return ret;
532 }
533
534 /* end of gnunet-service-resolver.c */