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