b6bc5eb1d8dfbfc5d73fab746fe46827fe1a1151
[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 = GNUNET_TIME_UNIT_FOREVER_ABS;
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
1140   rh = (struct ResolverHandle *) cls;
1141   rlh = (struct RecordLookupHandle *)rh->proc_cls;
1142   GNUNET_CRYPTO_short_hash(key,
1143                            sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1144                            &zone);
1145   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
1146
1147
1148
1149   rh->status = 0;
1150
1151   if (name != NULL)
1152   {
1153     rh->status |= RSL_RECORD_EXISTS;
1154
1155     if (remaining_time.rel_value == 0)
1156     {
1157       rh->status |= RSL_RECORD_EXPIRED;
1158     }
1159   }
1160
1161   if (rd_count == 0)
1162   {
1163     /**
1164      * Lookup terminated and no results
1165      */
1166     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1167                "GNS_PHASE_REC-%d: Namestore lookup for %s terminated without results\n",
1168                rh->id, name);
1169
1170     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1171                "GNS_PHASE_REC-%d: Record %s unknown in namestore\n",
1172                rh->id, rh->name);
1173     /**
1174      * Our zone and no result? Cannot resolve TT
1175      */
1176     rh->proc(rh->proc_cls, rh, 0, NULL);
1177     return;
1178
1179   }
1180   else
1181   {
1182
1183     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1184                "GNS_PHASE_REC-%d: Processing additional result %s from namestore\n",
1185                rh->id, name);
1186     int i;
1187     for (i=0; i<rd_count;i++)
1188     {
1189
1190       if (rd[i].record_type != rlh->record_type)
1191         continue;
1192
1193       if (ignore_pending_records &&
1194           (rd[i].flags & GNUNET_NAMESTORE_RF_PENDING))
1195       {
1196         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1197                    "GNS_PHASE_REC-%d: Record %s is awaiting user confirmation. Skipping\n",
1198                    rh->id, name);
1199         continue;
1200       }
1201
1202       if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
1203           == 0)
1204       {
1205         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1206                    "GNS_PHASE_REC-%d: This record is expired. Skipping\n",
1207                    rh->id);
1208         continue;
1209       }
1210
1211       rh->answered++;
1212
1213     }
1214
1215     /**
1216      * no answers found
1217      */
1218     if (rh->answered == 0)
1219     {
1220       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
1221                  "GNS_PHASE_REC-%d: No answers found. This is odd!\n", rh->id);
1222       rh->proc(rh->proc_cls, rh, 0, NULL);
1223       return;
1224     }
1225
1226     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1227                "GNS_PHASE_REC-%d: Found %d answer(s) to query in %d records!\n",
1228                rh->id, rh->answered, rd_count);
1229
1230     rh->proc(rh->proc_cls, rh, rd_count, rd);
1231   }
1232 }
1233
1234
1235 /**
1236  * VPN redirect result callback
1237  *
1238  * @param cls the resolver handle
1239  * @param af the requested address family
1240  * @param address in_addr(6) respectively
1241  */
1242 static void
1243 process_record_result_vpn (void* cls, int af, const void *address)
1244 {
1245   struct ResolverHandle *rh = cls;
1246   struct RecordLookupHandle *rlh;
1247   struct GNUNET_NAMESTORE_RecordData rd;
1248
1249   rlh = (struct RecordLookupHandle *)rh->proc_cls;
1250
1251   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1252              "GNS_PHASE_REC_VPN-%d: Got answer from VPN to query!\n",
1253              rh->id);
1254   if (af == AF_INET)
1255   {
1256     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1257                "GNS_PHASE_REC-%d: Answer is IPv4!\n",
1258                rh->id);
1259     if (rlh->record_type != GNUNET_GNS_RECORD_TYPE_A)
1260     {
1261       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1262                  "GNS_PHASE_REC-%d: Requested record is not IPv4!\n",
1263                  rh->id);
1264       rh->proc (rh->proc_cls, rh, 0, NULL);
1265       return;
1266     }
1267     rd.record_type = GNUNET_GNS_RECORD_TYPE_A;
1268     rd.expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
1269     rd.data = address;
1270     rd.data_size = sizeof (struct in_addr);
1271     rd.flags = 0;
1272     rh->proc (rh->proc_cls, rh, 1, &rd);
1273     return;
1274   }
1275   else if (af == AF_INET6)
1276   {
1277     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1278                "GNS_PHASE_REC-%d: Answer is IPv6!\n",
1279                rh->id);
1280     if (rlh->record_type != GNUNET_GNS_RECORD_AAAA)
1281     {
1282       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1283                  "GNS_PHASE_REC-%d: Requested record is not IPv6!\n",
1284                  rh->id);
1285       rh->proc (rh->proc_cls, rh, 0, NULL);
1286       return;
1287     }
1288     rd.record_type = GNUNET_GNS_RECORD_AAAA;
1289     rd.expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
1290     rd.data = address;
1291     rd.data_size = sizeof (struct in6_addr);
1292     rd.flags = 0;
1293     rh->proc (rh->proc_cls, rh, 1, &rd);
1294     return;
1295   }
1296
1297   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1298              "GNS_PHASE_REC-%d: Got garbage from VPN!\n",
1299              rh->id);
1300   rh->proc (rh->proc_cls, rh, 0, NULL);
1301 }
1302
1303
1304 /**
1305  * finish lookup
1306  *
1307  * @param rh resolver handle
1308  * @param rlh record lookup handle
1309  * @param rd_count number of results
1310  * @param rd results
1311  */
1312 static void
1313 finish_lookup(struct ResolverHandle *rh,
1314               struct RecordLookupHandle* rlh,
1315               unsigned int rd_count,
1316               const struct GNUNET_NAMESTORE_RecordData *rd);
1317
1318 /**
1319  * Process VPN lookup result for record
1320  *
1321  * @param cls the record lookup handle
1322  * @param rh resolver handle
1323  * @param rd_count number of results (1)
1324  * @param rd record data containing the result
1325  */
1326 static void
1327 handle_record_vpn (void* cls, struct ResolverHandle *rh,
1328                    unsigned int rd_count,
1329                    const struct GNUNET_NAMESTORE_RecordData *rd)
1330 {
1331   struct RecordLookupHandle* rlh = (struct RecordLookupHandle*) cls;
1332   
1333   if (rd_count == 0)
1334   {
1335     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1336                "GNS_PHASE_REC_VPN-%d: VPN returned no records. (status: %d)!\n",
1337                rh->id,
1338                rh->status);
1339     /* give up, cannot resolve */
1340     finish_lookup(rh, rlh, 0, NULL);
1341     free_resolver_handle(rh);
1342     return;
1343   }
1344
1345   /* results found yay */
1346   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1347              "GNS_PHASE_REC_VPN-%d: Record resolved from VPN!", rh->id);
1348
1349   finish_lookup(rh, rlh, rd_count, rd);
1350
1351   free_resolver_handle(rh);
1352 }
1353
1354
1355 /**
1356  * Sends a UDP dns query to a nameserver specified in the rh
1357  * 
1358  * @param rh the resolver handle
1359  */
1360 static void
1361 send_dns_packet (struct ResolverHandle *rh);
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 = GNUNET_TIME_UNIT_FOREVER_ABS;
1399
1400   finish_lookup (rh, rlh, 1, &rd);
1401   free_resolver_handle (rh);
1402   GNUNET_RESOLVER_request_cancel (rh->dns_resolver_handle);
1403 }
1404
1405 /**
1406  * Resolve DNS name via local stub resolver
1407  *
1408  * @param rh the resolver handle
1409  */
1410 static void
1411 resolve_dns_name (struct ResolverHandle *rh)
1412 {
1413   struct RecordLookupHandle *rlh = rh->proc_cls;
1414   int af;
1415
1416   if ((rlh->record_type != GNUNET_GNS_RECORD_TYPE_A) &&
1417       (rlh->record_type != GNUNET_GNS_RECORD_AAAA))
1418   {
1419     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1420                 "Can only resolve A/AAAA via stub... abort\n");
1421     finish_lookup (rh, rlh, 0, NULL);
1422     free_resolver_handle (rh);
1423     return;
1424   }
1425
1426   if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_A)
1427     af = AF_INET;
1428   else
1429     af = AF_INET6;
1430
1431   //GNUNET_RESOLVER_connect (cfg); FIXME into init
1432
1433   rh->dns_resolver_handle = GNUNET_RESOLVER_ip_get (rh->dns_name,
1434                                                     af,
1435                                                     rh->timeout,
1436                                                     &handle_dns_resolver,
1437                                                     rh);
1438 }
1439
1440
1441 /**
1442  * Read DNS udp packet from socket
1443  *
1444  * @param cls the resolver handle
1445  * @param tc task context
1446  */
1447 static void
1448 read_dns_response (void *cls,
1449                    const struct GNUNET_SCHEDULER_TaskContext *tc)
1450 {
1451   struct ResolverHandle *rh = cls;
1452   struct RecordLookupHandle *rlh = rh->proc_cls;
1453   char buf[UINT16_MAX];
1454   ssize_t r;
1455   struct sockaddr_in addr;
1456   socklen_t addrlen;
1457   struct GNUNET_DNSPARSER_Packet *packet;
1458   struct GNUNET_NAMESTORE_RecordData rd;
1459   int found_delegation = GNUNET_NO;
1460   int found_cname = GNUNET_NO;
1461   char* delegation_name = NULL;
1462   int zone_offset = 0;
1463   int i;
1464
1465   rh->dns_read_task = GNUNET_SCHEDULER_NO_TASK;
1466   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1467   {
1468     /* timeout or shutdown */
1469     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1470                 "Terminating DNS query\n");
1471     finish_lookup (rh, rlh, 0, NULL);
1472     GNUNET_NETWORK_socket_close (rh->dns_sock);
1473     free_resolver_handle (rh);
1474     return;
1475   }
1476
1477   addrlen = sizeof (addr);
1478   r = GNUNET_NETWORK_socket_recvfrom (rh->dns_sock,
1479                                       buf, sizeof (buf),
1480                                       (struct sockaddr*) &addr,
1481                                       &addrlen);
1482
1483   if (-1 == r)
1484   {
1485     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "recvfrom");
1486     finish_lookup (rh, rlh, 0, NULL);
1487     GNUNET_NETWORK_socket_close (rh->dns_sock);
1488     free_resolver_handle (rh);
1489     return;
1490   }
1491
1492   packet = GNUNET_DNSPARSER_parse (buf, r);
1493   
1494   if (NULL == packet)
1495   {
1496     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1497                 "Failed to parse DNS reply!\n");
1498     finish_lookup (rh, rlh, 0, NULL);
1499     GNUNET_NETWORK_socket_close (rh->dns_sock);
1500     free_resolver_handle (rh);
1501     return;
1502   }
1503
1504   for (i = 0; i < packet->num_answers; i++)
1505   {
1506     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1507                "Got record type %d (want %d)\n",
1508                packet->answers[i].type,
1509                rlh->record_type);
1510     /* http://tools.ietf.org/html/rfc1034#section-3.6.2 */
1511     if (packet->answers[i].type == GNUNET_GNS_RECORD_TYPE_CNAME)
1512     {
1513       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514                   "CNAME... restarting query with %s\n",
1515                   packet->answers[i].data.hostname
1516                  );
1517       strcpy (rh->dns_name, packet->answers[i].data.hostname);
1518       found_cname = GNUNET_YES;
1519       //send_dns_packet (rh);
1520       //GNUNET_DNSPARSER_free_packet (packet);
1521       continue;
1522     }
1523     
1524     if ((packet->answers[i].type == rlh->record_type) &&
1525         (0 == strcmp (packet->answers[i].name, rh->dns_name)))
1526     {
1527       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1528                   "Found record!\n");
1529       rd.data = packet->answers[i].data.raw.data;
1530       rd.data_size = packet->answers[i].data.raw.data_len;
1531       rd.record_type = packet->answers[i].type;
1532       rd.flags = 0;
1533       rd.expiration = packet->answers[i].expiration_time;
1534       finish_lookup (rh, rlh, 1, &rd);
1535       GNUNET_NETWORK_socket_close (rh->dns_sock);
1536       GNUNET_DNSPARSER_free_packet (packet);
1537       free_resolver_handle (rh);
1538       return;
1539     }
1540   }
1541
1542   if (GNUNET_YES == found_cname)
1543   {
1544     zone_offset = strlen (rh->dns_name) - strlen (rh->dns_zone) - 1;
1545     
1546     if (0 > zone_offset)
1547       zone_offset = 0;
1548
1549     /* restart query with CNAME */
1550     if (0 == strcmp (rh->dns_name+zone_offset, rh->dns_zone))
1551     {
1552       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1553                   "Asking same server for %s\n", rh->dns_name);
1554       send_dns_packet (rh);
1555     }
1556     else
1557     {
1558       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1559                   "Trying system resolver for %s\n", rh->dns_name);
1560       resolve_dns_name (rh);
1561     }
1562
1563     GNUNET_DNSPARSER_free_packet (packet);
1564     return;
1565   }
1566
1567   for (i = 0; i < packet->num_authority_records; i++)
1568   {
1569     
1570     if (packet->authority_records[i].type == GNUNET_GNS_RECORD_TYPE_NS)
1571     {
1572       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1573                   "Found NS delegation!\n");
1574       found_delegation = GNUNET_YES;
1575       delegation_name = packet->authority_records[i].data.hostname;
1576       break;
1577     }
1578   }
1579
1580   for (i = 0; i < packet->num_additional_records; i++)
1581   {
1582     if (found_delegation == GNUNET_NO)
1583       break;
1584
1585     if ((packet->additional_records[i].type == GNUNET_GNS_RECORD_TYPE_A) &&
1586         (0 == strcmp (packet->additional_records[i].name, delegation_name)))
1587     {
1588       GNUNET_assert (sizeof (struct in_addr) ==
1589                      packet->authority_records[i].data.raw.data_len);
1590       
1591       rh->dns_addr.sin_addr =
1592         *((struct in_addr*)packet->authority_records[i].data.raw.data);
1593       send_dns_packet (rh);
1594       GNUNET_DNSPARSER_free_packet (packet);
1595       return;
1596     }
1597   }
1598
1599   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600               "Nothing useful in DNS reply!\n");
1601   finish_lookup (rh, rlh, 0, NULL);
1602   GNUNET_NETWORK_socket_close (rh->dns_sock);
1603   free_resolver_handle (rh);
1604   GNUNET_DNSPARSER_free_packet (packet);
1605   return;
1606 }
1607
1608 /**
1609  * Sends a UDP dns query to a nameserver specified in the rh
1610  * 
1611  * @param rh the request handle
1612  */
1613 static void
1614 send_dns_packet (struct ResolverHandle *rh)
1615 {
1616   struct GNUNET_NETWORK_FDSet *rset = GNUNET_NETWORK_fdset_create ();
1617   GNUNET_NETWORK_fdset_set (rset, rh->dns_sock);
1618   
1619   GNUNET_NETWORK_socket_sendto (rh->dns_sock,
1620                                 rh->dns_raw_packet,
1621                                 rh->dns_raw_packet_size,
1622                                 (struct sockaddr*)&rh->dns_addr,
1623                                 sizeof (struct sockaddr_in));
1624
1625   rh->dns_read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1626                                                     rh->timeout, //FIXME less?
1627                                                     rset,
1628                                                     NULL,
1629                                                     &read_dns_response,
1630                                                     rh);
1631
1632   GNUNET_NETWORK_fdset_destroy (rset);
1633
1634 }
1635
1636 /**
1637  * The final phase of resoution.
1638  * We found a NS RR and want to resolve via DNS
1639  *
1640  * @param rh the pending lookup handle
1641  * @param rd_count length of record data
1642  * @param rd record data containing VPN RR
1643  */
1644 static void
1645 resolve_record_dns (struct ResolverHandle *rh,
1646                     int rd_count,
1647                     const struct GNUNET_NAMESTORE_RecordData *rd)
1648 {
1649   struct GNUNET_DNSPARSER_Query query;
1650   struct GNUNET_DNSPARSER_Packet packet;
1651   struct GNUNET_DNSPARSER_Flags flags;
1652   struct in_addr dnsip;
1653   struct sockaddr_in addr;
1654   struct sockaddr *sa;
1655   int i;
1656   struct RecordLookupHandle *rlh = rh->proc_cls;
1657   
1658   /* We cancel here as to not include the ns lookup in the timeout */
1659   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1660   {
1661     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1662     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1663   }
1664   /* Start shortening */
1665   if ((rh->priv_key != NULL) && is_canonical (rh->name))
1666   {
1667     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1668              "GNS_PHASE_REC_DNS-%llu: Trying to shorten authority chain\n",
1669              rh->id);
1670     start_shorten (rh->authority_chain_tail,
1671                    rh->priv_key);
1672   }
1673
1674   for (i = 0; i < rd_count; i++)
1675   {
1676     /* Synthesize dns name */
1677     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_NS)
1678     {
1679       strcpy (rh->dns_zone, (char*)rd[i].data);
1680       if (0 == strcmp (rh->name, ""))
1681         strcpy (rh->dns_name, (char*)rd[i].data);
1682       else
1683         sprintf (rh->dns_name, "%s.%s", rh->name, (char*)rd[i].data);
1684     }
1685     /* The glue */
1686     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_A)
1687       dnsip = *((struct in_addr*)rd[i].data);
1688   }
1689   
1690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691               "GNS_PHASE_REC_DNS-%llu: Looking up %s from %s\n",
1692               rh->id,
1693               rh->dns_name,
1694               inet_ntoa (dnsip));
1695   rh->dns_sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
1696   if (rh->dns_sock == NULL)
1697   {
1698     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699                 "GNS_PHASE_REC_DNS-%llu: Error creating udp socket for dns!\n",
1700                 rh->id);
1701     finish_lookup (rh, rlh, 0, NULL);
1702     free_resolver_handle (rh);
1703     return;
1704   }
1705
1706   memset (&addr, 0, sizeof (struct sockaddr_in));
1707   sa = (struct sockaddr *) &addr;
1708   sa->sa_family = AF_INET;
1709   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (rh->dns_sock,
1710                                                sa,
1711                                                sizeof (struct sockaddr_in)))
1712   {
1713     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714                 "GNS_PHASE_REC_DNS-%llu: Error binding udp socket for dns!\n",
1715                 rh->id);
1716     GNUNET_NETWORK_socket_close (rh->dns_sock);
1717     finish_lookup (rh, rlh, 0, NULL);
1718     free_resolver_handle (rh);
1719     return;
1720   }
1721   
1722   /*TODO create dnsparser query, serialize, sendto, handle reply*/
1723   query.name = rh->dns_name;
1724   query.type = rlh->record_type;
1725   query.class = GNUNET_DNSPARSER_CLASS_INTERNET;
1726   memset (&flags, 0, sizeof (flags));
1727   flags.recursion_desired = 1;
1728   flags.checking_disabled = 1;
1729   packet.queries = &query;
1730   packet.answers = NULL;
1731   packet.authority_records = NULL;
1732   packet.num_queries = 1;
1733   packet.num_answers = 0;
1734   packet.num_authority_records = 0;
1735   packet.num_additional_records = 0;
1736   packet.flags = flags;
1737   packet.id = rh->id;
1738   if (GNUNET_OK != GNUNET_DNSPARSER_pack (&packet,
1739                                           UINT16_MAX,
1740                                           &rh->dns_raw_packet,
1741                                           &rh->dns_raw_packet_size))
1742   {
1743     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1744                 "GNS_PHASE_REC_DNS-%llu: Creating raw dns packet!\n",
1745                 rh->id);
1746     GNUNET_NETWORK_socket_close (rh->dns_sock);
1747     finish_lookup (rh, rlh, 0, NULL);
1748     free_resolver_handle (rh);
1749     return;
1750   }
1751
1752   rh->dns_addr.sin_family = AF_INET;
1753   rh->dns_addr.sin_port = htons (53); //domain
1754   rh->dns_addr.sin_addr = dnsip;
1755 #if HAVE_SOCKADDR_IN_SIN_LEN
1756   rh->dns_addr.sin_len = (u_char) sizeof (struct sockaddr_in);
1757 #endif
1758
1759   send_dns_packet (rh);
1760 }
1761
1762
1763 /**
1764  * The final phase of resoution.
1765  * We found a VPN RR and want to request an IPv4/6 address
1766  *
1767  * @param rh the pending lookup handle
1768  * @param rd_count length of record data
1769  * @param rd record data containing VPN RR
1770  */
1771 static void
1772 resolve_record_vpn (struct ResolverHandle *rh,
1773                     int rd_count,
1774                     const struct GNUNET_NAMESTORE_RecordData *rd)
1775 {
1776   int af;
1777   int proto;
1778   struct GNUNET_HashCode peer_id;
1779   struct GNUNET_CRYPTO_HashAsciiEncoded s_pid;
1780   struct GNUNET_HashCode serv_desc;
1781   struct GNUNET_CRYPTO_HashAsciiEncoded s_sd;
1782   char* pos;
1783   size_t len = (sizeof (uint32_t) * 2) + (sizeof (struct GNUNET_HashCode) * 2);
1784   
1785   /* We cancel here as to not include the ns lookup in the timeout */
1786   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1787   {
1788     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1789     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1790   }
1791   /* Start shortening */
1792   if ((rh->priv_key != NULL) && is_canonical (rh->name))
1793   {
1794     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1795              "GNS_PHASE_REC_VPN-%llu: Trying to shorten authority chain\n",
1796              rh->id);
1797     start_shorten (rh->authority_chain_tail,
1798                    rh->priv_key);
1799   }
1800
1801   /* Extracting VPN information FIXME rd parsing with NS API?*/
1802   if (len != rd->data_size)
1803   {
1804     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1805                 "GNS_PHASE_REC_VPN-%llu: Error parsing VPN RR!\n",
1806                 rh->id);
1807     finish_lookup (rh, rh->proc_cls, 0, NULL);
1808     free_resolver_handle (rh);
1809     return;
1810   }
1811
1812   pos = (char*)rd;
1813   memcpy (&af, pos, sizeof (uint32_t));
1814   pos += sizeof (uint32_t);
1815   memcpy (&proto, pos, sizeof (uint32_t));
1816   pos += sizeof (uint32_t);
1817   memcpy (&s_pid, pos, sizeof (struct GNUNET_HashCode));
1818   pos += sizeof (struct GNUNET_HashCode);
1819   memcpy (&s_sd, pos, sizeof (struct GNUNET_HashCode));
1820
1821
1822   if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char*)&s_pid, &peer_id)) ||
1823       (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char*)&s_sd, &serv_desc)))
1824   {
1825     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1826                 "GNS_PHASE_REC_VPN-%llu: Error parsing VPN RR hashes!\n",
1827                 rh->id);
1828     finish_lookup (rh, rh->proc_cls, 0, NULL);
1829     free_resolver_handle (rh);
1830     return;
1831   }
1832
1833   rh->proc = &handle_record_vpn;
1834
1835   if (NULL == vpn_handle)
1836   {
1837     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1838                 "GNS_PHASE_REC_VPN-%llu: VPN not connected!\n",
1839                 rh->id);
1840     finish_lookup (rh, rh->proc_cls, 0, NULL);
1841     free_resolver_handle (rh);
1842     return;
1843   }
1844   
1845   //FIXME timeout??
1846   rh->vpn_handle = GNUNET_VPN_redirect_to_peer (vpn_handle,
1847                                           af, proto,
1848                                           (struct GNUNET_PeerIdentity*)&peer_id,
1849                                           &serv_desc,
1850                                           GNUNET_NO, //nac
1851                                           GNUNET_TIME_UNIT_FOREVER_ABS, //FIXME
1852                                           &process_record_result_vpn,
1853                                           rh);
1854
1855 }
1856
1857 /**
1858  * The final phase of resolution.
1859  * rh->name is a name that is canonical and we do not have a delegation.
1860  * Query namestore for this record
1861  *
1862  * @param rh the pending lookup handle
1863  */
1864 static void
1865 resolve_record_ns(struct ResolverHandle *rh)
1866 {
1867   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
1868   
1869   /* We cancel here as to not include the ns lookup in the timeout */
1870   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1871   {
1872     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1873     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1874   }
1875   /* Start shortening */
1876   if ((rh->priv_key != NULL) && is_canonical (rh->name))
1877   {
1878     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1879              "GNS_PHASE_REC-%llu: Trying to shorten authority chain\n",
1880              rh->id);
1881     start_shorten (rh->authority_chain_tail,
1882                    rh->priv_key);
1883   }
1884   
1885   /**
1886    * Try to resolve this record in our namestore.
1887    * The name to resolve is now in rh->authority_name
1888    * since we tried to resolve it to an authority
1889    * and failed.
1890    **/
1891   GNUNET_NAMESTORE_lookup_record(namestore_handle,
1892                                  &rh->authority,
1893                                  rh->name,
1894                                  rlh->record_type,
1895                                  &process_record_result_ns,
1896                                  rh);
1897 }
1898
1899
1900
1901 /**
1902  * Handle timeout for DHT requests
1903  *
1904  * @param cls the request handle as closure
1905  * @param tc the task context
1906  */
1907 static void
1908 dht_authority_lookup_timeout(void *cls,
1909                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1910 {
1911   struct ResolverHandle *rh = cls;
1912   struct RecordLookupHandle *rlh = rh->proc_cls;
1913   char new_name[MAX_DNS_NAME_LENGTH];
1914
1915   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1916          "GNS_PHASE_DELEGATE_DHT-%llu: dht lookup for query %s (%ds)timed out.\n",
1917          rh->id, rh->authority_name, rh->timeout.rel_value);
1918
1919   rh->status |= RSL_TIMED_OUT;
1920
1921   rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1922   
1923   GNUNET_DHT_get_stop (rh->get_handle);
1924   rh->get_handle = NULL;
1925   
1926   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
1927   {
1928     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1929                "GNS_PHASE_DELEGATE_DHT-%llu: Got shutdown\n",
1930                rh->id);
1931     rh->proc(rh->proc_cls, rh, 0, NULL);
1932     return;
1933   }
1934
1935   if (strcmp(rh->name, "") == 0)
1936   {
1937     /*
1938      * promote authority back to name and try to resolve record
1939      */
1940     strcpy(rh->name, rh->authority_name);
1941     rh->proc(rh->proc_cls, rh, 0, NULL);
1942     return;
1943   }
1944   
1945   /**
1946    * Start resolution in bg
1947    */
1948   GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH,
1949                   "%s.%s.%s", rh->name, rh->authority_name, GNUNET_GNS_TLD);
1950   //strcpy(new_name, rh->name);
1951   //strcpy(new_name+strlen(new_name), ".");
1952   //memcpy(new_name+strlen(new_name), GNUNET_GNS_TLD, strlen(GNUNET_GNS_TLD));
1953   
1954   strcpy(rh->name, new_name);
1955
1956   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1957         "GNS_PHASE_DELEGATE_DHT-%llu: Starting background query for %s type %d\n",
1958         rh->id, rh->name, rlh->record_type);
1959
1960   gns_resolver_lookup_record(rh->authority,
1961                              rh->private_local_zone,
1962                              rlh->record_type,
1963                              new_name,
1964                              rh->priv_key,
1965                              GNUNET_TIME_UNIT_FOREVER_REL,
1966                              GNUNET_NO,
1967                              &background_lookup_result_processor,
1968                              NULL);
1969
1970   rh->proc(rh->proc_cls, rh, 0, NULL);
1971 }
1972
1973 /* Prototype */
1974 static void resolve_delegation_dht(struct ResolverHandle *rh);
1975
1976 /* Prototype */
1977 static void resolve_delegation_ns(struct ResolverHandle *rh);
1978
1979
1980 /**
1981  * Namestore resolution for delegation finished. Processing result.
1982  *
1983  * @param cls the closure
1984  * @param rh resolver handle
1985  * @param rd_count number of results (always 0)
1986  * @param rd record data (always NULL)
1987  */
1988 static void
1989 handle_delegation_ns(void* cls, struct ResolverHandle *rh,
1990                           unsigned int rd_count,
1991                           const struct GNUNET_NAMESTORE_RecordData *rd);
1992
1993
1994 /**
1995  * This is a callback function that checks for key revocation
1996  *
1997  * @param cls the pending query
1998  * @param key the key of the zone we did the lookup
1999  * @param expiration expiration date of the record data set in the namestore
2000  * @param name the name for which we need an authority
2001  * @param rd_count the number of records with 'name'
2002  * @param rd the record data
2003  * @param signature the signature of the authority for the record data
2004  */
2005 static void
2006 process_pkey_revocation_result_ns (void *cls,
2007                     const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
2008                     struct GNUNET_TIME_Absolute expiration,
2009                     const char *name,
2010                     unsigned int rd_count,
2011                     const struct GNUNET_NAMESTORE_RecordData *rd,
2012                     const struct GNUNET_CRYPTO_RsaSignature *signature)
2013 {
2014   struct ResolverHandle *rh = cls;
2015   struct GNUNET_TIME_Relative remaining_time;
2016   int i;
2017   
2018   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
2019   
2020   for (i = 0; i < rd_count; i++)
2021   {
2022     if (rd[i].record_type == GNUNET_GNS_RECORD_REV)
2023     {
2024       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2025                  "GNS_PHASE_DELEGATE_REV-%llu: Zone has been revoked.\n",
2026                  rh->id);
2027       rh->status |= RSL_PKEY_REVOKED;
2028       rh->proc (rh->proc_cls, rh, 0, NULL);
2029       return;
2030     }
2031   }
2032   
2033   if ((name == NULL) ||
2034       (remaining_time.rel_value == 0))
2035   {
2036     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2037           "GNS_PHASE_DELEGATE_REV-%llu: + Records don't exist or are expired.\n",
2038           rh->id, name);
2039
2040     if (rh->timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
2041     {
2042       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2043         "GNS_PHASE_DELEGATE_REV-%d: Starting background lookup for %s type %d\n",
2044         rh->id, "+.gnunet", GNUNET_GNS_RECORD_REV);
2045
2046       gns_resolver_lookup_record(rh->authority,
2047                                  rh->private_local_zone,
2048                                  GNUNET_GNS_RECORD_REV,
2049                                  GNUNET_GNS_TLD,
2050                                  rh->priv_key,
2051                                  GNUNET_TIME_UNIT_FOREVER_REL,
2052                                  GNUNET_NO,
2053                                  &background_lookup_result_processor,
2054                                  NULL);
2055     }
2056   }
2057  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2058              "GNS_PHASE_DELEGATE_REV-%llu: Revocation checkpassed\n",
2059              rh->id);
2060   /**
2061    * We are done with PKEY resolution if name is empty
2062    * else resolve again with new authority
2063    */
2064   if (strcmp (rh->name, "") == 0)
2065     rh->proc (rh->proc_cls, rh, 0, NULL);
2066   else
2067     resolve_delegation_ns (rh);
2068   return;
2069 }
2070
2071
2072 /**
2073  * Function called when we get a result from the dht
2074  * for our query. Recursively tries to resolve authorities
2075  * for name in DHT.
2076  *
2077  * @param cls the request handle
2078  * @param exp lifetime
2079  * @param key the key the record was stored under
2080  * @param get_path get path
2081  * @param get_path_length get path length
2082  * @param put_path put path
2083  * @param put_path_length put path length
2084  * @param type the block type
2085  * @param size the size of the record
2086  * @param data the record data
2087  */
2088 static void
2089 process_delegation_result_dht(void* cls,
2090                  struct GNUNET_TIME_Absolute exp,
2091                  const struct GNUNET_HashCode * key,
2092                  const struct GNUNET_PeerIdentity *get_path,
2093                  unsigned int get_path_length,
2094                  const struct GNUNET_PeerIdentity *put_path,
2095                  unsigned int put_path_length,
2096                  enum GNUNET_BLOCK_Type type,
2097                  size_t size, const void *data)
2098 {
2099   struct ResolverHandle *rh;
2100   struct GNSNameRecordBlock *nrb;
2101   uint32_t num_records;
2102   char* name = NULL;
2103   char* rd_data = (char*) data;
2104   int i;
2105   int rd_size;
2106   struct GNUNET_CRYPTO_ShortHashCode zone, name_hash;
2107   struct GNUNET_HashCode zone_hash_double, name_hash_double;
2108
2109   rh = (struct ResolverHandle *)cls;
2110   
2111   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2112              "GNS_PHASE_DELEGATE_DHT-%llu: Got DHT result\n", rh->id);
2113
2114   if (data == NULL)
2115     return;
2116   
2117   nrb = (struct GNSNameRecordBlock*)data;
2118   
2119   /* stop dht lookup and timeout task */
2120   GNUNET_DHT_get_stop (rh->get_handle);
2121
2122   rh->get_handle = NULL;
2123
2124   if (rh->dht_heap_node != NULL)
2125   {
2126     GNUNET_CONTAINER_heap_remove_node(rh->dht_heap_node);
2127     rh->dht_heap_node = NULL;
2128   }
2129
2130   num_records = ntohl(nrb->rd_count);
2131   name = (char*)&nrb[1];
2132   {
2133     struct GNUNET_NAMESTORE_RecordData rd[num_records];
2134     
2135     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
2136     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
2137   
2138     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
2139                                                                rd_data,
2140                                                                num_records,
2141                                                                rd))
2142     {
2143       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2144                  "GNS_PHASE_DELEGATE_DHT-%llu: Error deserializing data!\n",
2145                  rh->id);
2146       return;
2147     }
2148
2149     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2150                "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2151                rh->id, name, rh->authority_name);
2152     for (i=0; i<num_records; i++)
2153     {
2154     
2155       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2156                 "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2157                 rh->id, name, rh->authority_name);
2158       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2159                  "GNS_PHASE_DELEGATE_DHT-%llu: Got type: %d (wanted %d)\n",
2160                  rh->id, rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
2161       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2162                  "GNS_PHASE_DELEGATE_DHT-%llu: Got data length: %d\n",
2163                  rh->id, rd[i].data_size);
2164       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2165                  "GNS_PHASE_DELEGATE_DHT-%llu: Got flag %d\n",
2166                  rh->id, rd[i].flags);
2167       
2168       if ((rd[i].record_type == GNUNET_GNS_RECORD_VPN) ||
2169           (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_NS) ||
2170           (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_CNAME))
2171       {
2172         /**
2173          * This is a VPN,NS,CNAME entry. Let namestore handle this after caching
2174          */
2175         if (strcmp(rh->name, "") == 0)
2176           strcpy(rh->name, rh->authority_name);
2177         else
2178           GNUNET_snprintf(rh->name, MAX_DNS_NAME_LENGTH, "%s.%s",
2179                  rh->name, rh->authority_name); //FIXME ret
2180         rh->answered = 1;
2181         break;
2182       }
2183
2184       if ((strcmp(name, rh->authority_name) == 0) &&
2185           (rd[i].record_type == GNUNET_GNS_RECORD_PKEY))
2186       {
2187         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2188                    "GNS_PHASE_DELEGATE_DHT-%llu: Authority found in DHT\n",
2189                    rh->id);
2190         rh->answered = 1;
2191         memcpy(&rh->authority, rd[i].data, sizeof(struct GNUNET_CRYPTO_ShortHashCode));
2192         struct AuthorityChain *auth =
2193           GNUNET_malloc(sizeof(struct AuthorityChain));
2194         auth->zone = rh->authority;
2195         memset(auth->name, 0, strlen(rh->authority_name)+1);
2196         strcpy(auth->name, rh->authority_name);
2197         GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
2198                                      rh->authority_chain_tail,
2199                                      auth);
2200
2201         /** try to import pkey if private key available */
2202         //if (rh->priv_key && is_canonical (rh->name))
2203         //  process_discovered_authority(name, auth->zone,
2204         //                               rh->authority_chain_tail->zone,
2205         //                               rh->priv_key);
2206       }
2207
2208     }
2209
2210
2211     GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
2212     GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2213     GNUNET_CRYPTO_hash_xor(key, &name_hash_double, &zone_hash_double);
2214     GNUNET_CRYPTO_short_hash_from_truncation (&zone_hash_double, &zone);
2215
2216     /* Save to namestore */
2217     if (0 != GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_tail->zone,
2218                                           &zone))
2219     {
2220       GNUNET_NAMESTORE_record_put (namestore_handle,
2221                                  &nrb->public_key,
2222                                  name,
2223                                  exp,
2224                                  num_records,
2225                                  rd,
2226                                  &nrb->signature,
2227                                  &on_namestore_record_put_result, //cont
2228                                  NULL); //cls
2229     }
2230   }
2231   
2232   if (rh->answered)
2233   {
2234     rh->answered = 0;
2235     /**
2236      * delegate
2237      * FIXME in this case. should we ask namestore again?
2238      */
2239     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2240       "GNS_PHASE_DELEGATE_DHT-%llu: Answer from DHT for %s. Yet to resolve: %s\n",
2241       rh->id, rh->authority_name, rh->name);
2242
2243     if (strcmp(rh->name, "") == 0)
2244     {
2245       /* Start shortening */
2246       if ((rh->priv_key != NULL) && is_canonical (rh->name))
2247       {
2248         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2249              "GNS_PHASE_DELEGATE_DHT-%llu: Trying to shorten authority chain\n",
2250              rh->id);
2251         start_shorten (rh->authority_chain_tail,
2252                        rh->priv_key);
2253       }
2254     }
2255     else
2256       rh->proc = &handle_delegation_ns;
2257
2258     /* Check for key revocation and delegate */
2259     GNUNET_NAMESTORE_lookup_record (namestore_handle,
2260                                     &rh->authority,
2261                                     "+",
2262                                     GNUNET_GNS_RECORD_REV,
2263                                     &process_pkey_revocation_result_ns,
2264                                     rh);   
2265     
2266     /*if (strcmp(rh->name, "") == 0)
2267     {
2268       if ((rh->priv_key != NULL) && is_canonical (rh->name))
2269       {
2270         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2271              "GNS_PHASE_DELEGATE_DHT-%llu: Trying to shorten authority chain\n",
2272              rh->id);
2273         start_shorten (rh->authority_chain_tail,
2274                        rh->priv_key);
2275       }
2276       
2277       rh->proc(rh->proc_cls, rh, 0, NULL);
2278     }
2279     else
2280     {
2281       rh->proc = &handle_delegation_ns;
2282       resolve_delegation_ns (rh);
2283     }
2284     */
2285     return;
2286   }
2287   
2288   /**
2289    * No pkey but name exists
2290    * promote back
2291    */
2292   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2293              "GNS_PHASE_DELEGATE_DHT-%llu: Adding %s back to %s\n",
2294              rh->id, rh->authority_name, rh->name);
2295   if (strcmp(rh->name, "") == 0)
2296     strcpy(rh->name, rh->authority_name);
2297   else
2298     GNUNET_snprintf(rh->name, MAX_DNS_NAME_LENGTH, "%s.%s",
2299                   rh->name, rh->authority_name); //FIXME ret
2300   
2301   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2302              "GNS_PHASE_DELEGATE_DHT-%llu: %s restored\n", rh->id, rh->name);
2303   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2304            "GNS_PHASE_DELEGATE_DHT-%llu: DHT authority lookup found no match!\n",
2305            rh->id);
2306   rh->proc(rh->proc_cls, rh, 0, NULL);
2307 }
2308
2309 #define MAX_SOA_LENGTH sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)\
2310                         +(MAX_DNS_NAME_LENGTH*2)
2311 #define MAX_MX_LENGTH sizeof(uint16_t)+MAX_DNS_NAME_LENGTH
2312
2313
2314 static void
2315 expand_plus(char** dest, char* src, char* repl)
2316 {
2317   char* pos;
2318   unsigned int s_len = strlen(src)+1;
2319
2320   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2321              "GNS_POSTPROCESS: Got %s to expand with %s\n", src, repl);
2322
2323   if (s_len < 3)
2324   {
2325     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2326                "GNS_POSTPROCESS: %s to short\n", src);
2327
2328     /* no postprocessing */
2329     memcpy(*dest, src, s_len+1);
2330     return;
2331   }
2332   
2333   if (0 == strcmp(src+s_len-3, ".+"))
2334   {
2335     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2336                "GNS_POSTPROCESS: Expanding .+ in %s\n", src);
2337     memset(*dest, 0, s_len+strlen(repl)+strlen(GNUNET_GNS_TLD));
2338     strcpy(*dest, src);
2339     pos = *dest+s_len-2;
2340     strcpy(pos, repl);
2341     pos += strlen(repl);
2342     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2343                "GNS_POSTPROCESS: Expanded to %s\n", *dest);
2344   }
2345   else
2346   {
2347     memcpy(*dest, src, s_len+1);
2348   }
2349 }
2350
2351 /**
2352  * finish lookup
2353  */
2354 static void
2355 finish_lookup(struct ResolverHandle *rh,
2356               struct RecordLookupHandle* rlh,
2357               unsigned int rd_count,
2358               const struct GNUNET_NAMESTORE_RecordData *rd)
2359 {
2360   int i;
2361   char new_rr_data[MAX_DNS_NAME_LENGTH];
2362   char new_mx_data[MAX_MX_LENGTH];
2363   char new_soa_data[MAX_SOA_LENGTH];
2364   struct GNUNET_NAMESTORE_RecordData p_rd[rd_count];
2365   char* repl_string;
2366   char* pos;
2367   unsigned int offset;
2368
2369   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2370   {
2371     GNUNET_SCHEDULER_cancel(rh->timeout_task);
2372     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2373   }
2374
2375   if (rd_count > 0)
2376     memcpy(p_rd, rd, rd_count*sizeof(struct GNUNET_NAMESTORE_RecordData));
2377
2378   for (i = 0; i < rd_count; i++)
2379   {
2380     
2381     if (rd[i].record_type != GNUNET_GNS_RECORD_TYPE_NS &&
2382         rd[i].record_type != GNUNET_GNS_RECORD_TYPE_CNAME &&
2383         rd[i].record_type != GNUNET_GNS_RECORD_MX &&
2384         rd[i].record_type != GNUNET_GNS_RECORD_TYPE_SOA)
2385     {
2386       p_rd[i].data = rd[i].data;
2387       continue;
2388     }
2389
2390     /**
2391      * for all those records we 'should'
2392      * also try to resolve the A/AAAA records (RFC1035)
2393      * This is a feature and not important
2394      */
2395     
2396     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2397                "GNS_POSTPROCESS: Postprocessing\n");
2398
2399     if (strcmp(rh->name, "+") == 0)
2400       repl_string = rlh->name;
2401     else
2402       repl_string = rlh->name+strlen(rh->name)+1;
2403
2404     offset = 0;
2405     if (rd[i].record_type == GNUNET_GNS_RECORD_MX)
2406     {
2407       memcpy(new_mx_data, (char*)rd[i].data, sizeof(uint16_t));
2408       offset = sizeof(uint16_t);
2409       pos = new_mx_data+offset;
2410       expand_plus(&pos, (char*)rd[i].data+sizeof(uint16_t),
2411                   repl_string);
2412       offset += strlen(new_mx_data+sizeof(uint16_t))+1;
2413       p_rd[i].data = new_mx_data;
2414       p_rd[i].data_size = offset;
2415     }
2416     else if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_SOA)
2417     {
2418       /* expand mname and rname */
2419       pos = new_soa_data;
2420       expand_plus(&pos, (char*)rd[i].data, repl_string);
2421       offset = strlen(new_soa_data)+1;
2422       pos = new_soa_data+offset;
2423       expand_plus(&pos, (char*)rd[i].data+offset, repl_string);
2424       offset += strlen(new_soa_data+offset)+1;
2425       /* cpy the 4 numbers serial refresh retry and expire */
2426       memcpy(new_soa_data+offset, (char*)rd[i].data+offset, sizeof(uint32_t)*5);
2427       offset += sizeof(uint32_t)*5;
2428       p_rd[i].data_size = offset;
2429       p_rd[i].data = new_soa_data;
2430     }
2431     else
2432     {
2433       pos = new_rr_data;
2434       expand_plus(&pos, (char*)rd[i].data, repl_string);
2435       p_rd[i].data_size = strlen(new_rr_data)+1;
2436       p_rd[i].data = new_rr_data;
2437     }
2438     
2439   }
2440
2441   rlh->proc(rlh->proc_cls, rd_count, p_rd);
2442   GNUNET_free(rlh);
2443   
2444 }
2445
2446 /**
2447  * Process DHT lookup result for record.
2448  *
2449  * @param cls the closure
2450  * @param rh resolver handle
2451  * @param rd_count number of results
2452  * @param rd record data
2453  */
2454 static void
2455 handle_record_dht(void* cls, struct ResolverHandle *rh,
2456                        unsigned int rd_count,
2457                        const struct GNUNET_NAMESTORE_RecordData *rd)
2458 {
2459   struct RecordLookupHandle* rlh;
2460
2461   rlh = (struct RecordLookupHandle*)cls;
2462   if (rd_count == 0)
2463   {
2464     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2465                "GNS_PHASE_REC-%d: No records for %s found in DHT. Aborting\n",
2466                rh->id, rh->name);
2467     /* give up, cannot resolve */
2468     finish_lookup(rh, rlh, 0, NULL);
2469     free_resolver_handle(rh);
2470     return;
2471   }
2472
2473   /* results found yay */
2474   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2475              "GNS_PHASE_REC-%d: Record resolved from DHT!", rh->id);
2476
2477   finish_lookup(rh, rlh, rd_count, rd);
2478   free_resolver_handle(rh);
2479
2480 }
2481
2482
2483
2484
2485 /**
2486  * Process namestore lookup result for record.
2487  *
2488  * @param cls the closure
2489  * @param rh resolver handle
2490  * @param rd_count number of results
2491  * @param rd record data
2492  */
2493 static void
2494 handle_record_ns (void* cls, struct ResolverHandle *rh,
2495                   unsigned int rd_count,
2496                   const struct GNUNET_NAMESTORE_RecordData *rd)
2497 {
2498   struct RecordLookupHandle* rlh;
2499   rlh = (struct RecordLookupHandle*) cls;
2500   if (rd_count == 0)
2501   {
2502     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2503                "GNS_PHASE_REC-%d: NS returned no records. (status: %d)!\n",
2504                rh->id,
2505                rh->status);
2506     
2507     /**
2508      * There are 5 conditions that have to met for us to consult the DHT:
2509      * 1. The entry in the DHT is RSL_RECORD_EXPIRED OR
2510      * 2. No entry in the NS existed AND
2511      * 3. The zone queried is not the local resolver's zone AND
2512      * 4. The name that was looked up is '+'
2513      *    because if it was any other canonical name we either already queried
2514      *    the DHT for the authority in the authority lookup phase (and thus
2515      *    would already have an entry in the NS for the record)
2516      * 5. We are not in cache only mode
2517      */
2518     if (((rh->status & RSL_RECORD_EXPIRED) || (rh->status &!RSL_RECORD_EXISTS))
2519         && GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
2520                                         &rh->private_local_zone) &&
2521         (strcmp(rh->name, "+") == 0) &&
2522         (rh->only_cached == GNUNET_NO))
2523     {
2524       rh->proc = &handle_record_dht;
2525       resolve_record_dht(rh);
2526       return;
2527     }
2528     /* give up, cannot resolve */
2529     finish_lookup(rh, rlh, 0, NULL);
2530     free_resolver_handle(rh);
2531     return;
2532   }
2533
2534   /* results found yay */
2535   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2536              "GNS_PHASE_REC-%d: Record resolved from namestore!", rh->id);
2537
2538   finish_lookup(rh, rlh, rd_count, rd);
2539
2540   free_resolver_handle(rh);
2541
2542 }
2543
2544
2545 /**
2546  * Move one level up in the domain hierarchy and return the
2547  * passed top level domain.
2548  *
2549  * @param name the domain
2550  * @param dest the destination where the tld will be put
2551  */
2552 void
2553 pop_tld(char* name, char* dest)
2554 {
2555   uint32_t len;
2556
2557   if (is_canonical(name))
2558   {
2559     strcpy(dest, name);
2560     strcpy(name, "");
2561     return;
2562   }
2563
2564   for (len = strlen(name); len > 0; len--)
2565   {
2566     if (*(name+len) == '.')
2567       break;
2568   }
2569   
2570   //Was canonical?
2571   if (len == 0)
2572     return;
2573
2574   name[len] = '\0';
2575
2576   strcpy(dest, (name+len+1));
2577 }
2578
2579 /**
2580  * Checks if name is in tld
2581  *
2582  * @param name the name to check
2583  * @param tld the TLD to check for
2584  * @return GNUNET_YES or GNUNET_NO
2585  */
2586 int
2587 is_tld(const char* name, const char* tld)
2588 {
2589   int offset = 0;
2590
2591   if (strlen(name) <= strlen(tld))
2592   {
2593     return GNUNET_NO;
2594   }
2595   
2596   offset = strlen(name)-strlen(tld);
2597   if (strcmp(name+offset, tld) != 0)
2598   {
2599     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2600                "%s is not in .%s TLD\n", name, tld);
2601     return GNUNET_NO;
2602   }
2603   return GNUNET_YES;
2604 }
2605
2606 /**
2607  * DHT resolution for delegation finished. Processing result.
2608  *
2609  * @param cls the closure
2610  * @param rh resolver handle
2611  * @param rd_count number of results (always 0)
2612  * @param rd record data (always NULL)
2613  */
2614 static void
2615 handle_delegation_dht(void* cls, struct ResolverHandle *rh,
2616                           unsigned int rd_count,
2617                           const struct GNUNET_NAMESTORE_RecordData *rd)
2618 {
2619   struct RecordLookupHandle* rlh;
2620   rlh = (struct RecordLookupHandle*) cls;
2621   
2622
2623   if (strcmp(rh->name, "") == 0)
2624   {
2625     if ((rlh->record_type == GNUNET_GNS_RECORD_PKEY))
2626     {
2627       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2628                  "GNS_PHASE_DELEGATE_DHT-%llu: Resolved queried PKEY via DHT.\n",
2629                  rh->id);
2630       finish_lookup(rh, rlh, rd_count, rd);
2631       free_resolver_handle(rh);
2632       return;
2633     }
2634     /* We resolved full name for delegation. resolving record */
2635     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2636      "GNS_PHASE_DELEGATE_DHT-%llu: Resolved full name for delegation via DHT.\n",
2637      rh->id);
2638     strcpy(rh->name, "+\0");
2639     rh->proc = &handle_record_ns;
2640     resolve_record_ns(rh);
2641     return;
2642   }
2643
2644   /**
2645    * we still have some left
2646    **/
2647   if (is_canonical(rh->name))
2648   {
2649     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2650              "GNS_PHASE_DELEGATE_DHT-%llu: Resolving canonical record %s in ns\n",
2651              rh->id,
2652              rh->name);
2653     rh->proc = &handle_record_ns;
2654     resolve_record_ns(rh);
2655     return;
2656   }
2657   /* give up, cannot resolve */
2658   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2659  "GNS_PHASE_DELEGATE_DHT-%llu: Cannot fully resolve delegation for %s via DHT!\n",
2660  rh->id, rh->name);
2661   finish_lookup(rh, rlh, 0, NULL);
2662   free_resolver_handle(rh);
2663 }
2664
2665
2666 /**
2667  * Start DHT lookup for a name -> PKEY (compare NS) record in
2668  * rh->authority's zone
2669  *
2670  * @param rh the pending gns query
2671  */
2672 static void
2673 resolve_delegation_dht(struct ResolverHandle *rh)
2674 {
2675   uint32_t xquery;
2676   struct GNUNET_CRYPTO_ShortHashCode name_hash;
2677   struct GNUNET_HashCode name_hash_double;
2678   struct GNUNET_HashCode zone_hash_double;
2679   struct GNUNET_HashCode lookup_key;
2680   struct ResolverHandle *rh_heap_root;
2681   
2682   pop_tld(rh->name, rh->authority_name); 
2683   GNUNET_CRYPTO_short_hash(rh->authority_name,
2684                      strlen(rh->authority_name),
2685                      &name_hash);
2686   GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2687   GNUNET_CRYPTO_short_hash_double(&rh->authority, &zone_hash_double);
2688   GNUNET_CRYPTO_hash_xor(&name_hash_double, &zone_hash_double, &lookup_key);
2689   
2690   rh->dht_heap_node = NULL;
2691
2692   if (rh->timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
2693   {
2694     //rh->timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
2695     //                                          &dht_authority_lookup_timeout,
2696     //                                                   rh);
2697     rh->timeout_cont = &dht_authority_lookup_timeout;
2698     rh->timeout_cont_cls = rh;
2699   }
2700   else 
2701   {
2702     if (max_allowed_background_queries <=
2703         GNUNET_CONTAINER_heap_get_size (dht_lookup_heap))
2704     {
2705       /* terminate oldest lookup */
2706       rh_heap_root = GNUNET_CONTAINER_heap_remove_root (dht_lookup_heap);
2707       GNUNET_DHT_get_stop(rh_heap_root->get_handle);
2708       rh_heap_root->dht_heap_node = NULL;
2709       
2710       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2711         "GNS_PHASE_DELEGATE_DHT-%llu: Replacing oldest background query for %s\n",
2712         rh->id, rh_heap_root->authority_name);
2713       
2714       rh_heap_root->proc(rh_heap_root->proc_cls,
2715                          rh_heap_root,
2716                          0,
2717                          NULL);
2718     }
2719     rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap,
2720                                          rh,
2721                                          GNUNET_TIME_absolute_get().abs_value);
2722   }
2723   
2724   xquery = htonl(GNUNET_GNS_RECORD_PKEY);
2725   
2726   GNUNET_assert(rh->get_handle == NULL);
2727   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
2728                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
2729                        &lookup_key,
2730                        DHT_GNS_REPLICATION_LEVEL,
2731                        GNUNET_DHT_RO_NONE,
2732                        &xquery,
2733                        sizeof(xquery),
2734                        &process_delegation_result_dht,
2735                        rh);
2736
2737 }
2738
2739
2740 /**
2741  * Namestore resolution for delegation finished. Processing result.
2742  *
2743  * @param cls the closure
2744  * @param rh resolver handle
2745  * @param rd_count number of results (always 0)
2746  * @param rd record data (always NULL)
2747  */
2748 static void
2749 handle_delegation_ns (void* cls, struct ResolverHandle *rh,
2750                       unsigned int rd_count,
2751                       const struct GNUNET_NAMESTORE_RecordData *rd)
2752 {
2753   struct RecordLookupHandle* rlh;
2754   rlh = (struct RecordLookupHandle*) cls;
2755
2756   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2757              "GNS_PHASE_DELEGATE_NS-%llu: Resolution status: %d.\n",
2758              rh->id, rh->status);
2759
2760   if (rh->status & RSL_PKEY_REVOKED)
2761   {
2762     finish_lookup (rh, rlh, 0, NULL);
2763     free_resolver_handle (rh);
2764     return;
2765   }
2766   
2767   if (strcmp(rh->name, "") == 0)
2768   {
2769     
2770     /* We resolved full name for delegation. resolving record */
2771     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2772               "GNS_PHASE_DELEGATE_NS-%llu: Resolved full name for delegation.\n",
2773               rh->id);
2774     if (rh->status & RSL_CNAME_FOUND)
2775     {
2776       if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_CNAME)
2777       {
2778         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2779                   "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried CNAME in NS.\n",
2780                   rh->id);
2781         finish_lookup(rh, rlh, rd_count, rd);
2782         free_resolver_handle(rh);
2783         return;
2784       }
2785       
2786       /* A CNAME can only occur alone */
2787       GNUNET_assert (is_canonical ((char*)rd->data));
2788       strcpy (rh->name, rd->data);
2789       resolve_delegation_ns (rh);
2790       return;
2791     }
2792     else if (rh->status & RSL_DELEGATE_VPN)
2793     {
2794       if (rlh->record_type == GNUNET_GNS_RECORD_VPN)
2795       {
2796         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2797                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried VPNRR in NS.\n",
2798                  rh->id);
2799         finish_lookup(rh, rlh, rd_count, rd);
2800         free_resolver_handle(rh);
2801         return;
2802       }
2803       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2804              "GNS_PHASE_DELEGATE_NS-%llu: VPN delegation starting.\n",
2805              rh->id);
2806       GNUNET_assert (NULL != rd);
2807       rh->proc = &handle_record_vpn;
2808       resolve_record_vpn (rh, rd_count, rd);
2809       return;
2810     }
2811     else if (rh->status & RSL_DELEGATE_NS)
2812     {
2813       if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_NS)
2814       {
2815         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2816                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried NSRR in NS.\n",
2817                    rh->id);
2818         finish_lookup(rh, rlh, rd_count, rd);
2819         free_resolver_handle(rh);
2820         return;
2821       }
2822       
2823       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2824                  "GNS_PHASE_DELEGATE_NS-%llu: NS delegation starting.\n",
2825                  rh->id);
2826       GNUNET_assert (NULL != rd);
2827       rh->proc = &handle_record_ns;
2828       resolve_record_dns (rh, rd_count, rd);
2829       return;
2830     }
2831     else if (rh->status & RSL_DELEGATE_PKEY)
2832     {
2833       if (rh->status & RSL_PKEY_REVOKED)
2834       {
2835         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2836                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved PKEY is revoked.\n",
2837                    rh->id);
2838         finish_lookup (rh, rlh, 0, NULL);
2839         free_resolver_handle (rh);
2840         return;
2841       }
2842       else if (rlh->record_type == GNUNET_GNS_RECORD_PKEY)
2843       {
2844         GNUNET_assert(rd_count == 1);
2845         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2846                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried PKEY in NS.\n",
2847                    rh->id);
2848         finish_lookup(rh, rlh, rd_count, rd);
2849         free_resolver_handle(rh);
2850         return;
2851       }
2852     }
2853     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2854                "GNS_PHASE_DELEGATE_NS-%llu: Resolving record +\n",
2855                rh->id);
2856     strcpy(rh->name, "+\0");
2857     rh->proc = &handle_record_ns;
2858     resolve_record_ns(rh);
2859     return;
2860   }
2861   
2862   if (rh->status & RSL_DELEGATE_NS)
2863   {
2864     if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_NS)
2865     {
2866       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2867                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried NSRR in NS.\n",
2868                  rh->id);
2869       finish_lookup(rh, rlh, rd_count, rd);
2870       free_resolver_handle(rh);
2871       return;
2872     }
2873     
2874     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2875                "GNS_PHASE_DELEGATE_NS-%llu: NS delegation starting.\n",
2876                rh->id);
2877     GNUNET_assert (NULL != rd);
2878     rh->proc = &handle_record_ns;
2879     resolve_record_dns (rh, rd_count, rd);
2880     return;
2881   }
2882   
2883   /**
2884    * we still have some left
2885    * check if authority in ns is fresh
2886    * and exists
2887    * or we are authority
2888    **/
2889   if (((rh->status & RSL_RECORD_EXISTS) && (!(rh->status & RSL_RECORD_EXPIRED)))
2890       || !GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
2891                                        &rh->private_local_zone))
2892   {
2893     if (is_canonical(rh->name))
2894     {
2895       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2896                  "GNS_PHASE_DELEGATE_NS-%llu: Resolving canonical record %s\n",
2897                  rh->id,
2898                  rh->name);
2899       rh->proc = &handle_record_ns;
2900       resolve_record_ns(rh);
2901     }
2902     else
2903     {
2904       /* give up, cannot resolve */
2905       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2906           "GNS_PHASE_DELEGATE_NS-%llu: Cannot fully resolve delegation for %s!\n",
2907           rh->id,
2908           rh->name);
2909       finish_lookup(rh, rlh, rd_count, rd);
2910       //rlh->proc(rlh->proc_cls, 0, NULL);
2911     }
2912     return;
2913   }
2914
2915   if (rh->only_cached == GNUNET_YES)
2916   {
2917     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2918                "GNS_PHASE_DELEGATE_NS-%llu: Only cache resolution, no result\n",
2919                rh->id, rh->name);
2920     finish_lookup(rh, rlh, rd_count, rd);
2921     return;
2922   }
2923   
2924   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2925       "GNS_PHASE_DELEGATE_NS-%llu: Trying to resolve delegation for %s via DHT\n",
2926       rh->id, rh->name);
2927   rh->proc = &handle_delegation_dht;
2928   resolve_delegation_dht(rh);
2929 }
2930
2931
2932 /**
2933  * This is a callback function that should give us only PKEY
2934  * records. Used to query the namestore for the authority (PKEY)
2935  * for 'name'. It will recursively try to resolve the
2936  * authority for a given name from the namestore.
2937  *
2938  * @param cls the pending query
2939  * @param key the key of the zone we did the lookup
2940  * @param expiration expiration date of the record data set in the namestore
2941  * @param name the name for which we need an authority
2942  * @param rd_count the number of records with 'name'
2943  * @param rd the record data
2944  * @param signature the signature of the authority for the record data
2945  */
2946 static void
2947 process_delegation_result_ns (void* cls,
2948                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
2949                    struct GNUNET_TIME_Absolute expiration,
2950                    const char *name,
2951                    unsigned int rd_count,
2952                    const struct GNUNET_NAMESTORE_RecordData *rd,
2953                    const struct GNUNET_CRYPTO_RsaSignature *signature)
2954 {
2955   struct ResolverHandle *rh;
2956   struct GNUNET_TIME_Relative remaining_time;
2957   struct GNUNET_CRYPTO_ShortHashCode zone;
2958   char new_name[MAX_DNS_NAME_LENGTH];
2959  
2960   rh = (struct ResolverHandle *)cls; 
2961   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2962              "GNS_PHASE_DELEGATE_NS-%llu: Got %d records from authority lookup\n",
2963              rh->id, rd_count);
2964
2965   GNUNET_CRYPTO_short_hash(key,
2966                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2967                      &zone);
2968   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
2969   
2970   rh->status = 0;
2971   
2972   if (name != NULL)
2973   {
2974     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2975                "GNS_PHASE_DELEGATE_NS-%llu: Records with name %s exist.\n",
2976                rh->id, name);
2977     rh->status |= RSL_RECORD_EXISTS;
2978   
2979     if (remaining_time.rel_value == 0)
2980     {
2981       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2982                  "GNS_PHASE_DELEGATE_NS-%llu: Record set %s expired.\n",
2983                  rh->id, name);
2984       rh->status |= RSL_RECORD_EXPIRED;
2985     }
2986   }
2987   
2988   /**
2989    * No authority found in namestore.
2990    */
2991   if (rd_count == 0)
2992   {
2993     /**
2994      * We did not find an authority in the namestore
2995      */
2996     
2997     /**
2998      * No PKEY in zone.
2999      * Promote this authority back to a name maybe it is
3000      * our record.
3001      */
3002     if (strcmp(rh->name, "") == 0)
3003     {
3004       /* simply promote back */
3005       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3006                  "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
3007                  rh->id, rh->authority_name);
3008       strcpy(rh->name, rh->authority_name);
3009     }
3010     else
3011     {
3012       /* add back to existing name */
3013       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3014                  "GNS_PHASE_DELEGATE_NS-%llu: Adding %s back to %s\n",
3015                  rh->id, rh->authority_name, rh->name);
3016       //memset(new_name, 0, strlen(rh->name) + strlen(rh->authority_name) + 2);
3017       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
3018                       rh->name, rh->authority_name);
3019       //strcpy(new_name, rh->name);
3020       //strcpy(new_name+strlen(new_name), ".");
3021       //strcpy(new_name+strlen(new_name), rh->authority_name);
3022       strcpy(rh->name, new_name);
3023       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3024                  "GNS_PHASE_DELEGATE_NS-%llu: %s restored\n", rh->id, rh->name);
3025     }
3026     rh->proc(rh->proc_cls, rh, 0, NULL);
3027     return;
3028   }
3029
3030   /**
3031    * We found an authority that may be able to help us
3032    * move on with query
3033    * Note only 1 pkey should have been returned.. anything else would be strange
3034    */
3035   int i;
3036   for (i=0; i<rd_count;i++)
3037   {
3038     
3039     /**
3040      * A CNAME. Like regular DNS this means the is no other record for this
3041      * name.
3042      */
3043     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_CNAME)
3044     {
3045       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3046                  "GNS_PHASE_DELEGATE_NS-%llu: CNAME found.\n",
3047                  rh->id);
3048       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3049                  "GNS_PHASE_DELEGATE_NS-%llu: new name to resolve: %s.\n",
3050                  rh->id, rh->name);
3051
3052       rh->status |= RSL_CNAME_FOUND;
3053       rh->proc (rh->proc_cls, rh, rd_count, rd);
3054       return;
3055     }
3056
3057     /**
3058      * Redirect via VPN
3059      */
3060     if (rd[i].record_type == GNUNET_GNS_RECORD_VPN)
3061     {
3062       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3063                  "GNS_PHASE_DELEGATE_NS-%llu: VPN found.\n",
3064                  rh->id);
3065       rh->status |= RSL_DELEGATE_VPN;
3066       rh->proc (rh->proc_cls, rh, rd_count, rd);
3067       return;
3068     }
3069
3070     /**
3071      * Redirect via NS
3072      * FIXME make optional
3073      */
3074     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_NS)
3075     {
3076       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3077                  "GNS_PHASE_DELEGATE_NS-%llu: NS found.\n",
3078                  rh->id);
3079       rh->status |= RSL_DELEGATE_NS;
3080       rh->proc (rh->proc_cls, rh, rd_count, rd);
3081       return;
3082     }
3083   
3084     if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
3085       continue;
3086
3087     rh->status |= RSL_DELEGATE_PKEY;
3088
3089     if (ignore_pending_records &&
3090         (rd[i].flags & GNUNET_NAMESTORE_RF_PENDING))
3091     {
3092       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3093       "GNS_PHASE_DELEGATE_NS-%llu: PKEY for %s is pending user confirmation.\n",
3094         rh->id,
3095         name);
3096       continue;
3097     }
3098     
3099     if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
3100          == 0)
3101     {
3102       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3103                  "GNS_PHASE_DELEGATE_NS-%llu: This pkey is expired.\n",
3104                  rh->id);
3105       if (remaining_time.rel_value == 0)
3106       {
3107         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3108                    "GNS_PHASE_DELEGATE_NS-%llu: This dht entry is expired.\n",
3109                    rh->id);
3110         rh->authority_chain_head->fresh = 0;
3111         rh->proc(rh->proc_cls, rh, 0, NULL);
3112         return;
3113       }
3114
3115       continue;
3116     }
3117
3118     /**
3119      * Resolve rest of query with new authority
3120      */
3121     GNUNET_assert(rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
3122     memcpy(&rh->authority, rd[i].data,
3123            sizeof(struct GNUNET_CRYPTO_ShortHashCode));
3124     struct AuthorityChain *auth = GNUNET_malloc(sizeof(struct AuthorityChain));
3125     auth->zone = rh->authority;
3126     memset(auth->name, 0, strlen(rh->authority_name)+1);
3127     strcpy(auth->name, rh->authority_name);
3128     GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
3129                                  rh->authority_chain_tail,
3130                                  auth);
3131     
3132     /* Check for key revocation and delegate */
3133     GNUNET_NAMESTORE_lookup_record (namestore_handle,
3134                                     &rh->authority,
3135                                     "+",
3136                                     GNUNET_GNS_RECORD_REV,
3137                                     &process_pkey_revocation_result_ns,
3138                                     rh);
3139     return;
3140     
3141   }
3142     
3143   /**
3144    * no answers found
3145    */
3146   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3147     "GNS_PHASE_DELEGATE_NS-%llu: Authority lookup and no PKEY...\n", rh->id);
3148   /**
3149    * If we have found some records for the LAST label
3150    * we return the results. Else null.
3151    */
3152   if (strcmp(rh->name, "") == 0)
3153   {
3154     /* Start shortening */
3155     if ((rh->priv_key != NULL) && is_canonical (rh->name))
3156     {
3157       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3158               "GNS_PHASE_DELEGATE_NS-%llu: Trying to shorten authority chain\n",
3159               rh->id);
3160       start_shorten (rh->authority_chain_tail,
3161                     rh->priv_key);
3162     }
3163     /* simply promote back */
3164     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3165                "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
3166                rh->id, rh->authority_name);
3167     strcpy(rh->name, rh->authority_name);
3168     rh->proc(rh->proc_cls, rh, rd_count, rd);
3169   }
3170   else
3171   {
3172     rh->proc(rh->proc_cls, rh, 0, NULL);
3173   }
3174 }
3175
3176
3177 /**
3178  * Resolve the delegation chain for the request in our namestore
3179  *
3180  * @param rh the resolver handle
3181  */
3182 static void
3183 resolve_delegation_ns (struct ResolverHandle *rh)
3184 {
3185   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3186              "GNS_PHASE_DELEGATE_NS-%llu: Resolving delegation for %s\n",
3187              rh->id, rh->name);
3188   pop_tld(rh->name, rh->authority_name);
3189   GNUNET_NAMESTORE_lookup_record(namestore_handle,
3190                                  &rh->authority,
3191                                  rh->authority_name,
3192                                  GNUNET_GNS_RECORD_ANY,
3193                                  &process_delegation_result_ns,
3194                                  rh);
3195
3196 }
3197
3198
3199 /**
3200  * Lookup of a record in a specific zone
3201  * calls lookup result processor on result
3202  *
3203  * @param zone the root zone
3204  * @param pzone the private local zone
3205  * @param record_type the record type to look up
3206  * @param name the name to look up
3207  * @param key a private key for use with PSEU import (can be NULL)
3208  * @param timeout timeout for resolution
3209  * @param only_cached GNUNET_NO to only check locally not DHT for performance
3210  * @param proc the processor to call on result
3211  * @param cls the closure to pass to proc
3212  */
3213 void
3214 gns_resolver_lookup_record(struct GNUNET_CRYPTO_ShortHashCode zone,
3215                            struct GNUNET_CRYPTO_ShortHashCode pzone,
3216                            uint32_t record_type,
3217                            const char* name,
3218                            struct GNUNET_CRYPTO_RsaPrivateKey *key,
3219                            struct GNUNET_TIME_Relative timeout,
3220                            int only_cached,
3221                            RecordLookupProcessor proc,
3222                            void* cls)
3223 {
3224   struct ResolverHandle *rh;
3225   struct RecordLookupHandle* rlh;
3226   char string_hash[MAX_DNS_LABEL_LENGTH];
3227   char nzkey[MAX_DNS_LABEL_LENGTH];
3228   char* nzkey_ptr = nzkey;
3229
3230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3231               "Starting resolution for %s (type=%d)!\n",
3232               name, record_type);
3233
3234   
3235   if (is_canonical((char*)name) && (strcmp(GNUNET_GNS_TLD, name) != 0))
3236   {
3237     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3238                 "%s is canonical and not gnunet -> cannot resolve!\n", name);
3239     proc(cls, 0, NULL);
3240     return;
3241   }
3242   
3243   rlh = GNUNET_malloc(sizeof(struct RecordLookupHandle));
3244   rh = GNUNET_malloc(sizeof (struct ResolverHandle));
3245
3246   rh->authority = zone;
3247   rh->id = rid++;
3248   rh->proc_cls = rlh;
3249   rh->priv_key = key;
3250   rh->timeout = timeout;
3251   rh->get_handle = NULL;
3252   rh->private_local_zone = pzone;
3253   rh->only_cached = only_cached;
3254   
3255   if (NULL == key)
3256   {
3257     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3258                 "No shorten key for resolution\n");
3259   }
3260
3261   if (timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3262   {
3263     /*
3264      * Set timeout for authority lookup phase to 1/2
3265      */
3266     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3267                 "Timeout for lookup set to %ds\n", rh->timeout.rel_value);
3268     rh->timeout_task = GNUNET_SCHEDULER_add_delayed(
3269                                 GNUNET_TIME_relative_divide(timeout, 2),
3270                                                 &handle_lookup_timeout,
3271                                                 rh);
3272     rh->timeout_cont = &dht_authority_lookup_timeout;
3273     rh->timeout_cont_cls = rh;
3274   }
3275   else
3276   {
3277     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No timeout for query!\n");
3278     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3279   }
3280   
3281   if (strcmp(GNUNET_GNS_TLD, name) == 0)
3282   {
3283     /**
3284      * Only 'gnunet' given
3285      */
3286     strcpy(rh->name, "\0");
3287   }
3288   else
3289   {
3290     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3291                 "Checking for TLD...\n");
3292     if (is_zkey_tld(name) == GNUNET_YES)
3293     {
3294       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3295                   "TLD is zkey\n");
3296       /**
3297        * This is a zkey tld
3298        * build hash and use as initial authority
3299        */
3300       memset(rh->name, 0,
3301              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY));
3302       memcpy(rh->name, name,
3303              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY) - 1);
3304       pop_tld(rh->name, string_hash);
3305
3306       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3307                   "ZKEY is %s!\n", string_hash);
3308       
3309       GNUNET_STRINGS_utf8_toupper(string_hash, &nzkey_ptr);
3310
3311       if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string(nzkey,
3312                                                       &rh->authority))
3313       {
3314         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3315                     "Cannot convert ZKEY %s to hash!\n", string_hash);
3316         GNUNET_free(rh);
3317         GNUNET_free(rlh);
3318         proc(cls, 0, NULL);
3319         return;
3320       }
3321
3322     }
3323     else
3324     {
3325       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3326                   "TLD is gnunet\n");
3327       /**
3328        * Presumably GNUNET tld
3329        */
3330       memset(rh->name, 0,
3331              strlen(name)-strlen(GNUNET_GNS_TLD));
3332       memcpy(rh->name, name,
3333              strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
3334     }
3335   }
3336   
3337   /**
3338    * Initialize authority chain
3339    */
3340   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
3341   rh->authority_chain_head->prev = NULL;
3342   rh->authority_chain_head->next = NULL;
3343   rh->authority_chain_tail = rh->authority_chain_head;
3344   rh->authority_chain_head->zone = rh->authority;
3345   
3346   /**
3347    * Copy original query into lookup handle
3348    */
3349   rlh->record_type = record_type;
3350   memset(rlh->name, 0, strlen(name) + 1);
3351   strcpy(rlh->name, name);
3352   rlh->proc = proc;
3353   rlh->proc_cls = cls;
3354
3355   rh->proc = &handle_delegation_ns;
3356   resolve_delegation_ns(rh);
3357 }
3358
3359 /******** END Record Resolver ***********/
3360
3361 /**
3362  * Callback calles by namestore for a zone to name
3363  * result
3364  *
3365  * @param cls the closure
3366  * @param zone_key the zone we queried
3367  * @param expire the expiration time of the name
3368  * @param name the name found or NULL
3369  * @param rd_len number of records for the name
3370  * @param rd the record data (PKEY) for the name
3371  * @param signature the signature for the record data
3372  */
3373 static void
3374 process_zone_to_name_shorten_root (void *cls,
3375                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3376                  struct GNUNET_TIME_Absolute expire,
3377                  const char *name,
3378                  unsigned int rd_len,
3379                  const struct GNUNET_NAMESTORE_RecordData *rd,
3380                  const struct GNUNET_CRYPTO_RsaSignature *signature);
3381
3382
3383 /**
3384  * Callback called by namestore for a zone to name
3385  * result
3386  *
3387  * @param cls the closure
3388  * @param zone_key the zone we queried
3389  * @param expire the expiration time of the name
3390  * @param name the name found or NULL
3391  * @param rd_len number of records for the name
3392  * @param rd the record data (PKEY) for the name
3393  * @param signature the signature for the record data
3394  */
3395 static void
3396 process_zone_to_name_shorten_shorten (void *cls,
3397                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3398                  struct GNUNET_TIME_Absolute expire,
3399                  const char *name,
3400                  unsigned int rd_len,
3401                  const struct GNUNET_NAMESTORE_RecordData *rd,
3402                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3403 {
3404   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3405   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3406   struct AuthorityChain *next_authority;
3407
3408   char result[MAX_DNS_NAME_LENGTH];
3409   char tmp_name[MAX_DNS_NAME_LENGTH];
3410   size_t answer_len;
3411   
3412   /* we found a match in our own root zone */
3413   if (rd_len != 0)
3414   {
3415     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3416                "result strlen %d\n", strlen(name));
3417     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3418     memset(result, 0, answer_len);
3419
3420     if (strlen(rh->name) > 0)
3421     {
3422       sprintf (result, "%s.%s.%s.%s.%s",
3423                rh->name, name,
3424                nsh->shorten_zone_name, nsh->private_zone_name,
3425                GNUNET_GNS_TLD);
3426     }
3427     else
3428     {
3429       sprintf (result, "%s.%s.%s.%s", name,
3430                nsh->shorten_zone_name, nsh->private_zone_name,
3431                GNUNET_GNS_TLD);
3432     }
3433     
3434     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3435                "Found shorten result %s\n", result);
3436     if (strlen (nsh->result) > strlen (result))
3437       strcpy (nsh->result, result);
3438   }
3439   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3440                                         nsh->shorten_zone) == 0)
3441   {
3442     /**
3443      * This is our zone append .gnunet unless name is empty
3444      * (it shouldn't be, usually FIXME what happens if we
3445      * shorten to our zone to a "" record??)
3446      */
3447     
3448     sprintf (result, "%s.%s.%s.%s",
3449              rh->name,
3450              nsh->shorten_zone_name, nsh->private_zone_name,
3451              GNUNET_GNS_TLD);
3452     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3453                "Our zone: Found %s as shorten result\n", result);
3454     
3455     if (strlen (nsh->result) > strlen (result))
3456       strcpy (nsh->result, result);
3457     //nsh->proc(nsh->proc_cls, result);
3458     //GNUNET_free(nsh);
3459     //free_resolver_handle(rh);
3460     //return;
3461   }
3462   
3463   
3464   /**
3465    * No PSEU found.
3466    * continue with next authority if exists
3467    */
3468   if ((rh->authority_chain_head->next == NULL))
3469   {
3470     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3471                 "Sending %s as shorten result\n", nsh->result);
3472     nsh->proc(nsh->proc_cls, nsh->result);
3473     GNUNET_free (nsh);
3474     free_resolver_handle (rh);
3475     return;
3476   }
3477   next_authority = rh->authority_chain_head;
3478   
3479   GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3480                   "%s.%s", rh->name, next_authority->name);
3481   
3482   strcpy(rh->name, tmp_name);
3483   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3484              "No PSEU found for authority %s. Promoting back: %s\n",
3485              next_authority->name, rh->name);
3486   
3487   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3488                             rh->authority_chain_tail,
3489                             next_authority);
3490
3491   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3492                                  &rh->authority_chain_tail->zone,
3493                                  &rh->authority_chain_head->zone,
3494                                  &process_zone_to_name_shorten_root,
3495                                  rh);
3496 }
3497
3498 /**
3499  * Callback calles by namestore for a zone to name
3500  * result
3501  *
3502  * @param cls the closure
3503  * @param zone_key the zone we queried
3504  * @param expire the expiration time of the name
3505  * @param name the name found or NULL
3506  * @param rd_len number of records for the name
3507  * @param rd the record data (PKEY) for the name
3508  * @param signature the signature for the record data
3509  */
3510 static void
3511 process_zone_to_name_shorten_private (void *cls,
3512                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3513                  struct GNUNET_TIME_Absolute expire,
3514                  const char *name,
3515                  unsigned int rd_len,
3516                  const struct GNUNET_NAMESTORE_RecordData *rd,
3517                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3518 {
3519   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3520   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3521   struct AuthorityChain *next_authority;
3522
3523   char result[MAX_DNS_NAME_LENGTH];
3524   char tmp_name[MAX_DNS_NAME_LENGTH];
3525   size_t answer_len;
3526   
3527   /* we found a match in our own root zone */
3528   if (rd_len != 0)
3529   {
3530     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3531                "result strlen %d\n", strlen(name));
3532     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3533     memset(result, 0, answer_len);
3534
3535     if (strlen(rh->name) > 0)
3536     {
3537       sprintf (result, "%s.%s.%s", rh->name, name, GNUNET_GNS_TLD);
3538     }
3539     else
3540     {
3541       sprintf (result, "%s.%s", name, GNUNET_GNS_TLD);
3542     }
3543     
3544     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3545                "Found shorten result %s\n", result);
3546     if (strlen (nsh->result) > strlen (result))
3547       strcpy (nsh->result, result);
3548   }
3549   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3550                                         nsh->private_zone) == 0)
3551   {
3552     /**
3553      * This is our zone append .gnunet unless name is empty
3554      * (it shouldn't be, usually FIXME what happens if we
3555      * shorten to our zone to a "" record??)
3556      */
3557     
3558     sprintf (result, "%s.%s.%s",
3559              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3560     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3561                "Our private zone: Found %s as shorten result %s\n", result);
3562     if (strlen (nsh->result) > strlen (result))
3563       strcpy (nsh->result, result);
3564   }
3565   
3566   if (nsh->shorten_zone != NULL)
3567   {
3568     /* backtrack authorities for names in priv zone */
3569     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3570                                    nsh->shorten_zone,
3571                                    &rh->authority_chain_head->zone,
3572                                    &process_zone_to_name_shorten_shorten,
3573                                    rh);
3574   }
3575   else
3576   {
3577     /**
3578      * No PSEU found.
3579      * continue with next authority if exists
3580      */
3581     if ((rh->authority_chain_head->next == NULL))
3582     {
3583       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3584                  "Sending %s as shorten result\n", nsh->result);
3585       nsh->proc(nsh->proc_cls, nsh->result);
3586       GNUNET_free(nsh);
3587       free_resolver_handle(rh);
3588       return;
3589     }
3590     next_authority = rh->authority_chain_head;
3591     
3592     GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3593                     "%s.%s", rh->name, next_authority->name);
3594     
3595     strcpy(rh->name, tmp_name);
3596     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3597                "No PSEU found for authority %s. Promoting back: %s\n",
3598                next_authority->name, rh->name);
3599     
3600     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3601                               rh->authority_chain_tail,
3602                               next_authority);
3603
3604     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3605                                    &rh->authority_chain_tail->zone,
3606                                    &rh->authority_chain_head->zone,
3607                                    &process_zone_to_name_shorten_root,
3608                                    rh);
3609   }
3610 }
3611
3612 /**
3613  * Callback calles by namestore for a zone to name
3614  * result
3615  *
3616  * @param cls the closure
3617  * @param zone_key the zone we queried
3618  * @param expire the expiration time of the name
3619  * @param name the name found or NULL
3620  * @param rd_len number of records for the name
3621  * @param rd the record data (PKEY) for the name
3622  * @param signature the signature for the record data
3623  */
3624 static void
3625 process_zone_to_name_shorten_root (void *cls,
3626                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3627                  struct GNUNET_TIME_Absolute expire,
3628                  const char *name,
3629                  unsigned int rd_len,
3630                  const struct GNUNET_NAMESTORE_RecordData *rd,
3631                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3632 {
3633   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3634   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3635   struct AuthorityChain *next_authority;
3636
3637   char result[MAX_DNS_NAME_LENGTH];
3638   char tmp_name[MAX_DNS_NAME_LENGTH];
3639   size_t answer_len;
3640   
3641   /* we found a match in our own root zone */
3642   if (rd_len != 0)
3643   {
3644     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3645                "result strlen %d\n", strlen(name));
3646     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3647     memset(result, 0, answer_len);
3648
3649     if (strlen(rh->name) > 0)
3650     {
3651       sprintf (result, "%s.%s.%s", rh->name, name, GNUNET_GNS_TLD);
3652     }
3653     else
3654     {
3655       sprintf (result, "%s.%s", name, GNUNET_GNS_TLD);
3656     }
3657     
3658     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3659                "Found shorten result %s\n", result);
3660     if (strlen (nsh->result) > strlen (result))
3661       strcpy (nsh->result, result);
3662   }
3663   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3664                                         nsh->root_zone) == 0)
3665   {
3666     /**
3667      * This is our zone append .gnunet unless name is empty
3668      * (it shouldn't be, usually FIXME what happens if we
3669      * shorten to our zone to a "" record??)
3670      */
3671     
3672     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
3673     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3674                "Our zone: Found %s as shorten result\n", result);
3675     if (strlen (nsh->result) > strlen (result))
3676       strcpy (nsh->result, result);
3677   }
3678   
3679   if (nsh->private_zone != NULL)
3680   {
3681     /* backtrack authorities for names in priv zone */
3682     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3683                                    nsh->private_zone,
3684                                    &rh->authority_chain_head->zone,
3685                                    &process_zone_to_name_shorten_private,
3686                                    rh);
3687   }
3688   else
3689   {
3690     /**
3691      * No PSEU found.
3692      * continue with next authority if exists
3693      */
3694     if ((rh->authority_chain_head->next == NULL))
3695     {
3696       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3697                  "Sending %s as shorten result\n", nsh->result);
3698       nsh->proc(nsh->proc_cls, nsh->result);
3699       GNUNET_free(nsh);
3700       free_resolver_handle(rh);
3701       return;
3702     }
3703     next_authority = rh->authority_chain_head;
3704     
3705     GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3706                     "%s.%s", rh->name, next_authority->name);
3707     
3708     strcpy(rh->name, tmp_name);
3709     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3710                "No PSEU found for authority %s. Promoting back: %s\n",
3711                next_authority->name, rh->name);
3712     
3713     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3714                               rh->authority_chain_tail,
3715                               next_authority);
3716
3717     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3718                                    &rh->authority_chain_tail->zone,
3719                                    &rh->authority_chain_head->zone,
3720                                    &process_zone_to_name_shorten_root,
3721                                    rh);
3722   }
3723 }
3724
3725
3726 /**
3727  * Process result from namestore delegation lookup
3728  * for shorten operation
3729  *
3730  * @param cls the client shorten handle
3731  * @param rh the resolver handle
3732  * @param rd_count number of results (0)
3733  * @param rd data (NULL)
3734  */
3735 void
3736 handle_delegation_ns_shorten (void* cls,
3737                       struct ResolverHandle *rh,
3738                       uint32_t rd_count,
3739                       const struct GNUNET_NAMESTORE_RecordData *rd)
3740 {
3741   struct NameShortenHandle *nsh;
3742   char result[MAX_DNS_NAME_LENGTH];
3743
3744   nsh = (struct NameShortenHandle *)cls;
3745   
3746   /**
3747    * At this point rh->name contains the part of the name
3748    * that we do not have a PKEY in our namestore to resolve.
3749    * The authority chain in the resolver handle is now
3750    * useful to backtrack if needed
3751    */
3752   
3753   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3754              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
3755   memset(result, 0, sizeof (result));
3756
3757   if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3758                                    nsh->root_zone) == 0)
3759   {
3760     /**
3761      * This is our zone append .gnunet unless name is empty
3762      * (it shouldn't be, usually FIXME what happens if we
3763      * shorten to our zone to a "" record??)
3764      */
3765     
3766     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
3767     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3768                "Our zone: Found %s as shorten result\n", result);
3769     
3770     if (strlen (nsh->result) > strlen (result))
3771       strcpy (nsh->result, result);
3772
3773   }
3774   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3775                                         nsh->private_zone) == 0)
3776   {
3777     /**
3778      * This is our zone append .gnunet unless name is empty
3779      * (it shouldn't be, usually FIXME what happens if we
3780      * shorten to our zone to a "" record??)
3781      */
3782     
3783     sprintf (result, "%s.%s.%s",
3784              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3785     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3786                "Our zone: Found %s as shorten result %s\n", result);
3787     
3788     if (strlen (nsh->result) > strlen (result))
3789       strcpy (nsh->result, result);
3790   }
3791   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3792                                         nsh->shorten_zone) == 0)
3793   {
3794     /**
3795      * This is our zone append .gnunet unless name is empty
3796      * (it shouldn't be, usually FIXME what happens if we
3797      * shorten to our zone to a "" record??)
3798      */
3799     
3800     sprintf (result, "%s.%s.%s",
3801              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3802     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3803                "Our zone: Found %s as shorten result\n", result);
3804     
3805     if (strlen (nsh->result) > strlen (result))
3806       strcpy (nsh->result, result);
3807   }
3808   
3809   
3810   /* backtrack authorities for names */
3811   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3812                                  nsh->root_zone,
3813                                  &rh->authority_chain_head->zone,
3814                                  &process_zone_to_name_shorten_root,
3815                                  rh);
3816   
3817 }
3818
3819
3820 /**
3821  * Callback calles by namestore for a zone to name
3822  * result
3823  *
3824  * @param cls the closure
3825  * @param zone_key the zone we queried
3826  * @param expire the expiration time of the name
3827  * @param name the name found or NULL
3828  * @param rd_len number of records for the name
3829  * @param rd the record data (PKEY) for the name
3830  * @param signature the signature for the record data
3831  */
3832 static void
3833 process_zone_to_name_zkey(void *cls,
3834                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3835                  struct GNUNET_TIME_Absolute expire,
3836                  const char *name,
3837                  unsigned int rd_len,
3838                  const struct GNUNET_NAMESTORE_RecordData *rd,
3839                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3840 {
3841   struct ResolverHandle *rh = cls;
3842   struct NameShortenHandle *nsh = rh->proc_cls;
3843   struct GNUNET_CRYPTO_ShortHashAsciiEncoded enc;
3844   char new_name[MAX_DNS_NAME_LENGTH];
3845
3846   /* zkey not in our zone */
3847   if (name == NULL)
3848   {
3849     /**
3850      * In this case we have not given this PKEY a name (yet)
3851      * It is either just not in our zone or not even cached
3852      * Since we do not know at this point we will not try to shorten
3853      * because PKEY import will happen if the user follows the zkey
3854      * link.
3855      */
3856     GNUNET_CRYPTO_short_hash_to_enc ((struct GNUNET_CRYPTO_ShortHashCode*)rd,
3857                                      &enc);
3858     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3859                "No name found for zkey %s returning verbatim!\n", enc);
3860     if (strcmp(rh->name, "") != 0)
3861       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s.%s",
3862                       rh->name, enc, GNUNET_GNS_TLD_ZKEY);
3863     else
3864       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
3865                       enc, GNUNET_GNS_TLD_ZKEY);
3866
3867     strcpy (nsh->result, new_name);
3868
3869     nsh->proc(nsh->proc_cls, new_name);
3870     GNUNET_free(nsh);
3871     free_resolver_handle(rh);
3872     return;
3873   }
3874   
3875   if (strcmp(rh->name, "") != 0)
3876     GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
3877                     rh->name, name);
3878   else
3879     strcpy(new_name, name);
3880
3881   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3882              "Continue shorten for %s!\n", new_name);
3883
3884   strcpy(rh->name, new_name);
3885   
3886   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
3887   rh->authority_chain_tail = rh->authority_chain_head;
3888   rh->authority_chain_head->zone = rh->authority;
3889   
3890   
3891   /* Start delegation resolution in our namestore */
3892   resolve_delegation_ns(rh);
3893 }
3894
3895
3896 /**
3897  * Shorten api from resolver
3898  *
3899  * @param zone the root zone to use
3900  * @param pzone the private zone to use
3901  * @param szone the shorten zone to use
3902  * @param name the name to shorten
3903  * @param private_zone_name name of the private zone
3904  * @param shorten_zone_name name of the shorten zone
3905  * @param proc the processor to call with result
3906  * @param proc_cls closure to pass to proc
3907  */
3908 void
3909 gns_resolver_shorten_name (struct GNUNET_CRYPTO_ShortHashCode *zone,
3910                            struct GNUNET_CRYPTO_ShortHashCode *pzone,
3911                            struct GNUNET_CRYPTO_ShortHashCode *szone,
3912                            const char* name,
3913                            const char* private_zone_name,
3914                            const char* shorten_zone_name,
3915                            ShortenResultProcessor proc,
3916                            void* proc_cls)
3917 {
3918   struct ResolverHandle *rh;
3919   struct NameShortenHandle *nsh;
3920   char string_hash[MAX_DNS_LABEL_LENGTH];
3921   struct GNUNET_CRYPTO_ShortHashCode zkey;
3922   char nzkey[MAX_DNS_LABEL_LENGTH];
3923   char* nzkey_ptr = nzkey;
3924
3925
3926   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3927               "Starting shorten for %s!\n", name);
3928   
3929   if (is_canonical ((char*)name))
3930   {
3931     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3932                 "%s is canonical. Returning verbatim\n", name);
3933     proc (proc_cls, name);
3934     return;
3935   }
3936
3937   nsh = GNUNET_malloc (sizeof (struct NameShortenHandle));
3938
3939   nsh->proc = proc;
3940   nsh->proc_cls = proc_cls;
3941   nsh->root_zone = zone;
3942   nsh->private_zone = pzone;
3943   nsh->shorten_zone = szone;
3944   strcpy (nsh->private_zone_name, private_zone_name);
3945   strcpy (nsh->shorten_zone_name, shorten_zone_name);
3946   strcpy (nsh->result, name);
3947   
3948   rh = GNUNET_malloc (sizeof (struct ResolverHandle));
3949   rh->authority = *zone;
3950   rh->id = rid++;
3951   rh->priv_key = NULL;
3952   rh->proc = &handle_delegation_ns_shorten;
3953   rh->proc_cls = nsh;
3954   rh->id = rid++;
3955   rh->private_local_zone = *zone;
3956   
3957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3958                 "Checking for TLD...\n");
3959   if (is_zkey_tld (name) == GNUNET_YES)
3960   {
3961     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3962                 "TLD is zkey\n");
3963     /**
3964      * This is a zkey tld
3965      * build hash and use as initial authority
3966      * FIXME sscanf
3967      */
3968     memset (rh->name, 0,
3969             strlen (name)-strlen (GNUNET_GNS_TLD_ZKEY));
3970     memcpy (rh->name, name,
3971             strlen(name)-strlen (GNUNET_GNS_TLD_ZKEY) - 1);
3972     pop_tld (rh->name, string_hash);
3973
3974     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3975                 "ZKEY is %s!\n", string_hash);
3976     
3977     GNUNET_STRINGS_utf8_toupper (string_hash, &nzkey_ptr);
3978
3979     if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string (nzkey,
3980                                                            &zkey))
3981     {
3982       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3983                   "Cannot convert ZKEY %s to hash!\n", nzkey);
3984       GNUNET_free (rh);
3985       GNUNET_free (nsh);
3986       proc (proc_cls, name);
3987       return;
3988     }
3989
3990     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3991                                    zone, //ours
3992                                    &zkey,
3993                                    &process_zone_to_name_zkey,
3994                                    rh);
3995     return;
3996
3997   }
3998   else
3999   {
4000     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4001                 "TLD is gnunet\n");
4002     /**
4003      * Presumably GNUNET tld
4004      */
4005     memset (rh->name, 0,
4006             strlen (name)-strlen (GNUNET_GNS_TLD));
4007     memcpy (rh->name, name,
4008             strlen (name)-strlen (GNUNET_GNS_TLD) - 1);
4009   }
4010
4011   rh->authority_chain_head = GNUNET_malloc (sizeof (struct AuthorityChain));
4012   rh->authority_chain_tail = rh->authority_chain_head;
4013   rh->authority_chain_head->zone = *zone;
4014   
4015   
4016   /* Start delegation resolution in our namestore */
4017   resolve_delegation_ns (rh);
4018 }
4019
4020 /*********** END NAME SHORTEN ********************/
4021
4022
4023 /**
4024  * Process result from namestore delegation lookup
4025  * for get authority operation
4026  *
4027  * @param cls the client get auth handle
4028  * @param rh the resolver handle
4029  * @param rd_count number of results (0)
4030  * @param rd data (NULL)
4031  */
4032 void
4033 handle_delegation_result_ns_get_auth(void* cls,
4034                       struct ResolverHandle *rh,
4035                       uint32_t rd_count,
4036                       const struct GNUNET_NAMESTORE_RecordData *rd)
4037 {
4038   struct GetNameAuthorityHandle* nah;
4039   char result[MAX_DNS_NAME_LENGTH];
4040   size_t answer_len;
4041
4042   nah = (struct GetNameAuthorityHandle*) rh->proc_cls;
4043   
4044   /**
4045    * At this point rh->name contains the part of the name
4046    * that we do not have a PKEY in our namestore to resolve.
4047    * The authority chain in the resolver handle is now
4048    * useful to backtrack if needed
4049    */
4050   
4051   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4052              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
4053
4054   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4055              "Building response!\n");
4056   if (is_canonical(rh->name))
4057   {
4058     /**
4059      * We successfully resolved the authority in the ns
4060      * FIXME for our purposes this is fine
4061      * but maybe we want to have an api that also looks
4062      * into the dht (i.e. option in message)
4063      **/
4064     if (strlen(rh->name) > strlen(nah->name))
4065     {
4066       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4067                  "Record name longer than original lookup name... odd!\n");
4068       //FIXME to sth here
4069     }
4070
4071     answer_len = strlen(nah->name) - strlen(rh->name)
4072       + strlen(GNUNET_GNS_TLD) + 1;
4073     memset(result, 0, answer_len);
4074     strcpy(result, nah->name + strlen(rh->name) + 1);
4075
4076     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4077                "Got authority result %s\n", result);
4078     
4079     nah->proc(nah->proc_cls, result);
4080     GNUNET_free(nah);
4081     free_resolver_handle(rh);
4082   }
4083   else
4084   {
4085     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4086                "Unable to resolve authority for remaining %s!\n", rh->name);
4087     nah->proc(nah->proc_cls, "");
4088     GNUNET_free(nah);
4089     free_resolver_handle(rh);
4090   }
4091
4092
4093 }
4094
4095
4096 /**
4097  * Tries to resolve the authority for name
4098  * in our namestore
4099  *
4100  * @param zone the root zone to look up for
4101  * @param pzone the private local zone
4102  * @param name the name to lookup up
4103  * @param proc the processor to call when finished
4104  * @param proc_cls the closure to pass to the processor
4105  */
4106 void
4107 gns_resolver_get_authority(struct GNUNET_CRYPTO_ShortHashCode zone,
4108                            struct GNUNET_CRYPTO_ShortHashCode pzone,
4109                            const char* name,
4110                            GetAuthorityResultProcessor proc,
4111                            void* proc_cls)
4112 {
4113   struct ResolverHandle *rh;
4114   struct GetNameAuthorityHandle *nah;
4115
4116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4117               "Starting authority resolution for %s!\n", name);
4118
4119   nah = GNUNET_malloc(sizeof (struct GetNameAuthorityHandle));
4120   rh = GNUNET_malloc(sizeof (struct ResolverHandle));
4121   rh->authority = zone;
4122   rh->id = rid++;
4123   rh->private_local_zone = pzone;
4124   
4125   if (strcmp(GNUNET_GNS_TLD, name) == 0)
4126   {
4127     strcpy(rh->name, "\0");
4128   }
4129   else
4130   {
4131     memset(rh->name, 0,
4132            strlen(name)-strlen(GNUNET_GNS_TLD));
4133     memcpy(rh->name, name,
4134            strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
4135   }
4136
4137   memset(nah->name, 0,
4138          strlen(name)+1);
4139   strcpy(nah->name, name);
4140   
4141   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
4142   rh->authority_chain_tail = rh->authority_chain_head;
4143   rh->authority_chain_head->zone = zone;
4144   rh->proc = &handle_delegation_result_ns_get_auth;
4145   rh->proc_cls = (void*)nah;
4146
4147   nah->proc = proc;
4148   nah->proc_cls = proc_cls;
4149
4150   /* Start delegation resolution in our namestore */
4151   resolve_delegation_ns(rh);
4152
4153 }
4154
4155 /******** END GET AUTHORITY *************/
4156
4157 /* end of gnunet-service-gns_resolver.c */