- next test
[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.gnunet  = 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_NONE,
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   rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
989
990   GNUNET_DHT_get_stop (rh->get_handle);
991   rh->get_handle = NULL;
992   rh->proc (rh->proc_cls, rh, 0, NULL);
993 }
994
995
996 /**
997  * Function called when we get a result from the dht
998  * for our record query
999  *
1000  * @param cls the request handle
1001  * @param exp lifetime
1002  * @param key the key the record was stored under
1003  * @param get_path get path
1004  * @param get_path_length get path length
1005  * @param put_path put path
1006  * @param put_path_length put path length
1007  * @param type the block type
1008  * @param size the size of the record
1009  * @param data the record data
1010  */
1011 static void
1012 process_record_result_dht (void* cls,
1013                            struct GNUNET_TIME_Absolute exp,
1014                            const struct GNUNET_HashCode * key,
1015                            const struct GNUNET_PeerIdentity *get_path,
1016                            unsigned int get_path_length,
1017                            const struct GNUNET_PeerIdentity *put_path,
1018                            unsigned int put_path_length,
1019                            enum GNUNET_BLOCK_Type type,
1020                            size_t size, const void *data)
1021 {
1022   struct ResolverHandle *rh;
1023   struct RecordLookupHandle *rlh;
1024   struct GNSNameRecordBlock *nrb;
1025   uint32_t num_records;
1026   char* name = NULL;
1027   char* rd_data = (char*)data;
1028   int i;
1029   int rd_size;
1030
1031   rh = (struct ResolverHandle *)cls;
1032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033               "GNS_PHASE_REC-%llu: got dht result (size=%d)\n", rh->id, size);
1034
1035   rlh = (struct RecordLookupHandle *) rh->proc_cls;
1036   nrb = (struct GNSNameRecordBlock*)data;
1037
1038   /* stop lookup and timeout task */
1039   GNUNET_DHT_get_stop (rh->get_handle);
1040   rh->get_handle = NULL;
1041
1042   if (rh->dht_heap_node != NULL)
1043   {
1044     GNUNET_CONTAINER_heap_remove_node (rh->dht_heap_node);
1045     rh->dht_heap_node = NULL;
1046   }
1047
1048   if (rh->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1049   {
1050     GNUNET_SCHEDULER_cancel (rh->timeout_task);
1051     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1052   }
1053
1054   rh->get_handle = NULL;
1055   name = (char*)&nrb[1];
1056   num_records = ntohl (nrb->rd_count);
1057   {
1058     struct GNUNET_NAMESTORE_RecordData rd[num_records];
1059     struct NamestoreBGTask *ns_heap_root;
1060     struct NamestoreBGTask *namestore_bg_task;
1061
1062     rd_data += strlen (name) + 1 + sizeof (struct GNSNameRecordBlock);
1063     rd_size = size - strlen (name) - 1 - sizeof (struct GNSNameRecordBlock);
1064
1065     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
1066                                                                rd_data,
1067                                                                num_records,
1068                                                                rd))
1069     {
1070       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1071                   "GNS_PHASE_REC-%llu: Error deserializing data!\n", rh->id);
1072       rh->proc (rh->proc_cls, rh, 0, NULL);
1073       return;
1074     }
1075
1076     for (i=0; i<num_records; i++)
1077     {
1078       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1079                   "GNS_PHASE_REC-%llu: Got name: %s (wanted %s)\n",
1080                   rh->id, name, rh->name);
1081       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082                   "GNS_PHASE_REC-%llu: Got type: %d (wanted %d)\n",
1083                   rh->id, rd[i].record_type, rlh->record_type);
1084       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1085                   "GNS_PHASE_REC-%llu: Got data length: %d\n",
1086                   rh->id, rd[i].data_size);
1087       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1088                   "GNS_PHASE_REC-%llu: Got flag %d\n",
1089                   rh->id, rd[i].flags);
1090
1091       if ((strcmp (name, rh->name) == 0) &&
1092           (rd[i].record_type == rlh->record_type))
1093       {
1094         rh->answered++;
1095       }
1096
1097     }
1098
1099     /**
1100      * FIXME check pubkey against existing key in namestore?
1101      * https://gnunet.org/bugs/view.php?id=2179
1102      */
1103     if (max_allowed_ns_tasks <=
1104         GNUNET_CONTAINER_heap_get_size (ns_task_heap))
1105     {
1106       ns_heap_root = GNUNET_CONTAINER_heap_remove_root (ns_task_heap);
1107       GNUNET_NAMESTORE_cancel (ns_heap_root->qe);
1108
1109       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1110                   "GNS_PHASE_REC-%llu: Replacing oldest background ns task\n",
1111                   rh->id);
1112     }
1113     
1114     /* Save to namestore */
1115     namestore_bg_task = GNUNET_malloc (sizeof (struct NamestoreBGTask));
1116     namestore_bg_task->qe = GNUNET_NAMESTORE_record_put (namestore_handle,
1117                                  &nrb->public_key,
1118                                  name,
1119                                  exp,
1120                                  num_records,
1121                                  rd,
1122                                  &nrb->signature,
1123                                  &on_namestore_record_put_result, //cont
1124                                  namestore_bg_task);
1125
1126     namestore_bg_task->node = GNUNET_CONTAINER_heap_insert (ns_task_heap,
1127                                   namestore_bg_task,
1128                                   GNUNET_TIME_absolute_get().abs_value);
1129
1130   
1131     if (0 < rh->answered)
1132      rh->proc (rh->proc_cls, rh, num_records, rd);
1133    else
1134      rh->proc (rh->proc_cls, rh, 0, NULL);
1135   }
1136
1137 }
1138
1139
1140 /**
1141  * Start DHT lookup for a (name -> query->record_type) record in
1142  * rh->authority's zone
1143  *
1144  * @param rh the pending gns query context
1145  */
1146 static void
1147 resolve_record_dht (struct ResolverHandle *rh)
1148 {
1149   uint32_t xquery;
1150   struct GNUNET_CRYPTO_ShortHashCode name_hash;
1151   struct GNUNET_HashCode lookup_key;
1152   struct GNUNET_HashCode name_hash_double;
1153   struct GNUNET_HashCode zone_hash_double;
1154   struct GNUNET_CRYPTO_HashAsciiEncoded lookup_key_string;
1155   struct RecordLookupHandle *rlh = rh->proc_cls;
1156   struct ResolverHandle *rh_heap_root;
1157
1158   GNUNET_CRYPTO_short_hash (rh->name, strlen (rh->name), &name_hash);
1159   GNUNET_CRYPTO_short_hash_double (&name_hash, &name_hash_double);
1160   GNUNET_CRYPTO_short_hash_double (&rh->authority, &zone_hash_double);
1161   GNUNET_CRYPTO_hash_xor (&name_hash_double, &zone_hash_double, &lookup_key);
1162   GNUNET_CRYPTO_hash_to_enc (&lookup_key, &lookup_key_string);
1163
1164   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1165               "GNS_PHASE_REC-%llu: starting dht lookup for %s with key: %s\n",
1166               rh->id, rh->name, (char*)&lookup_key_string);
1167
1168   //rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1169   rh->dht_heap_node = NULL;
1170
1171   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value != rh->timeout.rel_value)
1172   {
1173     /**
1174      * Update timeout if necessary
1175      */
1176     if (GNUNET_SCHEDULER_NO_TASK == rh->timeout_task)
1177     {
1178       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1179                   "GNS_PHASE_REC-%llu: Adjusting timeout\n", rh->id);
1180       /*
1181        * Set timeout for authority lookup phase to 1/2
1182        */
1183       rh->timeout_task = GNUNET_SCHEDULER_add_delayed (
1184                                    GNUNET_TIME_relative_divide (rh->timeout, 2),
1185                                    &handle_lookup_timeout,
1186                                    rh);
1187     }
1188     rh->timeout_cont = &dht_lookup_timeout;
1189     rh->timeout_cont_cls = rh;
1190   }
1191   else 
1192   {
1193     if (max_allowed_background_queries <=
1194         GNUNET_CONTAINER_heap_get_size (dht_lookup_heap))
1195     {
1196       rh_heap_root = GNUNET_CONTAINER_heap_remove_root (dht_lookup_heap);
1197       GNUNET_DHT_get_stop (rh_heap_root->get_handle);
1198       rh_heap_root->get_handle = NULL;
1199       rh_heap_root->dht_heap_node = NULL;
1200
1201       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1202                  "GNS_PHASE_REC-%llu: Replacing oldest background query for %s\n",
1203                  rh->id, rh_heap_root->name);
1204       rh_heap_root->proc (rh_heap_root->proc_cls,
1205                           rh_heap_root,
1206                           0,
1207                           NULL);
1208     }
1209     rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap,
1210                                          rh,
1211                                          GNUNET_TIME_absolute_get ().abs_value);
1212   }
1213
1214   xquery = htonl (rlh->record_type);
1215
1216   GNUNET_assert (rh->get_handle == NULL);
1217   rh->get_handle = GNUNET_DHT_get_start (dht_handle, 
1218                                          GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1219                                          &lookup_key,
1220                                          DHT_GNS_REPLICATION_LEVEL,
1221                                          GNUNET_DHT_RO_NONE,
1222                                          &xquery,
1223                                          sizeof (xquery),
1224                                          &process_record_result_dht,
1225                                          rh);
1226
1227 }
1228
1229
1230 /**
1231  * Namestore calls this function if we have record for this name.
1232  * (or with rd_count=0 to indicate no matches)
1233  *
1234  * @param cls the pending query
1235  * @param key the key of the zone we did the lookup
1236  * @param expiration expiration date of the namestore entry
1237  * @param name the name for which we need an authority
1238  * @param rd_count the number of records with 'name'
1239  * @param rd the record data
1240  * @param signature the signature of the authority for the record data
1241  */
1242 static void
1243 process_record_result_ns (void* cls,
1244                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1245                           struct GNUNET_TIME_Absolute expiration,
1246                           const char *name, unsigned int rd_count,
1247                           const struct GNUNET_NAMESTORE_RecordData *rd,
1248                           const struct GNUNET_CRYPTO_RsaSignature *signature)
1249 {
1250   struct ResolverHandle *rh;
1251   struct RecordLookupHandle *rlh;
1252   struct GNUNET_TIME_Relative remaining_time;
1253   struct GNUNET_CRYPTO_ShortHashCode zone;
1254   struct GNUNET_TIME_Absolute et;
1255   unsigned int i;
1256
1257   rh = cls;
1258   rlh = rh->proc_cls;
1259
1260   rh->namestore_task = NULL;
1261   GNUNET_CRYPTO_short_hash (key,
1262                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1263                         &zone);
1264   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
1265
1266
1267
1268   rh->status = 0;
1269
1270   if (NULL != name)
1271   {
1272     rh->status |= RSL_RECORD_EXISTS;
1273
1274     if (remaining_time.rel_value == 0)
1275     {
1276       rh->status |= RSL_RECORD_EXPIRED;
1277     }
1278   }
1279
1280   if (rd_count == 0)
1281   {
1282     /**
1283      * Lookup terminated and no results
1284      */
1285     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1286                "GNS_PHASE_REC-%llu: Namestore lookup for %s terminated without results\n",
1287                rh->id, name);
1288
1289     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1290                "GNS_PHASE_REC-%llu: Record %s unknown in namestore\n",
1291                rh->id, rh->name);
1292     /**
1293      * Our zone and no result? Cannot resolve TT
1294      */
1295     rh->proc(rh->proc_cls, rh, 0, NULL);
1296     return;
1297
1298   }
1299   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1300              "GNS_PHASE_REC-%llu: Processing additional result %s from namestore\n",
1301              rh->id, name);
1302   for (i=0; i<rd_count;i++)
1303   {
1304     if (rd[i].record_type != rlh->record_type)
1305       continue;
1306
1307     if (ignore_pending_records &&
1308         (rd[i].flags & GNUNET_NAMESTORE_RF_PENDING))
1309     {
1310       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1311                  "GNS_PHASE_REC-%llu: Record %s is awaiting user confirmation. Skipping\n",
1312                  rh->id, name);
1313       continue;
1314     }
1315     
1316     //FIXME: eh? do I have to handle this here?
1317     GNUNET_break (0 == (rd[i].flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
1318     et.abs_value = rd[i].expiration_time;
1319     if (0 == (GNUNET_TIME_absolute_get_remaining (et)).rel_value)
1320     {
1321       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1322                  "GNS_PHASE_REC-%llu: This record is expired. Skipping\n",
1323                  rh->id);
1324       continue;
1325     }
1326     rh->answered++;
1327   }
1328
1329   /**
1330    * no answers found
1331    */
1332   if (0 == rh->answered)
1333   {
1334     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
1335                "GNS_PHASE_REC-%llu: No answers found. This is odd!\n", rh->id);
1336     rh->proc(rh->proc_cls, rh, 0, NULL);
1337     return;
1338   }
1339
1340   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1341              "GNS_PHASE_REC-%llu: Found %d answer(s) to query in %d records!\n",
1342              rh->id, rh->answered, rd_count);
1343   rh->proc(rh->proc_cls, rh, rd_count, rd);
1344 }
1345
1346
1347 /**
1348  * VPN redirect result callback
1349  *
1350  * @param cls the resolver handle
1351  * @param af the requested address family
1352  * @param address in_addr(6) respectively
1353  */
1354 static void
1355 process_record_result_vpn (void* cls, int af, const void *address)
1356 {
1357   struct ResolverHandle *rh = cls;
1358   struct RecordLookupHandle *rlh;
1359   struct GNUNET_NAMESTORE_RecordData rd;
1360
1361   rlh = rh->proc_cls;
1362
1363   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1364              "GNS_PHASE_REC_VPN-%llu: Got answer from VPN to query!\n",
1365              rh->id);
1366   if (AF_INET == af)
1367   {
1368     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1369                "GNS_PHASE_REC-%llu: Answer is IPv4!\n",
1370                rh->id);
1371     if (GNUNET_GNS_RECORD_A != rlh->record_type)
1372     {
1373       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1374                  "GNS_PHASE_REC-%llu: Requested record is not IPv4!\n",
1375                  rh->id);
1376       rh->proc (rh->proc_cls, rh, 0, NULL);
1377       return;
1378     }
1379     rd.record_type = GNUNET_GNS_RECORD_A;
1380     rd.expiration_time = UINT64_MAX; /* FIXME: should probably pick something shorter... */
1381     rd.data = address;
1382     rd.data_size = sizeof (struct in_addr);
1383     rd.flags = 0;
1384     rh->proc (rh->proc_cls, rh, 1, &rd);
1385     return;
1386   }
1387   else if (AF_INET6 == af)
1388   {
1389     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1390                "GNS_PHASE_REC-%llu: Answer is IPv6!\n",
1391                rh->id);
1392     if (GNUNET_GNS_RECORD_AAAA != rlh->record_type)
1393     {
1394       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1395                  "GNS_PHASE_REC-%llu: Requested record is not IPv6!\n",
1396                  rh->id);
1397       rh->proc (rh->proc_cls, rh, 0, NULL);
1398       return;
1399     }
1400     rd.record_type = GNUNET_GNS_RECORD_AAAA;
1401     rd.expiration_time = UINT64_MAX; /* FIXME: should probably pick something shorter... */
1402     rd.data = address;
1403     rd.data_size = sizeof (struct in6_addr);
1404     rd.flags = 0;
1405     rh->proc (rh->proc_cls, rh, 1, &rd);
1406     return;
1407   }
1408
1409   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1410              "GNS_PHASE_REC-%llu: Got garbage from VPN!\n",
1411              rh->id);
1412   rh->proc (rh->proc_cls, rh, 0, NULL);
1413 }
1414
1415
1416
1417
1418 /**
1419  * Process VPN lookup result for record
1420  *
1421  * @param cls the record lookup handle
1422  * @param rh resolver handle
1423  * @param rd_count number of results (1)
1424  * @param rd record data containing the result
1425  */
1426 static void
1427 handle_record_vpn (void* cls, struct ResolverHandle *rh,
1428                    unsigned int rd_count,
1429                    const struct GNUNET_NAMESTORE_RecordData *rd)
1430 {
1431   struct RecordLookupHandle* rlh = cls;
1432   
1433   if (0 == rd_count)
1434   {
1435     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1436                "GNS_PHASE_REC_VPN-%llu: VPN returned no records. (status: %d)!\n",
1437                rh->id,
1438                rh->status);
1439     /* give up, cannot resolve */
1440     finish_lookup(rh, rlh, 0, NULL);
1441     return;
1442   }
1443
1444   /* results found yay */
1445   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1446              "GNS_PHASE_REC_VPN-%llu: Record resolved from VPN!", rh->id);
1447
1448   finish_lookup(rh, rlh, rd_count, rd);
1449 }
1450
1451
1452 /**
1453  * Sends a UDP dns query to a nameserver specified in the rh
1454  * 
1455  * @param rh the resolver handle
1456  */
1457 static void
1458 send_dns_packet (struct ResolverHandle *rh);
1459
1460
1461 static void
1462 handle_dns_resolver (void *cls,
1463                      const struct sockaddr *addr,
1464                      socklen_t addrlen)
1465 {
1466   struct ResolverHandle *rh = cls;
1467   struct RecordLookupHandle *rlh = rh->proc_cls;
1468   struct GNUNET_NAMESTORE_RecordData rd;
1469   struct sockaddr_in *sai;
1470   struct sockaddr_in6 *sai6;
1471
1472   if (NULL == addr)
1473   {
1474     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1475                 "No address found in DNS!\n");
1476     finish_lookup (rh, rlh, 0, NULL);
1477     return;
1478   }
1479   
1480   if (sizeof (struct sockaddr_in) == addrlen)
1481   {
1482     sai = (struct sockaddr_in*) addr;
1483     rd.record_type = GNUNET_GNS_RECORD_A;
1484     rd.data_size = sizeof (struct in_addr);
1485     rd.data = &sai->sin_addr;
1486   }
1487   else if (sizeof (struct sockaddr_in6) == addrlen)
1488   {
1489     sai6 = (struct sockaddr_in6*) addr;
1490     rd.record_type = GNUNET_GNS_RECORD_AAAA;
1491     rd.data_size = sizeof (struct in6_addr);
1492     rd.data = &sai6->sin6_addr;
1493   }
1494   else
1495   {
1496     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1497                 "Address length is garbage!\n");
1498     finish_lookup (rh, rlh, 0, NULL);
1499     return;
1500   }
1501   rd.expiration_time = UINT64_MAX; /* FIXME: should probably pick something shorter */
1502   rd.flags = 0;
1503   finish_lookup (rh, rlh, 1, &rd);
1504 }
1505
1506 /**
1507  * Resolve DNS name via local stub resolver
1508  *
1509  * @param rh the resolver handle
1510  */
1511 static void
1512 resolve_dns_name (struct ResolverHandle *rh)
1513 {
1514   struct RecordLookupHandle *rlh = rh->proc_cls;
1515   int af;
1516
1517   if ((GNUNET_GNS_RECORD_A != rlh->record_type) &&
1518       (GNUNET_GNS_RECORD_AAAA != rlh->record_type))
1519   {
1520     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1521                 "Can only resolve A/AAAA via stub... abort\n");
1522     finish_lookup (rh, rlh, 0, NULL);
1523     return;
1524   }
1525
1526   if (GNUNET_GNS_RECORD_A == rlh->record_type)
1527     af = AF_INET;
1528   else
1529     af = AF_INET6;
1530
1531   rh->dns_resolver_handle = GNUNET_RESOLVER_ip_get (rh->dns_name,
1532                                                     af,
1533                                                     rh->timeout,
1534                                                     &handle_dns_resolver,
1535                                                     rh);
1536 }
1537
1538
1539 /**
1540  * Read DNS udp packet from socket
1541  *
1542  * @param cls the resolver handle
1543  * @param tc task context
1544  */
1545 static void
1546 read_dns_response (void *cls,
1547                    const struct GNUNET_SCHEDULER_TaskContext *tc)
1548 {
1549   struct ResolverHandle *rh = cls;
1550   struct RecordLookupHandle *rlh = rh->proc_cls;
1551   char buf[UINT16_MAX];
1552   ssize_t r;
1553   struct sockaddr_in addr;
1554   socklen_t addrlen;
1555   struct GNUNET_DNSPARSER_Packet *packet;
1556   struct GNUNET_NAMESTORE_RecordData rd;
1557   int found_delegation = GNUNET_NO;
1558   int found_cname = GNUNET_NO;
1559   char* delegation_name = NULL;
1560   int zone_offset = 0;
1561   int i;
1562
1563   rh->dns_read_task = GNUNET_SCHEDULER_NO_TASK;
1564   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1565   {
1566     /* timeout or shutdown */
1567     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568                 "Terminating DNS query %d\n", tc->reason);
1569     finish_lookup (rh, rlh, 0, NULL);
1570     return;
1571   }
1572
1573   addrlen = sizeof (addr);
1574   r = GNUNET_NETWORK_socket_recvfrom (rh->dns_sock,
1575                                       buf, sizeof (buf),
1576                                       (struct sockaddr*) &addr,
1577                                       &addrlen);
1578
1579   if (-1 == r)
1580   {
1581     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "recvfrom");
1582     finish_lookup (rh, rlh, 0, NULL);
1583     return;
1584   }
1585
1586   packet = GNUNET_DNSPARSER_parse (buf, r);
1587   
1588   if (NULL == packet)
1589   {
1590     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1591                 "Failed to parse DNS reply!\n");
1592     finish_lookup (rh, rlh, 0, NULL);
1593     return;
1594   }
1595
1596   for (i = 0; i < packet->num_answers; i++)
1597   {
1598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599                "Got record type %d (want %d)\n",
1600                packet->answers[i].type,
1601                rlh->record_type);
1602     /* http://tools.ietf.org/html/rfc1034#section-3.6.2 */
1603     if (packet->answers[i].type == GNUNET_GNS_RECORD_CNAME)
1604     {
1605       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1606                   "CNAME... restarting query with %s\n",
1607                   packet->answers[i].data.hostname
1608                  );
1609       strcpy (rh->dns_name, packet->answers[i].data.hostname);
1610       found_cname = GNUNET_YES;
1611       continue;
1612     }
1613     
1614     if ((packet->answers[i].type == rlh->record_type) &&
1615         (0 == strcmp (packet->answers[i].name, rh->dns_name)))
1616     {
1617       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1618                   "Found record!\n");
1619       rd.data = packet->answers[i].data.raw.data;
1620       rd.data_size = packet->answers[i].data.raw.data_len;
1621       rd.record_type = packet->answers[i].type;
1622       rd.flags = 0;
1623       rd.expiration_time = packet->answers[i].expiration_time.abs_value;
1624       finish_lookup (rh, rlh, 1, &rd);
1625       GNUNET_DNSPARSER_free_packet (packet);
1626       return;
1627     }
1628   }
1629
1630   if (GNUNET_YES == found_cname)
1631   {
1632     zone_offset = strlen (rh->dns_name) - strlen (rh->dns_zone) - 1;
1633     
1634     if (0 > zone_offset)
1635       zone_offset = 0;
1636
1637     /* restart query with CNAME */
1638     if (0 == strcmp (rh->dns_name+zone_offset, rh->dns_zone))
1639     {
1640       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1641                   "Asking same server for %s\n", rh->dns_name);
1642       send_dns_packet (rh);
1643     }
1644     else
1645     {
1646       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1647                   "Trying system resolver for %s\n", rh->dns_name);
1648       resolve_dns_name (rh);
1649     }
1650
1651     GNUNET_DNSPARSER_free_packet (packet);
1652     return;
1653   }
1654
1655   for (i = 0; i < packet->num_authority_records; i++)
1656   {
1657     
1658     if (packet->authority_records[i].type == GNUNET_GNS_RECORD_NS)
1659     {
1660       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1661                   "Found NS delegation!\n");
1662       found_delegation = GNUNET_YES;
1663       delegation_name = packet->authority_records[i].data.hostname;
1664       break;
1665     }
1666   }
1667
1668   for (i = 0; i < packet->num_additional_records; i++)
1669   {
1670     if (GNUNET_NO == found_delegation)
1671       break;
1672
1673     if ((packet->additional_records[i].type == GNUNET_GNS_RECORD_A) &&
1674         (0 == strcmp (packet->additional_records[i].name, delegation_name)))
1675     {
1676       GNUNET_assert (sizeof (struct in_addr) ==
1677                      packet->authority_records[i].data.raw.data_len);
1678       
1679       rh->dns_addr.sin_addr =
1680         *((struct in_addr*)packet->authority_records[i].data.raw.data);
1681       send_dns_packet (rh);
1682       GNUNET_DNSPARSER_free_packet (packet);
1683       return;
1684     }
1685   }
1686
1687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1688               "Nothing useful in DNS reply!\n");
1689   finish_lookup (rh, rlh, 0, NULL);
1690   GNUNET_DNSPARSER_free_packet (packet);
1691   return;
1692 }
1693
1694 /**
1695  * Sends a UDP dns query to a nameserver specified in the rh
1696  * 
1697  * @param rh the request handle
1698  */
1699 static void
1700 send_dns_packet (struct ResolverHandle *rh)
1701 {
1702   struct GNUNET_NETWORK_FDSet *rset = GNUNET_NETWORK_fdset_create ();
1703   GNUNET_NETWORK_fdset_set (rset, rh->dns_sock);
1704
1705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1706               "Sending %dbyte DNS query\n",
1707               rh->dns_raw_packet_size);
1708   
1709   GNUNET_NETWORK_socket_sendto (rh->dns_sock,
1710                                 rh->dns_raw_packet,
1711                                 rh->dns_raw_packet_size,
1712                                 (struct sockaddr*)&rh->dns_addr,
1713                                 sizeof (struct sockaddr_in));
1714
1715   rh->dns_read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1716                                                     rh->timeout, //FIXME less?
1717                                                     rset,
1718                                                     NULL,
1719                                                     &read_dns_response,
1720                                                     rh);
1721
1722   GNUNET_NETWORK_fdset_destroy (rset);
1723
1724 }
1725
1726 /**
1727  * The final phase of resoution.
1728  * We found a NS RR and want to resolve via DNS
1729  *
1730  * @param rh the pending lookup handle
1731  * @param rd_count length of record data
1732  * @param rd record data containing VPN RR
1733  */
1734 static void
1735 resolve_record_dns (struct ResolverHandle *rh,
1736                     int rd_count,
1737                     const struct GNUNET_NAMESTORE_RecordData *rd)
1738 {
1739   struct GNUNET_DNSPARSER_Query query;
1740   struct GNUNET_DNSPARSER_Packet packet;
1741   struct GNUNET_DNSPARSER_Flags flags;
1742   struct in_addr dnsip;
1743   struct sockaddr_in addr;
1744   struct sockaddr *sa;
1745   int i;
1746   struct RecordLookupHandle *rlh = rh->proc_cls;
1747
1748   memset (&packet, 0, sizeof (struct GNUNET_DNSPARSER_Packet));
1749   
1750   /* We cancel here as to not include the ns lookup in the timeout */
1751   if (GNUNET_SCHEDULER_NO_TASK != rh->timeout_task)
1752   {
1753     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1754     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1755   }
1756   /* Start shortening */
1757   if ((NULL != rh->priv_key) &&
1758       (GNUNET_YES == is_canonical (rh->name)))
1759   {
1760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1761              "GNS_PHASE_REC_DNS-%llu: Trying to shorten authority chain\n",
1762              rh->id);
1763     start_shorten (rh->authority_chain_head,
1764                    rh->priv_key);
1765   }
1766
1767   for (i = 0; i < rd_count; i++)
1768   {
1769     /* Synthesize dns name */
1770     if (GNUNET_GNS_RECORD_NS == rd[i].record_type)
1771     {
1772       strcpy (rh->dns_zone, (char*)rd[i].data);
1773       if (0 == strcmp (rh->name, ""))
1774         strcpy (rh->dns_name, (char*)rd[i].data);
1775       else
1776         sprintf (rh->dns_name, "%s.%s", rh->name, (char*)rd[i].data);
1777     }
1778     /* The glue */
1779     if (GNUNET_GNS_RECORD_A == rd[i].record_type)
1780       dnsip = *((struct in_addr*)rd[i].data);
1781   }
1782   
1783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1784               "GNS_PHASE_REC_DNS-%llu: Looking up %s from %s\n",
1785               rh->id,
1786               rh->dns_name,
1787               inet_ntoa (dnsip));
1788   rh->dns_sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
1789   if (NULL == rh->dns_sock)
1790   {
1791     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1792                 "GNS_PHASE_REC_DNS-%llu: Error creating udp socket for dns!\n",
1793                 rh->id);
1794     finish_lookup (rh, rlh, 0, NULL);
1795     return;
1796   }
1797
1798   memset (&addr, 0, sizeof (struct sockaddr_in));
1799   sa = (struct sockaddr *) &addr;
1800   sa->sa_family = AF_INET;
1801   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (rh->dns_sock,
1802                                                sa,
1803                                                sizeof (struct sockaddr_in)))
1804   {
1805     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806                 "GNS_PHASE_REC_DNS-%llu: Error binding udp socket for dns!\n",
1807                 rh->id);
1808     finish_lookup (rh, rlh, 0, NULL);
1809     return;
1810   }
1811   query.name = rh->dns_name;
1812   query.type = rlh->record_type;
1813   query.class = GNUNET_DNSPARSER_CLASS_INTERNET;
1814   memset (&flags, 0, sizeof (flags));
1815   flags.recursion_desired = 1;
1816   flags.checking_disabled = 1;
1817   packet.queries = &query;
1818   packet.answers = NULL;
1819   packet.authority_records = NULL;
1820   packet.num_queries = 1;
1821   packet.num_answers = 0;
1822   packet.num_authority_records = 0;
1823   packet.num_additional_records = 0;
1824   packet.flags = flags;
1825   packet.id = rh->id;
1826   if (GNUNET_OK != GNUNET_DNSPARSER_pack (&packet,
1827                                           UINT16_MAX,
1828                                           &rh->dns_raw_packet,
1829                                           &rh->dns_raw_packet_size))
1830   {
1831     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1832                 "GNS_PHASE_REC_DNS-%llu: Creating raw dns packet!\n",
1833                 rh->id);
1834     GNUNET_NETWORK_socket_close (rh->dns_sock);
1835     finish_lookup (rh, rlh, 0, NULL);
1836     return;
1837   }
1838
1839   rh->dns_addr.sin_family = AF_INET;
1840   rh->dns_addr.sin_port = htons (53); //domain
1841   rh->dns_addr.sin_addr = dnsip;
1842 #if HAVE_SOCKADDR_IN_SIN_LEN
1843   rh->dns_addr.sin_len = (u_char) sizeof (struct sockaddr_in);
1844 #endif
1845
1846   send_dns_packet (rh);
1847 }
1848
1849
1850 /**
1851  * The final phase of resoution.
1852  * We found a VPN RR and want to request an IPv4/6 address
1853  *
1854  * @param rh the pending lookup handle
1855  * @param rd_count length of record data
1856  * @param rd record data containing VPN RR
1857  */
1858 static void
1859 resolve_record_vpn (struct ResolverHandle *rh,
1860                     int rd_count,
1861                     const struct GNUNET_NAMESTORE_RecordData *rd)
1862 {
1863   struct RecordLookupHandle *rlh = rh->proc_cls;
1864   struct GNUNET_HashCode serv_desc;
1865   struct vpn_data* vpn;
1866   int af;
1867   
1868   /* We cancel here as to not include the ns lookup in the timeout */
1869   if (GNUNET_SCHEDULER_NO_TASK != rh->timeout_task)
1870   {
1871     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1872     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1873   }
1874   /* Start shortening */
1875   if ((NULL != rh->priv_key) &&
1876       (GNUNET_YES == is_canonical (rh->name)))
1877   {
1878     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1879              "GNS_PHASE_REC_VPN-%llu: Trying to shorten authority chain\n",
1880              rh->id);
1881     start_shorten (rh->authority_chain_head,
1882                    rh->priv_key);
1883   }
1884
1885   vpn = (struct vpn_data*)rd->data;
1886
1887
1888   GNUNET_CRYPTO_hash ((char*)&vpn[1],
1889                       strlen ((char*)&vpn[1]) + 1,
1890                       &serv_desc);
1891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1892               "GNS_PHASE_REC_VPN-%llu: proto %hu peer %s!\n",
1893               rh->id,
1894               ntohs (vpn->proto),
1895               GNUNET_h2s (&vpn->peer));
1896
1897   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1898               "GNS_PHASE_REC_VPN-%llu: service %s -> %s!\n",
1899               rh->id,
1900               (char*)&vpn[1],
1901               GNUNET_h2s (&serv_desc));
1902   rh->proc = &handle_record_vpn;
1903   if (GNUNET_GNS_RECORD_A == rlh->record_type)
1904     af = AF_INET;
1905   else
1906     af = AF_INET6;
1907   if (NULL == vpn_handle)
1908   {
1909     vpn_handle = GNUNET_VPN_connect (cfg);
1910     if (NULL == vpn_handle)
1911     {
1912       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1913                   "GNS_PHASE_INIT: Error connecting to VPN!\n");
1914       finish_lookup (rh, rh->proc_cls, 0, NULL);
1915       return;
1916     }
1917   }
1918
1919   rh->vpn_handle = GNUNET_VPN_redirect_to_peer (vpn_handle,
1920                                                 af, ntohs (vpn->proto),
1921                                                 (struct GNUNET_PeerIdentity *)&vpn->peer,
1922                                                 &serv_desc,
1923                                                 GNUNET_NO, //nac
1924                                                 GNUNET_TIME_UNIT_FOREVER_ABS, //FIXME
1925                                                 &process_record_result_vpn,
1926                                                 rh);
1927
1928 }
1929
1930 /**
1931  * The final phase of resolution.
1932  * rh->name is a name that is canonical and we do not have a delegation.
1933  * Query namestore for this record
1934  *
1935  * @param rh the pending lookup handle
1936  */
1937 static void
1938 resolve_record_ns(struct ResolverHandle *rh)
1939 {
1940   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
1941   
1942   /* We cancel here as to not include the ns lookup in the timeout */
1943   if (GNUNET_SCHEDULER_NO_TASK != rh->timeout_task)
1944   {
1945     GNUNET_SCHEDULER_cancel(rh->timeout_task);
1946     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1947   }
1948   /* Start shortening */
1949   if ((NULL != rh->priv_key) &&
1950      (GNUNET_YES == is_canonical (rh->name)))
1951   {
1952     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953              "GNS_PHASE_REC-%llu: Trying to shorten authority chain\n",
1954              rh->id);
1955     start_shorten (rh->authority_chain_head,
1956                    rh->priv_key);
1957   }
1958   
1959   /**
1960    * Try to resolve this record in our namestore.
1961    * The name to resolve is now in rh->authority_name
1962    * since we tried to resolve it to an authority
1963    * and failed.
1964    **/
1965   rh->namestore_task = GNUNET_NAMESTORE_lookup_record(namestore_handle,
1966                                  &rh->authority,
1967                                  rh->name,
1968                                  rlh->record_type,
1969                                  &process_record_result_ns,
1970                                  rh);
1971 }
1972
1973
1974
1975 /**
1976  * Handle timeout for DHT requests
1977  *
1978  * @param cls the request handle as closure
1979  * @param tc the task context
1980  */
1981 static void
1982 dht_authority_lookup_timeout(void *cls,
1983                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1984 {
1985   struct ResolverHandle *rh = cls;
1986   struct RecordLookupHandle *rlh = rh->proc_cls;
1987   char new_name[MAX_DNS_NAME_LENGTH];
1988
1989   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1990          "GNS_PHASE_DELEGATE_DHT-%llu: dht lookup for query %s (%llus)timed out.\n",
1991          rh->id, rh->authority_name, rh->timeout.rel_value);
1992
1993   rh->status |= RSL_TIMED_OUT;
1994   rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1995   if (NULL != rh->get_handle)
1996     GNUNET_DHT_get_stop (rh->get_handle);
1997
1998   rh->get_handle = NULL;
1999   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
2000   {
2001     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2002                "GNS_PHASE_DELEGATE_DHT-%llu: Got shutdown\n",
2003                rh->id);
2004     rh->proc(rh->proc_cls, rh, 0, NULL);
2005     return;
2006   }
2007
2008   if (0 == strcmp(rh->name, ""))
2009   {
2010     /*
2011      * promote authority back to name and try to resolve record
2012      */
2013     strcpy(rh->name, rh->authority_name);
2014     rh->proc(rh->proc_cls, rh, 0, NULL);
2015     return;
2016   }
2017   
2018   /**
2019    * Start resolution in bg
2020    */
2021   GNUNET_assert (0 < GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH,
2022                   "%s.%s.%s", rh->name, rh->authority_name, GNUNET_GNS_TLD));
2023   
2024   strcpy(rh->name, new_name);
2025
2026   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2027         "GNS_PHASE_DELEGATE_DHT-%llu: Starting background query for %s type %d\n",
2028         rh->id, rh->name, rlh->record_type);
2029
2030   gns_resolver_lookup_record(rh->authority,
2031                              rh->private_local_zone,
2032                              rlh->record_type,
2033                              new_name,
2034                              NULL,
2035                              GNUNET_TIME_UNIT_FOREVER_REL,
2036                              GNUNET_NO,
2037                              &background_lookup_result_processor,
2038                              NULL);
2039
2040   rh->proc(rh->proc_cls, rh, 0, NULL);
2041 }
2042
2043 /* Prototype */
2044 static void resolve_delegation_dht(struct ResolverHandle *rh);
2045
2046 /* Prototype */
2047 static void resolve_delegation_ns(struct ResolverHandle *rh);
2048
2049
2050 /**
2051  * Namestore resolution for delegation finished. Processing result.
2052  *
2053  * @param cls the closure
2054  * @param rh resolver handle
2055  * @param rd_count number of results (always 0)
2056  * @param rd record data (always NULL)
2057  */
2058 static void
2059 handle_delegation_ns(void* cls, struct ResolverHandle *rh,
2060                           unsigned int rd_count,
2061                           const struct GNUNET_NAMESTORE_RecordData *rd);
2062
2063
2064 /**
2065  * This is a callback function that checks for key revocation
2066  *
2067  * @param cls the pending query
2068  * @param key the key of the zone we did the lookup
2069  * @param expiration expiration date of the record data set in the namestore
2070  * @param name the name for which we need an authority
2071  * @param rd_count the number of records with 'name'
2072  * @param rd the record data
2073  * @param signature the signature of the authority for the record data
2074  */
2075 static void
2076 process_pkey_revocation_result_ns (void *cls,
2077                     const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
2078                     struct GNUNET_TIME_Absolute expiration,
2079                     const char *name,
2080                     unsigned int rd_count,
2081                     const struct GNUNET_NAMESTORE_RecordData *rd,
2082                     const struct GNUNET_CRYPTO_RsaSignature *signature)
2083 {
2084   struct ResolverHandle *rh = cls;
2085   struct GNUNET_TIME_Relative remaining_time;
2086   int i;
2087   
2088   rh->namestore_task = NULL;
2089   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
2090   
2091   for (i = 0; i < rd_count; i++)
2092   {
2093     if (GNUNET_GNS_RECORD_REV == rd[i].record_type)
2094     {
2095       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2096                  "GNS_PHASE_DELEGATE_REV-%llu: Zone has been revoked.\n",
2097                  rh->id);
2098       rh->status |= RSL_PKEY_REVOKED;
2099       rh->proc (rh->proc_cls, rh, 0, NULL);
2100       return;
2101     }
2102   }
2103   
2104   if ((NULL == name) ||
2105       (0 == remaining_time.rel_value))
2106   {
2107     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2108           "GNS_PHASE_DELEGATE_REV-%llu: + Records don't exist or are expired.\n",
2109           rh->id, name);
2110
2111     if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value != rh->timeout.rel_value)
2112     {
2113       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2114         "GNS_PHASE_DELEGATE_REV-%llu: Starting background lookup for %s type %d\n",
2115         rh->id, "+.gnunet", GNUNET_GNS_RECORD_REV);
2116
2117       gns_resolver_lookup_record(rh->authority,
2118                                  rh->private_local_zone,
2119                                  GNUNET_GNS_RECORD_REV,
2120                                  GNUNET_GNS_TLD,
2121                                  NULL,
2122                                  GNUNET_TIME_UNIT_FOREVER_REL,
2123                                  GNUNET_NO,
2124                                  &background_lookup_result_processor,
2125                                  NULL);
2126     }
2127   }
2128  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2129              "GNS_PHASE_DELEGATE_REV-%llu: Revocation check passed\n",
2130              rh->id);
2131   /**
2132    * We are done with PKEY resolution if name is empty
2133    * else resolve again with new authority
2134    */
2135   if (strcmp (rh->name, "") == 0)
2136     rh->proc (rh->proc_cls, rh, rh->rd_count, &rh->rd);
2137   else
2138     resolve_delegation_ns (rh);
2139 }
2140
2141
2142 /**
2143  * Callback when record data is put into namestore
2144  *
2145  * @param cls the closure
2146  * @param success GNUNET_OK on success
2147  * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
2148  */
2149 void
2150 on_namestore_delegation_put_result(void *cls,
2151                                    int32_t success,
2152                                    const char *emsg)
2153 {
2154   struct NamestoreBGTask *nbg = cls;
2155
2156   GNUNET_CONTAINER_heap_remove_node (nbg->node);
2157   GNUNET_free (nbg);
2158
2159   if (GNUNET_NO == success)
2160   {
2161     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2162                "GNS_NS: records already in namestore\n");
2163     return;
2164   }
2165   else if (GNUNET_YES == success)
2166   {
2167     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2168                "GNS_NS: records successfully put in namestore\n");
2169     return;
2170   }
2171
2172   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2173              "GNS_NS: Error putting records into namestore: %s\n", emsg);
2174 }
2175
2176 /**
2177  * Function called when we get a result from the dht
2178  * for our query. Recursively tries to resolve authorities
2179  * for name in DHT.
2180  *
2181  * @param cls the request handle
2182  * @param exp lifetime
2183  * @param key the key the record was stored under
2184  * @param get_path get path
2185  * @param get_path_length get path length
2186  * @param put_path put path
2187  * @param put_path_length put path length
2188  * @param type the block type
2189  * @param size the size of the record
2190  * @param data the record data
2191  */
2192 static void
2193 process_delegation_result_dht(void* cls,
2194                  struct GNUNET_TIME_Absolute exp,
2195                  const struct GNUNET_HashCode * key,
2196                  const struct GNUNET_PeerIdentity *get_path,
2197                  unsigned int get_path_length,
2198                  const struct GNUNET_PeerIdentity *put_path,
2199                  unsigned int put_path_length,
2200                  enum GNUNET_BLOCK_Type type,
2201                  size_t size, const void *data)
2202 {
2203   struct ResolverHandle *rh = cls;
2204   struct GNSNameRecordBlock *nrb;
2205   uint32_t num_records;
2206   char* name = NULL;
2207   char* rd_data = (char*) data;
2208   int i;
2209   int rd_size;
2210   struct GNUNET_CRYPTO_ShortHashCode zone, name_hash;
2211   struct GNUNET_HashCode zone_hash_double, name_hash_double;
2212
2213   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2214              "GNS_PHASE_DELEGATE_DHT-%llu: Got DHT result\n", rh->id);
2215
2216   if (data == NULL)
2217     return;
2218   
2219   nrb = (struct GNSNameRecordBlock*)data;
2220   
2221   /* stop dht lookup and timeout task */
2222   GNUNET_DHT_get_stop (rh->get_handle);
2223   rh->get_handle = NULL;
2224   if (rh->dht_heap_node != NULL)
2225   {
2226     GNUNET_CONTAINER_heap_remove_node(rh->dht_heap_node);
2227     rh->dht_heap_node = NULL;
2228   }
2229
2230   num_records = ntohl(nrb->rd_count);
2231   name = (char*)&nrb[1];
2232   {
2233     struct GNUNET_NAMESTORE_RecordData rd[num_records];
2234     struct NamestoreBGTask *ns_heap_root;
2235     struct NamestoreBGTask *namestore_bg_task;
2236     
2237     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
2238     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
2239     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
2240                                                                rd_data,
2241                                                                num_records,
2242                                                                rd))
2243     {
2244       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2245                  "GNS_PHASE_DELEGATE_DHT-%llu: Error deserializing data!\n",
2246                  rh->id);
2247       return;
2248     }
2249
2250     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2251                "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2252                rh->id, name, rh->authority_name);
2253     for (i=0; i<num_records; i++)
2254     {
2255     
2256       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2257                 "GNS_PHASE_DELEGATE_DHT-%llu: Got name: %s (wanted %s)\n",
2258                 rh->id, name, rh->authority_name);
2259       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2260                  "GNS_PHASE_DELEGATE_DHT-%llu: Got type: %d (wanted %d)\n",
2261                  rh->id, rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
2262       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2263                  "GNS_PHASE_DELEGATE_DHT-%llu: Got data length: %d\n",
2264                  rh->id, rd[i].data_size);
2265       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2266                  "GNS_PHASE_DELEGATE_DHT-%llu: Got flag %d\n",
2267                  rh->id, rd[i].flags);
2268       
2269       if ((GNUNET_GNS_RECORD_VPN == rd[i].record_type) ||
2270           (GNUNET_GNS_RECORD_NS == rd[i].record_type) ||
2271           (GNUNET_GNS_RECORD_CNAME == rd[i].record_type))
2272       {
2273         /**
2274          * This is a VPN,NS,CNAME entry. Let namestore handle this after caching
2275          */
2276         if (0 == strcmp(rh->name, ""))
2277           strcpy(rh->name, rh->authority_name);
2278         else
2279           GNUNET_snprintf(rh->name, MAX_DNS_NAME_LENGTH, "%s.%s",
2280                  rh->name, rh->authority_name); //FIXME ret
2281         rh->answered = 1;
2282         break;
2283       }
2284
2285       if ((0 == strcmp(name, rh->authority_name)) &&
2286           (GNUNET_GNS_RECORD_PKEY == rd[i].record_type))
2287       {
2288         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2289                    "GNS_PHASE_DELEGATE_DHT-%llu: Authority found in DHT\n",
2290                    rh->id);
2291         rh->answered = 1;
2292         memcpy(&rh->authority, rd[i].data, sizeof(struct GNUNET_CRYPTO_ShortHashCode));
2293         struct AuthorityChain *auth =
2294           GNUNET_malloc(sizeof(struct AuthorityChain));
2295         auth->zone = rh->authority;
2296         memset(auth->name, 0, strlen(rh->authority_name)+1);
2297         strcpy(auth->name, rh->authority_name);
2298         GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
2299                                      rh->authority_chain_tail,
2300                                      auth);
2301
2302         if (NULL != rh->rd.data)
2303           GNUNET_free ((void*)rh->rd.data);
2304         
2305         memcpy (&rh->rd, &rd[i], sizeof (struct GNUNET_NAMESTORE_RecordData));
2306         rh->rd.data = GNUNET_malloc (rd[i].data_size);
2307         memcpy ((void*)(rh->rd.data), rd[i].data, rd[i].data_size);
2308         rh->rd_count = 1;
2309
2310         /** try to import pkey if private key available */
2311         //if (rh->priv_key && is_canonical (rh->name))
2312         //  process_discovered_authority(name, auth->zone,
2313         //                               rh->authority_chain_tail->zone,
2314         //                               rh->priv_key);
2315       }
2316
2317     }
2318
2319
2320     GNUNET_CRYPTO_short_hash(name, strlen(name), &name_hash);
2321     GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2322     GNUNET_CRYPTO_hash_xor(key, &name_hash_double, &zone_hash_double);
2323     GNUNET_CRYPTO_short_hash_from_truncation (&zone_hash_double, &zone);
2324
2325     /* Save to namestore */
2326     if (0 != GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_tail->zone,
2327                                           &zone))
2328     {
2329       if (max_allowed_ns_tasks <=
2330           GNUNET_CONTAINER_heap_get_size (ns_task_heap))
2331       {
2332         ns_heap_root = GNUNET_CONTAINER_heap_remove_root (ns_task_heap);
2333         GNUNET_NAMESTORE_cancel (ns_heap_root->qe);
2334
2335         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2336                    "GNS_PHASE_REC-%llu: Replacing oldest background ns task\n",
2337                    rh->id);
2338       }
2339       
2340       namestore_bg_task = GNUNET_malloc (sizeof (struct NamestoreBGTask));
2341
2342       namestore_bg_task->node = GNUNET_CONTAINER_heap_insert (ns_task_heap,
2343                                     namestore_bg_task,
2344                                     GNUNET_TIME_absolute_get().abs_value);
2345       namestore_bg_task->qe = GNUNET_NAMESTORE_record_put (namestore_handle,
2346                                  &nrb->public_key,
2347                                  name,
2348                                  exp,
2349                                  num_records,
2350                                  rd,
2351                                  &nrb->signature,
2352                                  &on_namestore_delegation_put_result, //cont
2353                                  namestore_bg_task); //cls
2354     }
2355   }
2356
2357   if (0 != rh->answered)
2358   {
2359     rh->answered = 0;
2360     /**
2361      * delegate
2362      * FIXME in this case. should we ask namestore again?
2363      */
2364     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2365     "GNS_PHASE_DELEGATE_DHT-%llu: Answer from DHT for %s. Yet to resolve: %s\n",
2366     rh->id, rh->authority_name, rh->name);
2367
2368     if (0 == strcmp(rh->name, ""))
2369     {
2370       /* Start shortening */
2371       if ((NULL != rh->priv_key) &&
2372           (GNUNET_YES == is_canonical (rh->name)))
2373       {
2374         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2375              "GNS_PHASE_DELEGATE_DHT-%llu: Trying to shorten authority chain\n",
2376              rh->id);
2377         start_shorten (rh->authority_chain_head,
2378                        rh->priv_key);
2379       }
2380     }
2381     else
2382       rh->proc = &handle_delegation_ns;
2383
2384
2385     /* Check for key revocation and delegate */
2386     rh->namestore_task = GNUNET_NAMESTORE_lookup_record (namestore_handle,
2387                                     &rh->authority,
2388                                     "+",
2389                                     GNUNET_GNS_RECORD_REV,
2390                                     &process_pkey_revocation_result_ns,
2391                                     rh);
2392
2393     return;
2394   }
2395   
2396   /**
2397    * No pkey but name exists
2398    * promote back
2399    */
2400   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2401              "GNS_PHASE_DELEGATE_DHT-%llu: Adding %s back to %s\n",
2402              rh->id, rh->authority_name, rh->name);
2403   if (0 == strcmp(rh->name, ""))
2404     strcpy(rh->name, rh->authority_name);
2405   else
2406     GNUNET_snprintf(rh->name, MAX_DNS_NAME_LENGTH, "%s.%s",
2407                   rh->name, rh->authority_name); //FIXME ret
2408   
2409   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2410              "GNS_PHASE_DELEGATE_DHT-%llu: %s restored\n", rh->id, rh->name);
2411   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2412           "GNS_PHASE_DELEGATE_DHT-%llu: DHT authority lookup found no match!\n",
2413            rh->id);
2414   rh->proc(rh->proc_cls, rh, 0, NULL);
2415 }
2416
2417 //FIXME maybe define somewhere else?
2418 #define MAX_SOA_LENGTH sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)\
2419                         +(MAX_DNS_NAME_LENGTH*2)
2420 #define MAX_MX_LENGTH sizeof(uint16_t)+MAX_DNS_NAME_LENGTH
2421 #define MAX_SRV_LENGTH (sizeof(uint16_t)*3)+MAX_DNS_NAME_LENGTH
2422
2423
2424 static void
2425 expand_plus(char* dest, char* src, char* repl)
2426 {
2427   char* pos;
2428   unsigned int s_len = strlen(src)+1;
2429
2430   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2431              "GNS_POSTPROCESS: Got %s to expand with %s\n", src, repl);
2432   //Eh? I guess this is at least strlen ('x.+') == 3 FIXME
2433   if (3 > s_len)
2434   {
2435     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2436                "GNS_POSTPROCESS: %s too short\n", src);
2437
2438     /* no postprocessing */
2439     memcpy(dest, src, s_len+1);
2440     return;
2441   }
2442   
2443   if (0 == strcmp(src+s_len-3, ".+"))
2444   {
2445     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2446                "GNS_POSTPROCESS: Expanding .+ in %s\n", src);
2447     memset(dest, 0, s_len+strlen(repl)+strlen(GNUNET_GNS_TLD));
2448     strcpy(dest, src);
2449     pos = dest+s_len-2;
2450     strcpy(pos, repl);
2451     pos += strlen(repl);
2452     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2453                "GNS_POSTPROCESS: Expanded to %s\n", dest);
2454   }
2455   else
2456   {
2457     memcpy(dest, src, s_len+1);
2458   }
2459 }
2460
2461 /**
2462  * finish lookup
2463  */
2464 static void
2465 finish_lookup (struct ResolverHandle *rh,
2466                struct RecordLookupHandle* rlh,
2467                unsigned int rd_count,
2468                const struct GNUNET_NAMESTORE_RecordData *rd)
2469 {
2470   int i;
2471   char new_rr_data[MAX_DNS_NAME_LENGTH];
2472   char new_mx_data[MAX_MX_LENGTH];
2473   char new_soa_data[MAX_SOA_LENGTH];
2474   char new_srv_data[MAX_SRV_LENGTH];
2475   struct srv_data *old_srv;
2476   struct srv_data *new_srv;
2477   struct soa_data *old_soa;
2478   struct soa_data *new_soa;
2479   struct GNUNET_NAMESTORE_RecordData p_rd[rd_count];
2480   char* repl_string;
2481   char* pos;
2482   unsigned int offset;
2483
2484   if (GNUNET_SCHEDULER_NO_TASK != rh->timeout_task)
2485   {
2486     GNUNET_SCHEDULER_cancel(rh->timeout_task);
2487     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2488   }
2489
2490   GNUNET_CONTAINER_DLL_remove (rlh_head, rlh_tail, rh);
2491
2492   if (0 < rd_count)
2493     memcpy(p_rd, rd, rd_count*sizeof(struct GNUNET_NAMESTORE_RecordData));
2494
2495   for (i = 0; i < rd_count; i++)
2496   {
2497     
2498     if ((GNUNET_GNS_RECORD_NS != rd[i].record_type) &&
2499         (GNUNET_GNS_RECORD_PTR != rd[i].record_type) &&
2500         (GNUNET_GNS_RECORD_CNAME != rd[i].record_type) &&
2501         (GNUNET_GNS_RECORD_MX != rd[i].record_type) &&
2502         (GNUNET_GNS_RECORD_SOA != rd[i].record_type) &&
2503         (GNUNET_GNS_RECORD_SRV != rd[i].record_type))
2504     {
2505       p_rd[i].data = rd[i].data;
2506       continue;
2507     }
2508
2509     /**
2510      * for all those records we 'should'
2511      * also try to resolve the A/AAAA records (RFC1035)
2512      * This is a feature and not important
2513      */
2514     
2515     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2516                "GNS_POSTPROCESS: Postprocessing\n");
2517     if (0 == strcmp(rh->name, "+"))
2518       repl_string = rlh->name;
2519     else
2520       repl_string = rlh->name+strlen(rh->name)+1;
2521
2522     offset = 0;
2523     if (GNUNET_GNS_RECORD_MX == rd[i].record_type)
2524     {
2525       memcpy (new_mx_data, (char*)rd[i].data, sizeof(uint16_t));
2526       offset = sizeof(uint16_t);
2527       pos = new_mx_data+offset;
2528       expand_plus(pos, (char*)rd[i].data+sizeof(uint16_t),
2529                   repl_string);
2530       offset += strlen(new_mx_data+sizeof(uint16_t))+1;
2531       p_rd[i].data = new_mx_data;
2532       p_rd[i].data_size = offset;
2533     }
2534     else if (GNUNET_GNS_RECORD_SRV == rd[i].record_type)
2535     {
2536       /*
2537        * Prio, weight and port
2538        */
2539       new_srv = (struct srv_data*)new_srv_data;
2540       old_srv = (struct srv_data*)rd[i].data;
2541       new_srv->prio = old_srv->prio;
2542       new_srv->weight = old_srv->weight;
2543       new_srv->port = old_srv->port;
2544       expand_plus((char*)&new_srv[1], (char*)&old_srv[1],
2545                   repl_string);
2546       p_rd[i].data = new_srv_data;
2547       p_rd[i].data_size = sizeof (struct srv_data) + strlen ((char*)&new_srv[1]) + 1;
2548     }
2549     else if (GNUNET_GNS_RECORD_SOA == rd[i].record_type)
2550     {
2551       /* expand mname and rname */
2552       old_soa = (struct soa_data*)rd[i].data;
2553       new_soa = (struct soa_data*)new_soa_data;
2554       memcpy (new_soa, old_soa, sizeof (struct soa_data));
2555       expand_plus((char*)&new_soa[1], (char*)&old_soa[1], repl_string);
2556       offset = strlen ((char*)&new_soa[1]) + 1;
2557       expand_plus((char*)&new_soa[1] + offset,
2558                   (char*)&old_soa[1] + strlen ((char*)&old_soa[1]) + 1,
2559                   repl_string);
2560       p_rd[i].data_size = sizeof (struct soa_data)
2561                           + offset
2562                           + strlen ((char*)&new_soa[1] + offset);
2563       p_rd[i].data = new_soa_data;
2564     }
2565     else
2566     {
2567       pos = new_rr_data;
2568       expand_plus(pos, (char*)rd[i].data, repl_string);
2569       p_rd[i].data_size = strlen(new_rr_data)+1;
2570       p_rd[i].data = new_rr_data;
2571     }
2572     
2573   }
2574
2575   rlh->proc(rlh->proc_cls, rd_count, p_rd);
2576   GNUNET_free(rlh);
2577   free_resolver_handle (rh);
2578 }
2579
2580 /**
2581  * Process DHT lookup result for record.
2582  *
2583  * @param cls the closure
2584  * @param rh resolver handle
2585  * @param rd_count number of results
2586  * @param rd record data
2587  */
2588 static void
2589 handle_record_dht(void* cls, struct ResolverHandle *rh,
2590                        unsigned int rd_count,
2591                        const struct GNUNET_NAMESTORE_RecordData *rd)
2592 {
2593   struct RecordLookupHandle* rlh = cls;
2594
2595   if (0 == rd_count)
2596   {
2597     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2598                "GNS_PHASE_REC-%llu: No records for %s found in DHT. Aborting\n",
2599                rh->id, rh->name);
2600     /* give up, cannot resolve */
2601     finish_lookup(rh, rlh, 0, NULL);
2602     return;
2603   }
2604   /* results found yay */
2605   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2606              "GNS_PHASE_REC-%llu: Record resolved from DHT!", rh->id);
2607   finish_lookup(rh, rlh, rd_count, rd);
2608 }
2609
2610
2611
2612
2613 /**
2614  * Process namestore lookup result for record.
2615  *
2616  * @param cls the closure
2617  * @param rh resolver handle
2618  * @param rd_count number of results
2619  * @param rd record data
2620  */
2621 static void
2622 handle_record_ns (void* cls, struct ResolverHandle *rh,
2623                   unsigned int rd_count,
2624                   const struct GNUNET_NAMESTORE_RecordData *rd)
2625 {
2626   struct RecordLookupHandle* rlh = cls;
2627   int check_dht = GNUNET_YES;
2628   
2629   if (0 != rd_count)
2630   {
2631     /* results found yay */
2632     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2633                "GNS_PHASE_REC-%llu: Record resolved from namestore!\n", rh->id);
2634     finish_lookup(rh, rlh, rd_count, rd);
2635     return;
2636   }
2637   
2638   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2639              "GNS_PHASE_REC-%llu: NS returned no records. (status: %d)!\n",
2640              rh->id,
2641              rh->status);
2642   /**
2643    * There are 5 conditions that have to met for us to consult the DHT:
2644    * 1. The entry in the DHT is RSL_RECORD_EXPIRED OR
2645    * 2. No entry in the NS existed AND
2646    * 3. The zone queried is not the local resolver's zone AND
2647    * 4. The name that was looked up is '+'
2648    *    because if it was any other canonical name we either already queried
2649    *    the DHT for the authority in the authority lookup phase (and thus
2650    *    would already have an entry in the NS for the record)
2651    * 5. We are not in cache only mode
2652    */
2653   if ((0 != (rh->status & RSL_RECORD_EXPIRED)) &&
2654       (0 == (rh->status & RSL_RECORD_EXISTS)) )
2655     check_dht = GNUNET_NO;
2656   
2657   if (0 != GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
2658                                         &rh->private_local_zone))
2659     check_dht = GNUNET_NO;
2660   
2661   if ((0 != strcmp (rh->name, "+")) && (GNUNET_YES == is_srv (rh->name)))
2662       check_dht = GNUNET_NO;
2663
2664   if (GNUNET_YES == rh->only_cached)
2665     check_dht = GNUNET_NO;
2666   
2667   if (GNUNET_YES == check_dht)
2668   {
2669     rh->proc = &handle_record_dht;
2670     resolve_record_dht(rh);
2671     return;
2672   }
2673   /* give up, cannot resolve */
2674   finish_lookup(rh, rlh, 0, NULL);
2675 }
2676
2677
2678 /**
2679  * Move one level up in the domain hierarchy and return the
2680  * passed top level domain.
2681  *
2682  * @param name the domain
2683  * @param dest the destination where the tld will be put
2684  */
2685 void
2686 pop_tld(char* name, char* dest)
2687 {
2688   uint32_t len;
2689
2690   if (GNUNET_YES == is_canonical (name))
2691   {
2692     strcpy(dest, name);
2693     strcpy(name, "");
2694     return;
2695   }
2696
2697   for (len = strlen(name); 0 < len; len--)
2698   {
2699     if (*(name+len) == '.')
2700       break;
2701   }
2702   
2703   //Was canonical?
2704   if (0 == len)
2705     return;
2706
2707   name[len] = '\0';
2708
2709   strcpy(dest, (name+len+1));
2710 }
2711
2712 /**
2713  * Checks if name is in tld
2714  *
2715  * @param name the name to check
2716  * @param tld the TLD to check for
2717  * @return GNUNET_YES or GNUNET_NO
2718  */
2719 int
2720 is_tld(const char* name, const char* tld)
2721 {
2722   int offset = 0;
2723
2724   if (strlen(name) <= strlen(tld))
2725     return GNUNET_NO;
2726   
2727   offset = strlen(name)-strlen(tld);
2728   if (0 != strcmp(name+offset, tld))
2729   {
2730     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2731                "%s is not in .%s TLD\n", name, tld);
2732     return GNUNET_NO;
2733   }
2734   return GNUNET_YES;
2735 }
2736
2737 /**
2738  * DHT resolution for delegation finished. Processing result.
2739  *
2740  * @param cls the closure
2741  * @param rh resolver handle
2742  * @param rd_count number of results (always 0)
2743  * @param rd record data (always NULL)
2744  */
2745 static void
2746 handle_delegation_dht(void* cls, struct ResolverHandle *rh,
2747                           unsigned int rd_count,
2748                           const struct GNUNET_NAMESTORE_RecordData *rd)
2749 {
2750   struct RecordLookupHandle* rlh;
2751   rlh = cls;
2752   
2753
2754   if (0 == strcmp(rh->name, ""))
2755   {
2756     if (GNUNET_GNS_RECORD_PKEY == rlh->record_type)
2757     {
2758       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2759                  "GNS_PHASE_DELEGATE_DHT-%llu: Resolved queried PKEY via DHT.\n",
2760                  rh->id);
2761       finish_lookup(rh, rlh, rd_count, rd);
2762       return;
2763     }
2764     /* We resolved full name for delegation. resolving record */
2765     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2766      "GNS_PHASE_DELEGATE_DHT-%llu: Resolved full name for delegation via DHT.\n",
2767      rh->id);
2768     strcpy(rh->name, "+\0");
2769     rh->proc = &handle_record_ns;
2770     resolve_record_ns(rh);
2771     return;
2772   }
2773
2774   /**
2775    * we still have some left
2776    **/
2777   if (GNUNET_YES == is_canonical (rh->name))
2778   {
2779     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2780              "GNS_PHASE_DELEGATE_DHT-%llu: Resolving canonical record %s in ns\n",
2781              rh->id,
2782              rh->name);
2783     rh->proc = &handle_record_ns;
2784     resolve_record_ns(rh);
2785     return;
2786   }
2787   /* give up, cannot resolve */
2788   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2789  "GNS_PHASE_DELEGATE_DHT-%llu: Cannot fully resolve delegation for %s via DHT!\n",
2790  rh->id, rh->name);
2791   finish_lookup(rh, rlh, 0, NULL);
2792 }
2793
2794
2795 /**
2796  * Start DHT lookup for a name -> PKEY (compare NS) record in
2797  * rh->authority's zone
2798  *
2799  * @param rh the pending gns query
2800  */
2801 static void
2802 resolve_delegation_dht(struct ResolverHandle *rh)
2803 {
2804   uint32_t xquery;
2805   struct GNUNET_CRYPTO_ShortHashCode name_hash;
2806   struct GNUNET_HashCode name_hash_double;
2807   struct GNUNET_HashCode zone_hash_double;
2808   struct GNUNET_HashCode lookup_key;
2809   struct ResolverHandle *rh_heap_root;
2810   
2811   pop_tld(rh->name, rh->authority_name);
2812
2813   //FIXME handle return values here
2814   GNUNET_CRYPTO_short_hash(rh->authority_name,
2815                      strlen(rh->authority_name),
2816                      &name_hash);
2817   GNUNET_CRYPTO_short_hash_double(&name_hash, &name_hash_double);
2818   GNUNET_CRYPTO_short_hash_double(&rh->authority, &zone_hash_double);
2819   GNUNET_CRYPTO_hash_xor(&name_hash_double, &zone_hash_double, &lookup_key);
2820   
2821   rh->dht_heap_node = NULL;
2822
2823   if (rh->timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
2824   {
2825     rh->timeout_cont = &dht_authority_lookup_timeout;
2826     rh->timeout_cont_cls = rh;
2827   }
2828   else 
2829   {
2830     if (max_allowed_background_queries <=
2831         GNUNET_CONTAINER_heap_get_size (dht_lookup_heap))
2832     {
2833       /* terminate oldest lookup */
2834       rh_heap_root = GNUNET_CONTAINER_heap_remove_root (dht_lookup_heap);
2835       GNUNET_DHT_get_stop (rh_heap_root->get_handle);
2836       rh_heap_root->get_handle = NULL;
2837       rh_heap_root->dht_heap_node = NULL;
2838       
2839       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2840         "GNS_PHASE_DELEGATE_DHT-%llu: Replacing oldest background query for %s\n",
2841         rh->id, rh_heap_root->authority_name);
2842       
2843       rh_heap_root->proc(rh_heap_root->proc_cls,
2844                          rh_heap_root,
2845                          0,
2846                          NULL);
2847     }
2848     rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap,
2849                                          rh,
2850                                          GNUNET_TIME_absolute_get().abs_value);
2851   }
2852   
2853   xquery = htonl(GNUNET_GNS_RECORD_PKEY);
2854   GNUNET_assert(rh->get_handle == NULL);
2855   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
2856                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
2857                        &lookup_key,
2858                        DHT_GNS_REPLICATION_LEVEL,
2859                        GNUNET_DHT_RO_NONE,
2860                        &xquery,
2861                        sizeof(xquery),
2862                        &process_delegation_result_dht,
2863                        rh);
2864 }
2865
2866
2867 /**
2868  * Namestore resolution for delegation finished. Processing result.
2869  *
2870  * @param cls the closure
2871  * @param rh resolver handle
2872  * @param rd_count number of results (always 0)
2873  * @param rd record data (always NULL)
2874  */
2875 static void
2876 handle_delegation_ns (void* cls, struct ResolverHandle *rh,
2877                       unsigned int rd_count,
2878                       const struct GNUNET_NAMESTORE_RecordData *rd)
2879 {
2880   struct RecordLookupHandle* rlh;
2881   rlh = cls;
2882   int check_dht = GNUNET_YES;
2883   int s_len = 0;
2884
2885   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2886              "GNS_PHASE_DELEGATE_NS-%llu: Resolution status: %d.\n",
2887              rh->id, rh->status);
2888
2889   if (rh->status & RSL_PKEY_REVOKED)
2890   {
2891     finish_lookup (rh, rlh, 0, NULL);
2892     return;
2893   }
2894   
2895   if (0 == strcmp(rh->name, ""))
2896   {
2897     
2898     /* We resolved full name for delegation. resolving record */
2899     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2900               "GNS_PHASE_DELEGATE_NS-%llu: Resolved full name for delegation.\n",
2901               rh->id);
2902     if (rh->status & RSL_CNAME_FOUND)
2903     {
2904       if (GNUNET_GNS_RECORD_CNAME == rlh->record_type)
2905       {
2906         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2907                   "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried CNAME in NS.\n",
2908                   rh->id);
2909         strcpy (rh->name, rh->authority_name);
2910         finish_lookup (rh, rlh, rd_count, rd);
2911         return;
2912       }
2913       
2914       /* A .+ CNAME  */
2915       if (GNUNET_YES == is_tld ((char*)rd->data, GNUNET_GNS_TLD_PLUS))
2916       {
2917         s_len = strlen (rd->data) - 2;
2918         memcpy (rh->name, rd->data, s_len);
2919         rh->name[s_len] = '\0';
2920         resolve_delegation_ns (rh);
2921         return;
2922       }
2923       else if (GNUNET_YES == is_tld ((char*)rd->data, GNUNET_GNS_TLD_ZKEY))
2924       {
2925         gns_resolver_lookup_record (rh->authority,
2926                                     rh->private_local_zone,
2927                                     rlh->record_type,
2928                                     (char*)rd->data,
2929                                     rh->priv_key,
2930                                     rh->timeout,
2931                                     rh->only_cached,
2932                                     rlh->proc,
2933                                     rlh->proc_cls);
2934         GNUNET_free (rlh);
2935         GNUNET_CONTAINER_DLL_remove (rlh_head, rlh_tail, rh);
2936         free_resolver_handle (rh);
2937         return;
2938       }
2939       else
2940       {
2941         //Try DNS resolver
2942         strcpy (rh->dns_name, (char*)rd->data);
2943         resolve_dns_name (rh);
2944         return;
2945       }
2946
2947     }
2948     else if (rh->status & RSL_DELEGATE_VPN)
2949     {
2950       if (GNUNET_GNS_RECORD_VPN == rlh->record_type)
2951       {
2952         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2953                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried VPNRR in NS.\n",
2954                  rh->id);
2955         finish_lookup(rh, rlh, rd_count, rd);
2956         return;
2957       }
2958       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2959              "GNS_PHASE_DELEGATE_NS-%llu: VPN delegation starting.\n",
2960              rh->id);
2961       GNUNET_assert (NULL != rd);
2962       rh->proc = &handle_record_vpn;
2963       resolve_record_vpn (rh, rd_count, rd);
2964       return;
2965     }
2966     else if (rh->status & RSL_DELEGATE_NS)
2967     {
2968       if (GNUNET_GNS_RECORD_NS == rlh->record_type)
2969       {
2970         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2971                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried NSRR in NS.\n",
2972                    rh->id);
2973         finish_lookup(rh, rlh, rd_count, rd);
2974         return;
2975       }
2976       
2977       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2978                  "GNS_PHASE_DELEGATE_NS-%llu: NS delegation starting.\n",
2979                  rh->id);
2980       GNUNET_assert (NULL != rd);
2981       rh->proc = &handle_record_ns;
2982       resolve_record_dns (rh, rd_count, rd);
2983       return;
2984     }
2985     else if (rh->status & RSL_DELEGATE_PKEY)
2986     {
2987       if (rh->status & RSL_PKEY_REVOKED)
2988       {
2989         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2990                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved PKEY is revoked.\n",
2991                    rh->id);
2992         finish_lookup (rh, rlh, 0, NULL);
2993         return;
2994       }
2995       else if (GNUNET_GNS_RECORD_PKEY == rlh->record_type)
2996       {
2997         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2998                    "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried PKEY in NS.\n",
2999                    rh->id);
3000         finish_lookup(rh, rlh, rd_count, rd);
3001         return;
3002       }
3003     }
3004     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3005                "GNS_PHASE_DELEGATE_NS-%llu: Resolving record +\n",
3006                rh->id);
3007     strcpy(rh->name, "+\0");
3008     rh->proc = &handle_record_ns;
3009     resolve_record_ns(rh);
3010     return;
3011   }
3012   
3013   if (rh->status & RSL_DELEGATE_NS)
3014   {
3015     if (GNUNET_GNS_RECORD_NS == rlh->record_type)
3016     {
3017       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3018                  "GNS_PHASE_DELEGATE_NS-%llu: Resolved queried NSRR in NS.\n",
3019                  rh->id);
3020       finish_lookup(rh, rlh, rd_count, rd);
3021       return;
3022     }
3023     
3024     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3025                "GNS_PHASE_DELEGATE_NS-%llu: NS delegation starting.\n",
3026                rh->id);
3027     GNUNET_assert (NULL != rd);
3028     rh->proc = &handle_record_ns;
3029     resolve_record_dns (rh, rd_count, rd);
3030     return;
3031   }
3032   
3033   /**
3034    * we still have some left
3035    * check if authority in ns is fresh
3036    * and exists
3037    * or we are authority
3038    **/
3039
3040   if ((rh->status & RSL_RECORD_EXISTS) &&
3041        !(rh->status & RSL_RECORD_EXPIRED))
3042     check_dht = GNUNET_NO;
3043
3044   if (0 == GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3045                                         &rh->private_local_zone))
3046     check_dht = GNUNET_NO;
3047
3048   if (GNUNET_YES == rh->only_cached)
3049     check_dht = GNUNET_NO;
3050
3051   if (GNUNET_YES == check_dht)
3052   {
3053
3054     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3055         "GNS_PHASE_DELEGATE_NS-%llu: Trying to resolve delegation for %s via DHT\n",
3056         rh->id, rh->name);
3057     rh->proc = &handle_delegation_dht;
3058     resolve_delegation_dht(rh);
3059     return;
3060   }
3061   
3062   if (GNUNET_NO == is_canonical (rh->name))
3063   {
3064     /* give up, cannot resolve */
3065     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3066         "GNS_PHASE_DELEGATE_NS-%llu: Cannot fully resolve delegation for %s!\n",
3067         rh->id,
3068         rh->name);
3069     finish_lookup(rh, rlh, rd_count, rd);
3070     return;
3071   }
3072   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3073              "GNS_PHASE_DELEGATE_NS-%llu: Resolving canonical record %s\n",
3074              rh->id,
3075              rh->name);
3076   rh->proc = &handle_record_ns;
3077   resolve_record_ns(rh);
3078 }
3079
3080
3081 /**
3082  * This is a callback function that should give us only PKEY
3083  * records. Used to query the namestore for the authority (PKEY)
3084  * for 'name'. It will recursively try to resolve the
3085  * authority for a given name from the namestore.
3086  *
3087  * @param cls the pending query
3088  * @param key the key of the zone we did the lookup
3089  * @param expiration expiration date of the record data set in the namestore
3090  * @param name the name for which we need an authority
3091  * @param rd_count the number of records with 'name'
3092  * @param rd the record data
3093  * @param signature the signature of the authority for the record data
3094  */
3095 static void
3096 process_delegation_result_ns (void* cls,
3097                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
3098                    struct GNUNET_TIME_Absolute expiration,
3099                    const char *name,
3100                    unsigned int rd_count,
3101                    const struct GNUNET_NAMESTORE_RecordData *rd,
3102                    const struct GNUNET_CRYPTO_RsaSignature *signature)
3103 {
3104   struct ResolverHandle *rh;
3105   struct GNUNET_TIME_Relative remaining_time;
3106   struct GNUNET_CRYPTO_ShortHashCode zone;
3107   char new_name[MAX_DNS_NAME_LENGTH];
3108   unsigned int i;
3109   struct GNUNET_TIME_Absolute et;
3110  
3111   rh = (struct ResolverHandle *)cls;
3112   rh->namestore_task = NULL;
3113   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3114           "GNS_PHASE_DELEGATE_NS-%llu: Got %d records from authority lookup\n",
3115           rh->id, rd_count);
3116
3117   GNUNET_CRYPTO_short_hash (key,
3118                       sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3119                       &zone);
3120   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
3121   
3122   rh->status = 0;
3123   
3124   if (name != NULL)
3125   {
3126     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3127                 "GNS_PHASE_DELEGATE_NS-%llu: Records with name %s exist.\n",
3128                 rh->id, name);
3129     rh->status |= RSL_RECORD_EXISTS;
3130   
3131     if (remaining_time.rel_value == 0)
3132     {
3133       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3134                   "GNS_PHASE_DELEGATE_NS-%llu: Record set %s expired.\n",
3135                   rh->id, name);
3136       rh->status |= RSL_RECORD_EXPIRED;
3137     }
3138   }
3139   
3140   /**
3141    * No authority found in namestore.
3142    */
3143   if (rd_count == 0)
3144   {
3145     /**
3146      * We did not find an authority in the namestore
3147      */
3148     
3149     /**
3150      * No PKEY in zone.
3151      * Promote this authority back to a name maybe it is
3152      * our record.
3153      */
3154     if (strcmp (rh->name, "") == 0)
3155     {
3156       /* simply promote back */
3157       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3158                   "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
3159                   rh->id, rh->authority_name);
3160       strcpy (rh->name, rh->authority_name);
3161     }
3162     else
3163     {
3164       /* add back to existing name */
3165       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3166                   "GNS_PHASE_DELEGATE_NS-%llu: Adding %s back to %s\n",
3167                   rh->id, rh->authority_name, rh->name);
3168       GNUNET_snprintf (new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
3169                        rh->name, rh->authority_name);
3170       strcpy (rh->name, new_name);
3171       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3172                   "GNS_PHASE_DELEGATE_NS-%llu: %s restored\n",
3173                   rh->id, rh->name);
3174     }
3175
3176     rh->proc (rh->proc_cls, rh, 0, NULL);
3177     return;
3178   }
3179
3180   /**
3181    * We found an authority that may be able to help us
3182    * move on with query
3183    * Note only 1 pkey should have been returned.. anything else would be strange
3184    */
3185   for (i=0; i < rd_count;i++)
3186   {
3187     
3188     /**
3189      * A CNAME. Like regular DNS this means the is no other record for this
3190      * name.
3191      */
3192     if (rd[i].record_type == GNUNET_GNS_RECORD_CNAME)
3193     {
3194       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3195                  "GNS_PHASE_DELEGATE_NS-%llu: CNAME found.\n",
3196                  rh->id);
3197
3198       rh->status |= RSL_CNAME_FOUND;
3199       rh->proc (rh->proc_cls, rh, rd_count, rd);
3200       return;
3201     }
3202
3203     /**
3204      * Redirect via VPN
3205      */
3206     if (rd[i].record_type == GNUNET_GNS_RECORD_VPN)
3207     {
3208       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3209                  "GNS_PHASE_DELEGATE_NS-%llu: VPN found.\n",
3210                  rh->id);
3211       rh->status |= RSL_DELEGATE_VPN;
3212       rh->proc (rh->proc_cls, rh, rd_count, rd);
3213       return;
3214     }
3215
3216     /**
3217      * Redirect via NS
3218      * FIXME make optional
3219      */
3220     if (rd[i].record_type == GNUNET_GNS_RECORD_NS)
3221     {
3222       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3223                  "GNS_PHASE_DELEGATE_NS-%llu: NS found.\n",
3224                  rh->id);
3225       rh->status |= RSL_DELEGATE_NS;
3226       rh->proc (rh->proc_cls, rh, rd_count, rd);
3227       return;
3228     }
3229   
3230     if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
3231       continue;
3232
3233     rh->status |= RSL_DELEGATE_PKEY;
3234
3235     if ((ignore_pending_records != 0) &&
3236         (rd[i].flags & GNUNET_NAMESTORE_RF_PENDING))
3237     {
3238       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3239      "GNS_PHASE_DELEGATE_NS-%llu: PKEY for %s is pending user confirmation.\n",
3240         rh->id,
3241         name);
3242       continue;
3243     }
3244     
3245     GNUNET_break (0 == (rd[i].flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION));
3246     et.abs_value = rd[i].expiration_time;
3247     if ((GNUNET_TIME_absolute_get_remaining (et)).rel_value
3248          == 0)
3249     {
3250       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3251                   "GNS_PHASE_DELEGATE_NS-%llu: This pkey is expired.\n",
3252                   rh->id);
3253       if (remaining_time.rel_value == 0)
3254       {
3255         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3256                     "GNS_PHASE_DELEGATE_NS-%llu: This dht entry is expired.\n",
3257                     rh->id);
3258         rh->authority_chain_head->fresh = 0;
3259         rh->proc (rh->proc_cls, rh, 0, NULL);
3260         return;
3261       }
3262
3263       continue;
3264     }
3265
3266     /**
3267      * Resolve rest of query with new authority
3268      */
3269     GNUNET_assert (rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
3270     memcpy (&rh->authority, rd[i].data,
3271             sizeof (struct GNUNET_CRYPTO_ShortHashCode));
3272     struct AuthorityChain *auth = GNUNET_malloc(sizeof (struct AuthorityChain));
3273     auth->zone = rh->authority;
3274     memset (auth->name, 0, strlen (rh->authority_name)+1);
3275     strcpy (auth->name, rh->authority_name);
3276     GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
3277                                  rh->authority_chain_tail,
3278                                  auth);
3279     if (NULL != rh->rd.data)
3280       GNUNET_free ((void*)(rh->rd.data));
3281     
3282     memcpy (&rh->rd, &rd[i], sizeof (struct GNUNET_NAMESTORE_RecordData));
3283     rh->rd.data = GNUNET_malloc (rd[i].data_size);
3284     memcpy ((void*)rh->rd.data, rd[i].data, rd[i].data_size);
3285     rh->rd_count = 1;
3286     /* Check for key revocation and delegate */
3287     rh->namestore_task = GNUNET_NAMESTORE_lookup_record (namestore_handle,
3288                                     &rh->authority,
3289                                     "+",
3290                                     GNUNET_GNS_RECORD_REV,
3291                                     &process_pkey_revocation_result_ns,
3292                                     rh);
3293     return;
3294   
3295   }
3296   
3297   /**
3298    * no answers found
3299    */
3300   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3301     "GNS_PHASE_DELEGATE_NS-%llu: Authority lookup and no PKEY...\n", rh->id);
3302   /**
3303    * If we have found some records for the LAST label
3304    * we return the results. Else null.
3305    */
3306   if (strcmp (rh->name, "") == 0)
3307   {
3308     /* Start shortening */
3309     if ((rh->priv_key != NULL) &&
3310         (is_canonical (rh->name) == GNUNET_YES))
3311     {
3312       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3313               "GNS_PHASE_DELEGATE_NS-%llu: Trying to shorten authority chain\n",
3314               rh->id);
3315       start_shorten (rh->authority_chain_head,
3316                     rh->priv_key);
3317     }
3318     /* simply promote back */
3319     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3320                 "GNS_PHASE_DELEGATE_NS-%llu: Promoting %s back to name\n",
3321                 rh->id, rh->authority_name);
3322     strcpy (rh->name, rh->authority_name);
3323     rh->proc (rh->proc_cls, rh, rd_count, rd);
3324   }
3325   else
3326   {
3327     GNUNET_snprintf (new_name, MAX_DNS_NAME_LENGTH,
3328                      "%s.%s", rh->name, rh->authority_name);
3329     strcpy (rh->name, new_name);
3330     rh->proc (rh->proc_cls, rh, 0, NULL);
3331   }
3332 }
3333
3334
3335 /**
3336  * Resolve the delegation chain for the request in our namestore
3337  *
3338  * @param rh the resolver handle
3339  */
3340 static void
3341 resolve_delegation_ns (struct ResolverHandle *rh)
3342 {
3343   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3344              "GNS_PHASE_DELEGATE_NS-%llu: Resolving delegation for %s\n",
3345              rh->id, rh->name);
3346   pop_tld(rh->name, rh->authority_name);
3347   rh->namestore_task = GNUNET_NAMESTORE_lookup_record(namestore_handle,
3348                                  &rh->authority,
3349                                  rh->authority_name,
3350                                  GNUNET_GNS_RECORD_ANY,
3351                                  &process_delegation_result_ns,
3352                                  rh);
3353
3354 }
3355
3356
3357 /**
3358  * Lookup of a record in a specific zone
3359  * calls lookup result processor on result
3360  *
3361  * @param zone the root zone
3362  * @param pzone the private local zone
3363  * @param record_type the record type to look up
3364  * @param name the name to look up
3365  * @param key a private key for use with PSEU import (can be NULL)
3366  * @param timeout timeout for resolution
3367  * @param only_cached GNUNET_NO to only check locally not DHT for performance
3368  * @param proc the processor to call on result
3369  * @param cls the closure to pass to proc
3370  */
3371 void
3372 gns_resolver_lookup_record (struct GNUNET_CRYPTO_ShortHashCode zone,
3373                             struct GNUNET_CRYPTO_ShortHashCode pzone,
3374                             uint32_t record_type,
3375                             const char* name,
3376                             struct GNUNET_CRYPTO_RsaPrivateKey *key,
3377                             struct GNUNET_TIME_Relative timeout,
3378                             int only_cached,
3379                             RecordLookupProcessor proc,
3380                             void* cls)
3381 {
3382   struct ResolverHandle *rh;
3383   struct RecordLookupHandle* rlh;
3384   char string_hash[MAX_DNS_LABEL_LENGTH];
3385   char nzkey[MAX_DNS_LABEL_LENGTH];
3386   char* nzkey_ptr = nzkey;
3387
3388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3389               "Starting resolution for %s (type=%d)!\n",
3390               name, record_type);
3391
3392   
3393   if ((is_canonical ((char*)name) == GNUNET_YES) &&
3394       (strcmp(GNUNET_GNS_TLD, name) != 0))
3395   {
3396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3397                 "%s is canonical and not gnunet -> cannot resolve!\n", name);
3398     proc(cls, 0, NULL);
3399     return;
3400   }
3401   
3402   rlh = GNUNET_malloc (sizeof(struct RecordLookupHandle));
3403   rh = GNUNET_malloc (sizeof (struct ResolverHandle));
3404   
3405   memset (rh, 0, sizeof (struct ResolverHandle));
3406   rh->authority = zone;
3407   rh->id = rid++;
3408   rh->proc_cls = rlh;
3409   rh->priv_key = key;
3410   rh->timeout = timeout;
3411   rh->get_handle = NULL;
3412   rh->private_local_zone = pzone;
3413   rh->only_cached = only_cached;
3414   rh->namestore_task = NULL;
3415   rh->rd.data = NULL;
3416
3417   GNUNET_CONTAINER_DLL_insert (rlh_head, rlh_tail, rh);
3418   
3419   if (NULL == key)
3420   {
3421     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3422                 "No shorten key for resolution\n");
3423   }
3424
3425   if (timeout.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3426   {
3427     /*
3428      * Set timeout for authority lookup phase to 1/2
3429      */
3430     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3431                 "Timeout for lookup set to %ds\n", rh->timeout.rel_value);
3432     rh->timeout_task = GNUNET_SCHEDULER_add_delayed(
3433                                 GNUNET_TIME_relative_divide(timeout, 2),
3434                                                 &handle_lookup_timeout,
3435                                                 rh);
3436     rh->timeout_cont = &dht_authority_lookup_timeout;
3437     rh->timeout_cont_cls = rh;
3438   }
3439   else
3440   {
3441     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No timeout for query!\n");
3442     rh->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3443   }
3444   
3445   if (strcmp(GNUNET_GNS_TLD, name) == 0)
3446   {
3447     /**
3448      * Only 'gnunet' given
3449      */
3450     strcpy(rh->name, "\0");
3451   }
3452   else
3453   {
3454     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3455                 "Checking for TLD...\n");
3456     if (is_zkey_tld(name) == GNUNET_YES)
3457     {
3458       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3459                   "TLD is zkey\n");
3460       /**
3461        * This is a zkey tld
3462        * build hash and use as initial authority
3463        */
3464       memset(rh->name, 0,
3465              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY));
3466       memcpy(rh->name, name,
3467              strlen(name)-strlen(GNUNET_GNS_TLD_ZKEY) - 1);
3468       pop_tld(rh->name, string_hash);
3469
3470       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3471                   "ZKEY is %s!\n", string_hash);
3472       
3473       GNUNET_STRINGS_utf8_toupper(string_hash, &nzkey_ptr);
3474
3475       if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string(nzkey,
3476                                                       &rh->authority))
3477       {
3478         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3479                     "Cannot convert ZKEY `%s' to hash!\n", string_hash);
3480         
3481         if (GNUNET_SCHEDULER_NO_TASK != rh->timeout_task)
3482           GNUNET_SCHEDULER_cancel (rh->timeout_task);
3483         GNUNET_CONTAINER_DLL_remove (rlh_head, rlh_tail, rh);
3484         GNUNET_free (rh);
3485         GNUNET_free (rlh);
3486         proc (cls, 0, NULL);
3487         return;
3488       }
3489
3490     }
3491     else if (is_gnunet_tld (name) == GNUNET_YES)
3492     {
3493       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3494                   "TLD is gnunet\n");
3495       /**
3496        * Presumably GNUNET tld
3497        */
3498       memset (rh->name, 0,
3499               strlen(name)-strlen(GNUNET_GNS_TLD));
3500       memcpy (rh->name, name,
3501               strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
3502     }
3503     else
3504     {
3505       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3506                   "Cannot handle this TLD %s\n", string_hash);
3507       
3508       if (GNUNET_SCHEDULER_NO_TASK != rh->timeout_task)
3509         GNUNET_SCHEDULER_cancel (rh->timeout_task);
3510       GNUNET_CONTAINER_DLL_remove (rlh_head, rlh_tail, rh);
3511       GNUNET_free (rh);
3512       GNUNET_free (rlh);
3513       proc (cls, 0, NULL);
3514       return;
3515     }
3516   }
3517   
3518   /**
3519    * Initialize authority chain
3520    */
3521   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
3522   rh->authority_chain_head->prev = NULL;
3523   rh->authority_chain_head->next = NULL;
3524   rh->authority_chain_tail = rh->authority_chain_head;
3525   rh->authority_chain_head->zone = rh->authority;
3526   strcpy (rh->authority_chain_head->name, "");
3527   
3528   /**
3529    * Copy original query into lookup handle
3530    */
3531   rlh->record_type = record_type;
3532   memset(rlh->name, 0, strlen(name) + 1);
3533   strcpy(rlh->name, name);
3534   rlh->proc = proc;
3535   rlh->proc_cls = cls;
3536
3537   rh->proc = &handle_delegation_ns;
3538   resolve_delegation_ns(rh);
3539 }
3540
3541 /******** END Record Resolver ***********/
3542
3543 static void
3544 finish_shorten (struct ResolverHandle *rh,
3545                 struct NameShortenHandle *nsh)
3546 {
3547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3548               "Sending %s as shorten result\n", nsh->result);
3549   nsh->proc (nsh->proc_cls, nsh->result);
3550   GNUNET_CONTAINER_DLL_remove (nsh_head, nsh_tail, rh);
3551   GNUNET_free (nsh);
3552   free_resolver_handle (rh);
3553 }
3554
3555
3556 /**
3557  * Callback calles by namestore for a zone to name
3558  * result
3559  *
3560  * @param cls the closure
3561  * @param zone_key the zone we queried
3562  * @param expire the expiration time of the name
3563  * @param name the name found or NULL
3564  * @param rd_len number of records for the name
3565  * @param rd the record data (PKEY) for the name
3566  * @param signature the signature for the record data
3567  */
3568 static void
3569 process_zone_to_name_shorten_root (void *cls,
3570                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3571                  struct GNUNET_TIME_Absolute expire,
3572                  const char *name,
3573                  unsigned int rd_len,
3574                  const struct GNUNET_NAMESTORE_RecordData *rd,
3575                  const struct GNUNET_CRYPTO_RsaSignature *signature);
3576
3577
3578 /**
3579  * Callback called by namestore for a zone to name
3580  * result
3581  *
3582  * @param cls the closure
3583  * @param zone_key the zone we queried
3584  * @param expire the expiration time of the name
3585  * @param name the name found or NULL
3586  * @param rd_len number of records for the name
3587  * @param rd the record data (PKEY) for the name
3588  * @param signature the signature for the record data
3589  */
3590 static void
3591 process_zone_to_name_shorten_shorten (void *cls,
3592                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3593                  struct GNUNET_TIME_Absolute expire,
3594                  const char *name,
3595                  unsigned int rd_len,
3596                  const struct GNUNET_NAMESTORE_RecordData *rd,
3597                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3598 {
3599   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3600   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3601   struct AuthorityChain *next_authority;
3602
3603   char result[MAX_DNS_NAME_LENGTH];
3604   char tmp_name[MAX_DNS_NAME_LENGTH];
3605   size_t answer_len;
3606   
3607   rh->namestore_task = NULL;
3608   /* we found a match in our own root zone */
3609   if (rd_len != 0)
3610   {
3611     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3612     memset(result, 0, answer_len);
3613
3614     if (strlen(rh->name) > 0)
3615     {
3616       sprintf (result, "%s.%s.%s.%s",
3617                rh->name, name,
3618                nsh->shorten_zone_name,
3619                GNUNET_GNS_TLD);
3620     }
3621     else
3622     {
3623       sprintf (result, "%s.%s.%s", name,
3624                nsh->shorten_zone_name,
3625                GNUNET_GNS_TLD);
3626     }
3627     
3628     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3629                "Found shorten result %s\n", result);
3630     if (strlen (nsh->result) > strlen (result))
3631       strcpy (nsh->result, result);
3632   }
3633   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3634                                         nsh->shorten_zone) == 0)
3635   {
3636     /**
3637      * This is our zone append .gnunet unless name is empty
3638      * (it shouldn't be, usually FIXME what happens if we
3639      * shorten to our zone to a "" record??)
3640      */
3641     
3642     sprintf (result, "%s.%s.%s",
3643              rh->name,
3644              nsh->shorten_zone_name,
3645              GNUNET_GNS_TLD);
3646     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3647                "Our zone: Found %s as shorten result\n", result);
3648     
3649     if (strlen (nsh->result) > strlen (result))
3650       strcpy (nsh->result, result);
3651     //nsh->proc(nsh->proc_cls, result);
3652     //GNUNET_free(nsh);
3653     //free_resolver_handle(rh);
3654     //return;
3655   }
3656   
3657   
3658   /**
3659    * No PSEU found.
3660    * continue with next authority if exists
3661    */
3662   if ((rh->authority_chain_head->next == NULL))
3663   {
3664     finish_shorten (rh, nsh);
3665     return;
3666   }
3667   next_authority = rh->authority_chain_head;
3668   
3669   GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3670                   "%s.%s", rh->name, next_authority->name);
3671   
3672   strcpy(rh->name, tmp_name);
3673   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3674              "No PSEU found for authority %s. Promoting back: %s\n",
3675              next_authority->name, rh->name);
3676   
3677   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3678                             rh->authority_chain_tail,
3679                             next_authority);
3680
3681   GNUNET_free (next_authority);
3682
3683   rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3684                                  &rh->authority_chain_tail->zone,
3685                                  &rh->authority_chain_head->zone,
3686                                  &process_zone_to_name_shorten_root,
3687                                  rh);
3688 }
3689
3690 /**
3691  * Callback calles by namestore for a zone to name
3692  * result
3693  *
3694  * @param cls the closure
3695  * @param zone_key the zone we queried
3696  * @param expire the expiration time of the name
3697  * @param name the name found or NULL
3698  * @param rd_len number of records for the name
3699  * @param rd the record data (PKEY) for the name
3700  * @param signature the signature for the record data
3701  */
3702 static void
3703 process_zone_to_name_shorten_private (void *cls,
3704                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3705                  struct GNUNET_TIME_Absolute expire,
3706                  const char *name,
3707                  unsigned int rd_len,
3708                  const struct GNUNET_NAMESTORE_RecordData *rd,
3709                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3710 {
3711   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3712   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3713   struct AuthorityChain *next_authority;
3714
3715   char result[MAX_DNS_NAME_LENGTH];
3716   char tmp_name[MAX_DNS_NAME_LENGTH];
3717   size_t answer_len;
3718   
3719   rh->namestore_task = NULL;
3720   /* we found a match in our own root zone */
3721   if (rd_len != 0)
3722   {
3723     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3724     memset(result, 0, answer_len);
3725
3726     if (strlen(rh->name) > 0)
3727     {
3728       sprintf (result, "%s.%s.%s", rh->name, name, GNUNET_GNS_TLD);
3729     }
3730     else
3731     {
3732       sprintf (result, "%s.%s", name, GNUNET_GNS_TLD);
3733     }
3734     
3735     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3736                "Found shorten result %s\n", result);
3737     if (strlen (nsh->result) > strlen (result))
3738       strcpy (nsh->result, result);
3739   }
3740   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3741                                         nsh->private_zone) == 0)
3742   {
3743     /**
3744      * This is our zone append .gnunet unless name is empty
3745      * (it shouldn't be, usually FIXME what happens if we
3746      * shorten to our zone to a "" record??)
3747      */
3748     
3749     sprintf (result, "%s.%s.%s",
3750              rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3751     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3752                "Our private zone: Found %s as shorten result %s\n", result);
3753     if (strlen (nsh->result) > strlen (result))
3754       strcpy (nsh->result, result);
3755   }
3756   
3757   if (0 != strcmp (nsh->shorten_zone_name, ""))
3758   {
3759     /* backtrack authorities for names in priv zone */
3760     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3761                                    nsh->shorten_zone,
3762                                    &rh->authority_chain_head->zone,
3763                                    &process_zone_to_name_shorten_shorten,
3764                                    rh);
3765   }
3766   else
3767   {
3768     /**
3769      * No PSEU found.
3770      * continue with next authority if exists
3771      */
3772     if ((rh->authority_chain_head->next == NULL))
3773     {
3774       finish_shorten (rh, nsh);
3775       return;
3776     }
3777     next_authority = rh->authority_chain_head;
3778     
3779     GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3780                     "%s.%s", rh->name, next_authority->name);
3781     
3782     strcpy(rh->name, tmp_name);
3783     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3784                "No PSEU found for authority %s. Promoting back: %s\n",
3785                next_authority->name, rh->name);
3786     
3787     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3788                               rh->authority_chain_tail,
3789                               next_authority);
3790
3791     GNUNET_free (next_authority);
3792
3793     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3794                                    &rh->authority_chain_tail->zone,
3795                                    &rh->authority_chain_head->zone,
3796                                    &process_zone_to_name_shorten_root,
3797                                    rh);
3798   }
3799 }
3800
3801 /**
3802  * Callback calles by namestore for a zone to name
3803  * result
3804  *
3805  * @param cls the closure
3806  * @param zone_key the zone we queried
3807  * @param expire the expiration time of the name
3808  * @param name the name found or NULL
3809  * @param rd_len number of records for the name
3810  * @param rd the record data (PKEY) for the name
3811  * @param signature the signature for the record data
3812  */
3813 static void
3814 process_zone_to_name_shorten_root (void *cls,
3815                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
3816                  struct GNUNET_TIME_Absolute expire,
3817                  const char *name,
3818                  unsigned int rd_len,
3819                  const struct GNUNET_NAMESTORE_RecordData *rd,
3820                  const struct GNUNET_CRYPTO_RsaSignature *signature)
3821 {
3822   struct ResolverHandle *rh = (struct ResolverHandle *)cls;
3823   struct NameShortenHandle* nsh = (struct NameShortenHandle*)rh->proc_cls;
3824   struct AuthorityChain *next_authority;
3825
3826   char result[MAX_DNS_NAME_LENGTH];
3827   char tmp_name[MAX_DNS_NAME_LENGTH];
3828   size_t answer_len;
3829   
3830   rh->namestore_task = NULL;
3831   /* we found a match in our own root zone */
3832   if (rd_len != 0)
3833   {
3834     answer_len = strlen(rh->name) + strlen(name) + strlen(GNUNET_GNS_TLD) + 3;
3835     memset(result, 0, answer_len);
3836
3837     if (strlen(rh->name) > 0)
3838     {
3839       sprintf (result, "%s.%s.%s", rh->name, name, GNUNET_GNS_TLD);
3840     }
3841     else
3842     {
3843       sprintf (result, "%s.%s", name, GNUNET_GNS_TLD);
3844     }
3845     
3846     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3847                "Found shorten result %s\n", result);
3848     if (strlen (nsh->result) > strlen (result))
3849       strcpy (nsh->result, result);
3850   }
3851   else if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3852                                         nsh->root_zone) == 0)
3853   {
3854     /**
3855      * This is our zone append .gnunet unless name is empty
3856      * (it shouldn't be, usually FIXME what happens if we
3857      * shorten to our zone to a "" record??)
3858      */
3859     
3860     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
3861     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3862                "Our zone: Found %s as shorten result\n", result);
3863     if (strlen (nsh->result) > strlen (result))
3864       strcpy (nsh->result, result);
3865   }
3866   
3867   if (NULL != nsh->private_zone)
3868   {
3869     /* backtrack authorities for names in priv zone */
3870     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3871                                    nsh->private_zone,
3872                                    &rh->authority_chain_head->zone,
3873                                    &process_zone_to_name_shorten_private,
3874                                    rh);
3875   }
3876   else if (NULL != nsh->shorten_zone)
3877   {
3878     /* backtrack authorities for names in shorten zone */
3879     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3880                                           nsh->shorten_zone,
3881                                           &rh->authority_chain_head->zone,
3882                                           &process_zone_to_name_shorten_shorten,
3883                                           rh);
3884   }
3885   else
3886   {
3887     /**
3888      * No PSEU found.
3889      * continue with next authority if exists
3890      */
3891     if ((rh->authority_chain_head->next == NULL))
3892     {
3893       finish_shorten (rh, nsh);
3894       return;
3895     }
3896     next_authority = rh->authority_chain_head;
3897     
3898     GNUNET_snprintf(tmp_name, MAX_DNS_NAME_LENGTH,
3899                     "%s.%s", rh->name, next_authority->name);
3900     
3901     strcpy(rh->name, tmp_name);
3902     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3903                "No PSEU found for authority %s. Promoting back: %s\n",
3904                next_authority->name, rh->name);
3905     
3906     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
3907                               rh->authority_chain_tail,
3908                               next_authority);
3909
3910     GNUNET_free (next_authority);
3911
3912     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
3913                                    &rh->authority_chain_tail->zone,
3914                                    &rh->authority_chain_head->zone,
3915                                    &process_zone_to_name_shorten_root,
3916                                    rh);
3917   }
3918 }
3919
3920
3921 /**
3922  * Process result from namestore delegation lookup
3923  * for shorten operation
3924  *
3925  * @param cls the client shorten handle
3926  * @param rh the resolver handle
3927  * @param rd_count number of results (0)
3928  * @param rd data (NULL)
3929  */
3930 void
3931 handle_delegation_ns_shorten (void* cls,
3932                       struct ResolverHandle *rh,
3933                       uint32_t rd_count,
3934                       const struct GNUNET_NAMESTORE_RecordData *rd)
3935 {
3936   struct NameShortenHandle *nsh;
3937   char result[MAX_DNS_NAME_LENGTH];
3938
3939   nsh = (struct NameShortenHandle *)cls;
3940   
3941   /**
3942    * At this point rh->name contains the part of the name
3943    * that we do not have a PKEY in our namestore to resolve.
3944    * The authority chain in the resolver handle is now
3945    * useful to backtrack if needed
3946    */
3947   
3948   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3949              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
3950   memset(result, 0, sizeof (result));
3951
3952   if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3953                                    nsh->root_zone) == 0)
3954   {
3955     /**
3956      * This is our zone append .gnunet unless name is empty
3957      * (it shouldn't be, usually FIXME what happens if we
3958      * shorten to our zone to a "" record??)
3959      */
3960     
3961     sprintf (result, "%s.%s", rh->name, GNUNET_GNS_TLD);
3962     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3963                "Our zone: Found %s as shorten result\n", result);
3964     
3965     if (strlen (nsh->result) > strlen (result))
3966       strcpy (nsh->result, result);
3967
3968   }
3969   else if (NULL != nsh->private_zone)
3970   {
3971     /**
3972      * This is our zone append .gnunet unless name is empty
3973      * (it shouldn't be, usually FIXME what happens if we
3974      * shorten to our zone to a "" record??)
3975      */
3976     if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3977                                      nsh->private_zone) == 0)
3978     {
3979     
3980       sprintf (result, "%s.%s.%s",
3981                rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
3982       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3983                  "Our zone: Found %s as shorten result in private zone %s\n",
3984                  result);
3985     
3986       if (strlen (nsh->result) > strlen (result))
3987         strcpy (nsh->result, result);
3988     }
3989   }
3990   else if (NULL != nsh->shorten_zone)
3991   {
3992     /**
3993      * This is our zone append .gnunet unless name is empty
3994      * (it shouldn't be, usually FIXME what happens if we
3995      * shorten to our zone to a "" record??)
3996      */
3997     if (GNUNET_CRYPTO_short_hash_cmp(&rh->authority_chain_head->zone,
3998                                      nsh->shorten_zone) == 0)
3999     {
4000       sprintf (result, "%s.%s.%s",
4001                rh->name, nsh->private_zone_name, GNUNET_GNS_TLD);
4002       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4003                  "Our zone: Found %s as shorten result in shorten zone\n",
4004                  result);
4005     
4006       if (strlen (nsh->result) > strlen (result))
4007         strcpy (nsh->result, result);
4008     }
4009   }
4010   
4011   
4012   /* backtrack authorities for names */
4013   rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
4014                                  nsh->root_zone,
4015                                  &rh->authority_chain_head->zone,
4016                                  &process_zone_to_name_shorten_root,
4017                                  rh);
4018   
4019 }
4020
4021
4022 /**
4023  * Callback calles by namestore for a zone to name
4024  * result
4025  *
4026  * @param cls the closure
4027  * @param zone_key the zone we queried
4028  * @param expire the expiration time of the name
4029  * @param name the name found or NULL
4030  * @param rd_len number of records for the name
4031  * @param rd the record data (PKEY) for the name
4032  * @param signature the signature for the record data
4033  */
4034 static void
4035 process_zone_to_name_zkey(void *cls,
4036                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
4037                  struct GNUNET_TIME_Absolute expire,
4038                  const char *name,
4039                  unsigned int rd_len,
4040                  const struct GNUNET_NAMESTORE_RecordData *rd,
4041                  const struct GNUNET_CRYPTO_RsaSignature *signature)
4042 {
4043   struct ResolverHandle *rh = cls;
4044   struct NameShortenHandle *nsh = rh->proc_cls;
4045   struct GNUNET_CRYPTO_ShortHashAsciiEncoded enc;
4046   char new_name[MAX_DNS_NAME_LENGTH];
4047
4048   /* zkey not in our zone */
4049   if (name == NULL)
4050   {
4051     /**
4052      * In this case we have not given this PKEY a name (yet)
4053      * It is either just not in our zone or not even cached
4054      * Since we do not know at this point we will not try to shorten
4055      * because PKEY import will happen if the user follows the zkey
4056      * link.
4057      */
4058     GNUNET_CRYPTO_short_hash_to_enc ((struct GNUNET_CRYPTO_ShortHashCode*)rd,
4059                                      &enc);
4060     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4061                "No name found for zkey %s returning verbatim!\n", enc);
4062     if (strcmp(rh->name, "") != 0)
4063       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s.%s",
4064                       rh->name, enc, GNUNET_GNS_TLD_ZKEY);
4065     else
4066       GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
4067                       enc, GNUNET_GNS_TLD_ZKEY);
4068
4069     strcpy (nsh->result, new_name);
4070
4071     finish_shorten (rh, nsh);
4072     return;
4073   }
4074   
4075   if (strcmp(rh->name, "") != 0)
4076     GNUNET_snprintf(new_name, MAX_DNS_NAME_LENGTH, "%s.%s",
4077                     rh->name, name);
4078   else
4079     strcpy(new_name, name);
4080
4081   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4082              "Continue shorten for %s!\n", new_name);
4083
4084   strcpy(rh->name, new_name);
4085   
4086   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
4087   rh->authority_chain_tail = rh->authority_chain_head;
4088   rh->authority_chain_head->zone = rh->authority;
4089   
4090   
4091   /* Start delegation resolution in our namestore */
4092   resolve_delegation_ns (rh);
4093 }
4094
4095
4096 /**
4097  * Shorten api from resolver
4098  *
4099  * @param zone the root zone to use
4100  * @param pzone the private zone to use
4101  * @param szone the shorten zone to use
4102  * @param name the name to shorten
4103  * @param private_zone_name name of the private zone
4104  * @param shorten_zone_name name of the shorten zone
4105  * @param proc the processor to call with result
4106  * @param proc_cls closure to pass to proc
4107  */
4108 void
4109 gns_resolver_shorten_name (struct GNUNET_CRYPTO_ShortHashCode *zone,
4110                            struct GNUNET_CRYPTO_ShortHashCode *pzone,
4111                            struct GNUNET_CRYPTO_ShortHashCode *szone,
4112                            const char* name,
4113                            const char* private_zone_name,
4114                            const char* shorten_zone_name,
4115                            ShortenResultProcessor proc,
4116                            void* proc_cls)
4117 {
4118   struct ResolverHandle *rh;
4119   struct NameShortenHandle *nsh;
4120   char string_hash[MAX_DNS_LABEL_LENGTH];
4121   struct GNUNET_CRYPTO_ShortHashCode zkey;
4122   char nzkey[MAX_DNS_LABEL_LENGTH];
4123   char* nzkey_ptr = nzkey;
4124
4125
4126   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4127               "Starting shorten for %s!\n", name);
4128   
4129   if (is_canonical ((char*)name) == GNUNET_YES)
4130   {
4131     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4132                 "%s is canonical. Returning verbatim\n", name);
4133     proc (proc_cls, name);
4134     return;
4135   }
4136
4137   nsh = GNUNET_malloc (sizeof (struct NameShortenHandle));
4138
4139   nsh->proc = proc;
4140   nsh->proc_cls = proc_cls;
4141   nsh->root_zone = zone;
4142   nsh->private_zone = pzone;
4143   nsh->shorten_zone = szone;
4144   strcpy (nsh->private_zone_name, private_zone_name);
4145   strcpy (nsh->shorten_zone_name, shorten_zone_name);
4146   strcpy (nsh->result, name);
4147   
4148
4149   rh = GNUNET_malloc (sizeof (struct ResolverHandle));
4150   rh->authority = *zone;
4151   rh->id = rid++;
4152   rh->priv_key = NULL;
4153   rh->namestore_task = NULL;
4154   rh->proc = &handle_delegation_ns_shorten;
4155   rh->proc_cls = nsh;
4156   rh->id = rid++;
4157   rh->private_local_zone = *zone;
4158
4159   GNUNET_CONTAINER_DLL_insert (nsh_head, nsh_tail, rh);
4160   
4161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4162                 "Checking for TLD...\n");
4163   if (is_zkey_tld (name) == GNUNET_YES)
4164   {
4165     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4166                 "TLD is zkey\n");
4167     /**
4168      * This is a zkey tld
4169      * build hash and use as initial authority
4170      * FIXME sscanf
4171      */
4172     memset (rh->name, 0,
4173             strlen (name)-strlen (GNUNET_GNS_TLD_ZKEY));
4174     memcpy (rh->name, name,
4175             strlen(name)-strlen (GNUNET_GNS_TLD_ZKEY) - 1);
4176     pop_tld (rh->name, string_hash);
4177
4178     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4179                 "ZKEY is %s!\n", string_hash);
4180     
4181     GNUNET_STRINGS_utf8_toupper (string_hash, &nzkey_ptr);
4182
4183     if (GNUNET_OK != GNUNET_CRYPTO_short_hash_from_string (nzkey,
4184                                                            &zkey))
4185     {
4186       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4187                   "Cannot convert ZKEY %s to hash!\n", nzkey);
4188       GNUNET_free (rh);
4189       GNUNET_free (nsh);
4190       GNUNET_CONTAINER_DLL_remove (nsh_head, nsh_tail, rh);
4191       proc (proc_cls, name);
4192       return;
4193     }
4194
4195     rh->namestore_task = GNUNET_NAMESTORE_zone_to_name (namestore_handle,
4196                                    zone, //ours
4197                                    &zkey,
4198                                    &process_zone_to_name_zkey,
4199                                    rh);
4200     return;
4201
4202   }
4203   else if (is_gnunet_tld (name) == GNUNET_YES)
4204   {
4205     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4206                 "TLD is gnunet\n");
4207     /**
4208      * Presumably GNUNET tld
4209      */
4210     memset (rh->name, 0,
4211             strlen (name)-strlen (GNUNET_GNS_TLD));
4212     memcpy (rh->name, name,
4213             strlen (name)-strlen (GNUNET_GNS_TLD) - 1);
4214   }
4215   else
4216   {
4217     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unknown TLD in %s\n", name);
4218     GNUNET_free (rh);
4219     GNUNET_free (nsh);
4220     GNUNET_CONTAINER_DLL_remove (nsh_head, nsh_tail, rh);
4221     proc (proc_cls, name);
4222     return;
4223   }
4224
4225   rh->authority_chain_head = GNUNET_malloc (sizeof (struct AuthorityChain));
4226   rh->authority_chain_tail = rh->authority_chain_head;
4227   rh->authority_chain_head->zone = *zone;
4228   
4229   
4230   /* Start delegation resolution in our namestore */
4231   resolve_delegation_ns (rh);
4232 }
4233
4234 /*********** END NAME SHORTEN ********************/
4235
4236 /**
4237  * Conclude get authority lookup
4238  *
4239  * @param rh resolver handle
4240  * @param nah get authority lookup handle
4241  */
4242 static void
4243 finish_get_auth (struct ResolverHandle *rh,
4244                  struct GetNameAuthorityHandle *nah)
4245 {
4246   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4247              "Got authority result %s\n", nah->result);
4248   
4249   nah->proc(nah->proc_cls, nah->result);
4250   GNUNET_CONTAINER_DLL_remove (nah_head, nah_tail, rh);
4251   GNUNET_free(nah);
4252   free_resolver_handle(rh);
4253 }
4254
4255 /**
4256  * Process result from namestore delegation lookup
4257  * for get authority operation
4258  *
4259  * @param cls the client get auth handle
4260  * @param rh the resolver handle
4261  * @param rd_count number of results (0)
4262  * @param rd data (NULL)
4263  */
4264 void
4265 handle_delegation_result_ns_get_auth(void* cls,
4266                       struct ResolverHandle *rh,
4267                       uint32_t rd_count,
4268                       const struct GNUNET_NAMESTORE_RecordData *rd)
4269 {
4270   struct GetNameAuthorityHandle* nah;
4271   size_t answer_len;
4272
4273   nah = (struct GetNameAuthorityHandle*) rh->proc_cls;
4274   
4275   /**
4276    * At this point rh->name contains the part of the name
4277    * that we do not have a PKEY in our namestore to resolve.
4278    * The authority chain in the resolver handle is now
4279    * useful to backtrack if needed
4280    */
4281   
4282   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4283              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
4284
4285   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4286              "Building response!\n");
4287   if (is_canonical (rh->name) == GNUNET_YES)
4288   {
4289     /**
4290      * We successfully resolved the authority in the ns
4291      * FIXME for our purposes this is fine
4292      * but maybe we want to have an api that also looks
4293      * into the dht (i.e. option in message)
4294      **/
4295     if (strlen(rh->name) > strlen(nah->name))
4296     {
4297       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4298                  "Record name longer than original lookup name... odd!\n");
4299       //FIXME to sth here
4300     }
4301
4302     answer_len = strlen(nah->name) - strlen(rh->name)
4303       + strlen(GNUNET_GNS_TLD) + 1;
4304     memset(nah->result, 0, answer_len);
4305     strcpy(nah->result, nah->name + strlen(rh->name) + 1);
4306
4307     finish_get_auth (rh, nah);
4308   }
4309   else
4310   {
4311     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4312                "Unable to resolve authority for remaining %s!\n", rh->name);
4313     strcpy(nah->result, "");
4314     finish_get_auth (rh, nah);
4315   }
4316
4317
4318 }
4319
4320
4321 /**
4322  * Tries to resolve the authority for name
4323  * in our namestore
4324  *
4325  * @param zone the root zone to look up for
4326  * @param pzone the private local zone
4327  * @param name the name to lookup up
4328  * @param proc the processor to call when finished
4329  * @param proc_cls the closure to pass to the processor
4330  */
4331 void
4332 gns_resolver_get_authority(struct GNUNET_CRYPTO_ShortHashCode zone,
4333                            struct GNUNET_CRYPTO_ShortHashCode pzone,
4334                            const char* name,
4335                            GetAuthorityResultProcessor proc,
4336                            void* proc_cls)
4337 {
4338   struct ResolverHandle *rh;
4339   struct GetNameAuthorityHandle *nah;
4340
4341   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4342               "Starting authority resolution for %s!\n", name);
4343
4344   nah = GNUNET_malloc(sizeof (struct GetNameAuthorityHandle));
4345   rh = GNUNET_malloc(sizeof (struct ResolverHandle));
4346   rh->authority = zone;
4347   rh->id = rid++;
4348   rh->private_local_zone = pzone;
4349   rh->namestore_task = NULL;
4350
4351   GNUNET_CONTAINER_DLL_insert (nah_head, nah_tail, rh);
4352   
4353   if (strcmp(GNUNET_GNS_TLD, name) == 0)
4354   {
4355     strcpy(rh->name, "\0");
4356   }
4357   else
4358   {
4359     memset(rh->name, 0,
4360            strlen(name)-strlen(GNUNET_GNS_TLD));
4361     memcpy(rh->name, name,
4362            strlen(name)-strlen(GNUNET_GNS_TLD) - 1);
4363   }
4364
4365   memset(nah->name, 0,
4366          strlen(name)+1);
4367   strcpy(nah->name, name);
4368   
4369   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
4370   rh->authority_chain_tail = rh->authority_chain_head;
4371   rh->authority_chain_head->zone = zone;
4372   rh->proc = &handle_delegation_result_ns_get_auth;
4373   rh->proc_cls = (void*)nah;
4374
4375   nah->proc = proc;
4376   nah->proc_cls = proc_cls;
4377   strcpy (nah->result, "");
4378
4379   /* Start delegation resolution in our namestore */
4380   resolve_delegation_ns(rh);
4381
4382 }
4383
4384 /******** END GET AUTHORITY *************/
4385
4386 /* end of gnunet-service-gns_resolver.c */