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