removing retry code
[oweals/gnunet.git] / src / util / resolver_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2011 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/resolver_api.c
23  * @brief resolver for writing a tool
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_getopt_lib.h"
28 #include "gnunet_os_lib.h"
29 #include "gnunet_client_lib.h"
30 #include "gnunet_container_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_resolver_service.h"
33 #include "gnunet_server_lib.h"
34 #include "resolver.h"
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "resolver-api", __VA_ARGS__)
37
38 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "resolver-api", syscall)
39
40 /**
41  * Maximum supported length for a hostname
42  */
43 #define MAX_HOSTNAME 1024
44
45
46 /**
47  * Possible hostnames for "loopback".
48  */
49 static const char *loopback[] = {
50   "localhost",
51   "ip6-localnet",
52   NULL
53 };
54
55
56 /**
57  * Configuration.
58  */
59 static const struct GNUNET_CONFIGURATION_Handle *resolver_cfg;
60
61 /**
62  * Our connection to the resolver service, created on-demand, but then
63  * persists until error or shutdown.
64  */
65 static struct GNUNET_CLIENT_Connection *client;
66
67 /**
68  * Head of DLL of requests.
69  */
70 static struct GNUNET_RESOLVER_RequestHandle *req_head;
71
72 /**
73  * Tail of DLL of requests.
74  */
75 static struct GNUNET_RESOLVER_RequestHandle *req_tail;
76
77 /**
78  * How long should we wait to reconnect?
79  */
80 static struct GNUNET_TIME_Relative backoff;
81
82 /**
83  * Task for reconnecting.
84  */
85 static GNUNET_SCHEDULER_TaskIdentifier r_task;
86
87 /**
88  * Task ID of shutdown task; only present while we have a
89  * connection to the resolver service.
90  */
91 static GNUNET_SCHEDULER_TaskIdentifier s_task;
92
93
94 /**
95  * Handle to a request given to the resolver.  Can be used to cancel
96  * the request prior to the timeout or successful execution.  Also
97  * used to track our internal state for the request.
98  */
99 struct GNUNET_RESOLVER_RequestHandle
100 {
101
102   /**
103    * Next entry in DLL of requests.
104    */
105   struct GNUNET_RESOLVER_RequestHandle *next;
106
107   /**
108    * Previous entry in DLL of requests.
109    */
110   struct GNUNET_RESOLVER_RequestHandle *prev;
111
112   /**
113    * Callback if this is an name resolution request,
114    * otherwise NULL.
115    */
116   GNUNET_RESOLVER_AddressCallback addr_callback;
117
118   /**
119    * Callback if this is a reverse lookup request,
120    * otherwise NULL.
121    */
122   GNUNET_RESOLVER_HostnameCallback name_callback;
123
124   /**
125    * Closure for the respective "callback".
126    */
127   void *cls;
128
129   /**
130    * When should this request time out?
131    */
132   struct GNUNET_TIME_Absolute timeout;
133
134   /**
135    * Task handle for numeric lookups.
136    */
137   GNUNET_SCHEDULER_TaskIdentifier task;
138
139   /**
140    * Desired address family.
141    */
142   int af;
143
144   /**
145    * Has this request been transmitted to the service?
146    * GNUNET_YES if transmitted
147    * GNUNET_YES if not transmitted
148    * GNUNET_SYSERR when request was canceled
149    */
150   int was_transmitted;
151
152   /**
153    * Did we add this request to the queue?
154    */
155   int was_queued;
156
157   /**
158    * Desired direction (IP to name or name to IP)
159    */
160   int direction;
161
162   /**
163    * GNUNET_YES if a response was received
164    */
165   int received_response;
166
167   /**
168    * Length of the data that follows this struct.
169    */
170   size_t data_len;
171 };
172
173
174 /**
175  * Check that the resolver service runs on localhost
176  * (or equivalent).
177  */
178 static void
179 check_config ()
180 {
181   char *hostname;
182   unsigned int i;
183   struct sockaddr_in v4;
184   struct sockaddr_in6 v6;
185
186   memset (&v4, 0, sizeof (v4));
187   v4.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
188   v4.sin_family = AF_INET;
189 #if HAVE_SOCKADDR_IN_SIN_LEN
190   v4.sin_len = sizeof (v4);
191 #endif
192   memset (&v6, 0, sizeof (v6));
193   v6.sin6_family = AF_INET6;
194 #if HAVE_SOCKADDR_IN_SIN_LEN
195   v6.sin6_len = sizeof (v6);
196 #endif
197   if (GNUNET_OK !=
198       GNUNET_CONFIGURATION_get_value_string (resolver_cfg, "resolver",
199                                              "HOSTNAME", &hostname))
200   {
201     LOG (GNUNET_ERROR_TYPE_ERROR,
202          _("Must specify `%s' for `%s' in configuration!\n"), "HOSTNAME",
203          "resolver");
204     GNUNET_assert (0);
205   }
206   if ((1 != inet_pton (AF_INET, hostname, &v4)) ||
207       (1 != inet_pton (AF_INET6, hostname, &v6)))
208   {
209     GNUNET_free (hostname);
210     return;
211   }
212   i = 0;
213   while (loopback[i] != NULL)
214     if (0 == strcasecmp (loopback[i++], hostname))
215     {
216       GNUNET_free (hostname);
217       return;
218     }
219   LOG (GNUNET_ERROR_TYPE_ERROR,
220        _
221        ("Must specify `%s' or numeric IP address for `%s' of `%s' in configuration!\n"),
222        "localhost", "HOSTNAME", "resolver");
223   GNUNET_free (hostname);
224   GNUNET_assert (0);
225 }
226
227
228 /**
229  * Create the connection to the resolver service.
230  *
231  * @param cfg configuration to use
232  */
233 void
234 GNUNET_RESOLVER_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
235 {
236   GNUNET_assert (NULL != cfg);
237   backoff = GNUNET_TIME_UNIT_MILLISECONDS;
238   resolver_cfg = cfg;
239   check_config ();
240 }
241
242
243 /**
244  * Destroy the connection to the resolver service.
245  */
246 void
247 GNUNET_RESOLVER_disconnect ()
248 {
249   GNUNET_assert (NULL == req_head);
250   GNUNET_assert (NULL == req_tail);
251   if (NULL != client)
252   {
253 #if DEBUG_RESOLVER
254     LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from DNS service\n");
255 #endif
256     GNUNET_CLIENT_disconnect (client, GNUNET_NO);
257     client = NULL;
258   }
259   if (r_task != GNUNET_SCHEDULER_NO_TASK)
260   {
261     GNUNET_SCHEDULER_cancel (r_task);
262     r_task = GNUNET_SCHEDULER_NO_TASK;
263   }
264   if (s_task != GNUNET_SCHEDULER_NO_TASK)
265   {
266     GNUNET_SCHEDULER_cancel (s_task);
267     s_task = GNUNET_SCHEDULER_NO_TASK;
268   }
269 }
270
271
272 /**
273  * Convert IP address to string without DNS resolution.
274  *
275  * @param sa the address
276  * @param salen number of bytes in sa
277  * @return address as a string, NULL on error
278  */
279 static char *
280 no_resolve (const struct sockaddr *sa, socklen_t salen)
281 {
282   char *ret;
283   char inet4[INET_ADDRSTRLEN];
284   char inet6[INET6_ADDRSTRLEN];
285
286   if (salen < sizeof (struct sockaddr))
287     return NULL;
288   switch (sa->sa_family)
289   {
290   case AF_INET:
291     if (salen != sizeof (struct sockaddr_in))
292       return NULL;
293     if (NULL ==
294         inet_ntop (AF_INET, &((struct sockaddr_in *) sa)->sin_addr, inet4,
295                    INET_ADDRSTRLEN))
296     {
297       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
298       return NULL;
299     }
300     ret = GNUNET_strdup (inet4);
301     break;
302   case AF_INET6:
303     if (salen != sizeof (struct sockaddr_in6))
304       return NULL;
305     if (NULL ==
306         inet_ntop (AF_INET6, &((struct sockaddr_in6 *) sa)->sin6_addr, inet6,
307                    INET6_ADDRSTRLEN))
308     {
309       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
310       return NULL;
311     }
312     ret = GNUNET_strdup (inet6);
313     break;
314   default:
315     ret = NULL;
316     break;
317   }
318   return ret;
319 }
320
321
322 /**
323  * Adjust exponential back-off and reconnect to the service.
324  */
325 static void
326 reconnect ();
327
328
329 /**
330  * Process pending requests to the resolver.
331  */
332 static void
333 process_requests ();
334
335
336 /**
337  * Process response with a hostname for a DNS lookup.
338  *
339  * @param cls our "struct GNUNET_RESOLVER_RequestHandle" context
340  * @param msg message with the hostname, NULL on error
341  */
342 static void
343 handle_response (void *cls, const struct GNUNET_MessageHeader *msg)
344 {
345   struct GNUNET_RESOLVER_RequestHandle *rh = cls;
346   uint16_t size;
347
348 #if DEBUG_RESOLVER
349   LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving response from DNS service\n");
350 #endif
351   if (msg == NULL)
352   {
353     char buf[INET6_ADDRSTRLEN];
354
355     if (NULL != rh->name_callback)
356       LOG (GNUNET_ERROR_TYPE_INFO,
357            _("Timeout trying to resolve IP address `%s'.\n"),
358            inet_ntop (rh->af, (const void *) &rh[1], buf, sizeof(buf)));
359     else
360       LOG (GNUNET_ERROR_TYPE_INFO,
361            _("Timeout trying to resolve hostname `%s'.\n"),
362            (const char *) &rh[1]);
363     /* check if request was canceled */
364     if (rh->was_transmitted != GNUNET_SYSERR)
365     {
366       if (NULL != rh->name_callback)
367       {
368         /* no reverse lookup was successful, return ip as string */
369         if (rh->received_response == GNUNET_NO)
370           rh->name_callback (rh->cls,
371                              no_resolve ((const struct sockaddr *) &rh[1],
372                                          rh->data_len));
373         /* at least one reverse lookup was successful */
374         else
375           rh->name_callback (rh->cls, NULL);
376       }
377       if (NULL != rh->addr_callback)
378         rh->addr_callback (rh->cls, NULL, 0);
379     }
380     GNUNET_CONTAINER_DLL_remove (req_head, req_tail, rh);
381     GNUNET_free (rh);
382     GNUNET_CLIENT_disconnect (client, GNUNET_NO);
383     client = NULL;
384     reconnect ();
385     return;
386   }
387   if (GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE != ntohs (msg->type))
388   {
389     GNUNET_break (0);
390     GNUNET_CLIENT_disconnect (client, GNUNET_NO);
391     client = NULL;
392     reconnect ();
393     return;
394   }
395   size = ntohs (msg->size);
396   /* message contains not data, just header */
397   if (size == sizeof (struct GNUNET_MessageHeader))
398   {
399     /* check if request was canceled */
400     if (rh->was_transmitted != GNUNET_SYSERR)
401     {
402       if (NULL != rh->name_callback)
403         rh->name_callback (rh->cls, NULL);
404       if (NULL != rh->addr_callback)
405         rh->addr_callback (rh->cls, NULL, 0);
406     }
407     GNUNET_CONTAINER_DLL_remove (req_head, req_tail, rh);
408     GNUNET_free (rh);
409     process_requests ();
410     return;
411   }
412   /* return reverse lookup results to caller */
413   if (NULL != rh->name_callback)
414   {
415     const char *hostname;
416
417     hostname = (const char *) &msg[1];
418     if (hostname[size - sizeof (struct GNUNET_MessageHeader) - 1] != '\0')
419     {
420       GNUNET_break (0);
421       if (rh->was_transmitted != GNUNET_SYSERR)
422         rh->name_callback (rh->cls, NULL);
423       GNUNET_CONTAINER_DLL_remove (req_head, req_tail, rh);
424       GNUNET_free (rh);
425       GNUNET_CLIENT_disconnect (client, GNUNET_NO);
426       client = NULL;
427       reconnect ();
428       return;
429     }
430 #if DEBUG_RESOLVER
431     LOG (GNUNET_ERROR_TYPE_DEBUG, _("Resolver returns `%s' for IP `%s'.\n"),
432          hostname, GNUNET_a2s ((const void *) &rh[1], rh->data_len));
433 #endif
434     if (rh->was_transmitted != GNUNET_SYSERR)
435       rh->name_callback (rh->cls, hostname);
436     rh->received_response = GNUNET_YES;
437     GNUNET_CLIENT_receive (client, &handle_response, rh,
438                            GNUNET_TIME_absolute_get_remaining (rh->timeout));
439   }
440   /* return lookup results to caller */
441   if (NULL != rh->addr_callback)
442   {
443     struct sockaddr_in v4;
444     struct sockaddr_in6 v6;
445     const struct sockaddr *sa;
446     socklen_t salen;
447     const void *ip;
448     size_t ip_len;
449
450     ip = &msg[1];
451     ip_len = size - sizeof (struct GNUNET_MessageHeader);
452     if (ip_len == sizeof (struct in_addr))
453     {
454       memset (&v4, 0, sizeof (v4));
455       v4.sin_family = AF_INET;
456       v4.sin_addr = *(struct in_addr*) ip;
457 #if HAVE_SOCKADDR_IN_SIN_LEN
458       v4.sin_len = sizeof (v4);
459 #endif
460       salen = sizeof (v4);
461       sa = (const struct sockaddr *) &v4;
462     }
463     else if (ip_len == sizeof (struct in6_addr))
464     {
465       memset (&v6, 0, sizeof (v6));
466       v6.sin6_family = AF_INET6;
467       v6.sin6_addr = *(struct in6_addr*) ip;
468 #if HAVE_SOCKADDR_IN_SIN_LEN
469       v6.sin6_len = sizeof (v6);
470 #endif
471       salen = sizeof (v6);
472       sa = (const struct sockaddr *) &v6;
473     }
474     else
475     {
476       GNUNET_break (0);
477       if (rh->was_transmitted != GNUNET_SYSERR)
478         rh->addr_callback (rh->cls, NULL, 0);
479       GNUNET_CONTAINER_DLL_remove (req_head, req_tail, rh);
480       GNUNET_free (rh);
481       GNUNET_CLIENT_disconnect (client, GNUNET_NO);
482       client = NULL;
483       reconnect ();
484       return;
485     }
486 #if DEBUG_RESOLVER
487     {
488       char *ips = no_resolve (sa, salen);
489
490       LOG (GNUNET_ERROR_TYPE_DEBUG, "Resolver returns `%s' for `%s'.\n", ips,
491            (const char *) &rh[1]);
492       GNUNET_free (ips);
493     }
494 #endif
495     rh->addr_callback (rh->cls, sa, salen);
496     GNUNET_CLIENT_receive (client, &handle_response, rh,
497                            GNUNET_TIME_absolute_get_remaining (rh->timeout));
498   }
499 }
500
501
502 /**
503  * We've been asked to lookup the address for a hostname and were
504  * given a valid numeric string.  Perform the callbacks for the
505  * numeric addresses.
506  *
507  * @param cls struct GNUNET_RESOLVER_RequestHandle for the request
508  * @param tc unused scheduler context
509  */
510 static void
511 numeric_resolution (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
512 {
513   struct GNUNET_RESOLVER_RequestHandle *rh = cls;
514   struct sockaddr_in v4;
515   struct sockaddr_in6 v6;
516   const char *hostname;
517
518   memset (&v4, 0, sizeof (v4));
519   v4.sin_family = AF_INET;
520 #if HAVE_SOCKADDR_IN_SIN_LEN
521   v4.sin_len = sizeof (v4);
522 #endif
523   memset (&v6, 0, sizeof (v6));
524   v6.sin6_family = AF_INET6;
525 #if HAVE_SOCKADDR_IN_SIN_LEN
526   v6.sin6_len = sizeof (v6);
527 #endif
528   hostname = (const char *) &rh[1];
529   if (((rh->af == AF_UNSPEC) || (rh->af == AF_INET)) &&
530       (1 == inet_pton (AF_INET, hostname, &v4.sin_addr)))
531   {
532     rh->addr_callback (rh->cls, (const struct sockaddr *) &v4, sizeof (v4));
533     if ((rh->af == AF_UNSPEC) &&
534         (1 == inet_pton (AF_INET6, hostname, &v6.sin6_addr)))
535     {
536       /* this can happen on some systems IF "hostname" is "localhost" */
537       rh->addr_callback (rh->cls, (const struct sockaddr *) &v6, sizeof (v6));
538     }
539     rh->addr_callback (rh->cls, NULL, 0);
540     GNUNET_free (rh);
541     return;
542   }
543   if (((rh->af == AF_UNSPEC) || (rh->af == AF_INET6)) &&
544       (1 == inet_pton (AF_INET6, hostname, &v6.sin6_addr)))
545   {
546     rh->addr_callback (rh->cls, (const struct sockaddr *) &v6, sizeof (v6));
547     rh->addr_callback (rh->cls, NULL, 0);
548     GNUNET_free (rh);
549     return;
550   }
551   /* why are we here? this task should not have been scheduled! */
552   GNUNET_assert (0);
553   GNUNET_free (rh);
554 }
555
556
557 /**
558  * We've been asked to lookup the address for a hostname and were
559  * given a variant of "loopback".  Perform the callbacks for the
560  * respective loopback numeric addresses.
561  *
562  * @param cls struct GNUNET_RESOLVER_RequestHandle for the request
563  * @param tc unused scheduler context
564  */
565 static void
566 loopback_resolution (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
567 {
568   struct GNUNET_RESOLVER_RequestHandle *rh = cls;
569   struct sockaddr_in v4;
570   struct sockaddr_in6 v6;
571
572   memset (&v4, 0, sizeof (v4));
573   v4.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
574   v4.sin_family = AF_INET;
575 #if HAVE_SOCKADDR_IN_SIN_LEN
576   v4.sin_len = sizeof (v4);
577 #endif
578   memset (&v6, 0, sizeof (v6));
579   v6.sin6_family = AF_INET6;
580 #if HAVE_SOCKADDR_IN_SIN_LEN
581   v6.sin6_len = sizeof (v6);
582 #endif
583   v6.sin6_addr = in6addr_loopback;
584   switch (rh->af)
585   {
586   case AF_INET:
587     rh->addr_callback (rh->cls, (const struct sockaddr *) &v4, sizeof (v4));
588     break;
589   case AF_INET6:
590     rh->addr_callback (rh->cls, (const struct sockaddr *) &v6, sizeof (v6));
591     break;
592   case AF_UNSPEC:
593     rh->addr_callback (rh->cls, (const struct sockaddr *) &v6, sizeof (v6));
594     rh->addr_callback (rh->cls, (const struct sockaddr *) &v4, sizeof (v4));
595     break;
596   default:
597     GNUNET_break (0);
598     break;
599   }
600   rh->addr_callback (rh->cls, NULL, 0);
601   GNUNET_free (rh);
602 }
603
604
605 /**
606  * Task executed on system shutdown.
607  */
608 static void
609 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
610 {
611   s_task = GNUNET_SCHEDULER_NO_TASK;
612   GNUNET_RESOLVER_disconnect ();
613 }
614
615
616 /**
617  * Process pending requests to the resolver.
618  */
619 static void
620 process_requests ()
621 {
622   struct GNUNET_RESOLVER_GetMessage *msg;
623   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
624   struct GNUNET_RESOLVER_RequestHandle *rh;
625
626   if (NULL == client)
627   {
628     reconnect ();
629     return;
630   }
631   rh = req_head;
632   if (NULL == rh)
633   {
634     /* nothing to do, release socket really soon if there is nothing
635      * else happening... */
636     s_task =
637         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MILLISECONDS,
638                                       &shutdown_task, NULL);
639     return;
640   }
641   if (GNUNET_YES == rh->was_transmitted)
642     return;                     /* waiting for reply */
643   msg = (struct GNUNET_RESOLVER_GetMessage *) buf;
644   msg->header.size =
645       htons (sizeof (struct GNUNET_RESOLVER_GetMessage) + rh->data_len);
646   msg->header.type = htons (GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST);
647   msg->direction = htonl (rh->direction);
648   msg->af = htonl (rh->af);
649   memcpy (&msg[1], &rh[1], rh->data_len);
650 #if DEBUG_RESOLVER
651   LOG (GNUNET_ERROR_TYPE_DEBUG,
652        "Transmitting DNS resolution request to DNS service\n");
653 #endif
654   if (GNUNET_OK !=
655       GNUNET_CLIENT_transmit_and_get_response (client, &msg->header,
656                                                GNUNET_TIME_absolute_get_remaining
657                                                (rh->timeout), GNUNET_YES,
658                                                &handle_response, rh))
659   {
660     GNUNET_CLIENT_disconnect (client, GNUNET_NO);
661     client = NULL;
662     reconnect ();
663     return;
664   }
665   rh->was_transmitted = GNUNET_YES;
666 }
667
668
669 /**
670  * Now try to reconnect to the resolver service.
671  *
672  * @param cls NULL
673  * @param tc scheduler context
674  */
675 static void
676 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
677 {
678   r_task = GNUNET_SCHEDULER_NO_TASK;
679   if (NULL == req_head)
680     return;                     /* no work pending */
681   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
682     return;
683 #if DEBUG_RESOLVER
684   LOG (GNUNET_ERROR_TYPE_DEBUG, "Trying to connect to DNS service\n");
685 #endif
686   client = GNUNET_CLIENT_connect ("resolver", resolver_cfg);
687   if (NULL == client)
688   {
689     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to connect, will try again later\n");
690     reconnect ();
691     return;
692   }
693   process_requests ();
694 }
695
696
697 /**
698  * Adjust exponential back-off and reconnect to the service.
699  */
700 static void
701 reconnect ()
702 {
703   struct GNUNET_RESOLVER_RequestHandle *rh;
704
705   if (GNUNET_SCHEDULER_NO_TASK != r_task)
706     return;
707   GNUNET_assert (NULL == client);
708   if (NULL != (rh = req_head))
709   {
710     switch (rh->was_transmitted)
711     {
712     case GNUNET_NO:
713       /* nothing more to do */
714       break;
715     case GNUNET_YES:
716       /* disconnected, transmit again! */
717       rh->was_transmitted = GNUNET_NO;
718       break;
719     case GNUNET_SYSERR:
720       /* request was cancelled, remove entirely */
721       GNUNET_CONTAINER_DLL_remove (req_head, req_tail, rh);
722       GNUNET_free (rh);
723       break;
724     default:
725       GNUNET_assert (0);
726       break;
727     }
728   }
729 #if DEBUG_RESOLVER
730   LOG (GNUNET_ERROR_TYPE_DEBUG,
731        "Will try to connect to DNS service in %llu ms\n",
732        (unsigned long long) backoff.rel_value);
733 #endif
734   GNUNET_assert (NULL != resolver_cfg);
735   r_task = GNUNET_SCHEDULER_add_delayed (backoff, &reconnect_task, NULL);
736   backoff = GNUNET_TIME_relative_multiply (backoff, 2);
737 }
738
739
740 /**
741  * Convert a string to one or more IP addresses.
742  *
743  * @param hostname the hostname to resolve
744  * @param af AF_INET or AF_INET6; use AF_UNSPEC for "any"
745  * @param callback function to call with addresses
746  * @param callback_cls closure for callback
747  * @param timeout how long to try resolving
748  * @return handle that can be used to cancel the request, NULL on error
749  */
750 struct GNUNET_RESOLVER_RequestHandle *
751 GNUNET_RESOLVER_ip_get (const char *hostname, int af,
752                         struct GNUNET_TIME_Relative timeout,
753                         GNUNET_RESOLVER_AddressCallback callback,
754                         void *callback_cls)
755 {
756   struct GNUNET_RESOLVER_RequestHandle *rh;
757   size_t slen;
758   unsigned int i;
759   struct in_addr v4;
760   struct in6_addr v6;
761
762   slen = strlen (hostname) + 1;
763   if (slen + sizeof (struct GNUNET_RESOLVER_GetMessage) >=
764       GNUNET_SERVER_MAX_MESSAGE_SIZE)
765   {
766     GNUNET_break (0);
767     return NULL;
768   }
769   rh = GNUNET_malloc (sizeof (struct GNUNET_RESOLVER_RequestHandle) + slen);
770   rh->af = af;
771   rh->addr_callback = callback;
772   rh->cls = callback_cls;
773   memcpy (&rh[1], hostname, slen);
774   rh->data_len = slen;
775   rh->timeout = GNUNET_TIME_relative_to_absolute (timeout);
776   rh->direction = GNUNET_NO;
777   /* first, check if this is a numeric address */
778   if (((1 == inet_pton (AF_INET, hostname, &v4)) &&
779        ((af == AF_INET) || (af == AF_UNSPEC))) ||
780       ((1 == inet_pton (AF_INET6, hostname, &v6)) &&
781        ((af == AF_INET6) || (af == AF_UNSPEC))))
782   {
783     rh->task = GNUNET_SCHEDULER_add_now (&numeric_resolution, rh);
784     return rh;
785   }
786   /* then, check if this is a loopback address */
787   i = 0;
788   while (loopback[i] != NULL)
789     if (0 == strcasecmp (loopback[i++], hostname))
790     {
791       rh->task = GNUNET_SCHEDULER_add_now (&loopback_resolution, rh);
792       return rh;
793     }
794   GNUNET_CONTAINER_DLL_insert_tail (req_head, req_tail, rh);
795   rh->was_queued = GNUNET_YES;
796   if (s_task != GNUNET_SCHEDULER_NO_TASK)
797   {
798     GNUNET_SCHEDULER_cancel (s_task);
799     s_task = GNUNET_SCHEDULER_NO_TASK;
800   }
801   process_requests ();
802   return rh;
803 }
804
805
806 /**
807  * We've been asked to convert an address to a string without
808  * a reverse lookup.  Do it.
809  *
810  * @param cls struct GNUNET_RESOLVER_RequestHandle for the request
811  * @param tc unused scheduler context
812  */
813 static void
814 numeric_reverse (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
815 {
816   struct GNUNET_RESOLVER_RequestHandle *rh = cls;
817   char *result;
818
819   result = no_resolve ((const struct sockaddr *) &rh[1], rh->data_len);
820 #if DEBUG_RESOLVER
821   LOG (GNUNET_ERROR_TYPE_DEBUG, _("Resolver returns `%s'.\n"), result);
822 #endif
823   if (result != NULL)
824   {
825     rh->name_callback (rh->cls, result);
826     GNUNET_free (result);
827   }
828   rh->name_callback (rh->cls, NULL);
829   GNUNET_free (rh);
830 }
831
832
833 /**
834  * Get an IP address as a string.
835  *
836  * @param sa host address
837  * @param salen length of host address
838  * @param do_resolve use GNUNET_NO to return numeric hostname
839  * @param timeout how long to try resolving
840  * @param callback function to call with hostnames
841  *        last callback is NULL when finished
842  * @param cls closure for callback
843  * @return handle that can be used to cancel the request
844  */
845 struct GNUNET_RESOLVER_RequestHandle *
846 GNUNET_RESOLVER_hostname_get (const struct sockaddr *sa, socklen_t salen,
847                               int do_resolve,
848                               struct GNUNET_TIME_Relative timeout,
849                               GNUNET_RESOLVER_HostnameCallback callback,
850                               void *cls)
851 {
852   struct GNUNET_RESOLVER_RequestHandle *rh;
853   size_t ip_len;
854   const void *ip;
855
856   check_config ();
857   switch (sa->sa_family)
858   {
859   case AF_INET:
860     ip_len = sizeof (struct in_addr);
861     ip = &((const struct sockaddr_in*)sa)->sin_addr;
862     break;
863   case AF_INET6:
864     ip_len = sizeof (struct in6_addr);
865     ip = &((const struct sockaddr_in6*)sa)->sin6_addr;
866     break;
867   default:
868     GNUNET_break (0);
869     return NULL;
870   }
871   rh = GNUNET_malloc (sizeof (struct GNUNET_RESOLVER_RequestHandle) + salen);
872   rh->name_callback = callback;
873   rh->cls = cls;
874   rh->af = sa->sa_family;
875   rh->timeout = GNUNET_TIME_relative_to_absolute (timeout);
876   memcpy (&rh[1], ip, ip_len);
877   rh->data_len = ip_len;
878   rh->direction = GNUNET_YES;
879   rh->received_response = GNUNET_NO;
880   if (GNUNET_NO == do_resolve)
881   {
882     rh->task = GNUNET_SCHEDULER_add_now (&numeric_reverse, rh);
883     return rh;
884   }
885   GNUNET_CONTAINER_DLL_insert_tail (req_head, req_tail, rh);
886   rh->was_queued = GNUNET_YES;
887   if (s_task != GNUNET_SCHEDULER_NO_TASK)
888   {
889     GNUNET_SCHEDULER_cancel (s_task);
890     s_task = GNUNET_SCHEDULER_NO_TASK;
891   }
892   process_requests ();
893   return rh;
894 }
895
896
897 /**
898  * Get local fully qualified af name
899  *
900  * @return fqdn
901  */
902 char *
903 GNUNET_RESOLVER_local_fqdn_get ()
904 {
905   struct hostent *host;
906   char hostname[GNUNET_OS_get_hostname_max_length () + 1];
907
908   if (0 != gethostname (hostname, sizeof (hostname) - 1))
909   {
910     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
911                   "gethostname");
912     return NULL;
913   }
914 #if DEBUG_RESOLVER
915   LOG (GNUNET_ERROR_TYPE_DEBUG, _("Resolving our FQDN `%s'\n"), hostname);
916 #endif
917   host = gethostbyname (hostname);
918   if (NULL == host)
919   {
920     LOG (GNUNET_ERROR_TYPE_ERROR, _("Could not resolve our FQDN : %s\n"),
921          hstrerror (h_errno));
922     return NULL;
923   }
924   return GNUNET_strdup (host->h_name);
925 }
926
927
928 /**
929  * Looking our own hostname.
930  *
931  * @param af AF_INET or AF_INET6; use AF_UNSPEC for "any"
932  * @param callback function to call with addresses
933  * @param cls closure for callback
934  * @param timeout how long to try resolving
935  * @return handle that can be used to cancel the request, NULL on error
936  */
937 struct GNUNET_RESOLVER_RequestHandle *
938 GNUNET_RESOLVER_hostname_resolve (int af,
939                                   struct GNUNET_TIME_Relative timeout,
940                                   GNUNET_RESOLVER_AddressCallback callback,
941                                   void *cls)
942 {
943   char hostname[GNUNET_OS_get_hostname_max_length () + 1];
944
945   if (0 != gethostname (hostname, sizeof (hostname) - 1))
946   {
947     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
948                   "gethostname");
949     return NULL;
950   }
951 #if DEBUG_RESOLVER
952   LOG (GNUNET_ERROR_TYPE_DEBUG, _("Resolving our hostname `%s'\n"), hostname);
953 #endif
954   return GNUNET_RESOLVER_ip_get (hostname, af, timeout, callback, cls);
955 }
956
957
958 /**
959  * Cancel a request that is still pending with the resolver.
960  * Note that a client MUST NOT cancel a request that has
961  * been completed (i.e, the callback has been called to
962  * signal timeout or the final result).
963  *
964  * @param rh handle of request to cancel
965  */
966 void
967 GNUNET_RESOLVER_request_cancel (struct GNUNET_RESOLVER_RequestHandle *rh)
968 {
969   if (rh->task != GNUNET_SCHEDULER_NO_TASK)
970   {
971     GNUNET_SCHEDULER_cancel (rh->task);
972     rh->task = GNUNET_SCHEDULER_NO_TASK;
973   }
974   if (rh->was_transmitted == GNUNET_NO)
975   {
976     if (rh->was_queued == GNUNET_YES)
977       GNUNET_CONTAINER_DLL_remove (req_head, req_tail, rh);
978     GNUNET_free (rh);
979     return;
980   }
981   GNUNET_assert (rh->was_transmitted == GNUNET_YES);
982   rh->was_transmitted = GNUNET_SYSERR;  /* mark as cancelled */
983 }
984
985
986 /* end of resolver_api.c */