56e6e39effbe033512dfdeaa8b042ae0e6883b02
[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   tok = 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-%d: dht lookup for query %s (%ds)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-%d: 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-%d: 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-%d: 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-%d: Got name: %s (wanted %s)\n",
1201                  rh->id, name, rh->name);
1202       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1203                  "GNS_PHASE_REC-%d: 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-%d: Got data length: %d\n",
1207                  rh->id, rd[i].data_size);
1208       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1209                  "GNS_PHASE_REC-%d: 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-%d: 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-%d: 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-%d: 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-%d: 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-%d: Namestore lookup for %s terminated without results\n",
1412                rh->id, name);
1413
1414     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1415                "GNS_PHASE_REC-%d: 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-%d: 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-%d: 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-%d: 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-%d: 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-%d: 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-%d: 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-%d: Answer is IPv4!\n",
1499                rh->id);
1500     if (rlh->record_type != GNUNET_GNS_RECORD_TYPE_A)
1501     {
1502       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1503                  "GNS_PHASE_REC-%d: 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_TYPE_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-%d: 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-%d: 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-%d: 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-%d: 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-%d: 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_TYPE_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_TYPE_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_TYPE_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_TYPE_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_TYPE_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_TYPE_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_TYPE_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_TYPE_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_TYPE_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 (%ds)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   GNUNET_DHT_get_stop (rh->get_handle);
2126   rh->get_handle = NULL;
2127   
2128   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
2129   {
2130     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2131                "GNS_PHASE_DELEGATE_DHT-%llu: Got shutdown\n",
2132                rh->id);
2133     rh->proc(rh->proc_cls, rh, 0, NULL);
2134     return;
2135   }
2136
2137   if (strcmp(rh->name, "") == 0)
2138   {
2139     /*
2140      * promote authority back to name and try to resolve record
2141      */
2142     strcpy(rh->name, rh->authority_name);
2143     rh->proc(rh->proc_cls, rh, 0, NULL);
2144     return;
2145   }
2146   
2147   /**
2148    * Start resolution in bg
2149    */
2150   GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH,
2151                   "%s.%s.%s", rh->name, rh->authority_name, GNUNET_GNS_TLD);
2152   //strcpy(new_name, rh->name);
2153   //strcpy(new_name+strlen(new_name), ".");
2154   //memcpy(new_name+strlen(new_name), GNUNET_GNS_TLD, strlen(GNUNET_GNS_TLD));
2155   
2156   strcpy(rh->name, new_name);
2157
2158   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2159         "GNS_PHASE_DELEGATE_DHT-%llu: Starting background query for %s type %d\n",
2160         rh->id, rh->name, rlh->record_type);
2161
2162   gns_resolver_lookup_record(rh->authority,
2163                              rh->private_local_zone,
2164                              rlh->record_type,
2165                              new_name,
2166                              rh->priv_key,
2167                              GNUNET_TIME_UNIT_FOREVER_REL,
2168                              GNUNET_NO,
2169                              &background_lookup_result_processor,
2170                              NULL);
2171
2172   rh->proc(rh->proc_cls, rh, 0, NULL);
2173 }
2174
2175 /* Prototype */
2176 static void resolve_delegation_dht(struct ResolverHandle *rh);
2177
2178 /* Prototype */
2179 static void resolve_delegation_ns(struct ResolverHandle *rh);
2180
2181
2182 /**
2183  * Namestore resolution for delegation finished. Processing result.
2184  *
2185  * @param cls the closure
2186  * @param rh resolver handle
2187  * @param rd_count number of results (always 0)
2188  * @param rd record data (always NULL)
2189  */
2190 static void
2191 handle_delegation_ns(void* cls, struct ResolverHandle *rh,
2192                           unsigned int rd_count,
2193                           const struct GNUNET_NAMESTORE_RecordData *rd);
2194
2195
2196 /**
2197  * This is a callback function that checks for key revocation
2198  *
2199  * @param cls the pending query
2200  * @param key the key of the zone we did the lookup
2201  * @param expiration expiration date of the record data set in the namestore
2202  * @param name the name for which we need an authority
2203  * @param rd_count the number of records with 'name'
2204  * @param rd the record data
2205  * @param signature the signature of the authority for the record data
2206  */
2207 static void
2208 process_pkey_revocation_result_ns (void *cls,
2209                     const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
2210                     struct GNUNET_TIME_Absolute expiration,
2211                     const char *name,
2212                     unsigned int rd_count,
2213                     const struct GNUNET_NAMESTORE_RecordData *rd,
2214                     const struct GNUNET_CRYPTO_RsaSignature *signature)
2215 {
2216   struct ResolverHandle *rh = cls;
2217   struct GNUNET_TIME_Relative remaining_time;
2218   int i;
2219   
2220   rh->namestore_task = NULL;
2221   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
2222   
2223   for (i = 0; i < rd_count; i++)
2224   {
2225     if (rd[i].record_type == GNUNET_GNS_RECORD_REV)
2226     {
2227       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2228                  "GNS_PHASE_DELEGATE_REV-%llu: Zone has been revoked.\n",
2229                  rh->id);
2230       rh->status |= RSL_PKEY_REVOKED;
2231       rh->proc (rh->proc_cls, rh, 0, NULL);
2232       return;
2233     }
2234   }
2235   
2236   if ((name == NULL) ||
2237       (remaining_time.rel_value == 0))
2238   {
2239     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2240           "GNS_PHASE_DELEGATE_REV-%llu: + Records don't exist or are expired.\n",
2241           rh->id, name);
2242
2243     if (rh->timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
2244     {
2245       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2246         "GNS_PHASE_DELEGATE_REV-%d: Starting background lookup for %s type %d\n",
2247         rh->id, "+.gnunet", GNUNET_GNS_RECORD_REV);
2248
2249       gns_resolver_lookup_record(rh->authority,
2250                                  rh->private_local_zone,
2251                                  GNUNET_GNS_RECORD_REV,
2252                                  GNUNET_GNS_TLD,
2253                                  rh->priv_key,
2254                                  GNUNET_TIME_UNIT_FOREVER_REL,
2255                                  GNUNET_NO,
2256                                  &background_lookup_result_processor,
2257                                  NULL);
2258     }
2259   }
2260  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2261              "GNS_PHASE_DELEGATE_REV-%llu: Revocation checkpassed\n",
2262              rh->id);
2263   /**
2264    * We are done with PKEY resolution if name is empty
2265    * else resolve again with new authority
2266    */
2267   if (strcmp (rh->name, "") == 0)
2268     rh->proc (rh->proc_cls, rh, 0, NULL);
2269   else
2270     resolve_delegation_ns (rh);
2271   return;
2272 }
2273
2274
2275 /**
2276  * Callback when record data is put into namestore
2277  *
2278  * @param cls the closure
2279  * @param success GNUNET_OK on success
2280  * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
2281  */
2282 void
2283 on_namestore_delegation_put_result(void *cls,
2284                                    int32_t success,
2285                                    const char *emsg)
2286 {
2287   struct NamestoreBGTask *nbg = cls;
2288
2289   GNUNET_CONTAINER_heap_remove_node (nbg->node);
2290   GNUNET_free (nbg);
2291
2292   if (GNUNET_NO == success)
2293   {
2294     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2295                "GNS_NS: records already in namestore\n");
2296     return;
2297   }
2298   else if (GNUNET_YES == success)
2299   {
2300     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2301                "GNS_NS: records successfully put in namestore\n");
2302     return;
2303   }
2304
2305   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2306              "GNS_NS: Error putting records into namestore: %s\n", emsg);
2307 }
2308
2309 /**
2310  * Function called when we get a result from the dht
2311  * for our query. Recursively tries to resolve authorities
2312  * for name in DHT.
2313  *
2314  * @param cls the request handle
2315  * @param exp lifetime
2316  * @param key the key the record was stored under
2317  * @param get_path get path
2318  * @param get_path_length get path length
2319  * @param put_path put path
2320  * @param put_path_length put path length
2321  * @param type the block type
2322  * @param size the size of the record
2323  * @param data the record data
2324  */
2325 static void
2326 process_delegation_result_dht(void* cls,
2327                  struct GNUNET_TIME_Absolute exp,
2328                  const struct GNUNET_HashCode * key,
2329                  const struct GNUNET_PeerIdentity *get_path,
2330                  unsigned int get_path_length,
2331                  const struct GNUNET_PeerIdentity *put_path,
2332                  unsigned int put_path_length,
2333                  enum GNUNET_BLOCK_Type type,
2334                  size_t size, const void *data)
2335 {
2336   struct ResolverHandle *rh;
2337   struct GNSNameRecordBlock *nrb;
2338   uint32_t num_records;
2339   char* name = NULL;
2340   char* rd_data = (char*) data;
2341   int i;
2342   int rd_size;
2343   struct GNUNET_CRYPTO_ShortHashCode zone, name_hash;
2344   struct GNUNET_HashCode zone_hash_double, name_hash_double;
2345
2346   rh = (struct ResolverHandle *)cls;
2347   
2348   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2349              "GNS_PHASE_DELEGATE_DHT-%llu: Got DHT result\n", rh->id);
2350
2351   if (data == NULL)
2352     return;
2353   
2354   nrb = (struct GNSNameRecordBlock*)data;
2355   
2356   /* stop dht lookup and timeout task */
2357   GNUNET_DHT_get_stop (rh->get_handle);
2358
2359   rh->get_handle = NULL;
2360
2361   if (rh->dht_heap_node != NULL)
2362   {
2363     GNUNET_CONTAINER_heap_remove_node(rh->dht_heap_node);
2364     rh->dht_heap_node = NULL;
2365   }
2366
2367   num_records = ntohl(nrb->rd_count);
2368   name = (char*)&nrb[1];
2369   {
2370     struct GNUNET_NAMESTORE_RecordData rd[num_records];
2371     struct NamestoreBGTask *ns_heap_root;
2372     struct NamestoreBGTask *namestore_bg_task;
2373     
2374     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
2375     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
2376   
2377     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
2378                                                                rd_data,
2379                                                                num_records,
2380                                                                rd))
2381     {
2382       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2383                  "GNS_PHASE_DELEGATE_DHT-%llu: Error deserializing data!\n",
2384                  rh->id);
2385       return;
2386     }
2387
2388     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2389                "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2390                rh->id, name, rh->authority_name);
2391     for (i=0; i<num_records; i++)
2392     {
2393     
2394       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2395                 "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2396                 rh->id, name, rh->authority_name);
2397       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2398                  "GNS_PHASE_DELEGATE_DHT-%llu: Got type: %d (wanted %d)\n",
2399                  rh->id, rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
2400       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2401                  "GNS_PHASE_DELEGATE_DHT-%llu: Got data length: %d\n",
2402                  rh->id, rd[i].data_size);
2403       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2404                  "GNS_PHASE_DELEGATE_DHT-%llu: Got flag %d\n",
2405                  rh->id, rd[i].flags);
2406       
2407       if ((rd[i].record_type == GNUNET_GNS_RECORD_VPN) ||
2408           (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_NS) ||
2409           (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_CNAME))
2410       {
2411         /**
2412          * This is a VPN,NS,CNAME entry. Let namestore handle this after caching
2413          */
2414         if (strcmp(rh->name, "") == 0)
2415           strcpy(rh->name, rh->authority_name);
2416         else
2417           GNUNET_snprintf(rh->name, MAX_DNS_NAME_LENGTH, "%s.%s",
2418                  rh->name, rh->authority_name); //FIXME ret
2419         rh->answered = 1;
2420         break;
2421       }
2422
2423       if ((strcmp(name, rh->authority_name) == 0) &&
2424           (rd[i].record_type == GNUNET_GNS_RECORD_PKEY))
2425       {
2426         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2427                    "GNS_PHASE_DELEGATE_DHT-%llu: Authority found in DHT\n",
2428                    rh->id);
2429         rh->answered = 1;
2430         memcpy(&rh->authority, rd[i].data, sizeof(struct GNUNET_CRYPTO_ShortHashCode));
2431         struct AuthorityChain *auth =
2432           GNUNET_malloc(sizeof(struct AuthorityChain));
2433         auth->zone = rh->authority;
2434         memset(auth->name, 0, strlen(rh->authority_name)+1);
2435         strcpy(auth->name, rh->authority_name);
2436         GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
2437                                      rh->authority_chain_tail,
2438                                      auth);
2439
2440         /** try to import pkey if private key available */
2441         //if (rh->priv_key && is_canonical (rh->name))
2442         //  process_discovered_authority(name, auth->zone,
2443         //                               rh->authority_chain_tail->zone,
2444         //                               rh->priv_key);
2445       }
2446
2447     }
2448
2449
2450     GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
2451     GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2452     GNUNET_CRYPTO_hash_xor(key, &name_hash_double, &zone_hash_double);
2453     GNUNET_CRYPTO_short_hash_from_truncation (&zone_hash_double, &zone);
2454
2455     /* Save to namestore */
2456     if (0 != GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_tail->zone,
2457                                           &zone))
2458     {
2459       if (max_allowed_ns_tasks <=
2460           GNUNET_CONTAINER_heap_get_size (ns_task_heap))
2461       {
2462         ns_heap_root = GNUNET_CONTAINER_heap_remove_root (ns_task_heap);
2463         GNUNET_NAMESTORE_cancel (ns_heap_root->qe);
2464
2465         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2466                    "GNS_PHASE_REC-%d: Replacing oldest background ns task\n",
2467                    rh->id);
2468       }
2469       
2470       namestore_bg_task = GNUNET_malloc (sizeof (struct NamestoreBGTask));
2471
2472       namestore_bg_task->node = GNUNET_CONTAINER_heap_insert (ns_task_heap,
2473                                     namestore_bg_task,
2474                                     GNUNET_TIME_absolute_get().abs_value);
2475       namestore_bg_task->qe = GNUNET_NAMESTORE_record_put (namestore_handle,
2476                                  &nrb->public_key,
2477                                  name,
2478                                  exp,
2479                                  num_records,
2480                                  rd,
2481                                  &nrb->signature,
2482                                  &on_namestore_delegation_put_result, //cont
2483                                  namestore_bg_task); //cls
2484     }
2485   }
2486
2487   if (rh->answered)
2488   {
2489     rh->answered = 0;
2490     /**
2491      * delegate
2492      * FIXME in this case. should we ask namestore again?
2493      */
2494     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2495     "GNS_PHASE_DELEGATE_DHT-%llu: Answer from DHT for %s. Yet to resolve: %s\n",
2496     rh->id, rh->authority_name, rh->name);
2497
2498     if (strcmp(rh->name, "") == 0)
2499     {
2500       /* Start shortening */
2501       if ((rh->priv_key != NULL) && is_canonical (rh->name))
2502       {
2503         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2504              "GNS_PHASE_DELEGATE_DHT-%llu: Trying to shorten authority chain\n",
2505              rh->id);
2506         start_shorten (rh->authority_chain_tail,
2507                        rh->priv_key);
2508       }
2509     }
2510     else
2511       rh->proc = &handle_delegation_ns;
2512
2513     /* Check for key revocation and delegate */
2514     rh->namestore_task = GNUNET_NAMESTORE_lookup_record (namestore_handle,
2515                                     &rh->authority,
2516                                     "+",
2517                                     GNUNET_GNS_RECORD_REV,
2518                                     &process_pkey_revocation_result_ns,
2519                                     rh);
2520
2521     return;
2522   }
2523   
2524   /**
2525    * No pkey but name exists
2526    * promote back
2527    */
2528   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2529              "GNS_PHASE_DELEGATE_DHT-%llu: Adding %s back to %s\n",
2530              rh->id, rh->authority_name, rh->name);
2531   if (strcmp(rh->name, "") == 0)
2532     strcpy(rh->name, rh->authority_name);
2533   else
2534     GNUNET_snprintf(rh->name, MAX_DNS_NAME_LENGTH, "%s.%s",
2535                   rh->name, rh->authority_name); //FIXME ret
2536   
2537   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2538              "GNS_PHASE_DELEGATE_DHT-%llu: %s restored\n", rh->id, rh->name);
2539   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2540           "GNS_PHASE_DELEGATE_DHT-%llu: DHT authority lookup found no match!\n",
2541            rh->id);
2542   rh->proc(rh->proc_cls, rh, 0, NULL);
2543 }
2544
2545 #define MAX_SOA_LENGTH sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)\
2546                         +(MAX_DNS_NAME_LENGTH*2)
2547 #define MAX_MX_LENGTH sizeof(uint16_t)+MAX_DNS_NAME_LENGTH
2548 #define MAX_SRV_LENGTH (sizeof(uint16_t)*3)+MAX_DNS_NAME_LENGTH
2549
2550
2551 static void
2552 expand_plus(char* dest, char* src, char* repl)
2553 {
2554   char* pos;
2555   unsigned int s_len = strlen(src)+1;
2556
2557   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2558              "GNS_POSTPROCESS: Got %s to expand with %s\n", src, repl);
2559
2560   if (s_len < 3)
2561   {
2562     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2563                "GNS_POSTPROCESS: %s to short\n", src);
2564
2565     /* no postprocessing */
2566     memcpy(dest, src, s_len+1);
2567     return;
2568   }
2569   
2570   if (0 == strcmp(src+s_len-3, ".+"))
2571   {
2572     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2573                "GNS_POSTPROCESS: Expanding .+ in %s\n", src);
2574     memset(dest, 0, s_len+strlen(repl)+strlen(GNUNET_GNS_TLD));
2575     strcpy(dest, src);
2576     pos = dest+s_len-2;
2577     strcpy(pos, repl);
2578     pos += strlen(repl);
2579     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2580                "GNS_POSTPROCESS: Expanded to %s\n", dest);
2581   }
2582   else
2583   {
2584     memcpy(dest, src, s_len+1);
2585   }
2586 }
2587
2588 /**
2589  * finish lookup
2590  */
2591 static void
2592 finish_lookup (struct ResolverHandle *rh,
2593                struct RecordLookupHandle* rlh,
2594                unsigned int rd_count,
2595                const struct GNUNET_NAMESTORE_RecordData *rd)
2596 {
2597   int i;
2598   char new_rr_data[MAX_DNS_NAME_LENGTH];
2599   char new_mx_data[MAX_MX_LENGTH];
2600   char new_soa_data[MAX_SOA_LENGTH];
2601   char new_srv_data[MAX_SRV_LENGTH];
2602   struct srv_data *old_srv;
2603   struct srv_data *new_srv;
2604   struct soa_data *old_soa;
2605   struct soa_data *new_soa;
2606   struct GNUNET_NAMESTORE_RecordData p_rd[rd_count];
2607   char* repl_string;
2608   char* pos;
2609   unsigned int offset;
2610
2611   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2612   {
2613     GNUNET_SCHEDULER_cancel(rh->timeout_task);
2614     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2615   }
2616
2617   GNUNET_CONTAINER_DLL_remove (rlh_head, rlh_tail, rh);
2618
2619   if (rd_count > 0)
2620     memcpy(p_rd, rd, rd_count*sizeof(struct GNUNET_NAMESTORE_RecordData));
2621
2622   for (i = 0; i < rd_count; i++)
2623   {
2624     
2625     if (rd[i].record_type != GNUNET_GNS_RECORD_TYPE_NS &&
2626         rd[i].record_type != GNUNET_GNS_RECORD_TYPE_CNAME &&
2627         rd[i].record_type != GNUNET_GNS_RECORD_MX &&
2628         rd[i].record_type != GNUNET_GNS_RECORD_TYPE_SOA &&
2629         rd[i].record_type != GNUNET_GNS_RECORD_TYPE_SRV)
2630     {
2631       p_rd[i].data = rd[i].data;
2632       continue;
2633     }
2634
2635     /**
2636      * for all those records we 'should'
2637      * also try to resolve the A/AAAA records (RFC1035)
2638      * This is a feature and not important
2639      */
2640     
2641     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2642                "GNS_POSTPROCESS: Postprocessing\n");
2643
2644     if (strcmp(rh->name, "+") == 0)
2645       repl_string = rlh->name;
2646     else
2647       repl_string = rlh->name+strlen(rh->name)+1;
2648
2649     offset = 0;
2650     if (rd[i].record_type == GNUNET_GNS_RECORD_MX)
2651     {
2652       memcpy (new_mx_data, (char*)rd[i].data, sizeof(uint16_t));
2653       offset = sizeof(uint16_t);
2654       pos = new_mx_data+offset;
2655       expand_plus(pos, (char*)rd[i].data+sizeof(uint16_t),
2656                   repl_string);
2657       offset += strlen(new_mx_data+sizeof(uint16_t))+1;
2658       p_rd[i].data = new_mx_data;
2659       p_rd[i].data_size = offset;
2660     }
2661     else if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_SRV)
2662     {
2663       /*
2664        * Prio, weight and port
2665        */
2666       new_srv = (struct srv_data*)new_srv_data;
2667       old_srv = (struct srv_data*)rd[i].data;
2668       new_srv->prio = old_srv->prio;
2669       new_srv->weight = old_srv->weight;
2670       new_srv->port = old_srv->port;
2671       expand_plus((char*)&new_srv[1], (char*)&old_srv[1],
2672                   repl_string);
2673       p_rd[i].data = new_srv_data;
2674       p_rd[i].data_size = sizeof (struct srv_data) + strlen ((char*)&new_srv[1]) + 1;
2675     }
2676     else if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_SOA)
2677     {
2678       /* expand mname and rname */
2679       old_soa = (struct soa_data*)rd[i].data;
2680       new_soa = (struct soa_data*)new_soa_data;
2681       memcpy (new_soa, old_soa, sizeof (struct soa_data));
2682       expand_plus((char*)&new_soa[1], (char*)&old_soa[1], repl_string);
2683       offset = strlen ((char*)&new_soa[1]) + 1;
2684       expand_plus((char*)&new_soa[1] + offset,
2685                   (char*)&old_soa[1] + strlen ((char*)&old_soa[1]) + 1,
2686                   repl_string);
2687       p_rd[i].data_size = sizeof (struct soa_data)
2688                           + offset
2689                           + strlen ((char*)&new_soa[1] + offset);
2690       p_rd[i].data = new_soa_data;
2691     }
2692     else
2693     {
2694       pos = new_rr_data;
2695       expand_plus(pos, (char*)rd[i].data, repl_string);
2696       p_rd[i].data_size = strlen(new_rr_data)+1;
2697       p_rd[i].data = new_rr_data;
2698     }
2699     
2700   }
2701
2702   rlh->proc(rlh->proc_cls, rd_count, p_rd);
2703   GNUNET_free(rlh);
2704   free_resolver_handle (rh);
2705 }
2706
2707 /**
2708  * Process DHT lookup result for record.
2709  *
2710  * @param cls the closure
2711  * @param rh resolver handle
2712  * @param rd_count number of results
2713  * @param rd record data
2714  */
2715 static void
2716 handle_record_dht(void* cls, struct ResolverHandle *rh,
2717                        unsigned int rd_count,
2718                        const struct GNUNET_NAMESTORE_RecordData *rd)
2719 {
2720   struct RecordLookupHandle* rlh;
2721
2722   rlh = (struct RecordLookupHandle*)cls;
2723   if (rd_count == 0)
2724   {
2725     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2726                "GNS_PHASE_REC-%d: No records for %s found in DHT. Aborting\n",
2727                rh->id, rh->name);
2728     /* give up, cannot resolve */
2729     finish_lookup(rh, rlh, 0, NULL);
2730     return;
2731   }
2732
2733   /* results found yay */
2734   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2735              "GNS_PHASE_REC-%d: Record resolved from DHT!", rh->id);
2736
2737   finish_lookup(rh, rlh, rd_count, rd);
2738
2739 }
2740
2741
2742
2743
2744 /**
2745  * Process namestore lookup result for record.
2746  *
2747  * @param cls the closure
2748  * @param rh resolver handle
2749  * @param rd_count number of results
2750  * @param rd record data
2751  */
2752 static void
2753 handle_record_ns (void* cls, struct ResolverHandle *rh,
2754                   unsigned int rd_count,
2755                   const struct GNUNET_NAMESTORE_RecordData *rd)
2756 {
2757   struct RecordLookupHandle* rlh;
2758   rlh = (struct RecordLookupHandle*) cls;
2759   int check_dht = GNUNET_YES;
2760
2761   if (rd_count == 0)
2762   {
2763     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2764                "GNS_PHASE_REC-%d: NS returned no records. (status: %d)!\n",
2765                rh->id,
2766                rh->status);
2767     
2768     /**
2769      * There are 5 conditions that have to met for us to consult the DHT:
2770      * 1. The entry in the DHT is RSL_RECORD_EXPIRED OR
2771      * 2. No entry in the NS existed AND
2772      * 3. The zone queried is not the local resolver's zone AND
2773      * 4. The name that was looked up is '+'
2774      *    because if it was any other canonical name we either already queried
2775      *    the DHT for the authority in the authority lookup phase (and thus
2776      *    would already have an entry in the NS for the record)
2777      * 5. We are not in cache only mode
2778      */
2779     if (((rh->status & RSL_RECORD_EXPIRED) != 0) &&
2780         ((rh->status & RSL_RECORD_EXISTS) == 0) )
2781       check_dht = GNUNET_NO;
2782     
2783     if (0 != GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
2784                                           &rh->private_local_zone))
2785       check_dht = GNUNET_NO;
2786     
2787     if ((strcmp (rh->name, "+") != 0) && (is_srv (rh->name) != 0))
2788         check_dht = GNUNET_NO;
2789
2790
2791     if (rh->only_cached == GNUNET_YES)
2792       check_dht = GNUNET_NO;
2793     
2794     if (GNUNET_YES == check_dht)
2795     {
2796       rh->proc = &handle_record_dht;
2797       resolve_record_dht(rh);
2798       return;
2799     }
2800     /* give up, cannot resolve */
2801     finish_lookup(rh, rlh, 0, NULL);
2802     return;
2803   }
2804
2805   /* results found yay */
2806   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2807              "GNS_PHASE_REC-%d: Record resolved from namestore!\n", rh->id);
2808
2809   finish_lookup(rh, rlh, rd_count, rd);
2810
2811
2812 }
2813
2814
2815 /**
2816  * Move one level up in the domain hierarchy and return the
2817  * passed top level domain.
2818  *
2819  * @param name the domain
2820  * @param dest the destination where the tld will be put
2821  */
2822 void
2823 pop_tld(char* name, char* dest)
2824 {
2825   uint32_t len;
2826
2827   if (is_canonical (name))
2828   {
2829     strcpy(dest, name);
2830     strcpy(name, "");
2831     return;
2832   }
2833
2834   for (len = strlen(name); len > 0; len--)
2835   {
2836     if (*(name+len) == '.')
2837       break;
2838   }
2839   
2840   //Was canonical?
2841   if (len == 0)
2842     return;
2843
2844   name[len] = '\0';
2845
2846   strcpy(dest, (name+len+1));
2847 }
2848
2849 /**
2850  * Checks if name is in tld
2851  *
2852  * @param name the name to check
2853  * @param tld the TLD to check for
2854  * @return GNUNET_YES or GNUNET_NO
2855  */
2856 int
2857 is_tld(const char* name, const char* tld)
2858 {
2859   int offset = 0;
2860
2861   if (strlen(name) <= strlen(tld))
2862   {
2863     return GNUNET_NO;
2864   }
2865   
2866   offset = strlen(name)-strlen(tld);
2867   if (strcmp(name+offset, tld) != 0)
2868   {
2869     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2870                "%s is not in .%s TLD\n", name, tld);
2871     return GNUNET_NO;
2872   }
2873   return GNUNET_YES;
2874 }
2875
2876 /**
2877  * DHT resolution for delegation finished. Processing result.
2878  *
2879  * @param cls the closure
2880  * @param rh resolver handle
2881  * @param rd_count number of results (always 0)
2882  * @param rd record data (always NULL)
2883  */
2884 static void
2885 handle_delegation_dht(void* cls, struct ResolverHandle *rh,
2886                           unsigned int rd_count,
2887                           const struct GNUNET_NAMESTORE_RecordData *rd)
2888 {
2889   struct RecordLookupHandle* rlh;
2890   rlh = (struct RecordLookupHandle*) cls;
2891   
2892
2893   if (strcmp(rh->name, "") == 0)
2894   {
2895     if ((rlh->record_type == GNUNET_GNS_RECORD_PKEY))
2896     {
2897       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2898                  "GNS_PHASE_DELEGATE_DHT-%llu: Resolved queried PKEY via DHT.\n",
2899                  rh->id);
2900       finish_lookup(rh, rlh, rd_count, rd);
2901       return;
2902     }
2903     /* We resolved full name for delegation. resolving record */
2904     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2905      "GNS_PHASE_DELEGATE_DHT-%llu: Resolved full name for delegation via DHT.\n",
2906      rh->id);
2907     strcpy(rh->name, "+\0");
2908     rh->proc = &handle_record_ns;
2909     resolve_record_ns(rh);
2910     return;
2911   }
2912
2913   /**
2914    * we still have some left
2915    **/
2916   if (is_canonical(rh->name))
2917   {
2918     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2919              "GNS_PHASE_DELEGATE_DHT-%llu: Resolving canonical record %s in ns\n",
2920              rh->id,
2921              rh->name);
2922     rh->proc = &handle_record_ns;
2923     resolve_record_ns(rh);
2924     return;
2925   }
2926   /* give up, cannot resolve */
2927   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2928  "GNS_PHASE_DELEGATE_DHT-%llu: Cannot fully resolve delegation for %s via DHT!\n",
2929  rh->id, rh->name);
2930   finish_lookup(rh, rlh, 0, NULL);
2931 }
2932
2933
2934 /**
2935  * Start DHT lookup for a name -> PKEY (compare NS) record in
2936  * rh->authority's zone
2937  *
2938  * @param rh the pending gns query
2939  */
2940 static void
2941 resolve_delegation_dht(struct ResolverHandle *rh)
2942 {
2943   uint32_t xquery;
2944   struct GNUNET_CRYPTO_ShortHashCode name_hash;
2945   struct GNUNET_HashCode name_hash_double;
2946   struct GNUNET_HashCode zone_hash_double;
2947   struct GNUNET_HashCode lookup_key;
2948   struct ResolverHandle *rh_heap_root;
2949   
2950   pop_tld(rh->name, rh->authority_name); 
2951   GNUNET_CRYPTO_short_hash(rh->authority_name,
2952                      strlen(rh->authority_name),
2953                      &name_hash);
2954   GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2955   GNUNET_CRYPTO_short_hash_double(&rh->authority, &zone_hash_double);
2956   GNUNET_CRYPTO_hash_xor(&name_hash_double, &zone_hash_double, &lookup_key);
2957   
2958   rh->dht_heap_node = NULL;
2959
2960   if (rh->timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
2961   {
2962     //rh->timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
2963     //                                          &dht_authority_lookup_timeout,
2964     //                                                   rh);
2965     rh->timeout_cont = &dht_authority_lookup_timeout;
2966     rh->timeout_cont_cls = rh;
2967   }
2968   else 
2969   {
2970     if (max_allowed_background_queries <=
2971         GNUNET_CONTAINER_heap_get_size (dht_lookup_heap))
2972     {
2973       /* terminate oldest lookup */
2974       rh_heap_root = GNUNET_CONTAINER_heap_remove_root (dht_lookup_heap);
2975       GNUNET_DHT_get_stop (rh_heap_root->get_handle);
2976       rh_heap_root->get_handle = NULL;
2977       rh_heap_root->dht_heap_node = NULL;
2978       
2979       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2980         "GNS_PHASE_DELEGATE_DHT-%llu: Replacing oldest background query for %s\n",
2981         rh->id, rh_heap_root->authority_name);
2982       
2983       rh_heap_root->proc(rh_heap_root->proc_cls,
2984                          rh_heap_root,
2985                          0,
2986                          NULL);
2987     }
2988     rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap,
2989                                          rh,
2990                                          GNUNET_TIME_absolute_get().abs_value);
2991   }
2992   
2993   xquery = htonl(GNUNET_GNS_RECORD_PKEY);
2994   
2995   GNUNET_assert(rh->get_handle == NULL);
2996   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
2997                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
2998                        &lookup_key,
2999                        DHT_GNS_REPLICATION_LEVEL,
3000                        GNUNET_DHT_RO_NONE,
3001                        &xquery,
3002                        sizeof(xquery),
3003                        &process_delegation_result_dht,
3004                        rh);
3005
3006 }
3007
3008
3009 /**
3010  * Namestore resolution for delegation finished. Processing result.
3011  *
3012  * @param cls the closure
3013  * @param rh resolver handle
3014  * @param rd_count number of results (always 0)
3015  * @param rd record data (always NULL)
3016  */
3017 static void
3018 handle_delegation_ns (void* cls, struct ResolverHandle *rh,
3019                       unsigned int rd_count,
3020                       const struct GNUNET_NAMESTORE_RecordData *rd)
3021 {
3022   struct RecordLookupHandle* rlh;
3023   rlh = (struct RecordLookupHandle*) cls;
3024   int check_dht = GNUNET_YES;
3025   int s_len = 0;
3026
3027   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3028              "GNS_PHASE_DELEGATE_NS-%llu: Resolution status: %d.\n",
3029              rh->id, rh->status);
3030
3031   if (rh->status & RSL_PKEY_REVOKED)
3032   {
3033     finish_lookup (rh, rlh, 0, NULL);
3034     return;
3035   }
3036   
3037   if (strcmp(rh->name, "") == 0)
3038   {
3039     
3040     /* We resolved full name for delegation. resolving record */
3041     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3042               "GNS_PHASE_DELEGATE_NS-%llu: Resolved full name for delegation.\n",
3043               rh->id);
3044     if (rh->status & RSL_CNAME_FOUND)
3045     {
3046       if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_CNAME)
3047       {
3048         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3049                   "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried CNAME in NS.\n",
3050                   rh->id);
3051         strcpy (rh->name, rh->authority_name);
3052         finish_lookup (rh, rlh, rd_count, rd);
3053         return;
3054       }
3055       
3056       /* A .+ CNAME  */
3057       if (is_tld ((char*)rd->data, GNUNET_GNS_TLD_PLUS))
3058       {
3059         s_len = strlen (rd->data) - 2;
3060         memcpy (rh->name, rd->data, s_len);
3061         rh->name[s_len] = '\0';
3062         resolve_delegation_ns (rh);
3063         return;
3064       }
3065       else if (is_tld ((char*)rd->data, GNUNET_GNS_TLD_ZKEY))
3066       {
3067         gns_resolver_lookup_record (rh->authority,
3068                                     rh->private_local_zone,
3069                                     rlh->record_type,
3070                                     (char*)rd->data,
3071                                     rh->priv_key,
3072                                     rh->timeout,
3073                                     rh->only_cached,
3074                                     rlh->proc,
3075                                     rlh->proc_cls);
3076         GNUNET_free (rlh);
3077         GNUNET_CONTAINER_DLL_remove (rlh_head, rlh_tail, rh);
3078         free_resolver_handle (rh);
3079         return;
3080       }
3081       else
3082       {
3083         //Try DNS resolver
3084         strcpy (rh->dns_name, (char*)rd->data);
3085         resolve_dns_name (rh);
3086         return;
3087       }
3088
3089     }
3090     else if (rh->status & RSL_DELEGATE_VPN)
3091     {
3092       if (rlh->record_type == GNUNET_GNS_RECORD_VPN)
3093       {
3094         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3095                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried VPNRR in NS.\n",
3096                  rh->id);
3097         finish_lookup(rh, rlh, rd_count, rd);
3098         return;
3099       }
3100       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3101              "GNS_PHASE_DELEGATE_NS-%llu: VPN delegation starting.\n",
3102              rh->id);
3103       GNUNET_assert (NULL != rd);
3104       rh->proc = &handle_record_vpn;
3105       resolve_record_vpn (rh, rd_count, rd);
3106       return;
3107     }
3108     else if (rh->status & RSL_DELEGATE_NS)
3109     {
3110       if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_NS)
3111       {
3112         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3113                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried NSRR in NS.\n",
3114                    rh->id);
3115         finish_lookup(rh, rlh, rd_count, rd);
3116         return;
3117       }
3118       
3119       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3120                  "GNS_PHASE_DELEGATE_NS-%llu: NS delegation starting.\n",
3121                  rh->id);
3122       GNUNET_assert (NULL != rd);
3123       rh->proc = &handle_record_ns;
3124       resolve_record_dns (rh, rd_count, rd);
3125       return;
3126     }
3127     else if (rh->status & RSL_DELEGATE_PKEY)
3128     {
3129       if (rh->status & RSL_PKEY_REVOKED)
3130       {
3131         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3132                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved PKEY is revoked.\n",
3133                    rh->id);
3134         finish_lookup (rh, rlh, 0, NULL);
3135         return;
3136       }
3137       else if (rlh->record_type == GNUNET_GNS_RECORD_PKEY)
3138       {
3139         GNUNET_assert(rd_count == 1);
3140         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3141                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried PKEY in NS.\n",
3142                    rh->id);
3143         finish_lookup(rh, rlh, rd_count, rd);
3144         return;
3145       }
3146     }
3147     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3148                "GNS_PHASE_DELEGATE_NS-%llu: Resolving record +\n",
3149                rh->id);
3150     strcpy(rh->name, "+\0");
3151     rh->proc = &handle_record_ns;
3152     resolve_record_ns(rh);
3153     return;
3154   }
3155   
3156   if (rh->status & RSL_DELEGATE_NS)
3157   {
3158     if (rlh->record_type == GNUNET_GNS_RECORD_TYPE_NS)
3159     {
3160       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3161                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried NSRR in NS.\n",
3162                  rh->id);
3163       finish_lookup(rh, rlh, rd_count, rd);
3164       return;
3165     }
3166     
3167     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3168                "GNS_PHASE_DELEGATE_NS-%llu: NS delegation starting.\n",
3169                rh->id);
3170     GNUNET_assert (NULL != rd);
3171     rh->proc = &handle_record_ns;
3172     resolve_record_dns (rh, rd_count, rd);
3173     return;
3174   }
3175   
3176   /**
3177    * we still have some left
3178    * check if authority in ns is fresh
3179    * and exists
3180    * or we are authority
3181    **/
3182
3183   if ((rh->status & RSL_RECORD_EXISTS) &&
3184        !(rh->status & RSL_RECORD_EXPIRED))
3185     check_dht = GNUNET_NO;
3186
3187   if (0 == GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3188                                         &rh->private_local_zone))
3189     check_dht = GNUNET_NO;
3190
3191   if (rh->only_cached == GNUNET_YES)
3192     check_dht = GNUNET_NO;
3193
3194   if (check_dht == GNUNET_NO)
3195   {
3196     if (is_canonical(rh->name))
3197     {
3198       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3199                  "GNS_PHASE_DELEGATE_NS-%llu: Resolving canonical record %s\n",
3200                  rh->id,
3201                  rh->name);
3202       rh->proc = &handle_record_ns;
3203       resolve_record_ns(rh);
3204     }
3205     else
3206     {
3207       /* give up, cannot resolve */
3208       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3209           "GNS_PHASE_DELEGATE_NS-%llu: Cannot fully resolve delegation for %s!\n",
3210           rh->id,
3211           rh->name);
3212       finish_lookup(rh, rlh, rd_count, rd);
3213       //rlh->proc(rlh->proc_cls, 0, NULL);
3214     }
3215     return;
3216   }
3217
3218   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3219       "GNS_PHASE_DELEGATE_NS-%llu: Trying to resolve delegation for %s via DHT\n",
3220       rh->id, rh->name);
3221   rh->proc = &handle_delegation_dht;
3222   resolve_delegation_dht(rh);
3223 }
3224
3225
3226 /**
3227  * This is a callback function that should give us only PKEY
3228  * records. Used to query the namestore for the authority (PKEY)
3229  * for 'name'. It will recursively try to resolve the
3230  * authority for a given name from the namestore.
3231  *
3232  * @param cls the pending query
3233  * @param key the key of the zone we did the lookup
3234  * @param expiration expiration date of the record data set in the namestore
3235  * @param name the name for which we need an authority
3236  * @param rd_count the number of records with 'name'
3237  * @param rd the record data
3238  * @param signature the signature of the authority for the record data
3239  */
3240 static void
3241 process_delegation_result_ns (void* cls,
3242                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
3243                    struct GNUNET_TIME_Absolute expiration,
3244                    const char *name,
3245                    unsigned int rd_count,
3246                    const struct GNUNET_NAMESTORE_RecordData *rd,
3247                    const struct GNUNET_CRYPTO_RsaSignature *signature)
3248 {
3249   struct ResolverHandle *rh;
3250   struct GNUNET_TIME_Relative remaining_time;
3251   struct GNUNET_CRYPTO_ShortHashCode zone;
3252   char new_name[MAX_DNS_NAME_LENGTH];
3253   unsigned int i;
3254   struct GNUNET_TIME_Absolute et;
3255  
3256   rh = (struct ResolverHandle *)cls;
3257   rh->namestore_task = NULL;
3258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3259           "GNS_PHASE_DELEGATE_NS-%llu: Got %d records from authority lookup\n",
3260           rh->id, rd_count);
3261
3262   GNUNET_CRYPTO_short_hash (key,
3263                       sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3264                       &zone);
3265   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
3266   
3267   rh->status = 0;
3268   
3269   if (name != NULL)
3270   {
3271     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3272                 "GNS_PHASE_DELEGATE_NS-%llu: Records with name %s exist.\n",
3273                 rh->id, name);
3274     rh->status |= RSL_RECORD_EXISTS;
3275   
3276     if (remaining_time.rel_value == 0)
3277     {
3278       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3279                   "GNS_PHASE_DELEGATE_NS-%llu: Record set %s expired.\n",
3280                   rh->id, name);
3281       rh->status |= RSL_RECORD_EXPIRED;
3282     }
3283   }
3284   
3285   /**
3286    * No authority found in namestore.
3287    */
3288   if (rd_count == 0)
3289   {
3290     /**
3291      * We did not find an authority in the namestore
3292      */
3293     
3294     /**
3295      * No PKEY in zone.
3296      * Promote this authority back to a name maybe it is
3297      * our record.
3298      */
3299     if (strcmp (rh->name, "") == 0)
3300     {
3301       /* simply promote back */
3302       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3303                   "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
3304                   rh->id, rh->authority_name);
3305       strcpy (rh->name, rh->authority_name);
3306     }
3307     else
3308     {
3309       /* add back to existing name */
3310       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3311                   "GNS_PHASE_DELEGATE_NS-%llu: Adding %s back to %s\n",
3312                   rh->id, rh->authority_name, rh->name);
3313       GNUNET_snprintf (new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
3314                        rh->name, rh->authority_name);
3315       strcpy (rh->name, new_name);
3316       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3317                   "GNS_PHASE_DELEGATE_NS-%llu: %s restored\n",
3318                   rh->id, rh->name);
3319     }
3320
3321     rh->proc (rh->proc_cls, rh, 0, NULL);
3322     return;
3323   }
3324
3325   /**
3326    * We found an authority that may be able to help us
3327    * move on with query
3328    * Note only 1 pkey should have been returned.. anything else would be strange
3329    */
3330   for (i=0; i < rd_count;i++)
3331   {
3332     
3333     /**
3334      * A CNAME. Like regular DNS this means the is no other record for this
3335      * name.
3336      */
3337     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_CNAME)
3338     {
3339       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3340                  "GNS_PHASE_DELEGATE_NS-%llu: CNAME found.\n",
3341                  rh->id);
3342
3343       rh->status |= RSL_CNAME_FOUND;
3344       rh->proc (rh->proc_cls, rh, rd_count, rd);
3345       return;
3346     }
3347
3348     /**
3349      * Redirect via VPN
3350      */
3351     if (rd[i].record_type == GNUNET_GNS_RECORD_VPN)
3352     {
3353       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3354                  "GNS_PHASE_DELEGATE_NS-%llu: VPN found.\n",
3355                  rh->id);
3356       rh->status |= RSL_DELEGATE_VPN;
3357       rh->proc (rh->proc_cls, rh, rd_count, rd);
3358       return;
3359     }
3360
3361     /**
3362      * Redirect via NS
3363      * FIXME make optional
3364      */
3365     if (rd[i].record_type == GNUNET_GNS_RECORD_TYPE_NS)
3366     {
3367       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3368                  "GNS_PHASE_DELEGATE_NS-%llu: NS found.\n",
3369                  rh->id);
3370       rh->status |= RSL_DELEGATE_NS;
3371       rh->proc (rh->proc_cls, rh, rd_count, rd);
3372       return;
3373     }
3374   
3375     if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
3376       continue;
3377
3378     rh->status |= RSL_DELEGATE_PKEY;
3379
3380     if ((ignore_pending_records != 0) &&
3381         (rd[i].flags & GNUNET_NAMESTORE_RF_PENDING))
3382     {
3383       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3384      "GNS_PHASE_DELEGATE_NS-%llu: PKEY for %s is pending user confirmation.\n",
3385         rh->id,
3386         name);
3387       continue;
3388     }
3389     
3390     GNUNET_break (0 == (rd[i].flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
3391     et.abs_value = rd[i].expiration_time;
3392     if ((GNUNET_TIME_absolute_get_remaining (et)).rel_value
3393          == 0)
3394     {
3395       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3396                   "GNS_PHASE_DELEGATE_NS-%llu: This pkey is expired.\n",
3397                   rh->id);
3398       if (remaining_time.rel_value == 0)
3399       {
3400         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3401                     "GNS_PHASE_DELEGATE_NS-%llu: This dht entry is expired.\n",
3402                     rh->id);
3403         rh->authority_chain_head->fresh = 0;
3404         rh->proc (rh->proc_cls, rh, 0, NULL);
3405         return;
3406       }
3407
3408       continue;
3409     }
3410
3411     /**
3412      * Resolve rest of query with new authority
3413      */
3414     GNUNET_assert (rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
3415     memcpy (&rh->authority, rd[i].data,
3416             sizeof (struct GNUNET_CRYPTO_ShortHashCode));
3417     struct AuthorityChain *auth = GNUNET_malloc(sizeof (struct AuthorityChain));
3418     auth->zone = rh->authority;
3419     memset (auth->name, 0, strlen (rh->authority_name)+1);
3420     strcpy (auth->name, rh->authority_name);
3421     GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
3422                                  rh->authority_chain_tail,
3423                                  auth);
3424     
3425     /* Check for key revocation and delegate */
3426     rh->namestore_task = GNUNET_NAMESTORE_lookup_record (namestore_handle,
3427                                     &rh->authority,
3428                                     "+",
3429                                     GNUNET_GNS_RECORD_REV,
3430                                     &process_pkey_revocation_result_ns,
3431                                     rh);
3432     return;
3433   
3434   }
3435   
3436   /**
3437    * no answers found
3438    */
3439   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3440     "GNS_PHASE_DELEGATE_NS-%llu: Authority lookup and no PKEY...\n", rh->id);
3441   /**
3442    * If we have found some records for the LAST label
3443    * we return the results. Else null.
3444    */
3445   if (strcmp(rh->name, "") == 0)
3446   {
3447     /* Start shortening */
3448     if ((rh->priv_key != NULL) && is_canonical (rh->name))
3449     {
3450       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3451               "GNS_PHASE_DELEGATE_NS-%llu: Trying to shorten authority chain\n",
3452               rh->id);
3453       start_shorten (rh->authority_chain_tail,
3454                     rh->priv_key);
3455     }
3456     /* simply promote back */
3457     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3458                "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
3459                rh->id, rh->authority_name);
3460     strcpy(rh->name, rh->authority_name);
3461     rh->proc(rh->proc_cls, rh, rd_count, rd);
3462   }
3463   else
3464   {
3465     rh->proc(rh->proc_cls, rh, 0, NULL);
3466   }
3467 }
3468
3469
3470 /**
3471  * Resolve the delegation chain for the request in our namestore
3472  *
3473  * @param rh the resolver handle
3474  */
3475 static void
3476 resolve_delegation_ns (struct ResolverHandle *rh)
3477 {
3478   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3479              "GNS_PHASE_DELEGATE_NS-%llu: Resolving delegation for %s\n",
3480              rh->id, rh->name);
3481   pop_tld(rh->name, rh->authority_name);
3482   rh->namestore_task = GNUNET_NAMESTORE_lookup_record(namestore_handle,
3483                                  &rh->authority,
3484                                  rh->authority_name,
3485                                  GNUNET_GNS_RECORD_ANY,
3486                                  &process_delegation_result_ns,
3487                                  rh);
3488
3489 }
3490
3491
3492 /**
3493  * Lookup of a record in a specific zone
3494  * calls lookup result processor on result
3495  *
3496  * @param zone the root zone
3497  * @param pzone the private local zone
3498  * @param record_type the record type to look up
3499  * @param name the name to look up
3500  * @param key a private key for use with PSEU import (can be NULL)
3501  * @param timeout timeout for resolution
3502  * @param only_cached GNUNET_NO to only check locally not DHT for performance
3503  * @param proc the processor to call on result
3504  * @param cls the closure to pass to proc
3505  */
3506 void
3507 gns_resolver_lookup_record (struct GNUNET_CRYPTO_ShortHashCode zone,
3508                             struct GNUNET_CRYPTO_ShortHashCode pzone,
3509                             uint32_t record_type,
3510                             const char* name,
3511                             struct GNUNET_CRYPTO_RsaPrivateKey *key,
3512                             struct GNUNET_TIME_Relative timeout,
3513                             int only_cached,
3514                             RecordLookupProcessor proc,
3515                             void* cls)
3516 {
3517   struct ResolverHandle *rh;
3518   struct RecordLookupHandle* rlh;
3519   char string_hash[MAX_DNS_LABEL_LENGTH];
3520   char nzkey[MAX_DNS_LABEL_LENGTH];
3521   char* nzkey_ptr = nzkey;
3522
3523   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3524               "Starting resolution for %s (type=%d)!\n",
3525               name, record_type);
3526
3527   
3528   if (is_canonical((char*)name) && (strcmp(GNUNET_GNS_TLD, name) != 0))
3529   {
3530     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3531                 "%s is canonical and not gnunet -> cannot resolve!\n", name);
3532     proc(cls, 0, NULL);
3533     return;
3534   }
3535   
3536   rlh = GNUNET_malloc (sizeof(struct RecordLookupHandle));
3537   rh = GNUNET_malloc (sizeof (struct ResolverHandle));
3538   
3539   memset (rh, 0, sizeof (struct ResolverHandle));
3540   rh->authority = zone;
3541   rh->id = rid++;
3542   rh->proc_cls = rlh;
3543   rh->priv_key = key;
3544   rh->timeout = timeout;
3545   rh->get_handle = NULL;
3546   rh->private_local_zone = pzone;
3547   rh->only_cached = only_cached;
3548   rh->namestore_task = NULL;
3549
3550   GNUNET_CONTAINER_DLL_insert (rlh_head, rlh_tail, rh);
3551   
3552   if (NULL == key)
3553   {
3554     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3555                 "No shorten key for resolution\n");
3556   }
3557
3558   if (timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3559   {
3560     /*
3561      * Set timeout for authority lookup phase to 1/2
3562      */
3563     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3564                 "Timeout for lookup set to %ds\n", rh->timeout.rel_value);
3565     rh->timeout_task = GNUNET_SCHEDULER_add_delayed(
3566                                 GNUNET_TIME_relative_divide(timeout, 2),
3567                                                 &handle_lookup_timeout,
3568                                                 rh);
3569     rh->timeout_cont = &dht_authority_lookup_timeout;
3570     rh->timeout_cont_cls = rh;
3571   }
3572   else
3573   {
3574     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No timeout for query!\n");
3575     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3576   }
3577   
3578   if (strcmp(GNUNET_GNS_TLD, name) == 0)
3579   {
3580     /**
3581      * Only 'gnunet' given
3582      */
3583     strcpy(rh->name, "\0");
3584   }
3585   else
3586   {
3587     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3588                 "Checking for TLD...\n");
3589     if (is_zkey_tld(name) == GNUNET_YES)
3590     {
3591       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3592                   "TLD is zkey\n");
3593       /**
3594        * This is a zkey tld
3595        * build hash and use as initial authority
3596        */
3597       memset(rh->name, 0,
3598              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY));
3599       memcpy(rh->name, name,
3600              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY) - 1);
3601       pop_tld(rh->name, string_hash);
3602
3603       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3604                   "ZKEY is %s!\n", string_hash);
3605       
3606       GNUNET_STRINGS_utf8_toupper(string_hash, &nzkey_ptr);
3607
3608       if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string(nzkey,
3609                                                       &rh->authority))
3610       {
3611         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3612                     "Cannot convert ZKEY %s to hash!\n", string_hash);
3613         
3614         GNUNET_CONTAINER_DLL_remove (rlh_head, rlh_tail, rh);
3615         GNUNET_free (rh);
3616         GNUNET_free (rlh);
3617         proc (cls, 0, NULL);
3618         return;
3619       }
3620
3621     }
3622     else
3623     {
3624       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3625                   "TLD is gnunet\n");
3626       /**
3627        * Presumably GNUNET tld
3628        */
3629       memset (rh->name, 0,
3630               strlen(name)-strlen(GNUNET_GNS_TLD));
3631       memcpy (rh->name, name,
3632               strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
3633     }
3634   }
3635   
3636   /**
3637    * Initialize authority chain
3638    */
3639   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
3640   rh->authority_chain_head->prev = NULL;
3641   rh->authority_chain_head->next = NULL;
3642   rh->authority_chain_tail = rh->authority_chain_head;
3643   rh->authority_chain_head->zone = rh->authority;
3644   
3645   /**
3646    * Copy original query into lookup handle
3647    */
3648   rlh->record_type = record_type;
3649   memset(rlh->name, 0, strlen(name) + 1);
3650   strcpy(rlh->name, name);
3651   rlh->proc = proc;
3652   rlh->proc_cls = cls;
3653
3654   rh->proc = &handle_delegation_ns;
3655   resolve_delegation_ns(rh);
3656 }
3657
3658 /******** END Record Resolver ***********/
3659
3660 static void
3661 finish_shorten (struct ResolverHandle *rh,
3662                 struct NameShortenHandle *nsh)
3663 {
3664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3665               "Sending %s as shorten result\n", nsh->result);
3666   nsh->proc (nsh->proc_cls, nsh->result);
3667   GNUNET_CONTAINER_DLL_remove (nsh_head, nsh_tail, rh);
3668   GNUNET_free (nsh);
3669   free_resolver_handle (rh);
3670 }
3671
3672
3673 /**
3674  * Callback calles by namestore for a zone to name
3675  * result
3676  *
3677  * @param cls the closure
3678  * @param zone_key the zone we queried
3679  * @param expire the expiration time of the name
3680  * @param name the name found or NULL
3681  * @param rd_len number of records for the name
3682  * @param rd the record data (PKEY) for the name
3683  * @param signature the signature for the record data
3684  */
3685 static void
3686 process_zone_to_name_shorten_root (void *cls,
3687                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3688                  struct GNUNET_TIME_Absolute expire,
3689                  const char *name,
3690                  unsigned int rd_len,
3691                  const struct GNUNET_NAMESTORE_RecordData *rd,
3692                  const struct GNUNET_CRYPTO_RsaSignature *signature);
3693
3694
3695 /**
3696  * Callback called by namestore for a zone to name
3697  * result
3698  *
3699  * @param cls the closure
3700  * @param zone_key the zone we queried
3701  * @param expire the expiration time of the name
3702  * @param name the name found or NULL
3703  * @param rd_len number of records for the name
3704  * @param rd the record data (PKEY) for the name
3705  * @param signature the signature for the record data
3706  */
3707 static void
3708 process_zone_to_name_shorten_shorten (void *cls,
3709                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3710                  struct GNUNET_TIME_Absolute expire,
3711                  const char *name,
3712                  unsigned int rd_len,
3713                  const struct GNUNET_NAMESTORE_RecordData *rd,
3714                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3715 {
3716   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3717   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3718   struct AuthorityChain *next_authority;
3719
3720   char result[MAX_DNS_NAME_LENGTH];
3721   char tmp_name[MAX_DNS_NAME_LENGTH];
3722   size_t answer_len;
3723   
3724   rh->namestore_task = NULL;
3725   /* we found a match in our own root zone */
3726   if (rd_len != 0)
3727   {
3728     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3729                "result strlen %d\n", strlen(name));
3730     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3731     memset(result, 0, answer_len);
3732
3733     if (strlen(rh->name) > 0)
3734     {
3735       sprintf (result, "%s.%s.%s.%s.%s",
3736                rh->name, name,
3737                nsh->shorten_zone_name, nsh->private_zone_name,
3738                GNUNET_GNS_TLD);
3739     }
3740     else
3741     {
3742       sprintf (result, "%s.%s.%s.%s", name,
3743                nsh->shorten_zone_name, nsh->private_zone_name,
3744                GNUNET_GNS_TLD);
3745     }
3746     
3747     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3748                "Found shorten result %s\n", result);
3749     if (strlen (nsh->result) > strlen (result))
3750       strcpy (nsh->result, result);
3751   }
3752   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3753                                         nsh->shorten_zone) == 0)
3754   {
3755     /**
3756      * This is our zone append .gnunet unless name is empty
3757      * (it shouldn't be, usually FIXME what happens if we
3758      * shorten to our zone to a "" record??)
3759      */
3760     
3761     sprintf (result, "%s.%s.%s.%s",
3762              rh->name,
3763              nsh->shorten_zone_name, nsh->private_zone_name,
3764              GNUNET_GNS_TLD);
3765     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3766                "Our zone: Found %s as shorten result\n", result);
3767     
3768     if (strlen (nsh->result) > strlen (result))
3769       strcpy (nsh->result, result);
3770     //nsh->proc(nsh->proc_cls, result);
3771     //GNUNET_free(nsh);
3772     //free_resolver_handle(rh);
3773     //return;
3774   }
3775   
3776   
3777   /**
3778    * No PSEU found.
3779    * continue with next authority if exists
3780    */
3781   if ((rh->authority_chain_head->next == NULL))
3782   {
3783     finish_shorten (rh, nsh);
3784     return;
3785   }
3786   next_authority = rh->authority_chain_head;
3787   
3788   GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3789                   "%s.%s", rh->name, next_authority->name);
3790   
3791   strcpy(rh->name, tmp_name);
3792   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3793              "No PSEU found for authority %s. Promoting back: %s\n",
3794              next_authority->name, rh->name);
3795   
3796   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3797                             rh->authority_chain_tail,
3798                             next_authority);
3799
3800   GNUNET_free (next_authority);
3801
3802   rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3803                                  &rh->authority_chain_tail->zone,
3804                                  &rh->authority_chain_head->zone,
3805                                  &process_zone_to_name_shorten_root,
3806                                  rh);
3807 }
3808
3809 /**
3810  * Callback calles by namestore for a zone to name
3811  * result
3812  *
3813  * @param cls the closure
3814  * @param zone_key the zone we queried
3815  * @param expire the expiration time of the name
3816  * @param name the name found or NULL
3817  * @param rd_len number of records for the name
3818  * @param rd the record data (PKEY) for the name
3819  * @param signature the signature for the record data
3820  */
3821 static void
3822 process_zone_to_name_shorten_private (void *cls,
3823                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3824                  struct GNUNET_TIME_Absolute expire,
3825                  const char *name,
3826                  unsigned int rd_len,
3827                  const struct GNUNET_NAMESTORE_RecordData *rd,
3828                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3829 {
3830   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3831   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3832   struct AuthorityChain *next_authority;
3833
3834   char result[MAX_DNS_NAME_LENGTH];
3835   char tmp_name[MAX_DNS_NAME_LENGTH];
3836   size_t answer_len;
3837   
3838   rh->namestore_task = NULL;
3839   /* we found a match in our own root zone */
3840   if (rd_len != 0)
3841   {
3842     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3843                "result strlen %d\n", strlen(name));
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 (nsh->shorten_zone != NULL)
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     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3956                "result strlen %d\n", strlen(name));
3957     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3958     memset(result, 0, answer_len);
3959
3960     if (strlen(rh->name) > 0)
3961     {
3962       sprintf (result, "%s.%s.%s", rh->name, name, GNUNET_GNS_TLD);
3963     }
3964     else
3965     {
3966       sprintf (result, "%s.%s", name, GNUNET_GNS_TLD);
3967     }
3968     
3969     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3970                "Found shorten result %s\n", result);
3971     if (strlen (nsh->result) > strlen (result))
3972       strcpy (nsh->result, result);
3973   }
3974   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3975                                         nsh->root_zone) == 0)
3976   {
3977     /**
3978      * This is our zone append .gnunet unless name is empty
3979      * (it shouldn't be, usually FIXME what happens if we
3980      * shorten to our zone to a "" record??)
3981      */
3982     
3983     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
3984     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3985                "Our zone: Found %s as shorten result\n", result);
3986     if (strlen (nsh->result) > strlen (result))
3987       strcpy (nsh->result, result);
3988   }
3989   
3990   if (nsh->private_zone != NULL)
3991   {
3992     /* backtrack authorities for names in priv zone */
3993     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3994                                    nsh->private_zone,
3995                                    &rh->authority_chain_head->zone,
3996                                    &process_zone_to_name_shorten_private,
3997                                    rh);
3998   }
3999   else
4000   {
4001     /**
4002      * No PSEU found.
4003      * continue with next authority if exists
4004      */
4005     if ((rh->authority_chain_head->next == NULL))
4006     {
4007       finish_shorten (rh, nsh);
4008       return;
4009     }
4010     next_authority = rh->authority_chain_head;
4011     
4012     GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
4013                     "%s.%s", rh->name, next_authority->name);
4014     
4015     strcpy(rh->name, tmp_name);
4016     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4017                "No PSEU found for authority %s. Promoting back: %s\n",
4018                next_authority->name, rh->name);
4019     
4020     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
4021                               rh->authority_chain_tail,
4022                               next_authority);
4023
4024     GNUNET_free (next_authority);
4025
4026     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
4027                                    &rh->authority_chain_tail->zone,
4028                                    &rh->authority_chain_head->zone,
4029                                    &process_zone_to_name_shorten_root,
4030                                    rh);
4031   }
4032 }
4033
4034
4035 /**
4036  * Process result from namestore delegation lookup
4037  * for shorten operation
4038  *
4039  * @param cls the client shorten handle
4040  * @param rh the resolver handle
4041  * @param rd_count number of results (0)
4042  * @param rd data (NULL)
4043  */
4044 void
4045 handle_delegation_ns_shorten (void* cls,
4046                       struct ResolverHandle *rh,
4047                       uint32_t rd_count,
4048                       const struct GNUNET_NAMESTORE_RecordData *rd)
4049 {
4050   struct NameShortenHandle *nsh;
4051   char result[MAX_DNS_NAME_LENGTH];
4052
4053   nsh = (struct NameShortenHandle *)cls;
4054   
4055   /**
4056    * At this point rh->name contains the part of the name
4057    * that we do not have a PKEY in our namestore to resolve.
4058    * The authority chain in the resolver handle is now
4059    * useful to backtrack if needed
4060    */
4061   
4062   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4063              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
4064   memset(result, 0, sizeof (result));
4065
4066   if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
4067                                    nsh->root_zone) == 0)
4068   {
4069     /**
4070      * This is our zone append .gnunet unless name is empty
4071      * (it shouldn't be, usually FIXME what happens if we
4072      * shorten to our zone to a "" record??)
4073      */
4074     
4075     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
4076     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4077                "Our zone: Found %s as shorten result\n", result);
4078     
4079     if (strlen (nsh->result) > strlen (result))
4080       strcpy (nsh->result, result);
4081
4082   }
4083   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
4084                                         nsh->private_zone) == 0)
4085   {
4086     /**
4087      * This is our zone append .gnunet unless name is empty
4088      * (it shouldn't be, usually FIXME what happens if we
4089      * shorten to our zone to a "" record??)
4090      */
4091     
4092     sprintf (result, "%s.%s.%s",
4093              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
4094     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4095                "Our zone: Found %s as shorten result %s\n", result);
4096     
4097     if (strlen (nsh->result) > strlen (result))
4098       strcpy (nsh->result, result);
4099   }
4100   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
4101                                         nsh->shorten_zone) == 0)
4102   {
4103     /**
4104      * This is our zone append .gnunet unless name is empty
4105      * (it shouldn't be, usually FIXME what happens if we
4106      * shorten to our zone to a "" record??)
4107      */
4108     
4109     sprintf (result, "%s.%s.%s",
4110              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
4111     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4112                "Our zone: Found %s as shorten result\n", result);
4113     
4114     if (strlen (nsh->result) > strlen (result))
4115       strcpy (nsh->result, result);
4116   }
4117   
4118   
4119   /* backtrack authorities for names */
4120   rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
4121                                  nsh->root_zone,
4122                                  &rh->authority_chain_head->zone,
4123                                  &process_zone_to_name_shorten_root,
4124                                  rh);
4125   
4126 }
4127
4128
4129 /**
4130  * Callback calles by namestore for a zone to name
4131  * result
4132  *
4133  * @param cls the closure
4134  * @param zone_key the zone we queried
4135  * @param expire the expiration time of the name
4136  * @param name the name found or NULL
4137  * @param rd_len number of records for the name
4138  * @param rd the record data (PKEY) for the name
4139  * @param signature the signature for the record data
4140  */
4141 static void
4142 process_zone_to_name_zkey(void *cls,
4143                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
4144                  struct GNUNET_TIME_Absolute expire,
4145                  const char *name,
4146                  unsigned int rd_len,
4147                  const struct GNUNET_NAMESTORE_RecordData *rd,
4148                  const struct GNUNET_CRYPTO_RsaSignature *signature)
4149 {
4150   struct ResolverHandle *rh = cls;
4151   struct NameShortenHandle *nsh = rh->proc_cls;
4152   struct GNUNET_CRYPTO_ShortHashAsciiEncoded enc;
4153   char new_name[MAX_DNS_NAME_LENGTH];
4154
4155   /* zkey not in our zone */
4156   if (name == NULL)
4157   {
4158     /**
4159      * In this case we have not given this PKEY a name (yet)
4160      * It is either just not in our zone or not even cached
4161      * Since we do not know at this point we will not try to shorten
4162      * because PKEY import will happen if the user follows the zkey
4163      * link.
4164      */
4165     GNUNET_CRYPTO_short_hash_to_enc ((struct GNUNET_CRYPTO_ShortHashCode*)rd,
4166                                      &enc);
4167     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4168                "No name found for zkey %s returning verbatim!\n", enc);
4169     if (strcmp(rh->name, "") != 0)
4170       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s.%s",
4171                       rh->name, enc, GNUNET_GNS_TLD_ZKEY);
4172     else
4173       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
4174                       enc, GNUNET_GNS_TLD_ZKEY);
4175
4176     strcpy (nsh->result, new_name);
4177
4178     finish_shorten (rh, nsh);
4179     return;
4180   }
4181   
4182   if (strcmp(rh->name, "") != 0)
4183     GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
4184                     rh->name, name);
4185   else
4186     strcpy(new_name, name);
4187
4188   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4189              "Continue shorten for %s!\n", new_name);
4190
4191   strcpy(rh->name, new_name);
4192   
4193   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
4194   rh->authority_chain_tail = rh->authority_chain_head;
4195   rh->authority_chain_head->zone = rh->authority;
4196   
4197   
4198   /* Start delegation resolution in our namestore */
4199   resolve_delegation_ns (rh);
4200 }
4201
4202
4203 /**
4204  * Shorten api from resolver
4205  *
4206  * @param zone the root zone to use
4207  * @param pzone the private zone to use
4208  * @param szone the shorten zone to use
4209  * @param name the name to shorten
4210  * @param private_zone_name name of the private zone
4211  * @param shorten_zone_name name of the shorten zone
4212  * @param proc the processor to call with result
4213  * @param proc_cls closure to pass to proc
4214  */
4215 void
4216 gns_resolver_shorten_name (struct GNUNET_CRYPTO_ShortHashCode *zone,
4217                            struct GNUNET_CRYPTO_ShortHashCode *pzone,
4218                            struct GNUNET_CRYPTO_ShortHashCode *szone,
4219                            const char* name,
4220                            const char* private_zone_name,
4221                            const char* shorten_zone_name,
4222                            ShortenResultProcessor proc,
4223                            void* proc_cls)
4224 {
4225   struct ResolverHandle *rh;
4226   struct NameShortenHandle *nsh;
4227   char string_hash[MAX_DNS_LABEL_LENGTH];
4228   struct GNUNET_CRYPTO_ShortHashCode zkey;
4229   char nzkey[MAX_DNS_LABEL_LENGTH];
4230   char* nzkey_ptr = nzkey;
4231
4232
4233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4234               "Starting shorten for %s!\n", name);
4235   
4236   if (is_canonical ((char*)name))
4237   {
4238     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4239                 "%s is canonical. Returning verbatim\n", name);
4240     proc (proc_cls, name);
4241     return;
4242   }
4243
4244   nsh = GNUNET_malloc (sizeof (struct NameShortenHandle));
4245
4246   nsh->proc = proc;
4247   nsh->proc_cls = proc_cls;
4248   nsh->root_zone = zone;
4249   nsh->private_zone = pzone;
4250   nsh->shorten_zone = szone;
4251   strcpy (nsh->private_zone_name, private_zone_name);
4252   strcpy (nsh->shorten_zone_name, shorten_zone_name);
4253   strcpy (nsh->result, name);
4254   
4255
4256   rh = GNUNET_malloc (sizeof (struct ResolverHandle));
4257   rh->authority = *zone;
4258   rh->id = rid++;
4259   rh->priv_key = NULL;
4260   rh->namestore_task = NULL;
4261   rh->proc = &handle_delegation_ns_shorten;
4262   rh->proc_cls = nsh;
4263   rh->id = rid++;
4264   rh->private_local_zone = *zone;
4265
4266   GNUNET_CONTAINER_DLL_insert (nsh_head, nsh_tail, rh);
4267   
4268   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4269                 "Checking for TLD...\n");
4270   if (is_zkey_tld (name) == GNUNET_YES)
4271   {
4272     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4273                 "TLD is zkey\n");
4274     /**
4275      * This is a zkey tld
4276      * build hash and use as initial authority
4277      * FIXME sscanf
4278      */
4279     memset (rh->name, 0,
4280             strlen (name)-strlen (GNUNET_GNS_TLD_ZKEY));
4281     memcpy (rh->name, name,
4282             strlen(name)-strlen (GNUNET_GNS_TLD_ZKEY) - 1);
4283     pop_tld (rh->name, string_hash);
4284
4285     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4286                 "ZKEY is %s!\n", string_hash);
4287     
4288     GNUNET_STRINGS_utf8_toupper (string_hash, &nzkey_ptr);
4289
4290     if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string (nzkey,
4291                                                            &zkey))
4292     {
4293       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4294                   "Cannot convert ZKEY %s to hash!\n", nzkey);
4295       GNUNET_free (rh);
4296       GNUNET_free (nsh);
4297       GNUNET_CONTAINER_DLL_remove (nsh_head, nsh_tail, rh);
4298       proc (proc_cls, name);
4299       return;
4300     }
4301
4302     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
4303                                    zone, //ours
4304                                    &zkey,
4305                                    &process_zone_to_name_zkey,
4306                                    rh);
4307     return;
4308
4309   }
4310   else
4311   {
4312     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4313                 "TLD is gnunet\n");
4314     /**
4315      * Presumably GNUNET tld
4316      */
4317     memset (rh->name, 0,
4318             strlen (name)-strlen (GNUNET_GNS_TLD));
4319     memcpy (rh->name, name,
4320             strlen (name)-strlen (GNUNET_GNS_TLD) - 1);
4321   }
4322
4323   rh->authority_chain_head = GNUNET_malloc (sizeof (struct AuthorityChain));
4324   rh->authority_chain_tail = rh->authority_chain_head;
4325   rh->authority_chain_head->zone = *zone;
4326   
4327   
4328   /* Start delegation resolution in our namestore */
4329   resolve_delegation_ns (rh);
4330 }
4331
4332 /*********** END NAME SHORTEN ********************/
4333
4334 static void
4335 finish_get_auth (struct ResolverHandle *rh,
4336                  struct GetNameAuthorityHandle *nah)
4337 {
4338   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4339              "Got authority result %s\n", nah->result);
4340   
4341   nah->proc(nah->proc_cls, nah->result);
4342   GNUNET_CONTAINER_DLL_remove (nah_head, nah_tail, rh);
4343   GNUNET_free(nah);
4344   free_resolver_handle(rh);
4345 }
4346
4347 /**
4348  * Process result from namestore delegation lookup
4349  * for get authority operation
4350  *
4351  * @param cls the client get auth handle
4352  * @param rh the resolver handle
4353  * @param rd_count number of results (0)
4354  * @param rd data (NULL)
4355  */
4356 void
4357 handle_delegation_result_ns_get_auth(void* cls,
4358                       struct ResolverHandle *rh,
4359                       uint32_t rd_count,
4360                       const struct GNUNET_NAMESTORE_RecordData *rd)
4361 {
4362   struct GetNameAuthorityHandle* nah;
4363   size_t answer_len;
4364
4365   nah = (struct GetNameAuthorityHandle*) rh->proc_cls;
4366   
4367   /**
4368    * At this point rh->name contains the part of the name
4369    * that we do not have a PKEY in our namestore to resolve.
4370    * The authority chain in the resolver handle is now
4371    * useful to backtrack if needed
4372    */
4373   
4374   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4375              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
4376
4377   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4378              "Building response!\n");
4379   if (is_canonical(rh->name))
4380   {
4381     /**
4382      * We successfully resolved the authority in the ns
4383      * FIXME for our purposes this is fine
4384      * but maybe we want to have an api that also looks
4385      * into the dht (i.e. option in message)
4386      **/
4387     if (strlen(rh->name) > strlen(nah->name))
4388     {
4389       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4390                  "Record name longer than original lookup name... odd!\n");
4391       //FIXME to sth here
4392     }
4393
4394     answer_len = strlen(nah->name) - strlen(rh->name)
4395       + strlen(GNUNET_GNS_TLD) + 1;
4396     memset(nah->result, 0, answer_len);
4397     strcpy(nah->result, nah->name + strlen(rh->name) + 1);
4398
4399     finish_get_auth (rh, nah);
4400   }
4401   else
4402   {
4403     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4404                "Unable to resolve authority for remaining %s!\n", rh->name);
4405     strcpy(nah->result, "");
4406     finish_get_auth (rh, nah);
4407   }
4408
4409
4410 }
4411
4412
4413 /**
4414  * Tries to resolve the authority for name
4415  * in our namestore
4416  *
4417  * @param zone the root zone to look up for
4418  * @param pzone the private local zone
4419  * @param name the name to lookup up
4420  * @param proc the processor to call when finished
4421  * @param proc_cls the closure to pass to the processor
4422  */
4423 void
4424 gns_resolver_get_authority(struct GNUNET_CRYPTO_ShortHashCode zone,
4425                            struct GNUNET_CRYPTO_ShortHashCode pzone,
4426                            const char* name,
4427                            GetAuthorityResultProcessor proc,
4428                            void* proc_cls)
4429 {
4430   struct ResolverHandle *rh;
4431   struct GetNameAuthorityHandle *nah;
4432
4433   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4434               "Starting authority resolution for %s!\n", name);
4435
4436   nah = GNUNET_malloc(sizeof (struct GetNameAuthorityHandle));
4437   rh = GNUNET_malloc(sizeof (struct ResolverHandle));
4438   rh->authority = zone;
4439   rh->id = rid++;
4440   rh->private_local_zone = pzone;
4441   rh->namestore_task = NULL;
4442
4443   GNUNET_CONTAINER_DLL_insert (nah_head, nah_tail, rh);
4444   
4445   if (strcmp(GNUNET_GNS_TLD, name) == 0)
4446   {
4447     strcpy(rh->name, "\0");
4448   }
4449   else
4450   {
4451     memset(rh->name, 0,
4452            strlen(name)-strlen(GNUNET_GNS_TLD));
4453     memcpy(rh->name, name,
4454            strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
4455   }
4456
4457   memset(nah->name, 0,
4458          strlen(name)+1);
4459   strcpy(nah->name, name);
4460   
4461   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
4462   rh->authority_chain_tail = rh->authority_chain_head;
4463   rh->authority_chain_head->zone = zone;
4464   rh->proc = &handle_delegation_result_ns_get_auth;
4465   rh->proc_cls = (void*)nah;
4466
4467   nah->proc = proc;
4468   nah->proc_cls = proc_cls;
4469   strcpy (nah->result, "");
4470
4471   /* Start delegation resolution in our namestore */
4472   resolve_delegation_ns(rh);
4473
4474 }
4475
4476 /******** END GET AUTHORITY *************/
4477
4478 /* end of gnunet-service-gns_resolver.c */