-leak
[oweals/gnunet.git] / src / gns / gnunet-service-gns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  *
23  * TODO:
24  *    - Write xquery and block plugin
25  *    - The smaller FIXME issues all around
26  *
27  * @file gns/gnunet-service-gns.c
28  * @brief GNUnet GNS service
29  * @author Martin Schanzenbach
30  */
31 #include "platform.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet_dns_service.h"
35 #include "gnunet_dnsparser_lib.h"
36 #include "gnunet_dht_service.h"
37 #include "gnunet_namestore_service.h"
38 #include "gnunet_gns_service.h"
39 #include "block_gns.h"
40 #include "gns.h"
41
42 #define DHT_OPERATION_TIMEOUT  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
43 #define DHT_LOOKUP_TIMEOUT DHT_OPERATION_TIMEOUT
44 #define DHT_GNS_REPLICATION_LEVEL 5
45 #define MAX_DNS_LABEL_LENGTH 63
46
47 /* Ignore for now not used anyway and probably never will */
48 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP 23
49 #define GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT 24
50 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN 25
51 #define GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT 26
52
53
54 struct AuthorityChain
55 {
56   struct AuthorityChain *prev;
57
58   struct AuthorityChain *next;
59
60   GNUNET_HashCode zone;
61
62   /* (local) name of the authority */
63   char* name;
64
65   /* was the ns entry fresh */
66   int fresh;
67 };
68
69 struct GNUNET_GNS_ResolverHandle;
70
71 typedef void (*ResolutionResultProcessor) (void *cls,
72                                   struct GNUNET_GNS_ResolverHandle *rh,
73                                   uint32_t rd_count,
74                                   const struct GNUNET_NAMESTORE_RecordData *rd);
75
76 enum ResolutionStatus
77 {
78   EXISTS = 1,
79   EXPIRED = 2
80 };
81
82 /**
83  * Handle to a currenty pending resolution
84  */
85 struct GNUNET_GNS_ResolverHandle
86 {
87   /* The name to resolve */
88   char *name;
89
90   
91   
92   /* has this query been answered? how many matches */
93   int answered;
94
95   /* the authoritative zone to query */
96   GNUNET_HashCode authority;
97
98   /* the name of the authoritative zone to query */
99   char *authority_name;
100
101   /**
102    * we have an authority in namestore that
103    * may be able to resolve
104    */
105   int authority_found;
106
107   /* a handle for dht lookups. should be NULL if no lookups are in progress */
108   struct GNUNET_DHT_GetHandle *get_handle;
109
110   /* timeout task for dht lookups */
111   GNUNET_SCHEDULER_TaskIdentifier dht_timeout_task;
112
113   /* called when resolution phase finishes */
114   ResolutionResultProcessor proc;
115   
116   /* closure passed to proc */
117   void* proc_cls;
118
119   struct AuthorityChain *authority_chain_head;
120   struct AuthorityChain *authority_chain_tail;
121
122   enum ResolutionStatus status;
123
124 };
125
126 /**
127  * Handle to a record lookup
128  */
129 struct RecordLookupHandle
130 {
131   /* the record type to look up */
132   enum GNUNET_GNS_RecordType record_type;
133
134   /* the name to look up */
135   char *name;
136
137   /* Method to call on record resolution result */
138   ResolutionResultProcessor proc;
139
140   /* closure to pass to proc */
141   void* proc_cls;
142
143 };
144
145 /**
146  * Handle to a shorten operation from api
147  */
148 struct ClientShortenHandle
149 {
150   /* the requesting client that */
151   struct GNUNET_SERVER_Client *client;
152
153   /* request id */
154   uint64_t unique_id;
155
156   /* request key */
157   GNUNET_HashCode key;
158
159   /* name to shorten */
160   char* name;
161
162 };
163
164 /**
165  * Handle to a lookup operation from api
166  */
167 struct ClientLookupHandle
168 {
169   /* the requesting client that */
170   struct GNUNET_SERVER_Client *client;
171
172   /* request id */
173   uint64_t unique_id;
174
175   /* request key */
176   GNUNET_HashCode key;
177
178   /* the name to look up */
179   char* name; //Needed?
180 };
181
182 /**
183  * Handle to a DNS intercepted
184  * reslution request
185  */
186 struct InterceptLookupHandle
187 {
188   /* the request handle to reply to */
189   struct GNUNET_DNS_RequestHandle *request_handle;
190   
191   /* the dns parser packet received */
192   struct GNUNET_DNSPARSER_Packet *packet;
193   
194   /* the query parsed from the packet */
195   struct GNUNET_DNSPARSER_Query *query;
196 };
197
198 /**
199  * Our handle to the DNS handler library
200  */
201 struct GNUNET_DNS_Handle *dns_handle;
202
203 /**
204  * Our handle to the DHT
205  */
206 struct GNUNET_DHT_Handle *dht_handle;
207
208 /**
209  * Our zone's private key
210  */
211 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
212
213 /**
214  * Our handle to the namestore service
215  * FIXME maybe need a second handle for iteration
216  */
217 struct GNUNET_NAMESTORE_Handle *namestore_handle;
218
219 /**
220  * Handle to iterate over our authoritative zone in namestore
221  */
222 struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
223
224 /**
225  * The configuration the GNS service is running with
226  */
227 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
228
229 /**
230  * Our notification context.
231  */
232 static struct GNUNET_SERVER_NotificationContext *nc;
233
234 /**
235  * Our zone hash
236  */
237 GNUNET_HashCode zone_hash;
238
239 /**
240  * Our tld. Maybe get from config file
241  */
242 const char* gnunet_tld = ".gnunet";
243
244 /**
245  * Useful for zone update for DHT put
246  */
247 static int num_public_records =  3600;
248 struct GNUNET_TIME_Relative dht_update_interval;
249 GNUNET_SCHEDULER_TaskIdentifier zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
250
251 /**
252  * Helper function to free resolver handle
253  */
254 static void
255 free_resolver_handle(struct GNUNET_GNS_ResolverHandle* rh)
256 {
257   struct AuthorityChain *ac;
258   struct AuthorityChain *ac_next;
259
260   if (NULL == rh)
261     return;
262
263   GNUNET_free_non_null (rh->name);
264   GNUNET_free_non_null (rh->authority_name);
265
266   ac = rh->authority_chain_head;
267
268   while (NULL != ac)
269   {
270     ac_next = ac->next;
271     GNUNET_free_non_null (ac->name);
272     GNUNET_free(ac);
273     ac = ac_next;
274   }
275   GNUNET_free(rh);
276 }
277
278
279 /**
280  * Reply to client with the result from our lookup.
281  *
282  * @param rh the request handle of the lookup
283  * @param rd_count the number of records to return
284  * @param rd the record data
285  */
286 static void
287 reply_to_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh, uint32_t rd_count,
288              const struct GNUNET_NAMESTORE_RecordData *rd)
289 {
290   int i;
291   size_t len;
292   int ret;
293   char *buf;
294   struct InterceptLookupHandle* ilh = (struct InterceptLookupHandle*)cls;
295   struct GNUNET_DNSPARSER_Packet *packet = ilh->packet;
296   struct GNUNET_DNSPARSER_Record answer_records[rh->answered];
297   struct GNUNET_DNSPARSER_Record additional_records[rd_count-(rh->answered)];
298   packet->answers = answer_records;
299   packet->additional_records = additional_records;
300   
301   /**
302    * Put records in the DNS packet and modify it
303    * to a response
304    */
305   len = sizeof(struct GNUNET_DNSPARSER_Record*);
306   for (i=0; i < rd_count; i++)
307   {
308     
309     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
310                "Adding type %d to DNS response\n", rd[i].record_type);
311     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Name: %s\n", rh->name);
312     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "QName: %s\n", ilh->query->name);
313     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Record %d/%d\n", i+1, rd_count);
314     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Record len %d\n", rd[i].data_size);
315     
316     if (rd[i].record_type == ilh->query->type)
317     {
318       answer_records[i].name = ilh->query->name;
319       answer_records[i].type = rd[i].record_type;
320       answer_records[i].data.raw.data_len = rd[i].data_size;
321       answer_records[i].data.raw.data = (char*)rd[i].data;
322       answer_records[i].expiration_time = rd[i].expiration;
323       answer_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
324     }
325     else
326     {
327       additional_records[i].name = ilh->query->name;
328       additional_records[i].type = rd[i].record_type;
329       additional_records[i].data.raw.data_len = rd[i].data_size;
330       additional_records[i].data.raw.data = (char*)rd[i].data;
331       additional_records[i].expiration_time = rd[i].expiration;
332       additional_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
333     }
334   }
335   
336   packet->num_answers = rh->answered;
337   packet->num_additional_records = rd_count-(rh->answered);
338   
339   if (0 == GNUNET_CRYPTO_hash_cmp(&rh->authority, &zone_hash))
340     packet->flags.authoritative_answer = 1;
341   else
342     packet->flags.authoritative_answer = 0;
343
344   if (rd == NULL)
345     packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NAME_ERROR;
346   else
347     packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR;
348   
349   packet->flags.query_or_response = 1;
350
351   
352   /**
353    * Reply to DNS
354    */
355   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
356              "Building DNS response\n");
357   ret = GNUNET_DNSPARSER_pack (packet,
358                                1024, /* FIXME magic from dns redirector */
359                                &buf,
360                                &len);
361   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
362              "Built DNS response! (ret=%d,len=%d)\n", ret, len);
363   if (ret == GNUNET_OK)
364   {
365     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
366                "Answering DNS request\n");
367     GNUNET_DNS_request_answer(ilh->request_handle,
368                               len,
369                               buf);
370
371     GNUNET_free(buf);
372     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Answered DNS request\n");
373   }
374   else
375   {
376     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
377                "Error building DNS response! (ret=%d)", ret);
378   }
379   
380   packet->num_answers = 0;
381   packet->answers = NULL;
382   packet->num_additional_records = 0;
383   packet->additional_records = NULL;
384   GNUNET_DNSPARSER_free_packet(packet);
385   //FIXME free more!
386   GNUNET_free((struct RecordLookupHandle*)rh->proc_cls);
387   free_resolver_handle(rh);
388   GNUNET_free(ilh);
389 }
390
391
392 /**
393  * Task run during shutdown.
394  *
395  * @param cls unused
396  * @param tc unused
397  */
398 static void
399 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
400 {
401
402   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
403              "Shutting down!");
404   /* Kill zone task for it may make the scheduler hang */
405   if (zone_update_taskid)
406     GNUNET_SCHEDULER_cancel(zone_update_taskid);
407   
408   GNUNET_SERVER_notification_context_destroy (nc);
409   GNUNET_DNS_disconnect(dns_handle);
410   GNUNET_NAMESTORE_disconnect(namestore_handle, 1);
411   GNUNET_DHT_disconnect(dht_handle);
412 }
413
414 /**
415  * Callback when record data is put into namestore
416  *
417  * @param cls the closure
418  * @param success GNUNET_OK on success
419  * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
420  */
421 void
422 on_namestore_record_put_result(void *cls,
423                                int32_t success,
424                                const char *emsg)
425 {
426   if (GNUNET_NO == success)
427   {
428     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "records already in namestore\n");
429     return;
430   }
431   else if (GNUNET_YES == success)
432   {
433     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
434                "records successfully put in namestore\n");
435     return;
436   }
437
438   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
439              "Error putting records into namestore: %s\n", emsg);
440 }
441
442 /**
443  * Handle timeout for DHT requests
444  *
445  * @param cls the request handle as closure
446  * @param tc the task context
447  */
448 static void
449 dht_lookup_timeout(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
450 {
451   struct GNUNET_GNS_ResolverHandle *rh = cls;
452
453   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
454              "dht lookup for query %s timed out.\n",
455              rh->name);
456
457   GNUNET_DHT_get_stop (rh->get_handle);
458   rh->proc(rh->proc_cls, rh, 0, NULL);
459 }
460
461
462
463 /**
464  * Function called when we get a result from the dht
465  * for our query
466  *
467  * @param cls the request handle
468  * @param exp lifetime
469  * @param key the key the record was stored under
470  * @param get_path get path
471  * @param get_path_length get path length
472  * @param put_path put path
473  * @param put_path_length put path length
474  * @param type the block type
475  * @param size the size of the record
476  * @param data the record data
477  */
478 static void
479 process_record_dht_result(void* cls,
480                  struct GNUNET_TIME_Absolute exp,
481                  const GNUNET_HashCode * key,
482                  const struct GNUNET_PeerIdentity *get_path,
483                  unsigned int get_path_length,
484                  const struct GNUNET_PeerIdentity *put_path,
485                  unsigned int put_path_length,
486                  enum GNUNET_BLOCK_Type type,
487                  size_t size, const void *data)
488 {
489   struct GNUNET_GNS_ResolverHandle *rh;
490   struct RecordLookupHandle *rlh;
491   struct GNSNameRecordBlock *nrb;
492   uint32_t num_records;
493   char* name = NULL;
494   char* rd_data = (char*)data;
495   int i;
496   int rd_size;
497   
498   GNUNET_HashCode zone, name_hash;
499   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "got dht result (size=%d)\n", size);
500   
501   if (data == NULL)
502     return;
503
504   //FIXME maybe check expiration here, check block type
505   
506   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
507   rlh = (struct RecordLookupHandle *) rh->proc_cls;
508   nrb = (struct GNSNameRecordBlock*)data;
509   
510   /* stop lookup and timeout task */
511   GNUNET_DHT_get_stop (rh->get_handle);
512   GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);
513   
514   rh->get_handle = NULL;
515   name = (char*)&nrb[1];
516   num_records = ntohl(nrb->rd_count);
517   {
518     struct GNUNET_NAMESTORE_RecordData rd[num_records];
519
520     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
521     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
522   
523     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
524                                                                rd_data,
525                                                                num_records,
526                                                                rd))
527     {
528       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
529       return;
530     }
531
532     for (i=0; i<num_records; i++)
533     {
534       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
535                "Got name: %s (wanted %s)\n", name, rh->name);
536       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
537                "Got type: %d\n",
538                rd[i].record_type);
539       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
540                "Got data length: %d\n", rd[i].data_size);
541       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
542                "Got flag %d\n", rd[i].flags);
543     
544      if ((strcmp(name, rh->name) == 0) &&
545          (rd[i].record_type == rlh->record_type))
546       {
547         rh->answered++;
548       }
549
550     }
551
552     GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
553     GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
554   
555     /**
556      * FIXME check pubkey against existing key in namestore?
557      * https://gnunet.org/bugs/view.php?id=2179
558      */
559
560     /* Save to namestore */
561     GNUNET_NAMESTORE_record_put (namestore_handle,
562                                  &nrb->public_key,
563                                  name,
564                                  exp,
565                                  num_records,
566                                  rd,
567                                  &nrb->signature,
568                                  &on_namestore_record_put_result, //cont
569                                  NULL); //cls
570   
571     if (rh->answered)
572       rh->proc(rh->proc_cls, rh, num_records, rd);
573     else
574       rh->proc(rh->proc_cls, rh, 0, NULL);
575   }
576
577 }
578
579
580 /**
581  * Start DHT lookup for a (name -> query->record_type) record in
582  * rh->authority's zone
583  *
584  * @param rh the pending gns query context
585  * @param name the name to query record
586  */
587 static void
588 resolve_record_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
589 {
590   uint32_t xquery;
591   GNUNET_HashCode name_hash;
592   GNUNET_HashCode lookup_key;
593   struct GNUNET_CRYPTO_HashAsciiEncoded lookup_key_string;
594   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
595
596   GNUNET_CRYPTO_hash(rh->name, strlen(rh->name), &name_hash);
597   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
598   GNUNET_CRYPTO_hash_to_enc (&lookup_key, &lookup_key_string);
599   
600   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
601              "starting dht lookup for %s with key: %s\n",
602              rh->name, (char*)&lookup_key_string);
603
604   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed(DHT_LOOKUP_TIMEOUT,
605                                                       &dht_lookup_timeout, rh);
606
607   xquery = htonl(rlh->record_type);
608   rh->get_handle = GNUNET_DHT_get_start(dht_handle, 
609                        DHT_OPERATION_TIMEOUT,
610                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
611                        &lookup_key,
612                        DHT_GNS_REPLICATION_LEVEL,
613                        GNUNET_DHT_RO_NONE,
614                        &xquery, 
615                        sizeof(xquery),
616                        &process_record_dht_result,
617                        rh);
618
619 }
620
621
622 /**
623  * Namestore calls this function if we have record for this name.
624  * (or with rd_count=0 to indicate no matches)
625  *
626  * @param cls the pending query
627  * @param key the key of the zone we did the lookup
628  * @param expiration expiration date of the namestore entry
629  * @param name the name for which we need an authority
630  * @param rd_count the number of records with 'name'
631  * @param rd the record data
632  * @param signature the signature of the authority for the record data
633  */
634 static void
635 process_record_lookup_ns(void* cls,
636                   const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
637                   struct GNUNET_TIME_Absolute expiration,
638                   const char *name, unsigned int rd_count,
639                   const struct GNUNET_NAMESTORE_RecordData *rd,
640                   const struct GNUNET_CRYPTO_RsaSignature *signature)
641 {
642   struct GNUNET_GNS_ResolverHandle *rh;
643   struct RecordLookupHandle *rlh;
644   struct GNUNET_TIME_Relative remaining_time;
645   GNUNET_HashCode zone;
646
647   rh = (struct GNUNET_GNS_ResolverHandle *) cls;
648   rlh = (struct RecordLookupHandle *)rh->proc_cls;
649   GNUNET_CRYPTO_hash(key,
650                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
651                      &zone);
652   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
653
654   rh->status = 0;
655   
656   if (name != NULL)
657   {
658     rh->status |= EXISTS;
659   }
660   
661   if (remaining_time.rel_value == 0)
662   {
663     rh->status |= EXPIRED;
664   }
665   
666   if (rd_count == 0)
667   {
668     /**
669      * Lookup terminated and no results
670      */
671     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
672                "Namestore lookup for %s terminated without results\n", name);
673     
674     
675
676     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
677                "Record %s unknown in namestore\n",
678                rh->name);
679     /**
680      * Our zone and no result? Cannot resolve TT
681      */
682     rh->proc(rh->proc_cls, rh, 0, NULL);
683     return;
684
685   }
686   else
687   {
688     
689     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
690                "Processing additional result %s from namestore\n", name);
691     int i;
692     for (i=0; i<rd_count;i++)
693     {
694       
695       if (rd[i].record_type != rlh->record_type)
696         continue;
697       
698       if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
699           == 0)
700       {
701         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This record is expired. Skipping\n");
702         continue;
703       }
704       
705       rh->answered++;
706       
707     }
708     
709     /**
710      * no answers found
711      */
712     if (rh->answered == 0)
713     {
714       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
715                  "No answers found. This is odd!\n");
716       rh->proc(rh->proc_cls, rh, 0, NULL);
717       return;
718     }
719     
720     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found %d answer(s) to query!\n",
721                rh->answered);
722
723     rh->proc(rh->proc_cls, rh, rd_count, rd);
724   }
725 }
726
727 /**
728  * The final phase of resolution.
729  * This is a name that is canonical and we do not have a delegation.
730  *
731  * @param rh the pending lookup
732  */
733 static void
734 resolve_record_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
735 {
736   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
737   /**
738    * Try to resolve this record in our namestore.
739    * The name to resolve is now in rh->authority_name
740    * since we tried to resolve it to an authority
741    * and failed.
742    **/
743   GNUNET_NAMESTORE_lookup_record(namestore_handle,
744                                  &rh->authority,
745                                  rh->name,
746                                  rlh->record_type,
747                                  &process_record_lookup_ns,
748                                  rh);
749
750 }
751
752
753 /**
754  * Handle timeout for DHT requests
755  *
756  * @param cls the request handle as closure
757  * @param tc the task context
758  */
759 static void
760 dht_authority_lookup_timeout(void *cls,
761                              const struct GNUNET_SCHEDULER_TaskContext *tc)
762 {
763   struct GNUNET_GNS_ResolverHandle *rh = cls;
764
765   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
766              "dht lookup for query %s timed out.\n",
767              rh->name);
768
769   GNUNET_DHT_get_stop (rh->get_handle);
770   if (strcmp(rh->name, "") == 0)
771   {
772     /*
773      * promote authority back to name and try to resolve record
774      */
775     strcpy(rh->name, rh->authority_name);
776   }
777   rh->proc(rh->proc_cls, rh, 0, NULL);
778 }
779
780 // Prototype
781 static void resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh);
782
783 /**
784  * Function called when we get a result from the dht
785  * for our query. Recursively tries to resolve PKEYs
786  * for name in DHT.
787  *
788  * @param cls the request handle
789  * @param exp lifetime
790  * @param key the key the record was stored under
791  * @param get_path get path
792  * @param get_path_length get path length
793  * @param put_path put path
794  * @param put_path_length put path length
795  * @param type the block type
796  * @param size the size of the record
797  * @param data the record data
798  */
799 static void
800 process_authority_dht_result(void* cls,
801                  struct GNUNET_TIME_Absolute exp,
802                  const GNUNET_HashCode * key,
803                  const struct GNUNET_PeerIdentity *get_path,
804                  unsigned int get_path_length,
805                  const struct GNUNET_PeerIdentity *put_path,
806                  unsigned int put_path_length,
807                  enum GNUNET_BLOCK_Type type,
808                  size_t size, const void *data)
809 {
810   struct GNUNET_GNS_ResolverHandle *rh;
811   struct GNSNameRecordBlock *nrb;
812   uint32_t num_records;
813   char* name = NULL;
814   char* rd_data = (char*) data;
815   int i;
816   int rd_size;
817   GNUNET_HashCode zone, name_hash;
818   
819   if (data == NULL)
820     return;
821   
822   //FIXME check expiration?
823   
824   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
825   nrb = (struct GNSNameRecordBlock*)data;
826   
827   /* stop dht lookup and timeout task */
828   GNUNET_DHT_get_stop (rh->get_handle);
829   GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);
830
831   rh->get_handle = NULL;
832   num_records = ntohl(nrb->rd_count);
833   name = (char*)&nrb[1];
834   {
835     struct GNUNET_NAMESTORE_RecordData rd[num_records];
836     
837     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
838     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
839   
840     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
841                                                                rd_data,
842                                                                num_records,
843                                                                rd))
844     {
845       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
846       return;
847     }
848
849     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
850                "Got name: %s (wanted %s)\n", name, rh->authority_name);
851     for (i=0; i<num_records; i++)
852     {
853     
854       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
855                 "Got name: %s (wanted %s)\n", name, rh->authority_name);
856       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
857                  "Got type: %d (wanted %d)\n",
858                  rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
859       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
860                  "Got data length: %d\n", rd[i].data_size);
861       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
862                  "Got flag %d\n", rd[i].flags);
863
864       if ((strcmp(name, rh->authority_name) == 0) &&
865           (rd[i].record_type == GNUNET_GNS_RECORD_PKEY))
866       {
867         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Authority found in DHT\n");
868         rh->answered = 1;
869         memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
870         struct AuthorityChain *auth =
871           GNUNET_malloc(sizeof(struct AuthorityChain));
872         auth->zone = rh->authority;
873         auth->name = GNUNET_malloc(strlen(rh->authority_name)+1);
874         memset(auth->name, 0, strlen(rh->authority_name)+1);
875         strcpy(auth->name, rh->authority_name);
876         GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
877                                      rh->authority_chain_tail,
878                                      auth);
879       }
880
881     }
882
883
884     GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
885     GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
886
887     /* Save to namestore */
888     if (0 != GNUNET_CRYPTO_hash_cmp(&zone_hash, &zone))
889     {
890       GNUNET_NAMESTORE_record_put (namestore_handle,
891                                  &nrb->public_key,
892                                  name,
893                                  exp,
894                                  num_records,
895                                  rd,
896                                  &nrb->signature,
897                                  &on_namestore_record_put_result, //cont
898                                  NULL); //cls
899     }
900   }
901   
902   if (rh->answered)
903   {
904     rh->answered = 0;
905     /* delegate */
906     if (strcmp(rh->name, "") == 0)
907       rh->proc(rh->proc_cls, rh, 0, NULL);
908     else
909       resolve_delegation_from_dht(rh);
910     return;
911   }
912
913   /**
914    * should never get here unless false dht key/put
915    * block plugin should handle this
916    **/
917   
918   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DHT authority lookup error!\n");
919   GNUNET_break(0);
920 }
921
922
923 /**
924  * Process DHT lookup result for record.
925  *
926  * @param cls the closure
927  * @param rh resolver handle
928  * @param rd_count number of results (always 0)
929  * @param rd record data (always NULL)
930  */
931 static void
932 process_record_result_dht(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
933                        unsigned int rd_count,
934                        const struct GNUNET_NAMESTORE_RecordData *rd)
935 {
936   struct RecordLookupHandle* rlh;
937   rlh = (struct RecordLookupHandle*)cls;
938   if (rd_count == 0)
939   {
940     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
941                "No records for %s found in DHT. Aborting\n",
942                rh->name);
943     /* give up, cannot resolve */
944     rlh->proc(rlh->proc_cls, rh, 0, NULL);
945     //reply_to_dns(NULL, rh, 0, NULL);
946     return;
947   }
948
949   /* results found yay */
950   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
951              "Record resolved from namestore!");
952   rlh->proc(rlh->proc_cls, rh, rd_count, rd);
953   //reply_to_dns(NULL, rh, rd_count, rd);
954
955 }
956
957
958 /**
959  * Process namestore lookup result for record.
960  *
961  * @param cls the closure
962  * @param rh resolver handle
963  * @param rd_count number of results (always 0)
964  * @param rd record data (always NULL)
965  */
966 static void
967 process_record_result_ns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
968                        unsigned int rd_count,
969                        const struct GNUNET_NAMESTORE_RecordData *rd)
970 {
971   struct RecordLookupHandle* rlh;
972   rlh = (struct RecordLookupHandle*) cls;
973   if (rd_count == 0)
974   {
975     /* ns entry expired. try dht */
976     if (rh->status & (EXPIRED | !EXISTS))
977     {
978       rh->proc = &process_record_result_dht;
979       resolve_record_from_dht(rh);
980       return;
981     }
982     /* give up, cannot resolve */
983     rlh->proc(rlh->proc_cls, rh, 0, NULL);
984     //reply_to_dns(NULL, rh, 0, NULL);
985     return;
986   }
987
988   /* results found yay */
989   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
990              "Record resolved from namestore!");
991   rlh->proc(rlh->proc_cls, rh, rd_count, rd);
992   //reply_to_dns(NULL, rh, rd_count, rd);
993
994 }
995
996
997 /**
998  * Determine if this name is canonical.
999  * i.e.
1000  * a.b.gnunet  = not canonical
1001  * a           = canonical
1002  *
1003  * @param name the name to test
1004  * @return 1 if canonical
1005  */
1006 static int
1007 is_canonical(char* name)
1008 {
1009   uint32_t len = strlen(name);
1010   int i;
1011
1012   for (i=0; i<len; i++)
1013   {
1014     if (*(name+i) == '.')
1015       return 0;
1016   }
1017   return 1;
1018 }
1019
1020 /**
1021  * Move one level up in the domain hierarchy and return the
1022  * passed top level domain.
1023  *
1024  * @param name the domain
1025  * @param dest the destination where the tld will be put
1026  */
1027 void
1028 pop_tld(char* name, char* dest)
1029 {
1030   uint32_t len;
1031
1032   if (is_canonical(name))
1033   {
1034     strcpy(dest, name);
1035     strcpy(name, "");
1036     return;
1037   }
1038
1039   for (len = strlen(name); len > 0; len--)
1040   {
1041     if (*(name+len) == '.')
1042       break;
1043   }
1044   
1045   //Was canonical?
1046   if (len == 0)
1047     return;
1048
1049   name[len] = '\0';
1050
1051   strcpy(dest, (name+len+1));
1052 }
1053
1054 /**
1055  * DHT resolution for delegation finished. Processing result.
1056  *
1057  * @param cls the closure
1058  * @param rh resolver handle
1059  * @param rd_count number of results (always 0)
1060  * @param rd record data (always NULL)
1061  */
1062 static void
1063 process_dht_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
1064                           unsigned int rd_count,
1065                           const struct GNUNET_NAMESTORE_RecordData *rd)
1066 {
1067   struct RecordLookupHandle* rlh;
1068   rlh = (struct RecordLookupHandle*) cls;
1069   
1070   if (strcmp(rh->name, "") == 0)
1071   {
1072     /* We resolved full name for delegation. resolving record */
1073     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1074       "Resolved full name for delegation via DHT. resolving record '' in ns\n");
1075     rh->proc = &process_record_result_ns;
1076     resolve_record_from_ns(rh);
1077     return;
1078   }
1079
1080   /**
1081    * we still have some left
1082    **/
1083   if (is_canonical(rh->name))
1084   {
1085     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1086                "Resolving canonical record %s in ns\n", rh->name);
1087     rh->proc = &process_record_result_ns;
1088     resolve_record_from_ns(rh);
1089     return;
1090   }
1091   /* give up, cannot resolve */
1092   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1093              "Cannot fully resolve delegation for %s via DHT!\n",
1094              rh->name);
1095   rlh->proc(rlh->proc_cls, rh, 0, NULL);
1096   //reply_to_dns(NULL, rh, 0, NULL);
1097 }
1098
1099
1100 /**
1101  * Start DHT lookup for a name -> PKEY (compare NS) record in
1102  * rh->authority's zone
1103  *
1104  * @param rh the pending gns query
1105  * @param name the name of the PKEY record
1106  */
1107 static void
1108 resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
1109 {
1110   uint32_t xquery;
1111   GNUNET_HashCode name_hash;
1112   GNUNET_HashCode lookup_key;
1113
1114   GNUNET_CRYPTO_hash(rh->authority_name,
1115                      strlen(rh->authority_name),
1116                      &name_hash);
1117   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
1118
1119   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1120                                                   &dht_authority_lookup_timeout,
1121                                                        rh);
1122
1123   xquery = htonl(GNUNET_GNS_RECORD_PKEY);
1124   
1125   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
1126                        DHT_OPERATION_TIMEOUT,
1127                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1128                        &lookup_key,
1129                        DHT_GNS_REPLICATION_LEVEL,
1130                        GNUNET_DHT_RO_NONE,
1131                        &xquery,
1132                        sizeof(xquery),
1133                        &process_authority_dht_result,
1134                        rh);
1135
1136 }
1137
1138
1139 /**
1140  * Namestore resolution for delegation finished. Processing result.
1141  *
1142  * @param cls the closure
1143  * @param rh resolver handle
1144  * @param rd_count number of results (always 0)
1145  * @param rd record data (always NULL)
1146  */
1147 static void
1148 process_ns_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
1149                           unsigned int rd_count,
1150                           const struct GNUNET_NAMESTORE_RecordData *rd)
1151 {
1152   struct RecordLookupHandle* rlh;
1153   rlh = (struct RecordLookupHandle*) cls;
1154   
1155   if (strcmp(rh->name, "") == 0)
1156   {
1157     /* We resolved full name for delegation. resolving record */
1158     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1159                "Resolved full name for delegation. resolving record ''\n");
1160     rh->proc = &process_record_result_ns;
1161     resolve_record_from_ns(rh);
1162     return;
1163   }
1164
1165   /**
1166    * we still have some left
1167    * check if ns entry is fresh
1168    **/
1169   if (rh->status & (EXISTS | !EXPIRED))
1170   {
1171     if (is_canonical(rh->name))
1172     {
1173       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1174                  "Resolving canonical record %s\n", rh->name);
1175       rh->proc = &process_record_result_ns;
1176       resolve_record_from_ns(rh);
1177     }
1178     else
1179     {
1180       /* give up, cannot resolve */
1181       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1182                  "Cannot fully resolve delegation for %s!\n",
1183                  rh->name);
1184       rlh->proc(rlh->proc_cls, rh, 0, NULL);
1185       //reply_to_dns(NULL, rh, 0, NULL);
1186     }
1187     return;
1188   }
1189   
1190   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1191              "Trying to resolve delegation for %s via DHT\n",
1192              rh->name);
1193   rh->proc = &process_dht_delegation_dns;
1194   resolve_delegation_from_dht(rh);
1195 }
1196
1197 //Prototype
1198 static void resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh);
1199
1200 /**
1201  * This is a callback function that should give us only PKEY
1202  * records. Used to query the namestore for the authority (PKEY)
1203  * for 'name'. It will recursively try to resolve the
1204  * authority for a given name from the namestore.
1205  *
1206  * @param cls the pending query
1207  * @param key the key of the zone we did the lookup
1208  * @param expiration expiration date of the record data set in the namestore
1209  * @param name the name for which we need an authority
1210  * @param rd_count the number of records with 'name'
1211  * @param rd the record data
1212  * @param signature the signature of the authority for the record data
1213  */
1214 static void
1215 process_authority_lookup_ns(void* cls,
1216                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1217                    struct GNUNET_TIME_Absolute expiration,
1218                    const char *name,
1219                    unsigned int rd_count,
1220                    const struct GNUNET_NAMESTORE_RecordData *rd,
1221                    const struct GNUNET_CRYPTO_RsaSignature *signature)
1222 {
1223   struct GNUNET_GNS_ResolverHandle *rh;
1224   struct GNUNET_TIME_Relative remaining_time;
1225   GNUNET_HashCode zone;
1226   char* new_name;
1227   
1228   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got %d records from authority lookup\n",
1229              rd_count);
1230
1231   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
1232   GNUNET_CRYPTO_hash(key,
1233                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1234                      &zone);
1235   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
1236   
1237   rh->status = 0;
1238   
1239   if (name != NULL)
1240   {
1241     rh->status |= EXISTS;
1242   }
1243   
1244   if (remaining_time.rel_value == 0)
1245   {
1246     rh->status |= EXPIRED;
1247   }
1248   
1249   /**
1250    * No authority found in namestore.
1251    */
1252   if (rd_count == 0)
1253   {
1254     /**
1255      * We did not find an authority in the namestore
1256      */
1257     
1258     /**
1259      * No PKEY in zone.
1260      * Promote this authority back to a name maybe it is
1261      * our record.
1262      */
1263     if (strcmp(rh->name, "") == 0)
1264     {
1265       /* simply promote back */
1266       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1267                  "Promoting %s back to name\n", rh->authority_name);
1268       strcpy(rh->name, rh->authority_name);
1269     }
1270     else
1271     {
1272       /* add back to existing name */
1273       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1274                  "Adding %s back to %s\n",
1275                  rh->authority_name, rh->name);
1276       new_name = GNUNET_malloc(strlen(rh->name)
1277                                + strlen(rh->authority_name) + 2);
1278       memset(new_name, 0, strlen(rh->name) + strlen(rh->authority_name) + 2);
1279       strcpy(new_name, rh->name);
1280       strcpy(new_name+strlen(new_name)+1, ".");
1281       strcpy(new_name+strlen(new_name)+2, rh->authority_name);
1282       GNUNET_free(rh->name);
1283       rh->name = new_name;
1284     }
1285     rh->proc(rh->proc_cls, rh, 0, NULL);
1286     return;
1287   }
1288
1289   //Note only 1 pkey should have been returned.. anything else would be strange
1290   /**
1291    * We found an authority that may be able to help us
1292    * move on with query
1293    */
1294   int i;
1295   for (i=0; i<rd_count;i++)
1296   {
1297   
1298     if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
1299       continue;
1300     
1301     if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
1302          == 0)
1303     {
1304       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This pkey is expired.\n");
1305       if (remaining_time.rel_value == 0)
1306       {
1307         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1308                    "This dht entry is expired.\n");
1309         rh->authority_chain_head->fresh = 0;
1310         rh->proc(rh->proc_cls, rh, 0, NULL);
1311         return;
1312       }
1313
1314       continue;
1315     }
1316
1317     /**
1318      * Resolve rest of query with new authority
1319      */
1320     GNUNET_assert(rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
1321     memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
1322     struct AuthorityChain *auth = GNUNET_malloc(sizeof(struct AuthorityChain));
1323     auth->zone = rh->authority;
1324     auth->name = GNUNET_malloc(strlen(rh->authority_name)+1);
1325     memset(auth->name, 0, strlen(rh->authority_name)+1);
1326     strcpy(auth->name, rh->authority_name);
1327     GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
1328                                  rh->authority_chain_tail,
1329                                  auth);
1330     
1331     /**
1332      * We are done with PKEY resolution if name is empty
1333      * else resolve again with new authority
1334      */
1335     if (strcmp(rh->name, "") == 0)
1336       rh->proc(rh->proc_cls, rh, 0, NULL);
1337     else
1338       resolve_delegation_from_ns(rh);
1339     return;
1340   }
1341     
1342   /**
1343    * no answers found
1344    */
1345   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1346              "Authority lookup successful but no PKEY... never get here\n");
1347   rh->proc(rh->proc_cls, rh, 0, NULL);
1348 }
1349
1350
1351 /**
1352  * Resolve the delegation chain for the request
1353  *
1354  * @param rh the resolver handle
1355  */
1356 static void
1357 resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
1358 {
1359   
1360   pop_tld(rh->name, rh->authority_name);
1361   GNUNET_NAMESTORE_lookup_record(namestore_handle,
1362                                  &rh->authority,
1363                                  rh->authority_name,
1364                                  GNUNET_GNS_RECORD_PKEY,
1365                                  &process_authority_lookup_ns,
1366                                  rh);
1367
1368 }
1369
1370 /**
1371  * Entry point for name resolution
1372  * Setup a new query and try to resolve
1373  *
1374  * @param request the request handle of the DNS request from a client
1375  * @param p the DNS query packet we received
1376  * @param q the DNS query we received parsed from p
1377  */
1378 static void
1379 start_resolution_from_dns(struct GNUNET_DNS_RequestHandle *request,
1380                           struct GNUNET_DNSPARSER_Packet *p,
1381                           struct GNUNET_DNSPARSER_Query *q)
1382 {
1383   struct GNUNET_GNS_ResolverHandle *rh;
1384   struct RecordLookupHandle* rlh;
1385   struct InterceptLookupHandle* ilh;
1386   
1387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1388               "Starting resolution for %s (type=%d)!\n",
1389               q->name, q->type);
1390   
1391   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
1392   rlh = GNUNET_malloc(sizeof(struct RecordLookupHandle));
1393   ilh = GNUNET_malloc(sizeof(struct InterceptLookupHandle));
1394   ilh->packet = p;
1395   ilh->query = q;
1396   ilh->request_handle = request;
1397   
1398   rh->authority = zone_hash;
1399
1400   rlh->record_type = q->type;
1401   rlh->name = q->name;
1402   rlh->proc = &reply_to_dns;
1403   rlh->proc_cls = ilh;
1404
1405   rh->proc_cls = rlh;
1406   
1407   rh->authority = zone_hash;
1408   rh->name = GNUNET_malloc(strlen(q->name)
1409                               - strlen(gnunet_tld) + 1);
1410   memset(rh->name, 0,
1411          strlen(q->name)-strlen(gnunet_tld) + 1);
1412   memcpy(rh->name, q->name,
1413          strlen(q->name)-strlen(gnunet_tld));
1414
1415   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
1416   
1417   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
1418   rh->authority_chain_head->prev = NULL;
1419   rh->authority_chain_head->next = NULL;
1420   rh->authority_chain_tail = rh->authority_chain_head;
1421   rh->authority_chain_head->zone = zone_hash;
1422
1423   /* Start resolution in our zone */
1424   rh->proc = &process_ns_delegation_dns;
1425   resolve_delegation_from_ns(rh);
1426 }
1427
1428
1429
1430 /**
1431  * The DNS request handler
1432  * Called for every incoming DNS request.
1433  *
1434  * @param cls closure
1435  * @param rh request handle to user for reply
1436  * @param request_length number of bytes in request
1437  * @param request udp payload of the DNS request
1438  */
1439 static void
1440 handle_dns_request(void *cls,
1441                    struct GNUNET_DNS_RequestHandle *rh,
1442                    size_t request_length,
1443                    const char *request)
1444 {
1445   struct GNUNET_DNSPARSER_Packet *p;
1446   int i;
1447   char *tldoffset;
1448
1449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hijacked a DNS request...processing\n");
1450   p = GNUNET_DNSPARSER_parse (request, request_length);
1451   
1452   if (NULL == p)
1453   {
1454     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1455                 "Received malformed DNS packet, leaving it untouched\n");
1456     GNUNET_DNS_request_forward (rh);
1457     GNUNET_DNSPARSER_free_packet (p);
1458     return;
1459   }
1460   
1461   /**
1462    * Check tld and decide if we or
1463    * legacy dns is responsible
1464    *
1465    * FIXME now in theory there could be more than 1 query in the request
1466    * but if this is case we get into trouble:
1467    * either we query the GNS or the DNS. We cannot do both!
1468    * So I suggest to either only allow a single query per request or
1469    * only allow GNS or DNS requests.
1470    * The way it is implemented here now is buggy and will lead to erratic
1471    * behaviour (if multiple queries are present).
1472    */
1473   if (p->num_queries == 0)
1474   {
1475     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476                 "No Queries in DNS packet... forwarding\n");
1477     GNUNET_DNS_request_forward (rh);
1478     GNUNET_DNSPARSER_free_packet(p);
1479     return;
1480   }
1481
1482   if (p->num_queries > 1)
1483   {
1484     /* Note: We could also look for .gnunet */
1485     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1486                 ">1 queriy in DNS packet... odd. We only process #1\n");
1487   }
1488
1489   
1490   /**
1491    * Check for .gnunet
1492    */
1493   tldoffset = p->queries[0].name + strlen(p->queries[0].name) - 1;
1494   
1495   for (i=0; i<strlen(p->queries[0].name); i++)
1496   {
1497     if (*(tldoffset-i) == '.')
1498       break;
1499   }
1500   
1501   if ((i==strlen(gnunet_tld)-1) && (0 == strcmp(tldoffset-i, gnunet_tld)))
1502   {
1503     start_resolution_from_dns(rh, p, p->queries);
1504   }
1505   else
1506   {
1507     /**
1508      * This request does not concern us. Forward to real DNS.
1509      */
1510     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1511                "Request for %s is forwarded to DNS\n", p->queries[0].name);
1512     GNUNET_DNS_request_forward (rh);
1513     GNUNET_DNSPARSER_free_packet (p);
1514   }
1515
1516 }
1517
1518 /**
1519  * Method called periodicattluy that triggers
1520  * iteration over root zone
1521  *
1522  * @param cls closure
1523  * @param tc task context
1524  */
1525 static void
1526 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1527 {
1528   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
1529 }
1530
1531 /**
1532  * Continuation for DHT put
1533  *
1534  * @param cls closure
1535  * @param tc task context
1536  */
1537 static void
1538 record_dht_put(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1539 {
1540   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
1541 }
1542
1543 /* prototype */
1544 static void
1545 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1546
1547 /**
1548  * Function used to put all records successively into the DHT.
1549  *
1550  * @param cls the closure (NULL)
1551  * @param key the public key of the authority (ours)
1552  * @param expiration lifetime of the namestore entry
1553  * @param name the name of the records
1554  * @param rd_count the number of records in data
1555  * @param rd the record data
1556  * @param signature the signature for the record data
1557  */
1558 static void
1559 put_gns_record(void *cls,
1560                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1561                 struct GNUNET_TIME_Absolute expiration,
1562                 const char *name,
1563                 unsigned int rd_count,
1564                 const struct GNUNET_NAMESTORE_RecordData *rd,
1565                 const struct GNUNET_CRYPTO_RsaSignature *signature)
1566 {
1567   
1568   struct GNSNameRecordBlock *nrb;
1569   GNUNET_HashCode name_hash;
1570   GNUNET_HashCode xor_hash;
1571   struct GNUNET_CRYPTO_HashAsciiEncoded xor_hash_string;
1572   uint32_t rd_payload_length;
1573   char* nrb_data = NULL;
1574
1575   /* we're done */
1576   if (NULL == name)
1577   {
1578     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Zone iteration finished\n");
1579     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
1580     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start,
1581                                                    NULL);
1582     return;
1583   }
1584   
1585   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1586              "Putting records for %s into the DHT\n", name);
1587   
1588   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
1589   
1590   nrb = GNUNET_malloc(rd_payload_length + strlen(name) + 1 
1591                       + sizeof(struct GNSNameRecordBlock));
1592   
1593   if (signature != NULL)
1594     nrb->signature = *signature;
1595   
1596   nrb->public_key = *key;
1597
1598   nrb->rd_count = htonl(rd_count);
1599   
1600   memset(&nrb[1], 0, strlen(name) + 1);
1601   memcpy(&nrb[1], name, strlen(name));
1602
1603   nrb_data = (char*)&nrb[1];
1604   nrb_data += strlen(name) + 1;
1605
1606   rd_payload_length += sizeof(struct GNSNameRecordBlock) +
1607     strlen(name) + 1;
1608
1609   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
1610                                                 rd,
1611                                                 rd_payload_length,
1612                                                 nrb_data))
1613   {
1614     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Record serialization failed!\n");
1615     return;
1616     //FIXME what to do
1617   }
1618
1619
1620   /*
1621    * calculate DHT key: H(name) xor H(pubkey)
1622    */
1623   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
1624   GNUNET_CRYPTO_hash_xor(&zone_hash, &name_hash, &xor_hash);
1625   GNUNET_CRYPTO_hash_to_enc (&xor_hash, &xor_hash_string);
1626   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1627              "putting records for %s under key: %s with size %d\n",
1628              name, (char*)&xor_hash_string, rd_payload_length);
1629
1630   GNUNET_DHT_put (dht_handle, &xor_hash,
1631                   DHT_GNS_REPLICATION_LEVEL,
1632                   GNUNET_DHT_RO_NONE,
1633                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1634                   rd_payload_length,
1635                   (char*)nrb,
1636                   expiration,
1637                   DHT_OPERATION_TIMEOUT,
1638                   &record_dht_put,
1639                   NULL); //cls for cont
1640   
1641   num_public_records++;
1642
1643   /**
1644    * Reschedule periodic put
1645    */
1646   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (dht_update_interval,
1647                                 &update_zone_dht_next,
1648                                 NULL);
1649
1650   GNUNET_free(nrb);
1651
1652 }
1653
1654 /**
1655  * Periodically iterate over our zone and store everything in dht
1656  *
1657  * @param cls NULL
1658  * @param tc task context
1659  */
1660 static void
1661 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1662 {
1663   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting DHT zone update!\n");
1664   if (0 == num_public_records)
1665   {
1666     dht_update_interval = GNUNET_TIME_relative_multiply(
1667                                                       GNUNET_TIME_UNIT_SECONDS,
1668                                                       1);
1669   }
1670   else
1671   {
1672     dht_update_interval = GNUNET_TIME_relative_multiply(
1673                                                       GNUNET_TIME_UNIT_SECONDS,
1674                                                      (3600/num_public_records));
1675   }
1676   num_public_records = 0; //start counting again
1677   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
1678                                                           &zone_hash,
1679                                                           GNUNET_NAMESTORE_RF_AUTHORITY,
1680                                                           GNUNET_NAMESTORE_RF_PRIVATE,
1681                                                           &put_gns_record,
1682                                                           NULL);
1683 }
1684
1685 //Prototype
1686 static void send_shorten_response(const char* name,
1687                                   struct ClientShortenHandle *csh);
1688 static void
1689 process_shorten_pseu_lookup_ns(void *cls,
1690                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1691                  struct GNUNET_TIME_Absolute expire,
1692                  const char *name,
1693                  unsigned int rd_len,
1694                  const struct GNUNET_NAMESTORE_RecordData *rd,
1695                  const struct GNUNET_CRYPTO_RsaSignature *signature)
1696 {
1697   struct GNUNET_GNS_ResolverHandle *rh = 
1698     (struct GNUNET_GNS_ResolverHandle *)cls;
1699   struct GNUNET_TIME_Relative remaining_time;
1700
1701   
1702   rh->status = 0;
1703   
1704   if (name != NULL)
1705   {
1706     rh->status |= EXISTS;
1707   }
1708   
1709   if (remaining_time.rel_value == 0)
1710   {
1711     rh->status |= EXPIRED;
1712   }
1713
1714   rh->proc(rh->proc_cls, rh, rd_len, rd);
1715 }
1716
1717
1718 /**
1719  * Start DHT lookup for a PSEUdonym record in
1720  * rh->authority's zone
1721  *
1722  * @param rh the pending gns query
1723  * @param name the name of the PKEY record
1724  */
1725 static void
1726 resolve_pseu_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
1727 {
1728   uint32_t xquery;
1729   GNUNET_HashCode name_hash;
1730   GNUNET_HashCode lookup_key;
1731
1732   //Empty string
1733   GNUNET_CRYPTO_hash("",
1734                      1,
1735                      &name_hash);
1736
1737   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
1738
1739   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1740                                                   &dht_lookup_timeout,
1741                                                   rh);
1742
1743   xquery = htonl(GNUNET_GNS_RECORD_PSEU);
1744   
1745   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
1746                        DHT_OPERATION_TIMEOUT,
1747                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1748                        &lookup_key,
1749                        DHT_GNS_REPLICATION_LEVEL,
1750                        GNUNET_DHT_RO_NONE,
1751                        &xquery,
1752                        sizeof(xquery),
1753                        &process_authority_dht_result,
1754                        rh);
1755
1756 }
1757
1758 //Prototype
1759 static void
1760 handle_shorten_pseu_ns_result(void* cls,
1761                               struct GNUNET_GNS_ResolverHandle *rh,
1762                               uint32_t rd_count,
1763                               const struct GNUNET_NAMESTORE_RecordData *rd);
1764
1765 static void
1766 handle_shorten_zone_to_name(void *cls,
1767                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1768                  struct GNUNET_TIME_Absolute expire,
1769                  const char *name,
1770                  unsigned int rd_len,
1771                  const struct GNUNET_NAMESTORE_RecordData *rd,
1772                  const struct GNUNET_CRYPTO_RsaSignature *signature)
1773 {
1774   struct GNUNET_GNS_ResolverHandle *rh = 
1775     (struct GNUNET_GNS_ResolverHandle *)cls;
1776   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) rh->proc_cls;
1777
1778   char* result;
1779   size_t answer_len;
1780   
1781   /* we found a match in our own zone */
1782   if (rd_len != 0)
1783   {
1784     answer_len = strlen(rh->name) + strlen(name) + strlen(gnunet_tld) + 2;
1785     result = GNUNET_malloc(answer_len);
1786     memset(result, 0, answer_len);
1787     strcpy(result, rh->name);
1788     strcpy(result+strlen(rh->name), ".");
1789     strcpy(result+strlen(rh->name)+1, name);
1790     strcpy(result+strlen(rh->name)+strlen(name), gnunet_tld);
1791     
1792     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1793                "Sending shorten result %s\n", result);
1794
1795     send_shorten_response(result, csh);
1796     free_resolver_handle(rh);
1797     GNUNET_free(result);
1798   }
1799   else
1800   {
1801     /**
1802      * Nothing in our zone
1803      * check PSEU for this authority in namestore
1804      */
1805     rh->proc = &handle_shorten_pseu_ns_result;
1806     GNUNET_NAMESTORE_lookup_record(namestore_handle,
1807                                    &rh->authority_chain_head->zone,
1808                                    "",
1809                                    GNUNET_GNS_RECORD_PSEU,
1810                                    &process_shorten_pseu_lookup_ns,
1811                                    rh);
1812   }
1813 }
1814
1815 /**
1816  * Process result from namestore delegation lookup
1817  * for shorten operation
1818  *
1819  * @param cls the client shorten handle
1820  * @param rh the resolver handle
1821  * @param rd_count number of results (0)
1822  * @param rd data (NULL)
1823  */
1824 void
1825 handle_shorten_pseu_dht_result(void* cls,
1826                       struct GNUNET_GNS_ResolverHandle *rh,
1827                       uint32_t rd_len,
1828                       const struct GNUNET_NAMESTORE_RecordData *rd)
1829 {
1830   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1831   struct AuthorityChain *auth_chain;
1832   char* pseu;
1833   char* result;
1834   char* new_name;
1835   size_t answer_len;
1836   int i;
1837   
1838   /**
1839    * PSEU found
1840    */
1841   if (rd_len != 0)
1842   {
1843     for (i=0; i < rd_len; i++)
1844     {
1845       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1846       {
1847         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1848                    "Found PSEU %s\n", (char*) rd[i].data);
1849         break;
1850       }
1851     }
1852
1853     pseu = (char*) rd[i].data;
1854     answer_len = strlen(rh->name) + strlen(pseu) + strlen(gnunet_tld) + 2;
1855     result = GNUNET_malloc(answer_len);
1856     memset(result, 0, answer_len);
1857     strcpy(result, rh->name);
1858     strcpy(result+strlen(rh->name), ".");
1859     strcpy(result+strlen(rh->name)+1, pseu);
1860     strcpy(result+strlen(rh->name)+strlen(pseu), gnunet_tld);
1861     
1862     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1863                "Sending pseudonym shorten result %s\n", result);
1864     
1865     send_shorten_response(result, csh);
1866     free_resolver_handle(rh);
1867     GNUNET_free(result);
1868     return;
1869   }
1870   
1871   /**
1872    * No PSEU found.
1873    * continue with next authority
1874    * backtrack
1875    */
1876   auth_chain = rh->authority_chain_head;
1877
1878   if ((auth_chain->next->next == NULL) &&
1879       GNUNET_CRYPTO_hash_cmp(&auth_chain->next->zone, &zone_hash) == 0)
1880   {
1881     /**
1882      * Our zone is next
1883      */
1884     answer_len = strlen(rh->name) + strlen(auth_chain->name)
1885       + strlen(gnunet_tld) + 2;
1886
1887     result = GNUNET_malloc(answer_len);
1888     memset(result, 0, answer_len);
1889     strcpy(result, rh->name);
1890     strcpy(result+strlen(rh->name), ".");
1891     strcpy(result+strlen(rh->name)+1, auth_chain->name);
1892     strcpy(result+strlen(rh->name)+strlen(auth_chain->name)+1, gnunet_tld);
1893     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1894                "Sending non pseudonym shorten result %s\n", result);
1895     
1896     send_shorten_response(result, csh);
1897     free_resolver_handle(rh);
1898     GNUNET_free(result);
1899     return;
1900   }
1901
1902   /**
1903    * Continue with next authority
1904    */
1905   new_name = GNUNET_malloc(strlen(rh->name)+
1906                            strlen(auth_chain->name) + 2);
1907   memset(new_name, 0, strlen(rh->name)+
1908                       strlen(auth_chain->name) + 2);
1909   strcpy(new_name, rh->name);
1910   strcpy(new_name+strlen(rh->name)+1, ".");
1911   strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
1912   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
1913                               rh->authority_chain_tail,
1914                               auth_chain);
1915   GNUNET_free(rh->name);
1916   rh->name = new_name;
1917   GNUNET_free(auth_chain->name);
1918   GNUNET_free(auth_chain);
1919   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1920                                  &zone_hash,
1921                                  &rh->authority_chain_head->zone,
1922                                  &handle_shorten_zone_to_name,
1923                                  rh);
1924
1925 }
1926
1927
1928
1929 /**
1930  * Process result from namestore PSEU lookup
1931  * for shorten operation
1932  * FIXME do we need to check for own zone here?
1933  *
1934  * @param cls the client shorten handle
1935  * @param rh the resolver handle
1936  * @param rd_count number of results (0 if none found)
1937  * @param rd data (NULL if none found)
1938  */
1939 static void
1940 handle_shorten_pseu_ns_result(void* cls,
1941                       struct GNUNET_GNS_ResolverHandle *rh,
1942                       uint32_t rd_len,
1943                       const struct GNUNET_NAMESTORE_RecordData *rd)
1944 {
1945   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1946   struct AuthorityChain *auth_chain;
1947   char* pseu;
1948   char* result;
1949   char* new_name;
1950   size_t answer_len;
1951   int i;
1952   
1953   /**
1954    * PSEU found
1955    */
1956   if (rd_len != 0)
1957   {
1958     for (i=0; i < rd_len; i++)
1959     {
1960       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1961       {
1962         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1963                    "Found PSEU %s\n", (char*) rd[i].data);
1964         break;
1965       }
1966     }
1967     
1968     pseu = (char*) rd[i].data;
1969     answer_len = strlen(rh->name) + strlen(pseu) + strlen(gnunet_tld) + 2;
1970     result = GNUNET_malloc(answer_len);
1971     memset(result, 0, answer_len);
1972     strcpy(result, rh->name);
1973     strcpy(result+strlen(rh->name), ".");
1974     strcpy(result+strlen(rh->name)+1, pseu);
1975     strcpy(result+strlen(rh->name)+strlen(pseu)+1, gnunet_tld);
1976     
1977     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1978                "Sending shorten result %s\n", result);
1979     
1980     send_shorten_response(result, csh);
1981     free_resolver_handle(rh);
1982     GNUNET_free(result);
1983     return;
1984   }
1985   
1986   /**
1987    * No PSEU found. Ask DHT if expired.
1988    * Else contunue with next authority
1989    */
1990   if (rh->status & (EXISTS | !EXPIRED))
1991   {
1992     /**
1993      * backtrack
1994      */
1995     auth_chain = rh->authority_chain_head;
1996     new_name = GNUNET_malloc(strlen(rh->name)+
1997                              strlen(auth_chain->name) + 2);
1998     memset(new_name, 0, strlen(rh->name)+
1999                         strlen(auth_chain->name) + 2);
2000     strcpy(new_name, rh->name);
2001     strcpy(new_name+strlen(rh->name)+1, ".");
2002     strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
2003     
2004     GNUNET_free(rh->name);
2005     rh->name = new_name;
2006     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
2007                                 rh->authority_chain_tail,
2008                                 auth_chain);
2009
2010     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
2011                                    &zone_hash,
2012                                    &rh->authority_chain_head->zone,
2013                                    &handle_shorten_zone_to_name,
2014                                    rh);
2015     return;
2016   }
2017
2018   /**
2019    * Ask DHT
2020    */
2021   rh->authority = rh->authority_chain_head->zone;
2022   rh->proc = &handle_shorten_pseu_dht_result;
2023   resolve_pseu_from_dht(rh);
2024
2025 }
2026
2027
2028
2029 /**
2030  * Process result from namestore delegation lookup
2031  * for shorten operation
2032  *
2033  * @param cls the client shorten handle
2034  * @param rh the resolver handle
2035  * @param rd_count number of results (0)
2036  * @param rd data (NULL)
2037  */
2038 void
2039 handle_shorten_delegation_result(void* cls,
2040                       struct GNUNET_GNS_ResolverHandle *rh,
2041                       uint32_t rd_count,
2042                       const struct GNUNET_NAMESTORE_RecordData *rd)
2043 {
2044   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
2045   struct AuthorityChain *auth_chain;
2046   char* result;
2047   size_t answer_len;
2048   
2049   /**
2050    * At this point rh->name contains the part of the name
2051    * that we do not have a PKEY in our namestore to resolve.
2052    * The authority chain in the resolver handle is now
2053    * useful to backtrack if needed
2054    */
2055   
2056   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2057              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
2058
2059   if (GNUNET_CRYPTO_hash_cmp(&rh->authority_chain_head->zone,
2060                              &zone_hash) == 0)
2061   {
2062     /**
2063      * This is our zone append .gnunet unless name is empty
2064      * (it shouldn't be, usually FIXME what happens if we
2065      * shorten to our zone to a "" record??)
2066      **/
2067     
2068     answer_len = strlen(rh->name) + strlen(gnunet_tld) + 2;
2069     result = GNUNET_malloc(answer_len);
2070     memset(result, 0, answer_len);
2071     strcpy(result, rh->name);
2072     strcpy(result+strlen(rh->name), ".");
2073     strcpy(result+strlen(rh->name)+1, gnunet_tld);
2074
2075     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2076                "Our zone: Sending name as shorten result %s\n", rh->name);
2077     
2078     send_shorten_response(rh->name, csh); //FIXME +.gnunet!
2079     free_resolver_handle(rh);
2080     GNUNET_free(csh->name);
2081     GNUNET_free(csh);
2082     GNUNET_free(result);
2083     return;
2084   }
2085   
2086   auth_chain = rh->authority_chain_head;
2087   /* backtrack authorities for pseu */
2088   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
2089                                  &zone_hash, //ours
2090                                  &auth_chain->zone,
2091                                  &handle_shorten_zone_to_name,
2092                                  rh);
2093
2094 }
2095
2096 typedef void (*ShortenResponseProc) (void* cls, const char* name);
2097
2098 /**
2099  * Shorten a given name
2100  *
2101  * @param name the name to shorten
2102  * @param proc the processor to call when finished
2103  * @praram cls the closure to the processor
2104  */
2105 static void
2106 shorten_name(char* name, struct ClientShortenHandle* csh)
2107 {
2108
2109   struct GNUNET_GNS_ResolverHandle *rh;
2110   
2111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2112               "Starting resolution for %s (type=%d)!\n",
2113               name, GNUNET_GNS_RECORD_PKEY);
2114   
2115   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
2116   rh->authority = zone_hash;
2117   
2118   rh->name = GNUNET_malloc(strlen(name)
2119                               - strlen(gnunet_tld) + 1);
2120   memset(rh->name, 0,
2121          strlen(name)-strlen(gnunet_tld) + 1);
2122   memcpy(rh->name, name,
2123          strlen(name)-strlen(gnunet_tld));
2124
2125   csh->name = GNUNET_malloc(strlen(name)
2126                             - strlen(gnunet_tld) + 1);
2127   memset(rh->name, 0,
2128          strlen(name)-strlen(gnunet_tld) + 1);
2129   memcpy(rh->name, name,
2130          strlen(name)-strlen(gnunet_tld));
2131
2132   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
2133
2134   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
2135   rh->authority_chain_tail = rh->authority_chain_head;
2136   rh->authority_chain_head->zone = zone_hash;
2137   rh->proc = &handle_shorten_delegation_result;
2138   rh->proc_cls = (void*)csh;
2139
2140   /* Start delegation resolution in our namestore */
2141   resolve_delegation_from_ns(rh);
2142
2143 }
2144
2145 /**
2146  * Send shorten response back to client
2147  * FIXME this is without .gnunet!
2148  * 
2149  * @param cls the client handle in closure
2150  * @param name the shortened name result or NULL if cannot be shortened
2151  */
2152 static void
2153 send_shorten_response(const char* name, struct ClientShortenHandle *csh)
2154 {
2155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
2156               "SHORTEN_RESULT", name);
2157   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
2158   
2159   if (name == NULL)
2160   {
2161     name = '\0';
2162   }
2163
2164   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
2165                        + strlen(name) + 1);
2166   
2167   rmsg->id = csh->unique_id;
2168   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
2169   rmsg->header.size = 
2170     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
2171           strlen(name) + 1);
2172
2173   strcpy((char*)&rmsg[1], name);
2174
2175   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
2176                               (const struct GNUNET_MessageHeader *) rmsg,
2177                               GNUNET_NO);
2178   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
2179   
2180   GNUNET_free(rmsg);
2181   GNUNET_free(csh->name);
2182   GNUNET_free(csh);
2183
2184 }
2185
2186 /**
2187  * Handle a shorten message from the api
2188  *
2189  * @param cls the closure
2190  * @param client the client
2191  * @param message the message
2192  */
2193 static void handle_shorten(void *cls,
2194                            struct GNUNET_SERVER_Client * client,
2195                            const struct GNUNET_MessageHeader * message)
2196 {
2197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
2198
2199   size_t msg_size = 0;
2200   struct ClientShortenHandle *csh;
2201
2202   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
2203   {
2204     GNUNET_break_op (0);
2205     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2206     return;
2207   }
2208
2209   GNUNET_SERVER_notification_context_add (nc, client);
2210
2211   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
2212     (struct GNUNET_GNS_ClientShortenMessage *) message;
2213   
2214   msg_size = ntohs(message->size);
2215
2216   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2217   {
2218     GNUNET_break_op (0);
2219     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2220     return;
2221   }
2222
2223   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
2224   csh->client = client;
2225   csh->unique_id = sh_msg->id;
2226   
2227   shorten_name((char*)&sh_msg[1], csh);
2228
2229 }
2230
2231 /**
2232  * TODO
2233  */
2234 static void
2235 handle_lookup(void *cls,
2236               struct GNUNET_SERVER_Client * client,
2237               const struct GNUNET_MessageHeader * message)
2238 {
2239 }
2240
2241 /**
2242  * Process GNS requests.
2243  *
2244  * @param cls closure)
2245  * @param server the initialized server
2246  * @param c configuration to use
2247  */
2248 static void
2249 run (void *cls, struct GNUNET_SERVER_Handle *server,
2250      const struct GNUNET_CONFIGURATION_Handle *c)
2251 {
2252   
2253   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
2254
2255   char* keyfile;
2256   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2257
2258   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2259     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
2260     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0}
2261   };
2262
2263   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (c, "gns",
2264                                              "ZONEKEY", &keyfile))
2265   {
2266     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2267                 "No private key for root zone specified%s!\n", keyfile);
2268     GNUNET_SCHEDULER_shutdown(0);
2269     return;
2270   }
2271
2272   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2273   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
2274
2275   GNUNET_CRYPTO_hash(&pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2276                      &zone_hash);
2277   GNUNET_free(keyfile);
2278
2279   if (GNUNET_YES ==
2280       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
2281                                             "HIJACK_DNS"))
2282   {
2283     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
2284                "DNS hijacking enabled... connecting to service.\n");
2285     /**
2286      * Do gnunet dns init here
2287      */
2288     dns_handle = GNUNET_DNS_connect(c,
2289                                     GNUNET_DNS_FLAG_PRE_RESOLUTION,
2290                                     &handle_dns_request, /* rh */
2291                                     NULL); /* Closure */
2292     if (NULL == dns_handle)
2293     {
2294       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2295                "Failed to connect to the dnsservice!\n");
2296     }
2297   }
2298
2299   
2300
2301   /**
2302    * handle to our local namestore
2303    */
2304   namestore_handle = GNUNET_NAMESTORE_connect(c);
2305
2306   if (NULL == namestore_handle)
2307   {
2308     //FIXME do error handling;
2309     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2310                "Failed to connect to the namestore!\n");
2311     GNUNET_SCHEDULER_shutdown(0);
2312     return;
2313   }
2314   
2315   /**
2316    * handle to the dht
2317    */
2318   dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg
2319
2320   if (NULL == dht_handle)
2321   {
2322     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
2323   }
2324
2325   //put_some_records(); //FIXME for testing
2326   
2327   /**
2328    * Schedule periodic put
2329    * for our records
2330    * We have roughly an hour for all records;
2331    */
2332   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
2333                                                       1);
2334   //zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
2335
2336   GNUNET_SERVER_add_handlers (server, handlers);
2337   
2338   //FIXME
2339   //GNUNET_SERVER_disconnect_notify (server,
2340   //                                 &client_disconnect_notification,
2341   //                                 NULL);
2342
2343   nc = GNUNET_SERVER_notification_context_create (server, 1);
2344
2345   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
2346                                 NULL);
2347 }
2348
2349
2350 /**
2351  * The main function for the GNS service.
2352  *
2353  * @param argc number of arguments from the command line
2354  * @param argv command line arguments
2355  * @return 0 ok, 1 on error
2356  */
2357 int
2358 main (int argc, char *const *argv)
2359 {
2360   int ret;
2361
2362   ret =
2363       (GNUNET_OK ==
2364        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
2365                            NULL)) ? 0 : 1;
2366   return ret;
2367 }
2368
2369 /* end of gnunet-service-gns.c */