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