8e8629c4d7f3e855e50a4ca84d89b7a1ec61857a
[oweals/gnunet.git] / src / gns / gnunet-service-gns_resolver.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 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 3, 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  *
23  *
24  * @file gns/gnunet-service-gns_resolver.c
25  * @brief GNUnet GNS resolver logic
26  * @author Martin Schanzenbach
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_transport_service.h"
31 #include "gnunet_dns_service.h"
32 #include "gnunet_dht_service.h"
33 #include "gnunet_namestore_service.h"
34 #include "gnunet_vpn_service.h"
35 #include "gnunet_dns_service.h"
36 #include "gnunet_resolver_service.h"
37 #include "gnunet_dnsparser_lib.h"
38 #include "gnunet_gns_service.h"
39 #include "block_gns.h"
40 #include "gns.h"
41 #include "gnunet-service-gns_resolver.h"
42
43 #define DHT_LOOKUP_TIMEOUT DHT_OPERATION_TIMEOUT
44 #define DHT_GNS_REPLICATION_LEVEL 5
45 #define MAX_DNS_LABEL_LENGTH 63
46
47
48 /**
49  * Our handle to the namestore service
50  */
51 static struct GNUNET_NAMESTORE_Handle *namestore_handle;
52
53 /**
54  * Our handle to the vpn service
55  */
56 static struct GNUNET_VPN_Handle *vpn_handle;
57
58 /**
59  * Resolver handle to the dht
60  */
61 static struct GNUNET_DHT_Handle *dht_handle;
62
63 /**
64  * Heap for parallel DHT lookups
65  */
66 static struct GNUNET_CONTAINER_Heap *dht_lookup_heap;
67
68 /**
69  * Maximum amount of parallel queries in background
70  */
71 static unsigned long long max_allowed_background_queries;
72
73 /**
74  * Wheather or not to ignore pending records
75  */
76 static int ignore_pending_records;
77
78 /**
79  * Our local zone
80  */
81 static struct GNUNET_CRYPTO_ShortHashCode local_zone;
82
83 /**
84  * a resolution identifier pool variable
85  * FIXME overflow?
86  * This is a non critical identifier useful for debugging
87  */
88 static unsigned long long rid = 0;
89
90
91 /**
92  * Determine if this name is canonical.
93  * i.e.
94  * a.b.gnunet  = not canonical
95  * a           = canonical
96  *
97  * @param name the name to test
98  * @return 1 if canonical
99  */
100 static int
101 is_canonical(char* name)
102 {
103   uint32_t len = strlen(name);
104   int i;
105
106   for (i=0; i<len; i++)
107   {
108     if (*(name+i) == '.')
109       return 0;
110   }
111   return 1;
112 }
113
114
115 /**
116  * Callback that shortens authorities
117  *
118  * @param gph the handle containing the name to shorten
119  */
120 static void
121 shorten_authority_chain (struct GetPseuAuthorityHandle *gph);
122
123
124 /**
125  * Namestore calls this function if we have record for this name.
126  * (or with rd_count=0 to indicate no matches)
127  *
128  * @param cls the pending query
129  * @param key the key of the zone we did the lookup
130  * @param expiration expiration date of the namestore entry
131  * @param name the name for which we need an authority
132  * @param rd_count the number of records with 'name'
133  * @param rd the record data
134  * @param signature the signature of the authority for the record data
135  */
136 static void
137 process_pseu_lookup_ns (void* cls,
138                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
139                       struct GNUNET_TIME_Absolute expiration,
140                       const char *name, unsigned int rd_count,
141                       const struct GNUNET_NAMESTORE_RecordData *rd,
142                       const struct GNUNET_CRYPTO_RsaSignature *signature)
143 {
144   struct GetPseuAuthorityHandle* gph = (struct GetPseuAuthorityHandle*)cls;
145   struct GNUNET_NAMESTORE_RecordData new_pkey;
146   struct AuthorityChain *iter;
147
148   if (rd_count > 0)
149   {
150     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
151                "GNS_AUTO_PSEU: Name %s already taken in NS!\n", name);
152     if (0 == strcmp (gph->name, name))
153     {
154       if (gph->ahead->next != NULL)
155       {
156         if (GNUNET_CRYPTO_short_hash_cmp (&gph->ahead->next->zone,
157                                           &gph->our_zone))
158         {
159           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GNS_GET_AUTH: trying next!\n");
160           iter = gph->ahead->next;
161           GNUNET_free (gph->ahead);
162           gph->ahead = iter;
163           shorten_authority_chain (gph);
164           return;
165         }
166       }
167
168       /* Clean up */
169       do
170       {
171         iter = gph->ahead->next;
172         GNUNET_free (gph->ahead);
173         gph->ahead = iter;
174       } while (iter != NULL);
175       GNUNET_CRYPTO_rsa_key_free (gph->key);
176
177       GNUNET_free (gph);
178       return;
179     }
180
181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
182                 "GNS_AUTO_PSEU: Trying delegated name %s\n", gph->name);
183     memcpy (gph->test_name, gph->name, strlen (gph->name)+1);
184     GNUNET_NAMESTORE_lookup_record (namestore_handle,
185                                     &gph->our_zone,
186                                     gph->test_name,
187                                     GNUNET_NAMESTORE_TYPE_ANY,
188                                     &process_pseu_lookup_ns,
189                                     gph);
190     return;
191   }
192
193   /** name is free */
194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
195             "GNS_AUTO_PSEU: Name %s not taken in NS! Adding\n", gph->test_name);
196
197   new_pkey.expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
198   new_pkey.data_size = sizeof (struct GNUNET_CRYPTO_ShortHashCode);
199   new_pkey.data = &gph->ahead->zone;
200   new_pkey.record_type = GNUNET_GNS_RECORD_PKEY;
201   new_pkey.flags = GNUNET_NAMESTORE_RF_AUTHORITY
202                  | GNUNET_NAMESTORE_RF_PRIVATE
203                  | GNUNET_NAMESTORE_RF_PENDING;
204   GNUNET_NAMESTORE_record_create (namestore_handle,
205                                   gph->key,
206                                   gph->test_name,
207                                   &new_pkey,
208                                   NULL, //cont
209                                   NULL); //cls
210   do
211   {
212     iter = gph->ahead->next;
213     GNUNET_free (gph->ahead);
214     gph->ahead = iter;
215   } while (iter != NULL);
216   GNUNET_CRYPTO_rsa_key_free (gph->key);
217   GNUNET_free (gph);
218
219 }
220
221 /**
222  * process result of a dht pseu lookup
223  *
224  * @param gph the handle
225  * @param name the pseu result or NULL
226  */
227 static void
228 process_pseu_result (struct GetPseuAuthorityHandle* gph, char* name)
229 {
230   if (NULL == name)
231   {
232     memcpy (gph->test_name, gph->ahead->name, strlen (gph->ahead->name)+1);
233   }
234   else
235   {
236     memcpy (gph->test_name, name, strlen(name)+1);
237   }
238
239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
240               "GNS_AUTO_PSEU: Checking %s for collision in NS\n",
241               gph->test_name);
242
243   /**
244    * Check for collision
245    */
246   GNUNET_NAMESTORE_lookup_record (namestore_handle,
247                                   &gph->our_zone,
248                                   gph->test_name,
249                                   GNUNET_NAMESTORE_TYPE_ANY,
250                                   &process_pseu_lookup_ns,
251                                   gph);
252 }
253
254 /**
255  * Handle timeout for dht request
256  *
257  * @param cls the request handle as closure
258  * @param tc the task context
259  */
260 static void
261 handle_auth_discovery_timeout(void *cls,
262                               const struct GNUNET_SCHEDULER_TaskContext *tc)
263 {
264   struct GetPseuAuthorityHandle* gph = (struct GetPseuAuthorityHandle*)cls;
265   struct AuthorityChain *iter;
266
267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
268               "GNS_GET_AUTH: dht lookup for query PSEU timed out.\n");
269   GNUNET_DHT_get_stop (gph->get_handle);
270   gph->get_handle = NULL;
271   
272   if (gph->ahead->next != NULL)
273   {
274     if (GNUNET_CRYPTO_short_hash_cmp (&gph->ahead->next->zone,
275                                       &gph->our_zone))
276     {
277       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GNS_GET_AUTH: trying next!\n");
278       iter = gph->ahead->next;
279       GNUNET_free (gph->ahead);
280       gph->ahead = iter;
281       shorten_authority_chain (gph);
282       return;
283     }
284   }
285   
286   process_pseu_result (gph, NULL);
287 }
288
289 /**
290  * Function called when we find a PSEU entry in the DHT
291  *
292  * @param cls the request handle
293  * @param exp lifetime
294  * @param key the key the record was stored under
295  * @param get_path get path
296  * @param get_path_length get path length
297  * @param put_path put path
298  * @param put_path_length put path length
299  * @param type the block type
300  * @param size the size of the record
301  * @param data the record data
302  */
303 static void
304 process_auth_discovery_dht_result(void* cls,
305                                   struct GNUNET_TIME_Absolute exp,
306                                   const struct GNUNET_HashCode * key,
307                                   const struct GNUNET_PeerIdentity *get_path,
308                                   unsigned int get_path_length,
309                                   const struct GNUNET_PeerIdentity *put_path,
310                                   unsigned int put_path_length,
311                                   enum GNUNET_BLOCK_Type type,
312                                   size_t size, const void *data)
313 {
314   struct GetPseuAuthorityHandle* gph = (struct GetPseuAuthorityHandle*)cls;
315   struct AuthorityChain *iter;
316   struct GNSNameRecordBlock *nrb;
317   char* rd_data = (char*)data;
318   char* name;
319   int num_records;
320   size_t rd_size;
321   int i;
322
323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
324               "GNS_GET_AUTH: got dht result (size=%d)\n", size);
325
326   if (data == NULL)
327   {
328     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
329                 "GNS_GET_AUTH: got dht result null!\n", size);
330     
331     do
332     {
333       iter = gph->ahead->next;
334       GNUNET_free (gph->ahead);
335       gph->ahead = iter;
336     } while (iter != NULL);
337     GNUNET_CRYPTO_rsa_key_free (gph->key);
338     GNUNET_free (gph);
339     return;
340   }
341   
342   nrb = (struct GNSNameRecordBlock*)data;
343
344   /* stop lookup and timeout task */
345   GNUNET_DHT_get_stop (gph->get_handle);
346   gph->get_handle = NULL;
347   GNUNET_SCHEDULER_cancel (gph->timeout);
348
349   gph->get_handle = NULL;
350
351   nrb = (struct GNSNameRecordBlock*)data;
352   
353   name = (char*)&nrb[1];
354   num_records = ntohl (nrb->rd_count);
355   {
356     struct GNUNET_NAMESTORE_RecordData rd[num_records];
357
358     rd_data += strlen (name) + 1 + sizeof (struct GNSNameRecordBlock);
359     rd_size = size - strlen (name) - 1 - sizeof (struct GNSNameRecordBlock);
360
361     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
362                                                                rd_data,
363                                                                num_records,
364                                                                rd))
365     {
366       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
367                   "GNS_GET_AUTH: Error deserializing data!\n");
368     }
369     else
370     {
371       for (i=0; i < num_records; i++)
372       {
373         if ((strcmp (name, "+") == 0) &&
374             (rd[i].record_type == GNUNET_GNS_RECORD_PSEU))
375         {
376           /* found pseu */
377           process_pseu_result (gph, (char*)rd[i].data);
378           return;
379         }
380       }
381     }
382   }
383
384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GNS_GET_AUTH: no pseu in dht!\n");
385
386   if (gph->ahead->next != NULL)
387   {
388     if (GNUNET_CRYPTO_short_hash_cmp (&gph->ahead->next->zone,
389                                       &gph->our_zone))
390     {
391       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GNS_GET_AUTH: trying next!\n");
392       iter = gph->ahead->next;
393       GNUNET_free (gph->ahead);
394       gph->ahead = iter;
395       shorten_authority_chain (gph);
396       return;
397     }
398   }
399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
400               "GNS_GET_AUTH: finished shorten, no results!\n");
401   process_pseu_result (gph, NULL);
402 }
403
404 /**
405  * Process PSEU discovery for shorten via namestore
406  *
407  * @param cls the GetPseuAuthorityHandle
408  * @param key the public key
409  * @param expiration recorddata expiration
410  * @param name the looked up name
411  * @param rd_count number of records in set
412  * @param rd record data
413  * @param signature the signature
414  */
415 static void
416 process_auth_discovery_ns_result(void* cls,
417                       const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
418                       struct GNUNET_TIME_Absolute expiration,
419                       const char *name,
420                       unsigned int rd_count,
421                       const struct GNUNET_NAMESTORE_RecordData *rd,
422                       const struct GNUNET_CRYPTO_RsaSignature *signature)
423 {
424   uint32_t xquery;
425   struct GNUNET_CRYPTO_ShortHashCode name_hash;
426   struct GNUNET_HashCode lookup_key;
427   struct GNUNET_CRYPTO_HashAsciiEncoded lookup_key_string;
428   struct GNUNET_HashCode name_hash_double;
429   struct GNUNET_HashCode zone_hash_double;
430   int i;
431   struct GetPseuAuthorityHandle* gph = (struct GetPseuAuthorityHandle*)cls;
432   struct AuthorityChain *iter;
433   
434   /* no pseu found */
435   if (rd_count == 0)
436   {
437     /**
438      * check dht
439      */
440     GNUNET_CRYPTO_short_hash ("+", strlen ("+"), &name_hash);
441     GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
442     GNUNET_CRYPTO_short_hash_double (&gph->ahead->zone, &zone_hash_double);
443     GNUNET_CRYPTO_hash_xor (&name_hash_double, &zone_hash_double, &lookup_key);
444     GNUNET_CRYPTO_hash_to_enc (&lookup_key, &lookup_key_string);
445
446     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
447                "GNS_AUTO_PSEU: starting dht lookup for %s with key: %s\n",
448                "+", (char*)&lookup_key_string);
449
450     gph->timeout = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
451                                          &handle_auth_discovery_timeout, gph);
452
453     xquery = htonl (GNUNET_GNS_RECORD_PSEU);
454     
455     GNUNET_assert (gph->get_handle == NULL);
456
457     gph->get_handle = GNUNET_DHT_get_start(dht_handle,
458                                            GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
459                                            &lookup_key,
460                                            DHT_GNS_REPLICATION_LEVEL,
461                                            GNUNET_DHT_RO_NONE,
462                                            &xquery,
463                                            sizeof(xquery),
464                                            &process_auth_discovery_dht_result,
465                                            gph);
466     return;
467   }
468
469   for (i=0; i < rd_count; i++)
470   {
471     if ((strcmp (name, "+") == 0) &&
472         (rd[i].record_type == GNUNET_GNS_RECORD_PSEU))
473     {
474       /* found pseu */
475       process_pseu_result (gph, (char*)rd[i].data);
476       return;
477     }
478   }
479
480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GNS_GET_AUTH: no pseu in namestore!\n");
481   
482   if (gph->ahead->next != NULL)
483   {
484     if (GNUNET_CRYPTO_short_hash_cmp (&gph->ahead->next->zone,
485                                       &gph->our_zone))
486     {
487       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GNS_GET_AUTH: trying next!\n");
488       iter = gph->ahead->next;
489       GNUNET_free (gph->ahead);
490       gph->ahead = iter;
491       shorten_authority_chain (gph);
492       return;
493     }
494   }
495   
496   process_pseu_result (gph, NULL);
497 }
498
499 /**
500  * Callback called by namestore for a zone to name
501  * result
502  *
503  * @param cls the closure
504  * @param zone_key the zone we queried
505  * @param expire the expiration time of the name
506  * @param name the name found or NULL
507  * @param rd_len number of records for the name
508  * @param rd the record data (PKEY) for the name
509  * @param signature the signature for the record data
510  */
511 static void
512 process_zone_to_name_discover (void *cls,
513                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
514                  struct GNUNET_TIME_Absolute expire,
515                  const char *name,
516                  unsigned int rd_len,
517                  const struct GNUNET_NAMESTORE_RecordData *rd,
518                  const struct GNUNET_CRYPTO_RsaSignature *signature)
519 {
520   struct GetPseuAuthorityHandle* gph = (struct GetPseuAuthorityHandle*)cls;
521   struct AuthorityChain *iter;
522
523   /* we found a match in our own zone */
524   if (rd_len != 0)
525   {
526     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
527                "GNS_AUTO_PSEU: name for zone in our root %s\n", name);
528
529     iter = gph->ahead;
530     do
531     {
532       iter = gph->ahead->next;
533       GNUNET_free (gph->ahead);
534       gph->ahead = iter;
535     } while (iter != NULL);
536     GNUNET_CRYPTO_rsa_key_free (gph->key);
537     GNUNET_free (gph);
538   }
539   else
540   {
541
542     GNUNET_NAMESTORE_lookup_record (namestore_handle,
543                                     &gph->ahead->zone,
544                                     "+",
545                                     GNUNET_GNS_RECORD_PSEU,
546                                     &process_auth_discovery_ns_result,
547                                     gph);
548   }
549
550 }
551
552
553 /**
554  * Callback that shortens authorities
555  *
556  * @param gph the handle to the shorten request
557  */
558 static void
559 shorten_authority_chain (struct GetPseuAuthorityHandle *gph)
560 {
561
562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
563               "GNS_AUTO_PSEU: New authority %s discovered\n",
564               gph->ahead->name);
565
566   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
567                                  &gph->our_zone,
568                                  &gph->ahead->zone,
569                                  &process_zone_to_name_discover,
570                                  gph);
571
572 }
573
574 static void
575 start_shorten (struct AuthorityChain *atail,
576                struct GNUNET_CRYPTO_RsaPrivateKey *key)
577 {
578   struct AuthorityChain *new_head = NULL;
579   struct AuthorityChain *new_tail = NULL;
580   struct AuthorityChain *iter;
581   struct AuthorityChain *acopy;
582   struct GetPseuAuthorityHandle *gph;
583   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
584   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *pb_key;
585
586   /* First copy the authority chain in reverse order */
587   for (iter = atail; iter != NULL; iter = iter->prev)
588   {
589     acopy = GNUNET_malloc (sizeof (struct AuthorityChain));
590     memcpy (acopy, iter, sizeof (struct AuthorityChain));
591     acopy->next = NULL;
592     acopy->prev = NULL;
593     GNUNET_CONTAINER_DLL_insert (new_head, new_tail, acopy);
594   }
595
596   gph = GNUNET_malloc (sizeof (struct GetPseuAuthorityHandle));
597
598   GNUNET_CRYPTO_rsa_key_get_public (key, &pkey);
599   pb_key = GNUNET_CRYPTO_rsa_encode_key (key);
600   gph->key = GNUNET_CRYPTO_rsa_decode_key ((char*)pb_key, ntohs (pb_key->len));
601   //gph->key = key;//GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
602   //memcpy (gph->key, key, sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
603   
604   GNUNET_CRYPTO_short_hash (&pkey,
605                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
606                         &gph->our_zone);
607   gph->ahead = new_head;
608
609   shorten_authority_chain (gph);
610 }
611
612 /**
613  * Initialize the resolver
614  *
615  * @param nh the namestore handle
616  * @param dh the dht handle
617  * @param lz the local zone's hash
618  * @param max_bg_queries maximum number of parallel background queries in dht
619  * @param ignore_pending ignore records that still require user confirmation
620  *        on lookup
621  * @return GNUNET_OK on success
622  */
623 int
624 gns_resolver_init(struct GNUNET_NAMESTORE_Handle *nh,
625                   struct GNUNET_DHT_Handle *dh,
626                   struct GNUNET_CRYPTO_ShortHashCode lz,
627                   const struct GNUNET_CONFIGURATION_Handle *cfg,
628                   unsigned long long max_bg_queries,
629                   int ignore_pending)
630 {
631   namestore_handle = nh;
632   dht_handle = dh;
633   local_zone = lz;
634   dht_lookup_heap =
635     GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
636   max_allowed_background_queries = max_bg_queries;
637   ignore_pending_records = ignore_pending;
638   
639   if (NULL == vpn_handle)
640   {
641     vpn_handle = GNUNET_VPN_connect (cfg);
642     if (NULL == vpn_handle)
643     {
644       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
645                   "GNS_PHASE_INIT: Error connecting to VPN!\n");
646
647       return GNUNET_SYSERR;
648     }
649   }
650
651   if ((namestore_handle != NULL) && (dht_handle != NULL))
652   {
653     return GNUNET_OK;
654   }
655
656   return GNUNET_SYSERR;
657 }
658
659 /**
660  * Cleanup background lookups
661  *
662  * @param cls closure to iterator
663  * @param node heap nodes
664  * @param element the resolver handle
665  * @param cost heap cost
666  * @return always GNUNET_YES
667  */
668 static int
669 cleanup_pending_background_queries(void* cls,
670                                    struct GNUNET_CONTAINER_HeapNode *node,
671                                    void *element,
672                                    GNUNET_CONTAINER_HeapCostType cost)
673 {
674   struct ResolverHandle *rh = (struct ResolverHandle *)element;
675   ResolverCleanupContinuation cont = cls;
676
677   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
678              "GNS_CLEANUP-%llu: Terminating background lookup for %s\n",
679              rh->id, rh->name);
680   GNUNET_DHT_get_stop(rh->get_handle);
681   rh->get_handle = NULL;
682   rh->proc(rh->proc_cls, rh, 0, NULL);
683
684   GNUNET_CONTAINER_heap_remove_node(node);
685
686   if (GNUNET_CONTAINER_heap_get_size(dht_lookup_heap) == 0)
687     cont();
688
689
690   return GNUNET_YES;
691 }
692
693
694 /**
695  * Shutdown resolver
696  */
697 void
698 gns_resolver_cleanup(ResolverCleanupContinuation cont)
699 {
700   unsigned int s = GNUNET_CONTAINER_heap_get_size(dht_lookup_heap);
701   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
702              "GNS_CLEANUP: %d pending background queries to terminate\n", s);
703
704   if (0 != s)
705     GNUNET_CONTAINER_heap_iterate (dht_lookup_heap,
706                                    &cleanup_pending_background_queries,
707                                    cont);
708   else
709     cont();
710 }
711
712
713 /**
714  * Helper function to free resolver handle
715  *
716  * @param rh the handle to free
717  */
718 static void
719 free_resolver_handle(struct ResolverHandle* rh)
720 {
721   struct AuthorityChain *ac;
722   struct AuthorityChain *ac_next;
723
724   if (NULL == rh)
725     return;
726
727   ac = rh->authority_chain_head;
728
729   while (NULL != ac)
730   {
731     ac_next = ac->next;
732     GNUNET_free(ac);
733     ac = ac_next;
734   }
735
736   if (NULL != rh->dns_raw_packet)
737     GNUNET_free (rh->dns_raw_packet);
738
739   GNUNET_free(rh);
740 }
741
742
743 /**
744  * Callback when record data is put into namestore
745  *
746  * @param cls the closure
747  * @param success GNUNET_OK on success
748  * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
749  */
750 void
751 on_namestore_record_put_result(void *cls,
752                                int32_t success,
753                                const char *emsg)
754 {
755   if (GNUNET_NO == success)
756   {
757     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
758                "GNS_NS: records already in namestore\n");
759     return;
760   }
761   else if (GNUNET_YES == success)
762   {
763     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
764                "GNS_NS: records successfully put in namestore\n");
765     return;
766   }
767
768   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
769              "GNS_NS: Error putting records into namestore: %s\n", emsg);
770 }
771
772 static void
773 handle_lookup_timeout(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
774 {
775   struct ResolverHandle *rh = cls;
776
777   if (rh->timeout_cont)
778     rh->timeout_cont(rh->timeout_cont_cls, tc);
779 }
780
781 /**
782  * Processor for background lookups in the DHT
783  *
784  * @param cls closure (NULL)
785  * @param rd_count number of records found (not 0)
786  * @param rd record data
787  */
788 static void
789 background_lookup_result_processor(void *cls,
790                                    uint32_t rd_count,
791                                    const struct GNUNET_NAMESTORE_RecordData *rd)
792 {
793   //We could do sth verbose/more useful here but it doesn't make any difference
794   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
795              "GNS_BG: background dht lookup for finished. (%d results)\n",
796              rd_count);
797 }
798
799 /**
800  * Handle timeout for DHT requests
801  *
802  * @param cls the request handle as closure
803  * @param tc the task context
804  */
805 static void
806 dht_lookup_timeout(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
807 {
808   struct ResolverHandle *rh = cls;
809   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
810   char new_name[MAX_DNS_NAME_LENGTH];
811
812   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
813              "GNS_PHASE_REC-%d: dht lookup for query %s (%ds)timed out.\n",
814              rh->id, rh->name, rh->timeout.rel_value);
815   /**
816    * Start resolution in bg
817    */
818   //strcpy(new_name, rh->name);
819   //memcpy(new_name+strlen(new_name), GNUNET_GNS_TLD, strlen(GNUNET_GNS_TLD));
820   GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
821                   rh->name, GNUNET_GNS_TLD);
822
823   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
824              "GNS_PHASE_REC-%d: Starting background lookup for %s type %d\n",
825              rh->id, new_name, rlh->record_type);
826
827   gns_resolver_lookup_record(rh->authority,
828                              rh->private_local_zone,
829                              rlh->record_type,
830                              new_name,
831                              rh->priv_key,
832                              GNUNET_TIME_UNIT_FOREVER_REL,
833                              GNUNET_NO,
834                              &background_lookup_result_processor,
835                              NULL);
836   rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
837
838   GNUNET_DHT_get_stop (rh->get_handle);
839   rh->get_handle = NULL;
840   rh->proc(rh->proc_cls, rh, 0, NULL);
841 }
842
843
844 /**
845  * Function called when we get a result from the dht
846  * for our record query
847  *
848  * @param cls the request handle
849  * @param exp lifetime
850  * @param key the key the record was stored under
851  * @param get_path get path
852  * @param get_path_length get path length
853  * @param put_path put path
854  * @param put_path_length put path length
855  * @param type the block type
856  * @param size the size of the record
857  * @param data the record data
858  */
859 static void
860 process_record_result_dht(void* cls,
861                           struct GNUNET_TIME_Absolute exp,
862                           const struct GNUNET_HashCode * key,
863                           const struct GNUNET_PeerIdentity *get_path,
864                           unsigned int get_path_length,
865                           const struct GNUNET_PeerIdentity *put_path,
866                           unsigned int put_path_length,
867                           enum GNUNET_BLOCK_Type type,
868                           size_t size, const void *data)
869 {
870   struct ResolverHandle *rh;
871   struct RecordLookupHandle *rlh;
872   struct GNSNameRecordBlock *nrb;
873   uint32_t num_records;
874   char* name = NULL;
875   char* rd_data = (char*)data;
876   int i;
877   int rd_size;
878
879   rh = (struct ResolverHandle *)cls;
880   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
881              "GNS_PHASE_REC-%d: got dht result (size=%d)\n", rh->id, size);
882
883   if (data == NULL)
884     return;
885
886   //FIXME maybe check expiration here, check block type
887
888
889   rlh = (struct RecordLookupHandle *) rh->proc_cls;
890   nrb = (struct GNSNameRecordBlock*)data;
891
892   /* stop lookup and timeout task */
893   GNUNET_DHT_get_stop (rh->get_handle);
894   rh->get_handle = NULL;
895
896   if (rh->dht_heap_node != NULL)
897   {
898     GNUNET_CONTAINER_heap_remove_node(rh->dht_heap_node);
899     rh->dht_heap_node = NULL;
900   }
901
902   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
903   {
904     GNUNET_SCHEDULER_cancel(rh->timeout_task);
905     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
906   }
907
908   rh->get_handle = NULL;
909   name = (char*)&nrb[1];
910   num_records = ntohl(nrb->rd_count);
911   {
912     struct GNUNET_NAMESTORE_RecordData rd[num_records];
913
914     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
915     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
916
917     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
918                                                                rd_data,
919                                                                num_records,
920                                                                rd))
921     {
922       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
923                  "GNS_PHASE_REC-%d: Error deserializing data!\n", rh->id);
924       return;
925     }
926
927     for (i=0; i<num_records; i++)
928     {
929       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
930                  "GNS_PHASE_REC-%d: Got name: %s (wanted %s)\n",
931                  rh->id, name, rh->name);
932       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
933                  "GNS_PHASE_REC-%d: Got type: %d\n",
934                  rh->id, rd[i].record_type);
935       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
936                  "GNS_PHASE_REC-%d: Got data length: %d\n",
937                  rh->id, rd[i].data_size);
938       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
939                  "GNS_PHASE_REC-%d: Got flag %d\n",
940                  rh->id, rd[i].flags);
941
942       if ((strcmp(name, rh->name) == 0) &&
943           (rd[i].record_type == rlh->record_type))
944       {
945         rh->answered++;
946       }
947
948     }
949
950     /**
951      * FIXME check pubkey against existing key in namestore?
952      * https://gnunet.org/bugs/view.php?id=2179
953      */
954
955     /* Save to namestore */
956     GNUNET_NAMESTORE_record_put (namestore_handle,
957                                  &nrb->public_key,
958                                  name,
959                                  exp,
960                                  num_records,
961                                  rd,
962                                  &nrb->signature,
963                                  &on_namestore_record_put_result, //cont
964                                  NULL); //cls
965
966
967     if (rh->answered)
968       rh->proc(rh->proc_cls, rh, num_records, rd);
969     else
970       rh->proc(rh->proc_cls, rh, 0, NULL);
971   }
972
973 }
974
975
976 /**
977  * Start DHT lookup for a (name -> query->record_type) record in
978  * rh->authority's zone
979  *
980  * @param rh the pending gns query context
981  */
982 static void
983 resolve_record_dht(struct ResolverHandle *rh)
984 {
985   uint32_t xquery;
986   struct GNUNET_CRYPTO_ShortHashCode name_hash;
987   struct GNUNET_HashCode lookup_key;
988   struct GNUNET_HashCode name_hash_double;
989   struct GNUNET_HashCode zone_hash_double;
990   struct GNUNET_CRYPTO_HashAsciiEncoded lookup_key_string;
991   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
992   struct ResolverHandle *rh_heap_root;
993
994   GNUNET_CRYPTO_short_hash(rh->name, strlen(rh->name), &name_hash);
995   GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
996   GNUNET_CRYPTO_short_hash_double(&rh->authority, &zone_hash_double);
997   GNUNET_CRYPTO_hash_xor(&name_hash_double, &zone_hash_double, &lookup_key);
998   GNUNET_CRYPTO_hash_to_enc (&lookup_key, &lookup_key_string);
999
1000   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1001              "GNS_PHASE_REC-%d: starting dht lookup for %s with key: %s\n",
1002              rh->id, rh->name, (char*)&lookup_key_string);
1003
1004   //rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1005   rh->dht_heap_node = NULL;
1006
1007   if (rh->timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1008   {
1009     /**
1010      * Update timeout if necessary
1011      */
1012     if (rh->timeout_task == GNUNET_SCHEDULER_NO_TASK)
1013     {
1014
1015       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1016                  "GNS_PHASE_REC-%d: Adjusting timeout\n", rh->id);
1017       /*
1018        * Set timeout for authority lookup phase to 1/2
1019        */
1020       rh->timeout_task = GNUNET_SCHEDULER_add_delayed(
1021                                                       GNUNET_TIME_relative_divide(rh->timeout, 2),
1022                                                       &handle_lookup_timeout,
1023                                                       rh);
1024     }
1025     //rh->timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1026     //                                                   &dht_lookup_timeout,
1027     //                                                   rh);
1028     rh->timeout_cont = &dht_lookup_timeout;
1029     rh->timeout_cont_cls = rh;
1030   }
1031   else 
1032   {
1033     if (max_allowed_background_queries <=
1034         GNUNET_CONTAINER_heap_get_size (dht_lookup_heap))
1035     {
1036       rh_heap_root = GNUNET_CONTAINER_heap_remove_root (dht_lookup_heap);
1037       GNUNET_DHT_get_stop(rh_heap_root->get_handle);
1038       rh_heap_root->get_handle = NULL;
1039       rh_heap_root->dht_heap_node = NULL;
1040
1041       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1042                  "GNS_PHASE_REC-%d: Replacing oldest background query for %s\n",
1043                  rh->id, rh_heap_root->name);
1044       rh_heap_root->proc(rh_heap_root->proc_cls,
1045                          rh_heap_root,
1046                          0,
1047                          NULL);
1048     }
1049     rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap,
1050                                                       rh,
1051                                                       GNUNET_TIME_absolute_get().abs_value);
1052   }
1053
1054   xquery = htonl(rlh->record_type);
1055
1056   GNUNET_assert(rh->get_handle == NULL);
1057   rh->get_handle = GNUNET_DHT_get_start(dht_handle, 
1058                                         GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1059                                         &lookup_key,
1060                                         DHT_GNS_REPLICATION_LEVEL,
1061                                         GNUNET_DHT_RO_NONE,
1062                                         &xquery, 
1063                                         sizeof(xquery),
1064                                         &process_record_result_dht,
1065                                         rh);
1066
1067 }
1068
1069
1070 /**
1071  * Namestore calls this function if we have record for this name.
1072  * (or with rd_count=0 to indicate no matches)
1073  *
1074  * @param cls the pending query
1075  * @param key the key of the zone we did the lookup
1076  * @param expiration expiration date of the namestore entry
1077  * @param name the name for which we need an authority
1078  * @param rd_count the number of records with 'name'
1079  * @param rd the record data
1080  * @param signature the signature of the authority for the record data
1081  */
1082 static void
1083 process_record_result_ns(void* cls,
1084                          const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1085                          struct GNUNET_TIME_Absolute expiration,
1086                          const char *name, unsigned int rd_count,
1087                          const struct GNUNET_NAMESTORE_RecordData *rd,
1088                          const struct GNUNET_CRYPTO_RsaSignature *signature)
1089 {
1090   struct ResolverHandle *rh;
1091   struct RecordLookupHandle *rlh;
1092   struct GNUNET_TIME_Relative remaining_time;
1093   struct GNUNET_CRYPTO_ShortHashCode zone;
1094
1095   rh = (struct ResolverHandle *) cls;
1096   rlh = (struct RecordLookupHandle *)rh->proc_cls;
1097   GNUNET_CRYPTO_short_hash(key,
1098                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1099                            &zone);
1100   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
1101
1102
1103
1104   rh->status = 0;
1105
1106   if (name != NULL)
1107   {
1108     rh->status |= RSL_RECORD_EXISTS;
1109   }
1110
1111   if (remaining_time.rel_value == 0)
1112   {
1113     rh->status |= RSL_RECORD_EXPIRED;
1114   }
1115
1116   if (rd_count == 0)
1117   {
1118     /**
1119      * Lookup terminated and no results
1120      */
1121     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1122                "GNS_PHASE_REC-%d: Namestore lookup for %s terminated without results\n",
1123                rh->id, name);
1124
1125     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1126                "GNS_PHASE_REC-%d: Record %s unknown in namestore\n",
1127                rh->id, rh->name);
1128     /**
1129      * Our zone and no result? Cannot resolve TT
1130      */
1131     rh->proc(rh->proc_cls, rh, 0, NULL);
1132     return;
1133
1134   }
1135   else
1136   {
1137
1138     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1139                "GNS_PHASE_REC-%d: Processing additional result %s from namestore\n",
1140                rh->id, name);
1141     int i;
1142     for (i=0; i<rd_count;i++)
1143     {
1144
1145       if (rd[i].record_type != rlh->record_type)
1146         continue;
1147
1148       if (ignore_pending_records &&
1149           (rd[i].flags & GNUNET_NAMESTORE_RF_PENDING))
1150       {
1151         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1152                    "GNS_PHASE_REC-%d: Record %s is awaiting user confirmation. Skipping\n",
1153                    rh->id, name);
1154         continue;
1155       }
1156
1157       if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
1158           == 0)
1159       {
1160         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1161                    "GNS_PHASE_REC-%d: This record is expired. Skipping\n",
1162                    rh->id);
1163         continue;
1164       }
1165
1166       rh->answered++;
1167
1168     }
1169
1170     /**
1171      * no answers found
1172      */
1173     if (rh->answered == 0)
1174     {
1175       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
1176                  "GNS_PHASE_REC-%d: No answers found. This is odd!\n", rh->id);
1177       rh->proc(rh->proc_cls, rh, 0, NULL);
1178       return;
1179     }
1180
1181     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1182                "GNS_PHASE_REC-%d: Found %d answer(s) to query in %d records!\n",
1183                rh->id, rh->answered, rd_count);
1184
1185     rh->proc(rh->proc_cls, rh, rd_count, rd);
1186   }
1187 }
1188
1189
1190 /**
1191  * VPN redirect result callback
1192  *
1193  * @param cls the resolver handle
1194  * @param af the requested address family
1195  * @param address in_addr(6) respectively
1196  */
1197 static void
1198 process_record_result_vpn (void* cls, int af, const void *address)
1199 {
1200   struct ResolverHandle *rh = cls;
1201   struct RecordLookupHandle *rlh;
1202   struct GNUNET_NAMESTORE_RecordData rd;
1203
1204   rlh = (struct RecordLookupHandle *)rh->proc_cls;
1205
1206   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1207              "GNS_PHASE_REC_VPN-%d: Got answer from VPN to query!\n",
1208              rh->id);
1209   if (af == AF_INET)
1210   {
1211     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1212                "GNS_PHASE_REC-%d: Answer is IPv4!\n",
1213                rh->id);
1214     if (rlh->record_type != GNUNET_GNS_RECORD_TYPE_A)
1215     {
1216       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1217                  "GNS_PHASE_REC-%d: Requested record is not IPv4!\n",
1218                  rh->id);
1219       rh->proc (rh->proc_cls, rh, 0, NULL);
1220       return;
1221     }
1222     rd.record_type = GNUNET_GNS_RECORD_TYPE_A;
1223     rd.expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
1224     rd.data = address;
1225     rd.data_size = sizeof (struct in_addr);
1226     rd.flags = 0;
1227     rh->proc (rh->proc_cls, rh, 1, &rd);
1228     return;
1229   }
1230   else if (af == AF_INET6)
1231   {
1232     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1233                "GNS_PHASE_REC-%d: Answer is IPv6!\n",
1234                rh->id);
1235     if (rlh->record_type != GNUNET_GNS_RECORD_AAAA)
1236     {
1237       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1238                  "GNS_PHASE_REC-%d: Requested record is not IPv6!\n",
1239                  rh->id);
1240       rh->proc (rh->proc_cls, rh, 0, NULL);
1241       return;
1242     }
1243     rd.record_type = GNUNET_GNS_RECORD_AAAA;
1244     rd.expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
1245     rd.data = address;
1246     rd.data_size = sizeof (struct in6_addr);
1247     rd.flags = 0;
1248     rh->proc (rh->proc_cls, rh, 1, &rd);
1249     return;
1250   }
1251
1252   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1253              "GNS_PHASE_REC-%d: Got garbage from VPN!\n",
1254              rh->id);
1255   rh->proc (rh->proc_cls, rh, 0, NULL);
1256 }
1257
1258
1259 /**
1260  * finish lookup
1261  *
1262  * @param rh resolver handle
1263  * @param rlh record lookup handle
1264  * @param rd_count number of results
1265  * @param rd results
1266  */
1267 static void
1268 finish_lookup(struct ResolverHandle *rh,
1269               struct RecordLookupHandle* rlh,
1270               unsigned int rd_count,
1271               const struct GNUNET_NAMESTORE_RecordData *rd);
1272
1273 /**
1274  * Process VPN lookup result for record
1275  *
1276  * @param cls the record lookup handle
1277  * @param rh resolver handle
1278  * @param rd_count number of results (1)
1279  * @param rd record data containing the result
1280  */
1281 static void
1282 handle_record_vpn (void* cls, struct ResolverHandle *rh,
1283                    unsigned int rd_count,
1284                    const struct GNUNET_NAMESTORE_RecordData *rd)
1285 {
1286   struct RecordLookupHandle* rlh = (struct RecordLookupHandle*) cls;
1287   
1288   if (rd_count == 0)
1289   {
1290     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1291                "GNS_PHASE_REC_VPN-%d: VPN returned no records. (status: %d)!\n",
1292                rh->id,
1293                rh->status);
1294     /* give up, cannot resolve */
1295     finish_lookup(rh, rlh, 0, NULL);
1296     free_resolver_handle(rh);
1297     return;
1298   }
1299
1300   /* results found yay */
1301   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1302              "GNS_PHASE_REC_VPN-%d: Record resolved from VPN!", rh->id);
1303
1304   finish_lookup(rh, rlh, rd_count, rd);
1305
1306   free_resolver_handle(rh);
1307 }
1308
1309
1310 /**
1311  * Sends a UDP dns query to a nameserver specified in the rh
1312  * 
1313  * @param rh the resolver handle
1314  */
1315 static void
1316 send_dns_packet (struct ResolverHandle *rh);
1317
1318 static void
1319 handle_dns_resolver (void *cls,
1320                      const struct sockaddr *addr,
1321                      socklen_t addrlen)
1322 {
1323   struct ResolverHandle *rh = cls;
1324   struct RecordLookupHandle *rlh = rh->proc_cls;
1325   struct GNUNET_NAMESTORE_RecordData rd;
1326
1327   if (NULL == addr)
1328   {
1329     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1330                 "No address found in DNS!\n");
1331     finish_lookup (rh, rlh, 0, NULL);
1332     free_resolver_handle (rh);
1333     return;
1334   }
1335   
1336   if (addrlen == sizeof (struct sockaddr_in))
1337     rd.record_type = GNUNET_GNS_RECORD_TYPE_A;
1338   else
1339     rd.record_type = GNUNET_GNS_RECORD_AAAA;
1340   
1341   rd.expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
1342   rd.data_size = addrlen;
1343   rd.data = addr;
1344
1345   finish_lookup (rh, rlh, 1, &rd);
1346   free_resolver_handle (rh);
1347 }
1348
1349 /**
1350  * Resolve DNS name via local stub resolver
1351  *
1352  * @param rh the resolver handle
1353  */
1354 static void
1355 resolve_dns_name (struct ResolverHandle *rh)
1356 {
1357   struct RecordLookupHandle *rlh = rh->proc_cls;
1358   int af;
1359
1360   if ((rlh->record_type != GNUNET_GNS_RECORD_TYPE_A) &&
1361       (rlh->record_type != GNUNET_GNS_RECORD_AAAA))
1362   {
1363     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364                 "Can only resolve A/AAAA via stub... abort\n");
1365     finish_lookup (rh, rlh, 0, NULL);
1366     free_resolver_handle (rh);
1367     return;
1368   }
1369
1370   if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_A)
1371     af = AF_INET;
1372   else
1373     af = AF_INET6;
1374
1375   //GNUNET_RESOLVER_connect (cfg); FIXME into init
1376
1377   rh->dns_resolver_handle = GNUNET_RESOLVER_ip_get (rh->dns_name,
1378                                                     af,
1379                                                     rh->timeout,
1380                                                     &handle_dns_resolver,
1381                                                     rh);
1382 }
1383
1384
1385 /**
1386  * Read DNS udp packet from socket
1387  *
1388  * @param cls the resolver handle
1389  * @param tc task context
1390  */
1391 static void
1392 read_dns_response (void *cls,
1393                    const struct GNUNET_SCHEDULER_TaskContext *tc)
1394 {
1395   struct ResolverHandle *rh = cls;
1396   struct RecordLookupHandle *rlh = rh->proc_cls;
1397   char buf[UINT16_MAX];
1398   ssize_t r;
1399   struct sockaddr_in addr;
1400   socklen_t addrlen;
1401   struct GNUNET_DNSPARSER_Packet *packet;
1402   struct GNUNET_NAMESTORE_RecordData rd;
1403   int found_delegation = GNUNET_NO;
1404   int found_cname = GNUNET_NO;
1405   char* delegation_name = NULL;
1406   int zone_offset = 0;
1407   int i;
1408
1409   rh->dns_read_task = GNUNET_SCHEDULER_NO_TASK;
1410   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1411   {
1412     /* timeout or shutdown */
1413     rh->proc (rh->proc_cls, rh, 0, NULL);
1414     GNUNET_NETWORK_socket_close (rh->dns_sock);
1415     free_resolver_handle (rh);
1416     return;
1417   }
1418
1419   addrlen = sizeof (addr);
1420   r = GNUNET_NETWORK_socket_recvfrom (rh->dns_sock,
1421                                       buf, sizeof (buf),
1422                                       (struct sockaddr*) &addr,
1423                                       &addrlen);
1424
1425   if (-1 == r)
1426   {
1427     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "recvfrom");
1428     rh->proc (rh->proc_cls, rh, 0, NULL);
1429     GNUNET_NETWORK_socket_close (rh->dns_sock);
1430     free_resolver_handle (rh);
1431     return;
1432   }
1433
1434   packet = GNUNET_DNSPARSER_parse (buf, r);
1435   
1436   if (NULL == packet)
1437   {
1438     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1439                 "Failed to parse DNS reply!\n");
1440     rh->proc (rh->proc_cls, rh, 0, NULL);
1441     GNUNET_NETWORK_socket_close (rh->dns_sock);
1442     free_resolver_handle (rh);
1443     return;
1444   }
1445
1446   for (i = 0; i < packet->num_answers; i++)
1447   {
1448     /* http://tools.ietf.org/html/rfc1034#section-3.6.2 */
1449     if (packet->authority_records[i].type == GNUNET_GNS_RECORD_TYPE_CNAME)
1450     {
1451       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1452                   "CNAME... restarting query with %s\n",
1453                   packet->answers[i].data.hostname
1454                  );
1455       strcpy (rh->dns_name, packet->answers[i].data.hostname);
1456       found_cname = GNUNET_YES;
1457       //send_dns_packet (rh);
1458       //GNUNET_DNSPARSER_free_packet (packet);
1459       continue;
1460     }
1461     
1462     if ((packet->answers[i].type == rlh->record_type) &&
1463         (0 == strcmp (packet->answers[i].name, rh->dns_name)))
1464     {
1465       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1466                   "Found record!\n");
1467       rd.data = packet->answers[i].data.raw.data;
1468       rd.data_size = packet->answers[i].data.raw.data_len;
1469       rd.record_type = packet->answers[i].type;
1470       rd.flags = 0;
1471       rd.expiration = packet->answers[i].expiration_time;
1472       rh->proc (rh->proc_cls, rh, 1, &rd);
1473       GNUNET_NETWORK_socket_close (rh->dns_sock);
1474       GNUNET_DNSPARSER_free_packet (packet);
1475       free_resolver_handle (rh);
1476       return;
1477     }
1478   }
1479
1480   if (GNUNET_YES == found_cname)
1481   {
1482     zone_offset = strlen (rh->dns_name) - strlen (rh->dns_zone) - 1;
1483     
1484     if (0 > zone_offset)
1485       zone_offset = 0;
1486
1487     /* restart query with CNAME */
1488     if (0 == strcmp (rh->dns_name+zone_offset, rh->dns_zone))
1489       send_dns_packet (rh);
1490     else
1491       resolve_dns_name (rh);
1492
1493     GNUNET_DNSPARSER_free_packet (packet);
1494     return;
1495   }
1496
1497   for (i = 0; i < packet->num_authority_records; i++)
1498   {
1499     
1500     if (packet->authority_records[i].type == GNUNET_GNS_RECORD_TYPE_NS)
1501     {
1502       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1503                   "Found NS delegation!\n");
1504       found_delegation = GNUNET_YES;
1505       delegation_name = packet->authority_records[i].data.hostname;
1506       break;
1507     }
1508   }
1509
1510   for (i = 0; i < packet->num_additional_records; i++)
1511   {
1512     if (found_delegation == GNUNET_NO)
1513       break;
1514
1515     if ((packet->additional_records[i].type == GNUNET_GNS_RECORD_TYPE_A) &&
1516         (0 == strcmp (packet->additional_records[i].name, delegation_name)))
1517     {
1518       GNUNET_assert (sizeof (struct in_addr) ==
1519                      packet->authority_records[i].data.raw.data_len);
1520       
1521       rh->dns_addr.sin_addr =
1522         *((struct in_addr*)packet->authority_records[i].data.raw.data);
1523       send_dns_packet (rh);
1524       GNUNET_DNSPARSER_free_packet (packet);
1525       return;
1526     }
1527   }
1528
1529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1530               "Failed to parse DNS reply!\n");
1531   rh->proc (rh->proc_cls, rh, 0, NULL);
1532   GNUNET_NETWORK_socket_close (rh->dns_sock);
1533   free_resolver_handle (rh);
1534   GNUNET_DNSPARSER_free_packet (packet);
1535   return;
1536 }
1537
1538 /**
1539  * Sends a UDP dns query to a nameserver specified in the rh
1540  * 
1541  * @param rh the request handle
1542  */
1543 static void
1544 send_dns_packet (struct ResolverHandle *rh)
1545 {
1546   struct GNUNET_NETWORK_FDSet *rset = GNUNET_NETWORK_fdset_create ();
1547   GNUNET_NETWORK_fdset_set (rset, rh->dns_sock);
1548   
1549   GNUNET_NETWORK_socket_sendto (rh->dns_sock,
1550                                 rh->dns_raw_packet,
1551                                 rh->dns_raw_packet_size,
1552                                 (struct sockaddr*)&rh->dns_addr,
1553                                 sizeof (struct sockaddr_in));
1554
1555   rh->dns_read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1556                                                     rh->timeout, //FIXME less?
1557                                                     rset,
1558                                                     NULL,
1559                                                     &read_dns_response,
1560                                                     rh);
1561
1562   GNUNET_NETWORK_fdset_destroy (rset);
1563
1564 }
1565
1566 /**
1567  * The final phase of resoution.
1568  * We found a NS RR and want to resolve via DNS
1569  *
1570  * @param rh the pending lookup handle
1571  * @param rd_count length of record data
1572  * @param rd record data containing VPN RR
1573  */
1574 static void
1575 resolve_record_dns (struct ResolverHandle *rh,
1576                     int rd_count,
1577                     const struct GNUNET_NAMESTORE_RecordData *rd)
1578 {
1579   struct GNUNET_DNSPARSER_Query query;
1580   struct GNUNET_DNSPARSER_Packet packet;
1581   struct GNUNET_DNSPARSER_Flags flags;
1582   char dns_name[MAX_DNS_NAME_LENGTH];
1583   struct in_addr dnsip;
1584   struct sockaddr_in addr;
1585   struct sockaddr *sa;
1586   int i;
1587   struct RecordLookupHandle *rlh = rh->proc_cls;
1588   
1589   /* We cancel here as to not include the ns lookup in the timeout */
1590   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1591   {
1592     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1593     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1594   }
1595   /* Start shortening */
1596   if ((rh->priv_key != NULL) && is_canonical (rh->name))
1597   {
1598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599              "GNS_PHASE_REC_DNS-%llu: Trying to shorten authority chain\n",
1600              rh->id);
1601              start_shorten (rh->authority_chain_tail,
1602              rh->priv_key);
1603   }
1604
1605   for (i = 0; i < rd_count; i++)
1606   {
1607     /* Synthesize dns name */
1608     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_NS)
1609     {
1610       strcpy (rh->dns_zone, (char*)rd[i].data);
1611       if (0 == strcmp (rh->name, ""))
1612         strcpy (rh->dns_name, (char*)rd[i].data);
1613       else
1614         sprintf (rh->dns_name, "%s.%s", rh->name, (char*)rd[i].data);
1615     }
1616     /* The glue */
1617     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_A)
1618       dnsip = *((struct in_addr*)rd[i].data);
1619   }
1620   
1621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1622               "GNS_PHASE_REC_DNS-%llu: Looking up %s from %s\n",
1623               dns_name,
1624               inet_ntoa (dnsip));
1625   rh->dns_sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
1626   if (rh->dns_sock == NULL)
1627   {
1628     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1629                 "GNS_PHASE_REC_DNS-%llu: Error creating udp socket for dns!\n",
1630                 rh->id);
1631     rh->proc(rh->proc_cls, rh, 0, NULL);
1632     return;
1633   }
1634
1635   memset (&addr, 0, sizeof (struct sockaddr_in));
1636   sa = (struct sockaddr *) &addr;
1637   sa->sa_family = AF_INET;
1638   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (rh->dns_sock,
1639                                                sa,
1640                                                sizeof (struct sockaddr_in)))
1641   {
1642     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1643                 "GNS_PHASE_REC_DNS-%llu: Error binding udp socket for dns!\n",
1644                 rh->id);
1645     GNUNET_NETWORK_socket_close (rh->dns_sock);
1646     rh->proc(rh->proc_cls, rh, 0, NULL);
1647     return;
1648   }
1649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1650               "GNS_PHASE_REC_DNS-%llu: NOT IMPLEMENTED!\n",
1651               rh->id);
1652   GNUNET_NETWORK_socket_close (rh->dns_sock);
1653   rh->proc(rh->proc_cls, rh, 0, NULL);
1654   /*TODO create dnsparser query, serialize, sendto, handle reply*/
1655   query.name = dns_name;
1656   query.type = rlh->record_type;
1657   query.class = GNUNET_DNSPARSER_CLASS_INTERNET;
1658   memset (&flags, 0, sizeof (flags));
1659   flags.recursion_desired = 1;
1660   flags.checking_disabled = 1;
1661   packet.queries = &query;
1662   packet.answers = NULL;
1663   packet.authority_records = NULL;
1664   packet.num_queries = 1;
1665   packet.num_answers = 0;
1666   packet.num_authority_records = 0;
1667   packet.num_additional_records = 0;
1668   packet.flags = flags;
1669   packet.id = rh->id;
1670   if (GNUNET_OK != GNUNET_DNSPARSER_pack (&packet,
1671                                           UINT16_MAX,
1672                                           &rh->dns_raw_packet,
1673                                           &rh->dns_raw_packet_size))
1674   {
1675     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1676                 "GNS_PHASE_REC_DNS-%llu: Creating raw dns packet!\n",
1677                 rh->id);
1678     GNUNET_NETWORK_socket_close (rh->dns_sock);
1679     rh->proc(rh->proc_cls, rh, 0, NULL);
1680     return;
1681   }
1682
1683   rh->dns_addr.sin_family = AF_INET;
1684   rh->dns_addr.sin_port = htons (53); //domain
1685   rh->dns_addr.sin_addr = dnsip;
1686 #if HAVE_SOCKADDR_IN_SIN_LEN
1687   rh->dns_addr.sin_len = (u_char) sizeof (struct sockaddr_in);
1688 #endif
1689
1690   send_dns_packet (rh);
1691   
1692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1693               "GNS_PHASE_REC_DNS-%llu: NOT IMPLEMENTED!\n",
1694               rh->id);
1695   GNUNET_free (rh->dns_raw_packet);
1696   GNUNET_NETWORK_socket_close (rh->dns_sock);
1697   rh->proc(rh->proc_cls, rh, 0, NULL);
1698 }
1699
1700
1701 /**
1702  * The final phase of resoution.
1703  * We found a VPN RR and want to request an IPv4/6 address
1704  *
1705  * @param rh the pending lookup handle
1706  * @param rd_count length of record data
1707  * @param rd record data containing VPN RR
1708  */
1709 static void
1710 resolve_record_vpn (struct ResolverHandle *rh,
1711                     int rd_count,
1712                     const struct GNUNET_NAMESTORE_RecordData *rd)
1713 {
1714   int af;
1715   int proto;
1716   struct GNUNET_HashCode peer_id;
1717   struct GNUNET_CRYPTO_HashAsciiEncoded s_pid;
1718   struct GNUNET_HashCode serv_desc;
1719   struct GNUNET_CRYPTO_HashAsciiEncoded s_sd;
1720   char* pos;
1721   size_t len = (sizeof (uint32_t) * 2) + (sizeof (struct GNUNET_HashCode) * 2);
1722   
1723   /* We cancel here as to not include the ns lookup in the timeout */
1724   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1725   {
1726     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1727     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1728   }
1729   /* Start shortening */
1730   if ((rh->priv_key != NULL) && is_canonical (rh->name))
1731   {
1732     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1733              "GNS_PHASE_REC_VPN-%llu: Trying to shorten authority chain\n",
1734              rh->id);
1735              start_shorten (rh->authority_chain_tail,
1736              rh->priv_key);
1737   }
1738
1739   /* Extracting VPN information FIXME rd parsing with NS API?*/
1740   if (len != rd->data_size)
1741   {
1742     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1743                 "GNS_PHASE_REC_VPN-%llu: Error parsing VPN RR!\n",
1744                 rh->id);
1745     finish_lookup (rh, rh->proc_cls, 0, NULL);
1746     free_resolver_handle (rh);
1747     return;
1748   }
1749
1750   pos = (char*)rd;
1751   memcpy (&af, pos, sizeof (uint32_t));
1752   pos += sizeof (uint32_t);
1753   memcpy (&proto, pos, sizeof (uint32_t));
1754   pos += sizeof (uint32_t);
1755   memcpy (&s_pid, pos, sizeof (struct GNUNET_HashCode));
1756   pos += sizeof (struct GNUNET_HashCode);
1757   memcpy (&s_sd, pos, sizeof (struct GNUNET_HashCode));
1758
1759
1760   if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char*)&s_pid, &peer_id)) ||
1761       (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char*)&s_sd, &serv_desc)))
1762   {
1763     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1764                 "GNS_PHASE_REC_VPN-%llu: Error parsing VPN RR hashes!\n",
1765                 rh->id);
1766     finish_lookup (rh, rh->proc_cls, 0, NULL);
1767     free_resolver_handle (rh);
1768     return;
1769   }
1770
1771   rh->proc = &handle_record_vpn;
1772
1773   if (NULL == vpn_handle)
1774   {
1775     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1776                 "GNS_PHASE_REC_VPN-%llu: VPN not connected!\n",
1777                 rh->id);
1778     finish_lookup (rh, rh->proc_cls, 0, NULL);
1779     free_resolver_handle (rh);
1780     return;
1781   }
1782   
1783   //FIXME timeout??
1784   rh->vpn_handle = GNUNET_VPN_redirect_to_peer (vpn_handle,
1785                                           af, proto,
1786                                           (struct GNUNET_PeerIdentity*)&peer_id,
1787                                           &serv_desc,
1788                                           GNUNET_NO, //nac
1789                                           GNUNET_TIME_UNIT_FOREVER_ABS, //FIXME
1790                                           &process_record_result_vpn,
1791                                           rh);
1792
1793 }
1794
1795 /**
1796  * The final phase of resolution.
1797  * rh->name is a name that is canonical and we do not have a delegation.
1798  * Query namestore for this record
1799  *
1800  * @param rh the pending lookup handle
1801  */
1802 static void
1803 resolve_record_ns(struct ResolverHandle *rh)
1804 {
1805   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
1806   
1807   /* We cancel here as to not include the ns lookup in the timeout */
1808   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1809   {
1810     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1811     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1812   }
1813   /* Start shortening */
1814   if ((rh->priv_key != NULL) && is_canonical (rh->name))
1815   {
1816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1817              "GNS_PHASE_REC-%llu: Trying to shorten authority chain\n",
1818              rh->id);
1819              start_shorten (rh->authority_chain_tail,
1820              rh->priv_key);
1821   }
1822   
1823   /**
1824    * Try to resolve this record in our namestore.
1825    * The name to resolve is now in rh->authority_name
1826    * since we tried to resolve it to an authority
1827    * and failed.
1828    **/
1829   GNUNET_NAMESTORE_lookup_record(namestore_handle,
1830                                  &rh->authority,
1831                                  rh->name,
1832                                  rlh->record_type,
1833                                  &process_record_result_ns,
1834                                  rh);
1835 }
1836
1837
1838
1839 /**
1840  * Handle timeout for DHT requests
1841  *
1842  * @param cls the request handle as closure
1843  * @param tc the task context
1844  */
1845 static void
1846 dht_authority_lookup_timeout(void *cls,
1847                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1848 {
1849   struct ResolverHandle *rh = cls;
1850   struct RecordLookupHandle *rlh = rh->proc_cls;
1851   char new_name[MAX_DNS_NAME_LENGTH];
1852
1853   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1854          "GNS_PHASE_DELEGATE_DHT-%llu: dht lookup for query %s (%ds)timed out.\n",
1855          rh->id, rh->authority_name, rh->timeout.rel_value);
1856
1857   rh->status |= RSL_TIMED_OUT;
1858
1859   rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1860   
1861   GNUNET_DHT_get_stop (rh->get_handle);
1862   rh->get_handle = NULL;
1863   
1864   if (strcmp(rh->name, "") == 0)
1865   {
1866     /*
1867      * promote authority back to name and try to resolve record
1868      */
1869     strcpy(rh->name, rh->authority_name);
1870     rh->proc(rh->proc_cls, rh, 0, NULL);
1871     return;
1872   }
1873   
1874   /**
1875    * Start resolution in bg
1876    */
1877   GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH,
1878                   "%s.%s.%s", rh->name, rh->authority_name, GNUNET_GNS_TLD);
1879   //strcpy(new_name, rh->name);
1880   //strcpy(new_name+strlen(new_name), ".");
1881   //memcpy(new_name+strlen(new_name), GNUNET_GNS_TLD, strlen(GNUNET_GNS_TLD));
1882   
1883   strcpy(rh->name, new_name);
1884
1885   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1886         "GNS_PHASE_DELEGATE_DHT-%llu: Starting background query for %s type %d\n",
1887         rh->id, rh->name, rlh->record_type);
1888
1889   gns_resolver_lookup_record(rh->authority,
1890                              rh->private_local_zone,
1891                              rlh->record_type,
1892                              new_name,
1893                              rh->priv_key,
1894                              GNUNET_TIME_UNIT_FOREVER_REL,
1895                              GNUNET_NO,
1896                              &background_lookup_result_processor,
1897                              NULL);
1898
1899   rh->proc(rh->proc_cls, rh, 0, NULL);
1900 }
1901
1902 /* Prototype */
1903 static void resolve_delegation_dht(struct ResolverHandle *rh);
1904
1905 /* Prototype */
1906 static void resolve_delegation_ns(struct ResolverHandle *rh);
1907
1908
1909 /**
1910  * Namestore resolution for delegation finished. Processing result.
1911  *
1912  * @param cls the closure
1913  * @param rh resolver handle
1914  * @param rd_count number of results (always 0)
1915  * @param rd record data (always NULL)
1916  */
1917 static void
1918 handle_delegation_ns(void* cls, struct ResolverHandle *rh,
1919                           unsigned int rd_count,
1920                           const struct GNUNET_NAMESTORE_RecordData *rd);
1921
1922
1923 /**
1924  * Function called when we get a result from the dht
1925  * for our query. Recursively tries to resolve authorities
1926  * for name in DHT.
1927  *
1928  * @param cls the request handle
1929  * @param exp lifetime
1930  * @param key the key the record was stored under
1931  * @param get_path get path
1932  * @param get_path_length get path length
1933  * @param put_path put path
1934  * @param put_path_length put path length
1935  * @param type the block type
1936  * @param size the size of the record
1937  * @param data the record data
1938  */
1939 static void
1940 process_delegation_result_dht(void* cls,
1941                  struct GNUNET_TIME_Absolute exp,
1942                  const struct GNUNET_HashCode * key,
1943                  const struct GNUNET_PeerIdentity *get_path,
1944                  unsigned int get_path_length,
1945                  const struct GNUNET_PeerIdentity *put_path,
1946                  unsigned int put_path_length,
1947                  enum GNUNET_BLOCK_Type type,
1948                  size_t size, const void *data)
1949 {
1950   struct ResolverHandle *rh;
1951   struct GNSNameRecordBlock *nrb;
1952   uint32_t num_records;
1953   char* name = NULL;
1954   char* rd_data = (char*) data;
1955   int i;
1956   int rd_size;
1957   struct GNUNET_CRYPTO_ShortHashCode zone, name_hash;
1958   struct GNUNET_HashCode zone_hash_double, name_hash_double;
1959
1960   rh = (struct ResolverHandle *)cls;
1961   
1962   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1963              "GNS_PHASE_DELEGATE_DHT-%llu: Got DHT result\n", rh->id);
1964
1965   if (data == NULL)
1966     return;
1967   
1968   nrb = (struct GNSNameRecordBlock*)data;
1969   
1970   /* stop dht lookup and timeout task */
1971   GNUNET_DHT_get_stop (rh->get_handle);
1972
1973   rh->get_handle = NULL;
1974
1975   if (rh->dht_heap_node != NULL)
1976   {
1977     GNUNET_CONTAINER_heap_remove_node(rh->dht_heap_node);
1978     rh->dht_heap_node = NULL;
1979   }
1980
1981   num_records = ntohl(nrb->rd_count);
1982   name = (char*)&nrb[1];
1983   {
1984     struct GNUNET_NAMESTORE_RecordData rd[num_records];
1985     
1986     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
1987     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
1988   
1989     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
1990                                                                rd_data,
1991                                                                num_records,
1992                                                                rd))
1993     {
1994       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1995                  "GNS_PHASE_DELEGATE_DHT-%llu: Error deserializing data!\n",
1996                  rh->id);
1997       return;
1998     }
1999
2000     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2001                "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2002                rh->id, name, rh->authority_name);
2003     for (i=0; i<num_records; i++)
2004     {
2005     
2006       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2007                 "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2008                 rh->id, name, rh->authority_name);
2009       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2010                  "GNS_PHASE_DELEGATE_DHT-%llu: Got type: %d (wanted %d)\n",
2011                  rh->id, rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
2012       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2013                  "GNS_PHASE_DELEGATE_DHT-%llu: Got data length: %d\n",
2014                  rh->id, rd[i].data_size);
2015       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2016                  "GNS_PHASE_DELEGATE_DHT-%llu: Got flag %d\n",
2017                  rh->id, rd[i].flags);
2018
2019       if ((strcmp(name, rh->authority_name) == 0) &&
2020           (rd[i].record_type == GNUNET_GNS_RECORD_PKEY))
2021       {
2022         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2023                    "GNS_PHASE_DELEGATE_DHT-%llu: Authority found in DHT\n",
2024                    rh->id);
2025         rh->answered = 1;
2026         memcpy(&rh->authority, rd[i].data, sizeof(struct GNUNET_CRYPTO_ShortHashCode));
2027         struct AuthorityChain *auth =
2028           GNUNET_malloc(sizeof(struct AuthorityChain));
2029         auth->zone = rh->authority;
2030         memset(auth->name, 0, strlen(rh->authority_name)+1);
2031         strcpy(auth->name, rh->authority_name);
2032         GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
2033                                      rh->authority_chain_tail,
2034                                      auth);
2035
2036         /** try to import pkey if private key available */
2037         //if (rh->priv_key && is_canonical (rh->name))
2038         //  process_discovered_authority(name, auth->zone,
2039         //                               rh->authority_chain_tail->zone,
2040         //                               rh->priv_key);
2041       }
2042
2043     }
2044
2045
2046     GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
2047     GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2048     GNUNET_CRYPTO_hash_xor(key, &name_hash_double, &zone_hash_double);
2049     GNUNET_CRYPTO_short_hash_from_truncation (&zone_hash_double, &zone);
2050
2051     /* Save to namestore */
2052     if (0 != GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_tail->zone,
2053                                           &zone))
2054     {
2055       GNUNET_NAMESTORE_record_put (namestore_handle,
2056                                  &nrb->public_key,
2057                                  name,
2058                                  exp,
2059                                  num_records,
2060                                  rd,
2061                                  &nrb->signature,
2062                                  &on_namestore_record_put_result, //cont
2063                                  NULL); //cls
2064     }
2065   }
2066   
2067   if (rh->answered)
2068   {
2069     rh->answered = 0;
2070     /**
2071      * delegate
2072      * FIXME in this case. should we ask namestore again?
2073      */
2074     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2075       "GNS_PHASE_DELEGATE_DHT-%llu: Answer from DHT for %s. Yet to resolve: %s\n",
2076       rh->id, rh->authority_name, rh->name);
2077     
2078     if (strcmp(rh->name, "") == 0)
2079     {
2080       /* Start shortening */
2081       if ((rh->priv_key != NULL) && is_canonical (rh->name))
2082       {
2083         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2084              "GNS_PHASE_DELEGATE_DHT-%llu: Trying to shorten authority chain\n",
2085              rh->id);
2086         start_shorten (rh->authority_chain_tail,
2087                        rh->priv_key);
2088       }
2089       
2090       rh->proc(rh->proc_cls, rh, 0, NULL);
2091     }
2092     else
2093     {
2094       rh->proc = &handle_delegation_ns;
2095       resolve_delegation_ns(rh);
2096     }
2097     return;
2098   }
2099   
2100   /**
2101    * No pkey but name exists
2102    * promote back
2103    */
2104   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2105              "GNS_PHASE_DELEGATE_DHT-%llu: Adding %s back to %s\n",
2106              rh->id, rh->authority_name, rh->name);
2107   if (strcmp(rh->name, "") == 0)
2108     strcpy(rh->name, rh->authority_name);
2109   else
2110     GNUNET_snprintf(rh->name, MAX_DNS_NAME_LENGTH, "%s.%s",
2111                   rh->name, rh->authority_name); //FIXME ret
2112   
2113   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2114              "GNS_PHASE_DELEGATE_DHT-%llu: %s restored\n", rh->id, rh->name);
2115   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2116            "GNS_PHASE_DELEGATE_DHT-%llu: DHT authority lookup found no match!\n",
2117            rh->id);
2118   rh->proc(rh->proc_cls, rh, 0, NULL);
2119 }
2120
2121 #define MAX_SOA_LENGTH sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)\
2122                         +(MAX_DNS_NAME_LENGTH*2)
2123 #define MAX_MX_LENGTH sizeof(uint16_t)+MAX_DNS_NAME_LENGTH
2124
2125
2126 static void
2127 expand_plus(char** dest, char* src, char* repl)
2128 {
2129   char* pos;
2130   unsigned int s_len = strlen(src)+1;
2131
2132   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2133              "GNS_POSTPROCESS: Got %s to expand with %s\n", src, repl);
2134
2135   if (s_len < 3)
2136   {
2137     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2138                "GNS_POSTPROCESS: %s to short\n", src);
2139
2140     /* no postprocessing */
2141     memcpy(*dest, src, s_len+1);
2142     return;
2143   }
2144   
2145   if (0 == strcmp(src+s_len-3, ".+"))
2146   {
2147     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2148                "GNS_POSTPROCESS: Expanding .+ in %s\n", src);
2149     memset(*dest, 0, s_len+strlen(repl)+strlen(GNUNET_GNS_TLD));
2150     strcpy(*dest, src);
2151     pos = *dest+s_len-2;
2152     strcpy(pos, repl);
2153     pos += strlen(repl);
2154     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2155                "GNS_POSTPROCESS: Expanded to %s\n", *dest);
2156   }
2157   else
2158   {
2159     memcpy(*dest, src, s_len+1);
2160   }
2161 }
2162
2163 /**
2164  * finish lookup
2165  */
2166 static void
2167 finish_lookup(struct ResolverHandle *rh,
2168               struct RecordLookupHandle* rlh,
2169               unsigned int rd_count,
2170               const struct GNUNET_NAMESTORE_RecordData *rd)
2171 {
2172   int i;
2173   char new_rr_data[MAX_DNS_NAME_LENGTH];
2174   char new_mx_data[MAX_MX_LENGTH];
2175   char new_soa_data[MAX_SOA_LENGTH];
2176   struct GNUNET_NAMESTORE_RecordData p_rd[rd_count];
2177   char* repl_string;
2178   char* pos;
2179   unsigned int offset;
2180
2181   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2182   {
2183     GNUNET_SCHEDULER_cancel(rh->timeout_task);
2184     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2185   }
2186
2187   if (rd_count > 0)
2188     memcpy(p_rd, rd, rd_count*sizeof(struct GNUNET_NAMESTORE_RecordData));
2189
2190   for (i = 0; i < rd_count; i++)
2191   {
2192     
2193     if (rd[i].record_type != GNUNET_GNS_RECORD_TYPE_NS &&
2194         rd[i].record_type != GNUNET_GNS_RECORD_TYPE_CNAME &&
2195         rd[i].record_type != GNUNET_GNS_RECORD_MX &&
2196         rd[i].record_type != GNUNET_GNS_RECORD_TYPE_SOA)
2197     {
2198       p_rd[i].data = rd[i].data;
2199       continue;
2200     }
2201
2202     /**
2203      * for all those records we 'should'
2204      * also try to resolve the A/AAAA records (RFC1035)
2205      * This is a feature and not important
2206      */
2207     
2208     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2209                "GNS_POSTPROCESS: Postprocessing\n");
2210
2211     if (strcmp(rh->name, "+") == 0)
2212       repl_string = rlh->name;
2213     else
2214       repl_string = rlh->name+strlen(rh->name)+1;
2215
2216     offset = 0;
2217     if (rd[i].record_type == GNUNET_GNS_RECORD_MX)
2218     {
2219       memcpy(new_mx_data, (char*)rd[i].data, sizeof(uint16_t));
2220       offset = sizeof(uint16_t);
2221       pos = new_mx_data+offset;
2222       expand_plus(&pos, (char*)rd[i].data+sizeof(uint16_t),
2223                   repl_string);
2224       offset += strlen(new_mx_data+sizeof(uint16_t))+1;
2225       p_rd[i].data = new_mx_data;
2226       p_rd[i].data_size = offset;
2227     }
2228     else if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_SOA)
2229     {
2230       /* expand mname and rname */
2231       pos = new_soa_data;
2232       expand_plus(&pos, (char*)rd[i].data, repl_string);
2233       offset = strlen(new_soa_data)+1;
2234       pos = new_soa_data+offset;
2235       expand_plus(&pos, (char*)rd[i].data+offset, repl_string);
2236       offset += strlen(new_soa_data+offset)+1;
2237       /* cpy the 4 numbers serial refresh retry and expire */
2238       memcpy(new_soa_data+offset, (char*)rd[i].data+offset, sizeof(uint32_t)*5);
2239       offset += sizeof(uint32_t)*5;
2240       p_rd[i].data_size = offset;
2241       p_rd[i].data = new_soa_data;
2242     }
2243     else
2244     {
2245       pos = new_rr_data;
2246       expand_plus(&pos, (char*)rd[i].data, repl_string);
2247       p_rd[i].data_size = strlen(new_rr_data)+1;
2248       p_rd[i].data = new_rr_data;
2249     }
2250     
2251   }
2252
2253   rlh->proc(rlh->proc_cls, rd_count, p_rd);
2254   GNUNET_free(rlh);
2255   
2256 }
2257
2258 /**
2259  * Process DHT lookup result for record.
2260  *
2261  * @param cls the closure
2262  * @param rh resolver handle
2263  * @param rd_count number of results
2264  * @param rd record data
2265  */
2266 static void
2267 handle_record_dht(void* cls, struct ResolverHandle *rh,
2268                        unsigned int rd_count,
2269                        const struct GNUNET_NAMESTORE_RecordData *rd)
2270 {
2271   struct RecordLookupHandle* rlh;
2272
2273   rlh = (struct RecordLookupHandle*)cls;
2274   if (rd_count == 0)
2275   {
2276     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2277                "GNS_PHASE_REC-%d: No records for %s found in DHT. Aborting\n",
2278                rh->id, rh->name);
2279     /* give up, cannot resolve */
2280     finish_lookup(rh, rlh, 0, NULL);
2281     free_resolver_handle(rh);
2282     return;
2283   }
2284
2285   /* results found yay */
2286   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2287              "GNS_PHASE_REC-%d: Record resolved from DHT!", rh->id);
2288
2289   finish_lookup(rh, rlh, rd_count, rd);
2290   free_resolver_handle(rh);
2291
2292 }
2293
2294
2295
2296
2297 /**
2298  * Process namestore lookup result for record.
2299  *
2300  * @param cls the closure
2301  * @param rh resolver handle
2302  * @param rd_count number of results
2303  * @param rd record data
2304  */
2305 static void
2306 handle_record_ns (void* cls, struct ResolverHandle *rh,
2307                   unsigned int rd_count,
2308                   const struct GNUNET_NAMESTORE_RecordData *rd)
2309 {
2310   struct RecordLookupHandle* rlh;
2311   rlh = (struct RecordLookupHandle*) cls;
2312   if (rd_count == 0)
2313   {
2314     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2315                "GNS_PHASE_REC-%d: NS returned no records. (status: %d)!\n",
2316                rh->id,
2317                rh->status);
2318     
2319     /**
2320      * There are 5 conditions that have to met for us to consult the DHT:
2321      * 1. The entry in the DHT is RSL_RECORD_EXPIRED AND
2322      * 2. No entry in the NS existed AND
2323      * 3. The zone queried is not the local resolver's zone AND
2324      * 4. The name that was looked up is '+'
2325      *    because if it was any other canonical name we either already queried
2326      *    the DHT for the authority in the authority lookup phase (and thus
2327      *    would already have an entry in the NS for the record)
2328      * 5. We are not in cache only mode
2329      */
2330     if (rh->status & (RSL_RECORD_EXPIRED | !RSL_RECORD_EXISTS) &&
2331         GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
2332                                      &rh->private_local_zone) &&
2333         (strcmp(rh->name, "+") == 0) &&
2334         (rh->only_cached == GNUNET_NO))
2335     {
2336       rh->proc = &handle_record_dht;
2337       resolve_record_dht(rh);
2338       return;
2339     }
2340     /* give up, cannot resolve */
2341     finish_lookup(rh, rlh, 0, NULL);
2342     free_resolver_handle(rh);
2343     return;
2344   }
2345
2346   /* results found yay */
2347   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2348              "GNS_PHASE_REC-%d: Record resolved from namestore!", rh->id);
2349
2350   finish_lookup(rh, rlh, rd_count, rd);
2351
2352   free_resolver_handle(rh);
2353
2354 }
2355
2356
2357 /**
2358  * Move one level up in the domain hierarchy and return the
2359  * passed top level domain.
2360  *
2361  * @param name the domain
2362  * @param dest the destination where the tld will be put
2363  */
2364 void
2365 pop_tld(char* name, char* dest)
2366 {
2367   uint32_t len;
2368
2369   if (is_canonical(name))
2370   {
2371     strcpy(dest, name);
2372     strcpy(name, "");
2373     return;
2374   }
2375
2376   for (len = strlen(name); len > 0; len--)
2377   {
2378     if (*(name+len) == '.')
2379       break;
2380   }
2381   
2382   //Was canonical?
2383   if (len == 0)
2384     return;
2385
2386   name[len] = '\0';
2387
2388   strcpy(dest, (name+len+1));
2389 }
2390
2391 /**
2392  * Checks if name is in tld
2393  *
2394  * @param name the name to check
2395  * @param tld the TLD to check for
2396  * @return GNUNET_YES or GNUNET_NO
2397  */
2398 int
2399 is_tld(const char* name, const char* tld)
2400 {
2401   int offset = 0;
2402
2403   if (strlen(name) <= strlen(tld))
2404   {
2405     return GNUNET_NO;
2406   }
2407   
2408   offset = strlen(name)-strlen(tld);
2409   if (strcmp(name+offset, tld) != 0)
2410   {
2411     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2412                "%s is not in .%s TLD\n", name, tld);
2413     return GNUNET_NO;
2414   }
2415   return GNUNET_YES;
2416 }
2417
2418 /**
2419  * DHT resolution for delegation finished. Processing result.
2420  *
2421  * @param cls the closure
2422  * @param rh resolver handle
2423  * @param rd_count number of results (always 0)
2424  * @param rd record data (always NULL)
2425  */
2426 static void
2427 handle_delegation_dht(void* cls, struct ResolverHandle *rh,
2428                           unsigned int rd_count,
2429                           const struct GNUNET_NAMESTORE_RecordData *rd)
2430 {
2431   struct RecordLookupHandle* rlh;
2432   rlh = (struct RecordLookupHandle*) cls;
2433   
2434
2435   if (strcmp(rh->name, "") == 0)
2436   {
2437     if ((rlh->record_type == GNUNET_GNS_RECORD_PKEY))
2438     {
2439       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2440                  "GNS_PHASE_DELEGATE_DHT-%llu: Resolved queried PKEY via DHT.\n",
2441                  rh->id);
2442       finish_lookup(rh, rlh, rd_count, rd);
2443       free_resolver_handle(rh);
2444       return;
2445     }
2446     /* We resolved full name for delegation. resolving record */
2447     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2448      "GNS_PHASE_DELEGATE_DHT-%llu: Resolved full name for delegation via DHT.\n",
2449      rh->id);
2450     strcpy(rh->name, "+\0");
2451     rh->proc = &handle_record_ns;
2452     resolve_record_ns(rh);
2453     return;
2454   }
2455
2456   /**
2457    * we still have some left
2458    **/
2459   if (is_canonical(rh->name))
2460   {
2461     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2462              "GNS_PHASE_DELEGATE_DHT-%llu: Resolving canonical record %s in ns\n",
2463              rh->id,
2464              rh->name);
2465     rh->proc = &handle_record_ns;
2466     resolve_record_ns(rh);
2467     return;
2468   }
2469   /* give up, cannot resolve */
2470   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2471  "GNS_PHASE_DELEGATE_DHT-%llu: Cannot fully resolve delegation for %s via DHT!\n",
2472  rh->id, rh->name);
2473   finish_lookup(rh, rlh, 0, NULL);
2474   free_resolver_handle(rh);
2475 }
2476
2477
2478 /**
2479  * Start DHT lookup for a name -> PKEY (compare NS) record in
2480  * rh->authority's zone
2481  *
2482  * @param rh the pending gns query
2483  */
2484 static void
2485 resolve_delegation_dht(struct ResolverHandle *rh)
2486 {
2487   uint32_t xquery;
2488   struct GNUNET_CRYPTO_ShortHashCode name_hash;
2489   struct GNUNET_HashCode name_hash_double;
2490   struct GNUNET_HashCode zone_hash_double;
2491   struct GNUNET_HashCode lookup_key;
2492   struct ResolverHandle *rh_heap_root;
2493   
2494   pop_tld(rh->name, rh->authority_name); 
2495   GNUNET_CRYPTO_short_hash(rh->authority_name,
2496                      strlen(rh->authority_name),
2497                      &name_hash);
2498   GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2499   GNUNET_CRYPTO_short_hash_double(&rh->authority, &zone_hash_double);
2500   GNUNET_CRYPTO_hash_xor(&name_hash_double, &zone_hash_double, &lookup_key);
2501   
2502   rh->dht_heap_node = NULL;
2503
2504   if (rh->timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
2505   {
2506     //rh->timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
2507     //                                          &dht_authority_lookup_timeout,
2508     //                                                   rh);
2509     rh->timeout_cont = &dht_authority_lookup_timeout;
2510     rh->timeout_cont_cls = rh;
2511   }
2512   else 
2513   {
2514     if (max_allowed_background_queries <=
2515         GNUNET_CONTAINER_heap_get_size (dht_lookup_heap))
2516     {
2517       /* terminate oldest lookup */
2518       rh_heap_root = GNUNET_CONTAINER_heap_remove_root (dht_lookup_heap);
2519       GNUNET_DHT_get_stop(rh_heap_root->get_handle);
2520       rh_heap_root->dht_heap_node = NULL;
2521       
2522       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2523         "GNS_PHASE_DELEGATE_DHT-%llu: Replacing oldest background query for %s\n",
2524         rh->id, rh_heap_root->authority_name);
2525       
2526       rh_heap_root->proc(rh_heap_root->proc_cls,
2527                          rh_heap_root,
2528                          0,
2529                          NULL);
2530     }
2531     rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap,
2532                                          rh,
2533                                          GNUNET_TIME_absolute_get().abs_value);
2534   }
2535   
2536   xquery = htonl(GNUNET_GNS_RECORD_PKEY);
2537   
2538   GNUNET_assert(rh->get_handle == NULL);
2539   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
2540                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
2541                        &lookup_key,
2542                        DHT_GNS_REPLICATION_LEVEL,
2543                        GNUNET_DHT_RO_NONE,
2544                        &xquery,
2545                        sizeof(xquery),
2546                        &process_delegation_result_dht,
2547                        rh);
2548
2549 }
2550
2551
2552 /**
2553  * Namestore resolution for delegation finished. Processing result.
2554  *
2555  * @param cls the closure
2556  * @param rh resolver handle
2557  * @param rd_count number of results (always 0)
2558  * @param rd record data (always NULL)
2559  */
2560 static void
2561 handle_delegation_ns(void* cls, struct ResolverHandle *rh,
2562                           unsigned int rd_count,
2563                           const struct GNUNET_NAMESTORE_RecordData *rd)
2564 {
2565   struct RecordLookupHandle* rlh;
2566   rlh = (struct RecordLookupHandle*) cls;
2567
2568   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2569              "GNS_PHASE_DELEGATE_NS-%llu: Resolution status: %d.\n",
2570              rh->id, rh->status);
2571   
2572   if (strcmp(rh->name, "") == 0)
2573   {
2574     if (rlh->record_type == GNUNET_GNS_RECORD_PKEY)
2575     {
2576       GNUNET_assert(rd_count == 1);
2577       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2578                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried PKEY in NS.\n",
2579                  rh->id);
2580       finish_lookup(rh, rlh, rd_count, rd);
2581       free_resolver_handle(rh);
2582       return;
2583     }
2584     /* We resolved full name for delegation. resolving record */
2585     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2586               "GNS_PHASE_DELEGATE_NS-%llu: Resolved full name for delegation.\n",
2587               rh->id);
2588
2589     if (rh->status & RSL_DELEGATE_VPN)
2590     {
2591       if (rlh->record_type == GNUNET_GNS_RECORD_VPN)
2592       {
2593         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2594                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried VPNRR in NS.\n",
2595                  rh->id);
2596         finish_lookup(rh, rlh, rd_count, rd);
2597         free_resolver_handle(rh);
2598         return;
2599       }
2600       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2601              "GNS_PHASE_DELEGATE_NS-%llu: VPN delegation starting.\n",
2602              rh->id);
2603       GNUNET_assert (NULL != rd);
2604       rh->proc = &handle_record_vpn;
2605       resolve_record_vpn (rh, rd_count, rd);
2606     }
2607     else if (rh->status & RSL_DELEGATE_NS)
2608     {
2609       if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_NS)
2610       {
2611         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2612                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried NSRR in NS.\n",
2613                    rh->id);
2614         finish_lookup(rh, rlh, rd_count, rd);
2615         free_resolver_handle(rh);
2616         return;
2617       }
2618       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2619                  "GNS_PHASE_DELEGATE_NS-%llu: VPN delegation starting.\n",
2620                  rh->id);
2621       GNUNET_assert (NULL != rd);
2622       rh->proc = &handle_record_ns;
2623       resolve_record_dns (rh, rd_count, rd);
2624     }
2625     else
2626     {
2627       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2628                  "GNS_PHASE_DELEGATE_NS-%llu: Resolving record +\n",
2629                  rh->id);
2630       strcpy(rh->name, "+\0");
2631       rh->proc = &handle_record_ns;
2632       resolve_record_ns(rh);
2633     }
2634     return;
2635   }
2636
2637   /**
2638    * we still have some left
2639    * check if authority in ns is fresh
2640    * and exists
2641    * or we are authority
2642    **/
2643   if (((rh->status & RSL_RECORD_EXISTS) && (!(rh->status & RSL_RECORD_EXPIRED)))
2644       || !GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
2645                                        &rh->private_local_zone))
2646   {
2647     if (is_canonical(rh->name))
2648     {
2649       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2650                  "GNS_PHASE_DELEGATE_NS-%llu: Resolving canonical record %s\n",
2651                  rh->id,
2652                  rh->name);
2653       rh->proc = &handle_record_ns;
2654       resolve_record_ns(rh);
2655     }
2656     else
2657     {
2658       /* give up, cannot resolve */
2659       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2660           "GNS_PHASE_DELEGATE_NS-%llu: Cannot fully resolve delegation for %s!\n",
2661           rh->id,
2662           rh->name);
2663       finish_lookup(rh, rlh, rd_count, rd);
2664       //rlh->proc(rlh->proc_cls, 0, NULL);
2665     }
2666     return;
2667   }
2668
2669   if (rh->only_cached == GNUNET_YES)
2670   {
2671     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2672                "GNS_PHASE_DELEGATE_NS-%llu: Only cache resolution, no result\n",
2673                rh->id, rh->name);
2674     finish_lookup(rh, rlh, rd_count, rd);
2675     return;
2676   }
2677   
2678   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2679       "GNS_PHASE_DELEGATE_NS-%llu: Trying to resolve delegation for %s via DHT\n",
2680       rh->id, rh->name);
2681   rh->proc = &handle_delegation_dht;
2682   resolve_delegation_dht(rh);
2683 }
2684
2685
2686
2687 /**
2688  * This is a callback function that should give us only PKEY
2689  * records. Used to query the namestore for the authority (PKEY)
2690  * for 'name'. It will recursively try to resolve the
2691  * authority for a given name from the namestore.
2692  *
2693  * @param cls the pending query
2694  * @param key the key of the zone we did the lookup
2695  * @param expiration expiration date of the record data set in the namestore
2696  * @param name the name for which we need an authority
2697  * @param rd_count the number of records with 'name'
2698  * @param rd the record data
2699  * @param signature the signature of the authority for the record data
2700  */
2701 static void
2702 process_delegation_result_ns(void* cls,
2703                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
2704                    struct GNUNET_TIME_Absolute expiration,
2705                    const char *name,
2706                    unsigned int rd_count,
2707                    const struct GNUNET_NAMESTORE_RecordData *rd,
2708                    const struct GNUNET_CRYPTO_RsaSignature *signature)
2709 {
2710   struct ResolverHandle *rh;
2711   struct GNUNET_TIME_Relative remaining_time;
2712   struct GNUNET_CRYPTO_ShortHashCode zone;
2713   char new_name[MAX_DNS_NAME_LENGTH];
2714  
2715   rh = (struct ResolverHandle *)cls; 
2716   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2717              "GNS_PHASE_DELEGATE_NS-%llu: Got %d records from authority lookup\n",
2718              rh->id, rd_count);
2719
2720   GNUNET_CRYPTO_short_hash(key,
2721                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2722                      &zone);
2723   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
2724   
2725   rh->status = 0;
2726   
2727   if (name != NULL)
2728   {
2729     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2730                "GNS_PHASE_DELEGATE_NS-%llu: Records with name %s exist.\n",
2731                rh->id, name);
2732     rh->status |= RSL_RECORD_EXISTS;
2733   }
2734   
2735   if (remaining_time.rel_value == 0)
2736   {
2737     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2738                "GNS_PHASE_DELEGATE_NS-%llu: Record set %s expired.\n",
2739                rh->id, name);
2740     rh->status |= RSL_RECORD_EXPIRED;
2741   }
2742   
2743   /**
2744    * No authority found in namestore.
2745    */
2746   if (rd_count == 0)
2747   {
2748     /**
2749      * We did not find an authority in the namestore
2750      */
2751     
2752     /**
2753      * No PKEY in zone.
2754      * Promote this authority back to a name maybe it is
2755      * our record.
2756      */
2757     if (strcmp(rh->name, "") == 0)
2758     {
2759       /* simply promote back */
2760       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2761                  "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
2762                  rh->id, rh->authority_name);
2763       strcpy(rh->name, rh->authority_name);
2764     }
2765     else
2766     {
2767       /* add back to existing name */
2768       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2769                  "GNS_PHASE_DELEGATE_NS-%llu: Adding %s back to %s\n",
2770                  rh->id, rh->authority_name, rh->name);
2771       //memset(new_name, 0, strlen(rh->name) + strlen(rh->authority_name) + 2);
2772       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
2773                       rh->name, rh->authority_name);
2774       //strcpy(new_name, rh->name);
2775       //strcpy(new_name+strlen(new_name), ".");
2776       //strcpy(new_name+strlen(new_name), rh->authority_name);
2777       strcpy(rh->name, new_name);
2778       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2779                  "GNS_PHASE_DELEGATE_NS-%llu: %s restored\n", rh->id, rh->name);
2780     }
2781     rh->proc(rh->proc_cls, rh, 0, NULL);
2782     return;
2783   }
2784
2785   /**
2786    * We found an authority that may be able to help us
2787    * move on with query
2788    * Note only 1 pkey should have been returned.. anything else would be strange
2789    */
2790   int i;
2791   for (i=0; i<rd_count;i++)
2792   {
2793     /**
2794      * Redirect via VPN
2795      */
2796     if (rd[i].record_type == GNUNET_GNS_RECORD_VPN)
2797     {
2798       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2799                  "GNS_PHASE_DELEGATE_NS-%llu: VPNRR found.\n",
2800                  rh->id);
2801       rh->status |= RSL_DELEGATE_VPN;
2802       rh->proc (rh->proc_cls, rh, rd_count, rd);
2803       return;
2804     }
2805
2806     /**
2807      * Redirect via NS
2808      * FIXME make optional
2809      */
2810     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_NS)
2811     {
2812       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2813                  "GNS_PHASE_DELEGATE_NS-%llu: NS found.\n",
2814                  rh->id);
2815       rh->status |= RSL_DELEGATE_NS;
2816       rh->proc (rh->proc_cls, rh, rd_count, rd);
2817     }
2818   
2819     if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
2820       continue;
2821
2822     if (ignore_pending_records &&
2823         (rd[i].flags & GNUNET_NAMESTORE_RF_PENDING))
2824     {
2825       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2826       "GNS_PHASE_DELEGATE_NS-%llu: PKEY for %s is pending user confirmation.\n",
2827         rh->id,
2828         name);
2829       continue;
2830     }
2831     
2832     if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
2833          == 0)
2834     {
2835       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2836                  "GNS_PHASE_DELEGATE_NS-%llu: This pkey is expired.\n",
2837                  rh->id);
2838       if (remaining_time.rel_value == 0)
2839       {
2840         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2841                    "GNS_PHASE_DELEGATE_NS-%llu: This dht entry is expired.\n",
2842                    rh->id);
2843         rh->authority_chain_head->fresh = 0;
2844         rh->proc(rh->proc_cls, rh, 0, NULL);
2845         return;
2846       }
2847
2848       continue;
2849     }
2850
2851     /**
2852      * Resolve rest of query with new authority
2853      */
2854     GNUNET_assert(rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
2855     memcpy(&rh->authority, rd[i].data,
2856            sizeof(struct GNUNET_CRYPTO_ShortHashCode));
2857     struct AuthorityChain *auth = GNUNET_malloc(sizeof(struct AuthorityChain));
2858     auth->zone = rh->authority;
2859     memset(auth->name, 0, strlen(rh->authority_name)+1);
2860     strcpy(auth->name, rh->authority_name);
2861     GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
2862                                  rh->authority_chain_tail,
2863                                  auth);
2864     
2865     /** try to import pkey if private key available
2866      * TODO: Only import last one?
2867      */
2868     //if (rh->priv_key && (name != NULL) && is_canonical (rh->name))
2869     //  process_discovered_authority((char*)name, auth->zone,
2870     //                               rh->authority_chain_tail->zone,
2871     //                               rh->priv_key);
2872     /**
2873      * We are done with PKEY resolution if name is empty
2874      * else resolve again with new authority
2875      */
2876     if (strcmp(rh->name, "") == 0)
2877       rh->proc(rh->proc_cls, rh, rd_count, rd);
2878     else
2879       resolve_delegation_ns(rh);
2880     return;
2881   }
2882     
2883   /**
2884    * no answers found
2885    */
2886   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2887     "GNS_PHASE_DELEGATE_NS-%llu: Authority lookup and no PKEY...\n", rh->id);
2888   /**
2889    * If we have found some records for the LAST label
2890    * we return the results. Else null.
2891    */
2892   if (strcmp(rh->name, "") == 0)
2893   {
2894     /* Start shortening */
2895     if ((rh->priv_key != NULL) && is_canonical (rh->name))
2896     {
2897       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2898               "GNS_PHASE_DELEGATE_NS-%llu: Trying to shorten authority chain\n",
2899               rh->id);
2900       start_shorten (rh->authority_chain_tail,
2901                     rh->priv_key);
2902     }
2903     /* simply promote back */
2904     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2905                "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
2906                rh->id, rh->authority_name);
2907     strcpy(rh->name, rh->authority_name);
2908     rh->proc(rh->proc_cls, rh, rd_count, rd);
2909   }
2910   else
2911   {
2912     rh->proc(rh->proc_cls, rh, 0, NULL);
2913   }
2914 }
2915
2916
2917 /**
2918  * Resolve the delegation chain for the request in our namestore
2919  *
2920  * @param rh the resolver handle
2921  */
2922 static void
2923 resolve_delegation_ns(struct ResolverHandle *rh)
2924 {
2925   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2926              "GNS_PHASE_DELEGATE_NS-%llu: Resolving delegation for %s\n",
2927              rh->id, rh->name);
2928   pop_tld(rh->name, rh->authority_name);
2929   GNUNET_NAMESTORE_lookup_record(namestore_handle,
2930                                  &rh->authority,
2931                                  rh->authority_name,
2932                                  GNUNET_GNS_RECORD_ANY,
2933                                  &process_delegation_result_ns,
2934                                  rh);
2935
2936 }
2937
2938
2939 /**
2940  * Lookup of a record in a specific zone
2941  * calls lookup result processor on result
2942  *
2943  * @param zone the root zone
2944  * @param pzone the private local zone
2945  * @param record_type the record type to look up
2946  * @param name the name to look up
2947  * @param key a private key for use with PSEU import (can be NULL)
2948  * @param timeout timeout for resolution
2949  * @param only_cached GNUNET_NO to only check locally not DHT for performance
2950  * @param proc the processor to call on result
2951  * @param cls the closure to pass to proc
2952  */
2953 void
2954 gns_resolver_lookup_record(struct GNUNET_CRYPTO_ShortHashCode zone,
2955                            struct GNUNET_CRYPTO_ShortHashCode pzone,
2956                            uint32_t record_type,
2957                            const char* name,
2958                            struct GNUNET_CRYPTO_RsaPrivateKey *key,
2959                            struct GNUNET_TIME_Relative timeout,
2960                            int only_cached,
2961                            RecordLookupProcessor proc,
2962                            void* cls)
2963 {
2964   struct ResolverHandle *rh;
2965   struct RecordLookupHandle* rlh;
2966   char string_hash[MAX_DNS_LABEL_LENGTH];
2967   char nzkey[MAX_DNS_LABEL_LENGTH];
2968   char* nzkey_ptr = nzkey;
2969
2970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971               "Starting resolution for %s (type=%d)!\n",
2972               name, record_type);
2973
2974   
2975   if (is_canonical((char*)name) && (strcmp(GNUNET_GNS_TLD, name) != 0))
2976   {
2977     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2978                 "%s is canonical and not gnunet -> cannot resolve!\n", name);
2979     proc(cls, 0, NULL);
2980     return;
2981   }
2982   
2983   rlh = GNUNET_malloc(sizeof(struct RecordLookupHandle));
2984   rh = GNUNET_malloc(sizeof (struct ResolverHandle));
2985
2986   rh->authority = zone;
2987   rh->id = rid++;
2988   rh->proc_cls = rlh;
2989   rh->priv_key = key;
2990   rh->timeout = timeout;
2991   rh->get_handle = NULL;
2992   rh->private_local_zone = pzone;
2993   rh->only_cached = only_cached;
2994   
2995   if (NULL == key)
2996   {
2997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2998                 "No shorten key for resolution\n");
2999   }
3000
3001   if (timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3002   {
3003     /*
3004      * Set timeout for authority lookup phase to 1/2
3005      */
3006     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3007                 "Timeout for lookup set to %ds\n", rh->timeout.rel_value);
3008     rh->timeout_task = GNUNET_SCHEDULER_add_delayed(
3009                                 GNUNET_TIME_relative_divide(timeout, 2),
3010                                                 &handle_lookup_timeout,
3011                                                 rh);
3012     rh->timeout_cont = &dht_authority_lookup_timeout;
3013     rh->timeout_cont_cls = rh;
3014   }
3015   else
3016   {
3017     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No timeout for query!\n");
3018     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3019   }
3020   
3021   if (strcmp(GNUNET_GNS_TLD, name) == 0)
3022   {
3023     /**
3024      * Only 'gnunet' given
3025      */
3026     strcpy(rh->name, "\0");
3027   }
3028   else
3029   {
3030     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3031                 "Checking for TLD...\n");
3032     if (is_zkey_tld(name) == GNUNET_YES)
3033     {
3034       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3035                   "TLD is zkey\n");
3036       /**
3037        * This is a zkey tld
3038        * build hash and use as initial authority
3039        */
3040       memset(rh->name, 0,
3041              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY));
3042       memcpy(rh->name, name,
3043              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY) - 1);
3044       pop_tld(rh->name, string_hash);
3045
3046       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3047                   "ZKEY is %s!\n", string_hash);
3048       
3049       GNUNET_STRINGS_utf8_toupper(string_hash, &nzkey_ptr);
3050
3051       if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string(nzkey,
3052                                                       &rh->authority))
3053       {
3054         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3055                     "Cannot convert ZKEY %s to hash!\n", string_hash);
3056         GNUNET_free(rh);
3057         GNUNET_free(rlh);
3058         proc(cls, 0, NULL);
3059         return;
3060       }
3061
3062     }
3063     else
3064     {
3065       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3066                   "TLD is gnunet\n");
3067       /**
3068        * Presumably GNUNET tld
3069        */
3070       memset(rh->name, 0,
3071              strlen(name)-strlen(GNUNET_GNS_TLD));
3072       memcpy(rh->name, name,
3073              strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
3074     }
3075   }
3076   
3077   /**
3078    * Initialize authority chain
3079    */
3080   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
3081   rh->authority_chain_head->prev = NULL;
3082   rh->authority_chain_head->next = NULL;
3083   rh->authority_chain_tail = rh->authority_chain_head;
3084   rh->authority_chain_head->zone = rh->authority;
3085   
3086   /**
3087    * Copy original query into lookup handle
3088    */
3089   rlh->record_type = record_type;
3090   memset(rlh->name, 0, strlen(name) + 1);
3091   strcpy(rlh->name, name);
3092   rlh->proc = proc;
3093   rlh->proc_cls = cls;
3094
3095   rh->proc = &handle_delegation_ns;
3096   resolve_delegation_ns(rh);
3097 }
3098
3099 /******** END Record Resolver ***********/
3100
3101 /**
3102  * Callback calles by namestore for a zone to name
3103  * result
3104  *
3105  * @param cls the closure
3106  * @param zone_key the zone we queried
3107  * @param expire the expiration time of the name
3108  * @param name the name found or NULL
3109  * @param rd_len number of records for the name
3110  * @param rd the record data (PKEY) for the name
3111  * @param signature the signature for the record data
3112  */
3113 static void
3114 process_zone_to_name_shorten_root (void *cls,
3115                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3116                  struct GNUNET_TIME_Absolute expire,
3117                  const char *name,
3118                  unsigned int rd_len,
3119                  const struct GNUNET_NAMESTORE_RecordData *rd,
3120                  const struct GNUNET_CRYPTO_RsaSignature *signature);
3121
3122
3123 /**
3124  * Callback called by namestore for a zone to name
3125  * result
3126  *
3127  * @param cls the closure
3128  * @param zone_key the zone we queried
3129  * @param expire the expiration time of the name
3130  * @param name the name found or NULL
3131  * @param rd_len number of records for the name
3132  * @param rd the record data (PKEY) for the name
3133  * @param signature the signature for the record data
3134  */
3135 static void
3136 process_zone_to_name_shorten_shorten (void *cls,
3137                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3138                  struct GNUNET_TIME_Absolute expire,
3139                  const char *name,
3140                  unsigned int rd_len,
3141                  const struct GNUNET_NAMESTORE_RecordData *rd,
3142                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3143 {
3144   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3145   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3146   struct AuthorityChain *next_authority;
3147
3148   char result[MAX_DNS_NAME_LENGTH];
3149   char tmp_name[MAX_DNS_NAME_LENGTH];
3150   size_t answer_len;
3151   
3152   /* we found a match in our own root zone */
3153   if (rd_len != 0)
3154   {
3155     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3156                "result strlen %d\n", strlen(name));
3157     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3158     memset(result, 0, answer_len);
3159
3160     if (strlen(rh->name) > 0)
3161     {
3162       sprintf (result, "%s.%s.%s.%s.%s",
3163                rh->name, name,
3164                nsh->shorten_zone_name, nsh->private_zone_name,
3165                GNUNET_GNS_TLD);
3166     }
3167     else
3168     {
3169       sprintf (result, "%s.%s.%s.%s", name,
3170                nsh->shorten_zone_name, nsh->private_zone_name,
3171                GNUNET_GNS_TLD);
3172     }
3173     
3174     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3175                "Found shorten result %s\n", result);
3176     if (strlen (nsh->result) > strlen (result))
3177       strcpy (nsh->result, result);
3178   }
3179   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3180                                         nsh->shorten_zone) == 0)
3181   {
3182     /**
3183      * This is our zone append .gnunet unless name is empty
3184      * (it shouldn't be, usually FIXME what happens if we
3185      * shorten to our zone to a "" record??)
3186      */
3187     
3188     sprintf (result, "%s.%s.%s.%s",
3189              rh->name,
3190              nsh->shorten_zone_name, nsh->private_zone_name,
3191              GNUNET_GNS_TLD);
3192     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3193                "Our zone: Found %s as shorten result\n", result);
3194     
3195     if (strlen (nsh->result) > strlen (result))
3196       strcpy (nsh->result, result);
3197     //nsh->proc(nsh->proc_cls, result);
3198     //GNUNET_free(nsh);
3199     //free_resolver_handle(rh);
3200     //return;
3201   }
3202   
3203   
3204   /**
3205    * No PSEU found.
3206    * continue with next authority if exists
3207    */
3208   if ((rh->authority_chain_head->next == NULL))
3209   {
3210     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3211                 "Sending %s as shorten result\n", nsh->result);
3212     nsh->proc(nsh->proc_cls, nsh->result);
3213     GNUNET_free (nsh);
3214     free_resolver_handle (rh);
3215     return;
3216   }
3217   next_authority = rh->authority_chain_head;
3218   
3219   GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3220                   "%s.%s", rh->name, next_authority->name);
3221   
3222   strcpy(rh->name, tmp_name);
3223   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3224              "No PSEU found for authority %s. Promoting back: %s\n",
3225              next_authority->name, rh->name);
3226   
3227   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3228                             rh->authority_chain_tail,
3229                             next_authority);
3230
3231   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3232                                  &rh->authority_chain_tail->zone,
3233                                  &rh->authority_chain_head->zone,
3234                                  &process_zone_to_name_shorten_root,
3235                                  rh);
3236 }
3237
3238 /**
3239  * Callback calles by namestore for a zone to name
3240  * result
3241  *
3242  * @param cls the closure
3243  * @param zone_key the zone we queried
3244  * @param expire the expiration time of the name
3245  * @param name the name found or NULL
3246  * @param rd_len number of records for the name
3247  * @param rd the record data (PKEY) for the name
3248  * @param signature the signature for the record data
3249  */
3250 static void
3251 process_zone_to_name_shorten_private (void *cls,
3252                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3253                  struct GNUNET_TIME_Absolute expire,
3254                  const char *name,
3255                  unsigned int rd_len,
3256                  const struct GNUNET_NAMESTORE_RecordData *rd,
3257                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3258 {
3259   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3260   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3261   struct AuthorityChain *next_authority;
3262
3263   char result[MAX_DNS_NAME_LENGTH];
3264   char tmp_name[MAX_DNS_NAME_LENGTH];
3265   size_t answer_len;
3266   
3267   /* we found a match in our own root zone */
3268   if (rd_len != 0)
3269   {
3270     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3271                "result strlen %d\n", strlen(name));
3272     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3273     memset(result, 0, answer_len);
3274
3275     if (strlen(rh->name) > 0)
3276     {
3277       sprintf (result, "%s.%s.%s", rh->name, name, GNUNET_GNS_TLD);
3278     }
3279     else
3280     {
3281       sprintf (result, "%s.%s", name, GNUNET_GNS_TLD);
3282     }
3283     
3284     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3285                "Found shorten result %s\n", result);
3286     if (strlen (nsh->result) > strlen (result))
3287       strcpy (nsh->result, result);
3288   }
3289   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3290                                         nsh->private_zone) == 0)
3291   {
3292     /**
3293      * This is our zone append .gnunet unless name is empty
3294      * (it shouldn't be, usually FIXME what happens if we
3295      * shorten to our zone to a "" record??)
3296      */
3297     
3298     sprintf (result, "%s.%s.%s",
3299              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3300     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3301                "Our private zone: Found %s as shorten result %s\n", result);
3302     if (strlen (nsh->result) > strlen (result))
3303       strcpy (nsh->result, result);
3304   }
3305   
3306   if (nsh->shorten_zone != NULL)
3307   {
3308     /* backtrack authorities for names in priv zone */
3309     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3310                                    nsh->shorten_zone,
3311                                    &rh->authority_chain_head->zone,
3312                                    &process_zone_to_name_shorten_shorten,
3313                                    rh);
3314   }
3315   else
3316   {
3317     /**
3318      * No PSEU found.
3319      * continue with next authority if exists
3320      */
3321     if ((rh->authority_chain_head->next == NULL))
3322     {
3323       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3324                  "Sending %s as shorten result\n", nsh->result);
3325       nsh->proc(nsh->proc_cls, nsh->result);
3326       GNUNET_free(nsh);
3327       free_resolver_handle(rh);
3328       return;
3329     }
3330     next_authority = rh->authority_chain_head;
3331     
3332     GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3333                     "%s.%s", rh->name, next_authority->name);
3334     
3335     strcpy(rh->name, tmp_name);
3336     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3337                "No PSEU found for authority %s. Promoting back: %s\n",
3338                next_authority->name, rh->name);
3339     
3340     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3341                               rh->authority_chain_tail,
3342                               next_authority);
3343
3344     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3345                                    &rh->authority_chain_tail->zone,
3346                                    &rh->authority_chain_head->zone,
3347                                    &process_zone_to_name_shorten_root,
3348                                    rh);
3349   }
3350 }
3351
3352 /**
3353  * Callback calles by namestore for a zone to name
3354  * result
3355  *
3356  * @param cls the closure
3357  * @param zone_key the zone we queried
3358  * @param expire the expiration time of the name
3359  * @param name the name found or NULL
3360  * @param rd_len number of records for the name
3361  * @param rd the record data (PKEY) for the name
3362  * @param signature the signature for the record data
3363  */
3364 static void
3365 process_zone_to_name_shorten_root (void *cls,
3366                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3367                  struct GNUNET_TIME_Absolute expire,
3368                  const char *name,
3369                  unsigned int rd_len,
3370                  const struct GNUNET_NAMESTORE_RecordData *rd,
3371                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3372 {
3373   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3374   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3375   struct AuthorityChain *next_authority;
3376
3377   char result[MAX_DNS_NAME_LENGTH];
3378   char tmp_name[MAX_DNS_NAME_LENGTH];
3379   size_t answer_len;
3380   
3381   /* we found a match in our own root zone */
3382   if (rd_len != 0)
3383   {
3384     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3385                "result strlen %d\n", strlen(name));
3386     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3387     memset(result, 0, answer_len);
3388
3389     if (strlen(rh->name) > 0)
3390     {
3391       sprintf (result, "%s.%s.%s", rh->name, name, GNUNET_GNS_TLD);
3392     }
3393     else
3394     {
3395       sprintf (result, "%s.%s", name, GNUNET_GNS_TLD);
3396     }
3397     
3398     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3399                "Found shorten result %s\n", result);
3400     if (strlen (nsh->result) > strlen (result))
3401       strcpy (nsh->result, result);
3402   }
3403   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3404                                         nsh->root_zone) == 0)
3405   {
3406     /**
3407      * This is our zone append .gnunet unless name is empty
3408      * (it shouldn't be, usually FIXME what happens if we
3409      * shorten to our zone to a "" record??)
3410      */
3411     
3412     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
3413     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3414                "Our zone: Found %s as shorten result\n", result);
3415     if (strlen (nsh->result) > strlen (result))
3416       strcpy (nsh->result, result);
3417   }
3418   
3419   if (nsh->private_zone != NULL)
3420   {
3421     /* backtrack authorities for names in priv zone */
3422     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3423                                    nsh->private_zone,
3424                                    &rh->authority_chain_head->zone,
3425                                    &process_zone_to_name_shorten_private,
3426                                    rh);
3427   }
3428   else
3429   {
3430     /**
3431      * No PSEU found.
3432      * continue with next authority if exists
3433      */
3434     if ((rh->authority_chain_head->next == NULL))
3435     {
3436       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3437                  "Sending %s as shorten result\n", nsh->result);
3438       nsh->proc(nsh->proc_cls, nsh->result);
3439       GNUNET_free(nsh);
3440       free_resolver_handle(rh);
3441       return;
3442     }
3443     next_authority = rh->authority_chain_head;
3444     
3445     GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3446                     "%s.%s", rh->name, next_authority->name);
3447     
3448     strcpy(rh->name, tmp_name);
3449     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3450                "No PSEU found for authority %s. Promoting back: %s\n",
3451                next_authority->name, rh->name);
3452     
3453     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3454                               rh->authority_chain_tail,
3455                               next_authority);
3456
3457     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3458                                    &rh->authority_chain_tail->zone,
3459                                    &rh->authority_chain_head->zone,
3460                                    &process_zone_to_name_shorten_root,
3461                                    rh);
3462   }
3463 }
3464
3465
3466 /**
3467  * Process result from namestore delegation lookup
3468  * for shorten operation
3469  *
3470  * @param cls the client shorten handle
3471  * @param rh the resolver handle
3472  * @param rd_count number of results (0)
3473  * @param rd data (NULL)
3474  */
3475 void
3476 handle_delegation_ns_shorten(void* cls,
3477                       struct ResolverHandle *rh,
3478                       uint32_t rd_count,
3479                       const struct GNUNET_NAMESTORE_RecordData *rd)
3480 {
3481   struct NameShortenHandle *nsh;
3482   char result[MAX_DNS_NAME_LENGTH];
3483
3484   nsh = (struct NameShortenHandle *)cls;
3485   
3486   /**
3487    * At this point rh->name contains the part of the name
3488    * that we do not have a PKEY in our namestore to resolve.
3489    * The authority chain in the resolver handle is now
3490    * useful to backtrack if needed
3491    */
3492   
3493   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3494              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
3495   memset(result, 0, sizeof (result));
3496
3497   if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3498                                    nsh->root_zone) == 0)
3499   {
3500     /**
3501      * This is our zone append .gnunet unless name is empty
3502      * (it shouldn't be, usually FIXME what happens if we
3503      * shorten to our zone to a "" record??)
3504      */
3505     
3506     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
3507     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3508                "Our zone: Found %s as shorten result\n", result);
3509     
3510     if (strlen (nsh->result) > strlen (result))
3511       strcpy (nsh->result, result);
3512
3513   }
3514   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3515                                         nsh->private_zone) == 0)
3516   {
3517     /**
3518      * This is our zone append .gnunet unless name is empty
3519      * (it shouldn't be, usually FIXME what happens if we
3520      * shorten to our zone to a "" record??)
3521      */
3522     
3523     sprintf (result, "%s.%s.%s",
3524              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3525     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3526                "Our zone: Found %s as shorten result %s\n", result);
3527     
3528     if (strlen (nsh->result) > strlen (result))
3529       strcpy (nsh->result, result);
3530   }
3531   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3532                                         nsh->shorten_zone) == 0)
3533   {
3534     /**
3535      * This is our zone append .gnunet unless name is empty
3536      * (it shouldn't be, usually FIXME what happens if we
3537      * shorten to our zone to a "" record??)
3538      */
3539     
3540     sprintf (result, "%s.%s.%s",
3541              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3542     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3543                "Our zone: Found %s as shorten result\n", result);
3544     
3545     if (strlen (nsh->result) > strlen (result))
3546       strcpy (nsh->result, result);
3547   }
3548   
3549   
3550   /* backtrack authorities for names */
3551   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3552                                  nsh->root_zone,
3553                                  &rh->authority_chain_head->zone,
3554                                  &process_zone_to_name_shorten_root,
3555                                  rh);
3556   
3557 }
3558
3559
3560 /**
3561  * Callback calles by namestore for a zone to name
3562  * result
3563  *
3564  * @param cls the closure
3565  * @param zone_key the zone we queried
3566  * @param expire the expiration time of the name
3567  * @param name the name found or NULL
3568  * @param rd_len number of records for the name
3569  * @param rd the record data (PKEY) for the name
3570  * @param signature the signature for the record data
3571  */
3572 static void
3573 process_zone_to_name_zkey(void *cls,
3574                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3575                  struct GNUNET_TIME_Absolute expire,
3576                  const char *name,
3577                  unsigned int rd_len,
3578                  const struct GNUNET_NAMESTORE_RecordData *rd,
3579                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3580 {
3581   struct ResolverHandle *rh = cls;
3582   struct NameShortenHandle *nsh = rh->proc_cls;
3583   struct GNUNET_CRYPTO_ShortHashAsciiEncoded enc;
3584   char new_name[MAX_DNS_NAME_LENGTH];
3585
3586   /* zkey not in our zone */
3587   if (name == NULL)
3588   {
3589     /**
3590      * In this case we have not given this PKEY a name (yet)
3591      * It is either just not in our zone or not even cached
3592      * Since we do not know at this point we will not try to shorten
3593      * because PKEY import will happen if the user follows the zkey
3594      * link.
3595      */
3596     GNUNET_CRYPTO_short_hash_to_enc ((struct GNUNET_CRYPTO_ShortHashCode*)rd,
3597                                      &enc);
3598     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3599                "No name found for zkey %s returning verbatim!\n", enc);
3600     if (strcmp(rh->name, "") != 0)
3601       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s.%s",
3602                       rh->name, enc, GNUNET_GNS_TLD_ZKEY);
3603     else
3604       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
3605                       enc, GNUNET_GNS_TLD_ZKEY);
3606
3607     strcpy (nsh->result, new_name);
3608
3609     nsh->proc(nsh->proc_cls, new_name);
3610     GNUNET_free(nsh);
3611     free_resolver_handle(rh);
3612     return;
3613   }
3614   
3615   if (strcmp(rh->name, "") != 0)
3616     GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
3617                     rh->name, name);
3618   else
3619     strcpy(new_name, name);
3620
3621   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3622              "Continue shorten for %s!\n", new_name);
3623
3624   strcpy(rh->name, new_name);
3625   
3626   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
3627   rh->authority_chain_tail = rh->authority_chain_head;
3628   rh->authority_chain_head->zone = rh->authority;
3629   
3630   
3631   /* Start delegation resolution in our namestore */
3632   resolve_delegation_ns(rh);
3633 }
3634
3635
3636 /**
3637  * Shorten api from resolver
3638  *
3639  * @param zone the root zone to use
3640  * @param pzone the private zone to use
3641  * @param szone the shorten zone to use
3642  * @param name the name to shorten
3643  * @param private_zone_name name of the private zone
3644  * @param shorten_zone_name name of the shorten zone
3645  * @param proc the processor to call with result
3646  * @param proc_cls closure to pass to proc
3647  */
3648 void
3649 gns_resolver_shorten_name (struct GNUNET_CRYPTO_ShortHashCode *zone,
3650                            struct GNUNET_CRYPTO_ShortHashCode *pzone,
3651                            struct GNUNET_CRYPTO_ShortHashCode *szone,
3652                            const char* name,
3653                            const char* private_zone_name,
3654                            const char* shorten_zone_name,
3655                            ShortenResultProcessor proc,
3656                            void* proc_cls)
3657 {
3658   struct ResolverHandle *rh;
3659   struct NameShortenHandle *nsh;
3660   char string_hash[MAX_DNS_LABEL_LENGTH];
3661   struct GNUNET_CRYPTO_ShortHashCode zkey;
3662   char nzkey[MAX_DNS_LABEL_LENGTH];
3663   char* nzkey_ptr = nzkey;
3664
3665
3666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3667               "Starting shorten for %s!\n", name);
3668   
3669   if (is_canonical ((char*)name))
3670   {
3671     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3672                 "%s is canonical. Returning verbatim\n", name);
3673     proc (proc_cls, name);
3674     return;
3675   }
3676
3677   nsh = GNUNET_malloc (sizeof (struct NameShortenHandle));
3678
3679   nsh->proc = proc;
3680   nsh->proc_cls = proc_cls;
3681   nsh->root_zone = zone;
3682   nsh->private_zone = pzone;
3683   nsh->shorten_zone = szone;
3684   strcpy (nsh->private_zone_name, private_zone_name);
3685   strcpy (nsh->shorten_zone_name, shorten_zone_name);
3686   strcpy (nsh->result, name);
3687   
3688   rh = GNUNET_malloc (sizeof (struct ResolverHandle));
3689   rh->authority = *zone;
3690   rh->id = rid++;
3691   rh->priv_key = NULL;
3692   rh->proc = &handle_delegation_ns_shorten;
3693   rh->proc_cls = nsh;
3694   rh->id = rid++;
3695   rh->private_local_zone = *zone;
3696   
3697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3698                 "Checking for TLD...\n");
3699   if (is_zkey_tld (name) == GNUNET_YES)
3700   {
3701     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3702                 "TLD is zkey\n");
3703     /**
3704      * This is a zkey tld
3705      * build hash and use as initial authority
3706      * FIXME sscanf
3707      */
3708     memset (rh->name, 0,
3709             strlen (name)-strlen (GNUNET_GNS_TLD_ZKEY));
3710     memcpy (rh->name, name,
3711             strlen(name)-strlen (GNUNET_GNS_TLD_ZKEY) - 1);
3712     pop_tld (rh->name, string_hash);
3713
3714     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3715                 "ZKEY is %s!\n", string_hash);
3716     
3717     GNUNET_STRINGS_utf8_toupper (string_hash, &nzkey_ptr);
3718
3719     if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string (nzkey,
3720                                                            &zkey))
3721     {
3722       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3723                   "Cannot convert ZKEY %s to hash!\n", nzkey);
3724       GNUNET_free (rh);
3725       GNUNET_free (nsh);
3726       proc (proc_cls, name);
3727       return;
3728     }
3729
3730     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3731                                    zone, //ours
3732                                    &zkey,
3733                                    &process_zone_to_name_zkey,
3734                                    rh);
3735     return;
3736
3737   }
3738   else
3739   {
3740     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3741                 "TLD is gnunet\n");
3742     /**
3743      * Presumably GNUNET tld
3744      */
3745     memset (rh->name, 0,
3746             strlen (name)-strlen (GNUNET_GNS_TLD));
3747     memcpy (rh->name, name,
3748             strlen (name)-strlen (GNUNET_GNS_TLD) - 1);
3749   }
3750
3751   rh->authority_chain_head = GNUNET_malloc (sizeof (struct AuthorityChain));
3752   rh->authority_chain_tail = rh->authority_chain_head;
3753   rh->authority_chain_head->zone = *zone;
3754   
3755   
3756   /* Start delegation resolution in our namestore */
3757   resolve_delegation_ns (rh);
3758 }
3759
3760 /*********** END NAME SHORTEN ********************/
3761
3762
3763 /**
3764  * Process result from namestore delegation lookup
3765  * for get authority operation
3766  *
3767  * @param cls the client get auth handle
3768  * @param rh the resolver handle
3769  * @param rd_count number of results (0)
3770  * @param rd data (NULL)
3771  */
3772 void
3773 handle_delegation_result_ns_get_auth(void* cls,
3774                       struct ResolverHandle *rh,
3775                       uint32_t rd_count,
3776                       const struct GNUNET_NAMESTORE_RecordData *rd)
3777 {
3778   struct GetNameAuthorityHandle* nah;
3779   char result[MAX_DNS_NAME_LENGTH];
3780   size_t answer_len;
3781
3782   nah = (struct GetNameAuthorityHandle*) rh->proc_cls;
3783   
3784   /**
3785    * At this point rh->name contains the part of the name
3786    * that we do not have a PKEY in our namestore to resolve.
3787    * The authority chain in the resolver handle is now
3788    * useful to backtrack if needed
3789    */
3790   
3791   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3792              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
3793
3794   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3795              "Building response!\n");
3796   if (is_canonical(rh->name))
3797   {
3798     /**
3799      * We successfully resolved the authority in the ns
3800      * FIXME for our purposes this is fine
3801      * but maybe we want to have an api that also looks
3802      * into the dht (i.e. option in message)
3803      **/
3804     if (strlen(rh->name) > strlen(nah->name))
3805     {
3806       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3807                  "Record name longer than original lookup name... odd!\n");
3808       //FIXME to sth here
3809     }
3810
3811     answer_len = strlen(nah->name) - strlen(rh->name)
3812       + strlen(GNUNET_GNS_TLD) + 1;
3813     memset(result, 0, answer_len);
3814     strcpy(result, nah->name + strlen(rh->name) + 1);
3815
3816     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3817                "Got authority result %s\n", result);
3818     
3819     nah->proc(nah->proc_cls, result);
3820     GNUNET_free(nah);
3821     free_resolver_handle(rh);
3822   }
3823   else
3824   {
3825     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3826                "Unable to resolve authority for remaining %s!\n", rh->name);
3827     nah->proc(nah->proc_cls, "");
3828     GNUNET_free(nah);
3829     free_resolver_handle(rh);
3830   }
3831
3832
3833 }
3834
3835
3836 /**
3837  * Tries to resolve the authority for name
3838  * in our namestore
3839  *
3840  * @param zone the root zone to look up for
3841  * @param pzone the private local zone
3842  * @param name the name to lookup up
3843  * @param proc the processor to call when finished
3844  * @param proc_cls the closure to pass to the processor
3845  */
3846 void
3847 gns_resolver_get_authority(struct GNUNET_CRYPTO_ShortHashCode zone,
3848                            struct GNUNET_CRYPTO_ShortHashCode pzone,
3849                            const char* name,
3850                            GetAuthorityResultProcessor proc,
3851                            void* proc_cls)
3852 {
3853   struct ResolverHandle *rh;
3854   struct GetNameAuthorityHandle *nah;
3855
3856   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3857               "Starting authority resolution for %s!\n", name);
3858
3859   nah = GNUNET_malloc(sizeof (struct GetNameAuthorityHandle));
3860   rh = GNUNET_malloc(sizeof (struct ResolverHandle));
3861   rh->authority = zone;
3862   rh->id = rid++;
3863   rh->private_local_zone = pzone;
3864   
3865   if (strcmp(GNUNET_GNS_TLD, name) == 0)
3866   {
3867     strcpy(rh->name, "\0");
3868   }
3869   else
3870   {
3871     memset(rh->name, 0,
3872            strlen(name)-strlen(GNUNET_GNS_TLD));
3873     memcpy(rh->name, name,
3874            strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
3875   }
3876
3877   memset(nah->name, 0,
3878          strlen(name)+1);
3879   strcpy(nah->name, name);
3880   
3881   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
3882   rh->authority_chain_tail = rh->authority_chain_head;
3883   rh->authority_chain_head->zone = zone;
3884   rh->proc = &handle_delegation_result_ns_get_auth;
3885   rh->proc_cls = (void*)nah;
3886
3887   nah->proc = proc;
3888   nah->proc_cls = proc_cls;
3889
3890   /* Start delegation resolution in our namestore */
3891   resolve_delegation_ns(rh);
3892
3893 }
3894
3895 /******** END GET AUTHORITY *************/
3896
3897 /* end of gnunet-service-gns_resolver.c */