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