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