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