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