move SUID test code to util
[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   check_config (c);
227   backoff = GNUNET_TIME_UNIT_MILLISECONDS;
228   cfg = c;
229 }
230
231
232 /**
233  * Destroy the connection to the resolver service.
234  */
235 void
236 GNUNET_RESOLVER_disconnect ()
237 {
238   GNUNET_assert (NULL == req_head);
239   GNUNET_assert (NULL == req_tail);
240   if (NULL != client)
241     {
242 #if DEBUG_RESOLVER
243       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
244                   "Disconnecting from DNS service\n");
245 #endif
246       GNUNET_CLIENT_disconnect (client, GNUNET_NO);
247       client = NULL;
248     }
249   if (r_task != GNUNET_SCHEDULER_NO_TASK)
250     {
251       GNUNET_SCHEDULER_cancel (r_task);
252       r_task = GNUNET_SCHEDULER_NO_TASK;
253     }
254   if (s_task != GNUNET_SCHEDULER_NO_TASK)
255     {
256       GNUNET_SCHEDULER_cancel (s_task);
257       s_task = GNUNET_SCHEDULER_NO_TASK;
258     }
259   cfg = NULL;
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   r_task = GNUNET_SCHEDULER_add_delayed (backoff,
710                                          &reconnect_task,
711                                          NULL);
712   backoff = GNUNET_TIME_relative_multiply (backoff, 2);
713 }
714
715
716 /**
717  * Convert a string to one or more IP addresses.
718  *
719  * @param hostname the hostname to resolve
720  * @param domain AF_INET or AF_INET6; use AF_UNSPEC for "any"
721  * @param callback function to call with addresses
722  * @param callback_cls closure for callback
723  * @param timeout how long to try resolving
724  * @return handle that can be used to cancel the request, NULL on error
725  */
726 struct GNUNET_RESOLVER_RequestHandle *
727 GNUNET_RESOLVER_ip_get (const char *hostname,
728                         int domain,
729                         struct GNUNET_TIME_Relative timeout,
730                         GNUNET_RESOLVER_AddressCallback callback,
731                         void *callback_cls)
732 {
733   struct GNUNET_RESOLVER_RequestHandle *rh;
734   size_t slen;
735   unsigned int i;
736   struct in_addr v4;
737   struct in6_addr v6;
738
739   slen = strlen (hostname) + 1;
740   if (slen + sizeof (struct GNUNET_RESOLVER_GetMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
741     {
742       GNUNET_break (0);
743       return NULL;
744     }
745   rh = GNUNET_malloc (sizeof (struct GNUNET_RESOLVER_RequestHandle) + slen);
746   rh->domain = domain;
747   rh->addr_callback = callback;
748   rh->cls = callback_cls;
749   memcpy (&rh[1], hostname, slen);
750   rh->data_len = slen;
751   rh->timeout = GNUNET_TIME_relative_to_absolute (timeout);
752   rh->direction = GNUNET_NO;
753   /* first, check if this is a numeric address */
754   if (((1 == inet_pton (AF_INET,
755                         hostname,
756                         &v4)) &&
757        ((domain == AF_INET) || (domain == AF_UNSPEC))) ||
758       ((1 == inet_pton (AF_INET6,
759                         hostname,
760                         &v6)) &&
761        ((domain == AF_INET6) || (domain == AF_UNSPEC))))
762     {
763       rh->task = GNUNET_SCHEDULER_add_now (&numeric_resolution, rh);
764       return rh;
765     }
766   /* then, check if this is a loopback address */
767   i = 0;
768   while (loopback[i] != NULL)
769     if (0 == strcasecmp (loopback[i++], hostname))
770       {
771         rh->task = GNUNET_SCHEDULER_add_now (&loopback_resolution, rh);
772         return rh;
773       }
774   GNUNET_CONTAINER_DLL_insert_tail (req_head,
775                                     req_tail,
776                                     rh);
777   rh->was_queued = GNUNET_YES;
778   if (s_task != GNUNET_SCHEDULER_NO_TASK)
779     {
780       GNUNET_SCHEDULER_cancel (s_task);
781       s_task = GNUNET_SCHEDULER_NO_TASK;
782     }
783   process_requests ();
784   return rh;
785 }
786
787
788 /**
789  * We've been asked to convert an address to a string without
790  * a reverse lookup.  Do it.
791  *
792  * @param cls struct GNUNET_RESOLVER_RequestHandle for the request
793  * @param tc unused scheduler context
794  */
795 static void
796 numeric_reverse (void *cls, 
797                  const struct GNUNET_SCHEDULER_TaskContext *tc)
798 {
799   struct GNUNET_RESOLVER_RequestHandle *rh = cls;
800   char *result;
801
802   result = no_resolve ((const struct sockaddr *) &rh[1], rh->data_len);
803 #if DEBUG_RESOLVER
804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Resolver returns `%s'.\n"), result);
805 #endif
806   if (result != NULL)
807     {
808       rh->name_callback (rh->cls, result);
809       GNUNET_free (result);
810     }
811   rh->name_callback (rh->cls, NULL);
812   GNUNET_free (rh);
813 }
814
815
816 /**
817  * Get an IP address as a string.
818  *
819  * @param sa host address
820  * @param salen length of host address
821  * @param do_resolve use GNUNET_NO to return numeric hostname
822  * @param timeout how long to try resolving
823  * @param callback function to call with hostnames
824  * @param cls closure for callback
825  * @return handle that can be used to cancel the request
826  */
827 struct GNUNET_RESOLVER_RequestHandle *
828 GNUNET_RESOLVER_hostname_get (const struct sockaddr *sa,
829                               socklen_t salen,
830                               int do_resolve,
831                               struct GNUNET_TIME_Relative timeout,
832                               GNUNET_RESOLVER_HostnameCallback callback,
833                               void *cls)
834 {
835   struct GNUNET_RESOLVER_RequestHandle *rh;
836
837   check_config (cfg);
838   rh = GNUNET_malloc (sizeof (struct GNUNET_RESOLVER_RequestHandle) + salen);
839   rh->name_callback = callback;
840   rh->cls = cls;
841   rh->timeout = GNUNET_TIME_relative_to_absolute (timeout);
842   memcpy (&rh[1], sa, salen);
843   rh->data_len = salen;
844   rh->direction = GNUNET_YES;
845   if (GNUNET_NO == do_resolve)
846     {
847       rh->task = GNUNET_SCHEDULER_add_now (&numeric_reverse, rh);
848       return rh;
849     }
850   if (salen + sizeof (struct GNUNET_RESOLVER_GetMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
851     {
852       GNUNET_break (0);
853       GNUNET_free (rh);
854       return NULL;
855     }
856   GNUNET_CONTAINER_DLL_insert_tail (req_head,
857                                     req_tail,
858                                     rh);
859   rh->was_queued = GNUNET_YES;
860   if (s_task != GNUNET_SCHEDULER_NO_TASK)
861     {
862       GNUNET_SCHEDULER_cancel (s_task);
863       s_task = GNUNET_SCHEDULER_NO_TASK;
864     }
865   process_requests ();
866   return rh;
867 }
868
869
870 /**
871  * Get local fully qualified domain name
872  *
873  * @return fqdn
874  */
875 char *
876 GNUNET_RESOLVER_local_fqdn_get ()
877 {
878   struct hostent *host;
879   char hostname[GNUNET_OS_get_hostname_max_length() + 1];
880
881   if (0 != gethostname (hostname, sizeof (hostname) - 1))
882     {
883       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR |
884                            GNUNET_ERROR_TYPE_BULK, "gethostname");
885       return NULL;
886     }
887 #if DEBUG_RESOLVER
888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
889               _("Resolving our FQDN `%s'\n"), hostname);
890 #endif
891   host = gethostbyname (hostname);
892   if (NULL == host)
893     {
894       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
895                   _("Could not resolve our FQDN : %s\n"),
896                   hstrerror (h_errno));
897       return NULL;
898     }
899   return GNUNET_strdup (host->h_name);
900 }
901
902
903 /**
904  * Looking our own hostname.
905  *
906  * @param domain AF_INET or AF_INET6; use AF_UNSPEC for "any"
907  * @param callback function to call with addresses
908  * @param cls closure for callback
909  * @param timeout how long to try resolving
910  * @return handle that can be used to cancel the request, NULL on error
911  */
912 struct GNUNET_RESOLVER_RequestHandle *
913 GNUNET_RESOLVER_hostname_resolve (int domain,
914                                   struct GNUNET_TIME_Relative timeout,
915                                   GNUNET_RESOLVER_AddressCallback callback,
916                                   void *cls)
917 {
918   char hostname[GNUNET_OS_get_hostname_max_length() + 1];
919
920   if (0 != gethostname (hostname, sizeof (hostname) - 1))
921     {
922       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR |
923                            GNUNET_ERROR_TYPE_BULK, "gethostname");
924       return NULL;
925     }
926 #if DEBUG_RESOLVER
927   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
928               _("Resolving our hostname `%s'\n"), hostname);
929 #endif
930   return GNUNET_RESOLVER_ip_get (hostname,
931                                  domain, 
932                                  timeout,
933                                  callback, cls);
934 }
935
936
937 /**
938  * Cancel a request that is still pending with the resolver.
939  * Note that a client MUST NOT cancel a request that has
940  * been completed (i.e, the callback has been called to
941  * signal timeout or the final result).
942  *
943  * @param rh handle of request to cancel
944  */
945 void
946 GNUNET_RESOLVER_request_cancel (struct GNUNET_RESOLVER_RequestHandle *rh)
947 {
948   if (rh->task != GNUNET_SCHEDULER_NO_TASK)
949     {
950       GNUNET_SCHEDULER_cancel (rh->task);
951       rh->task = GNUNET_SCHEDULER_NO_TASK;
952     }
953   if (rh->was_transmitted == GNUNET_NO)
954     {
955       if (rh->was_queued == GNUNET_YES)
956         GNUNET_CONTAINER_DLL_remove (req_head,
957                                      req_tail,
958                                      rh);
959       GNUNET_free (rh);
960       return;
961     }
962   GNUNET_assert (rh->was_transmitted == GNUNET_YES);
963   rh->was_transmitted = GNUNET_SYSERR; /* mark as cancelled */
964 }
965
966
967 /* end of resolver_api.c */