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