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