c15f0d3f54925bb742e6f90cab73961c1cbfda7b
[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 ==
91       getnameinfo (cache->sa, cache->salen, hostname, sizeof (hostname), NULL,
92                    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 =
113         gethostbyaddr (&((struct sockaddr_in *) cache->sa)->sin_addr,
114                        sizeof (struct in_addr), AF_INET);
115       break;
116     case AF_INET6:
117       ent =
118         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, cache->addr,
232                                                 strlen (cache->addr) + 1,
233                                                 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
234   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
235                                               GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
236   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
237 }
238
239
240 #if HAVE_GETADDRINFO
241 static int
242 getaddrinfo_resolve (struct GNUNET_SERVER_TransmitContext *tc,
243                      const char *hostname, int domain)
244 {
245   int s;
246   struct addrinfo hints;
247   struct addrinfo *result;
248   struct addrinfo *pos;
249
250   memset (&hints, 0, sizeof (struct addrinfo));
251 // FIXME in PlibC
252 #ifndef MINGW
253   hints.ai_family = domain;
254 #else
255   hints.ai_family = AF_INET;
256 #endif
257   hints.ai_socktype = SOCK_STREAM;      /* go for TCP */
258
259   if (0 != (s = getaddrinfo (hostname, NULL, &hints, &result)))
260     {
261       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
262                   _("Could not resolve `%s' (%s): %s\n"), hostname,
263                   (domain ==
264                    AF_INET) ? "IPv4" : ((domain ==
265                                          AF_INET6) ? "IPv6" : "any"),
266                   gai_strerror (s));
267       if ((s == EAI_BADFLAGS) || (s == EAI_MEMORY)
268 #ifndef MINGW
269           || (s == EAI_SYSTEM)
270 #else
271           // FIXME NILS
272           || 1
273 #endif
274         )
275         return GNUNET_NO;       /* other function may still succeed */
276       return GNUNET_SYSERR;
277     }
278   if (result == NULL)
279     return GNUNET_SYSERR;
280   pos = result;
281   while (pos != NULL)
282     {
283       GNUNET_SERVER_transmit_context_append_data (tc, 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"), hostname,
319                   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, &a4, sizeof (a4),
333                                                   GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
334     }
335   else
336     {
337       GNUNET_assert (hp->h_length == sizeof (struct in6_addr));
338       memset (&a6, 0, sizeof (a6));
339       a6.sin6_family = AF_INET6;
340 #if HAVE_SOCKADDR_IN_SIN_LEN
341       a6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
342 #endif
343       memcpy (&a6.sin6_addr, hp->h_addr_list[0], hp->h_length);
344       GNUNET_SERVER_transmit_context_append_data (tc, &a6, sizeof (a6),
345                                                   GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
346     }
347   return GNUNET_OK;
348 }
349 #endif
350
351 #if HAVE_GETHOSTBYNAME
352 static int
353 gethostbyname_resolve (struct GNUNET_SERVER_TransmitContext *tc,
354                        const char *hostname)
355 {
356   struct hostent *hp;
357   struct sockaddr_in addr;
358
359   hp = GETHOSTBYNAME (hostname);
360   if (hp == NULL)
361     {
362       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
363                   _("Could not find IP of host `%s': %s\n"), hostname,
364                   hstrerror (h_errno));
365       return GNUNET_SYSERR;
366     }
367   if (hp->h_addrtype != AF_INET)
368     {
369       GNUNET_break (0);
370       return GNUNET_SYSERR;
371     }
372   GNUNET_assert (hp->h_length == sizeof (struct in_addr));
373   memset (&addr, 0, sizeof (addr));
374   addr.sin_family = AF_INET;
375 #if HAVE_SOCKADDR_IN_SIN_LEN
376   addr.sin_len = (u_char) sizeof (struct sockaddr_in);
377 #endif
378   memcpy (&addr.sin_addr, hp->h_addr_list[0], hp->h_length);
379   GNUNET_SERVER_transmit_context_append_data (tc, &addr, 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_data (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, struct GNUNET_SERVER_Client *client,
429             const struct GNUNET_MessageHeader *message)
430 {
431   uint16_t msize;
432   const struct GNUNET_RESOLVER_GetMessage *msg;
433   const char *hostname;
434   const struct sockaddr *sa;
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       char buf[INET6_ADDRSTRLEN];
470 #endif
471       if (size < sizeof (struct sockaddr))
472         {
473           GNUNET_break (0);
474           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
475           return;
476         }
477       sa = (const struct sockaddr *) &msg[1];
478       switch (sa->sa_family)
479         {
480         case AF_INET:
481           if (size != sizeof (struct sockaddr_in))
482             {
483               GNUNET_break (0);
484               GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
485               return;
486             }
487 #if DEBUG_RESOLVER
488           inet_ntop (AF_INET, sa, buf, size);
489 #endif
490           break;
491         case AF_INET6:
492           if (size != sizeof (struct sockaddr_in6))
493             {
494               GNUNET_break (0);
495               GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
496               return;
497             }
498 #if DEBUG_RESOLVER
499           inet_ntop (AF_INET6, sa, buf, size);
500 #endif
501           break;
502         default:
503           GNUNET_break (0);
504           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
505           return;
506         }
507 #if DEBUG_RESOLVER
508       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
509                   _("Resolver asked to look up IP address `%s'.\n"), buf);
510 #endif
511       get_ip_as_string (client, sa, size);
512     }
513 }
514
515
516 /**
517  * Process resolver requests.
518  *
519  * @param cls closure
520  * @param server the initialized server
521  * @param cfg configuration to use
522  */
523 static void
524 run (void *cls, struct GNUNET_SERVER_Handle *server,
525      const struct GNUNET_CONFIGURATION_Handle *cfg)
526 {
527   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
528     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST, 0},
529     {NULL, NULL, 0, 0}
530   };
531   GNUNET_SERVER_add_handlers (server, handlers);
532 }
533
534
535 /**
536  * The main function for the resolver service.
537  *
538  * @param argc number of arguments from the command line
539  * @param argv command line arguments
540  * @return 0 ok, 1 on error
541  */
542 int
543 main (int argc, char *const *argv)
544 {
545   int ret;
546   struct IPCache *pos;
547
548   ret =
549     (GNUNET_OK ==
550      GNUNET_SERVICE_run (argc, argv, "resolver", GNUNET_SERVICE_OPTION_NONE,
551                          &run, NULL)) ? 0 : 1;
552
553   while (head != NULL)
554     {
555       pos = head->next;
556       GNUNET_free_non_null (head->addr);
557       GNUNET_free (head->sa);
558       GNUNET_free (head);
559       head = pos;
560     }
561   return ret;
562 }
563
564 /* end of gnunet-service-resolver.c */