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