-closing of control pipe is no error
[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 type */
157   enum GNUNET_GNS_RecordType type;
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 type */
176   enum GNUNET_GNS_RecordType type;
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   
410   if (dns_handle)
411     GNUNET_DNS_disconnect(dns_handle);
412   
413   GNUNET_NAMESTORE_disconnect(namestore_handle, 1);
414   GNUNET_DHT_disconnect(dht_handle);
415 }
416
417 /**
418  * Callback when record data is put into namestore
419  *
420  * @param cls the closure
421  * @param success GNUNET_OK on success
422  * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
423  */
424 void
425 on_namestore_record_put_result(void *cls,
426                                int32_t success,
427                                const char *emsg)
428 {
429   if (GNUNET_NO == success)
430   {
431     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "records already in namestore\n");
432     return;
433   }
434   else if (GNUNET_YES == success)
435   {
436     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
437                "records successfully put in namestore\n");
438     return;
439   }
440
441   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
442              "Error putting records into namestore: %s\n", emsg);
443 }
444
445 /**
446  * Handle timeout for DHT requests
447  *
448  * @param cls the request handle as closure
449  * @param tc the task context
450  */
451 static void
452 dht_lookup_timeout(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
453 {
454   struct GNUNET_GNS_ResolverHandle *rh = cls;
455
456   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
457              "dht lookup for query %s timed out.\n",
458              rh->name);
459
460   GNUNET_DHT_get_stop (rh->get_handle);
461   rh->proc(rh->proc_cls, rh, 0, NULL);
462 }
463
464
465
466 /**
467  * Function called when we get a result from the dht
468  * for our query
469  *
470  * @param cls the request handle
471  * @param exp lifetime
472  * @param key the key the record was stored under
473  * @param get_path get path
474  * @param get_path_length get path length
475  * @param put_path put path
476  * @param put_path_length put path length
477  * @param type the block type
478  * @param size the size of the record
479  * @param data the record data
480  */
481 static void
482 process_record_dht_result(void* cls,
483                  struct GNUNET_TIME_Absolute exp,
484                  const GNUNET_HashCode * key,
485                  const struct GNUNET_PeerIdentity *get_path,
486                  unsigned int get_path_length,
487                  const struct GNUNET_PeerIdentity *put_path,
488                  unsigned int put_path_length,
489                  enum GNUNET_BLOCK_Type type,
490                  size_t size, const void *data)
491 {
492   struct GNUNET_GNS_ResolverHandle *rh;
493   struct RecordLookupHandle *rlh;
494   struct GNSNameRecordBlock *nrb;
495   uint32_t num_records;
496   char* name = NULL;
497   char* rd_data = (char*)data;
498   int i;
499   int rd_size;
500   
501   GNUNET_HashCode zone, name_hash;
502   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "got dht result (size=%d)\n", size);
503   
504   if (data == NULL)
505     return;
506
507   //FIXME maybe check expiration here, check block type
508   
509   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
510   rlh = (struct RecordLookupHandle *) rh->proc_cls;
511   nrb = (struct GNSNameRecordBlock*)data;
512   
513   /* stop lookup and timeout task */
514   GNUNET_DHT_get_stop (rh->get_handle);
515   GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);
516   
517   rh->get_handle = NULL;
518   name = (char*)&nrb[1];
519   num_records = ntohl(nrb->rd_count);
520   {
521     struct GNUNET_NAMESTORE_RecordData rd[num_records];
522
523     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
524     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
525   
526     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
527                                                                rd_data,
528                                                                num_records,
529                                                                rd))
530     {
531       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
532       return;
533     }
534
535     for (i=0; i<num_records; i++)
536     {
537       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
538                "Got name: %s (wanted %s)\n", name, rh->name);
539       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
540                "Got type: %d\n",
541                rd[i].record_type);
542       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
543                "Got data length: %d\n", rd[i].data_size);
544       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
545                "Got flag %d\n", rd[i].flags);
546     
547      if ((strcmp(name, rh->name) == 0) &&
548          (rd[i].record_type == rlh->record_type))
549       {
550         rh->answered++;
551       }
552
553     }
554
555     GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
556     GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
557   
558     /**
559      * FIXME check pubkey against existing key in namestore?
560      * https://gnunet.org/bugs/view.php?id=2179
561      */
562
563     /* Save to namestore */
564     GNUNET_NAMESTORE_record_put (namestore_handle,
565                                  &nrb->public_key,
566                                  name,
567                                  exp,
568                                  num_records,
569                                  rd,
570                                  &nrb->signature,
571                                  &on_namestore_record_put_result, //cont
572                                  NULL); //cls
573   
574     if (rh->answered)
575       rh->proc(rh->proc_cls, rh, num_records, rd);
576     else
577       rh->proc(rh->proc_cls, rh, 0, NULL);
578   }
579
580 }
581
582
583 /**
584  * Start DHT lookup for a (name -> query->record_type) record in
585  * rh->authority's zone
586  *
587  * @param rh the pending gns query context
588  * @param name the name to query record
589  */
590 static void
591 resolve_record_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
592 {
593   uint32_t xquery;
594   GNUNET_HashCode name_hash;
595   GNUNET_HashCode lookup_key;
596   struct GNUNET_CRYPTO_HashAsciiEncoded lookup_key_string;
597   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
598
599   GNUNET_CRYPTO_hash(rh->name, strlen(rh->name), &name_hash);
600   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
601   GNUNET_CRYPTO_hash_to_enc (&lookup_key, &lookup_key_string);
602   
603   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
604              "starting dht lookup for %s with key: %s\n",
605              rh->name, (char*)&lookup_key_string);
606
607   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed(DHT_LOOKUP_TIMEOUT,
608                                                       &dht_lookup_timeout, rh);
609
610   xquery = htonl(rlh->record_type);
611   rh->get_handle = GNUNET_DHT_get_start(dht_handle, 
612                        DHT_OPERATION_TIMEOUT,
613                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
614                        &lookup_key,
615                        DHT_GNS_REPLICATION_LEVEL,
616                        GNUNET_DHT_RO_NONE,
617                        &xquery, 
618                        sizeof(xquery),
619                        &process_record_dht_result,
620                        rh);
621
622 }
623
624
625 /**
626  * Namestore calls this function if we have record for this name.
627  * (or with rd_count=0 to indicate no matches)
628  *
629  * @param cls the pending query
630  * @param key the key of the zone we did the lookup
631  * @param expiration expiration date of the namestore entry
632  * @param name the name for which we need an authority
633  * @param rd_count the number of records with 'name'
634  * @param rd the record data
635  * @param signature the signature of the authority for the record data
636  */
637 static void
638 process_record_lookup_ns(void* cls,
639                   const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
640                   struct GNUNET_TIME_Absolute expiration,
641                   const char *name, unsigned int rd_count,
642                   const struct GNUNET_NAMESTORE_RecordData *rd,
643                   const struct GNUNET_CRYPTO_RsaSignature *signature)
644 {
645   struct GNUNET_GNS_ResolverHandle *rh;
646   struct RecordLookupHandle *rlh;
647   struct GNUNET_TIME_Relative remaining_time;
648   GNUNET_HashCode zone;
649
650   rh = (struct GNUNET_GNS_ResolverHandle *) cls;
651   rlh = (struct RecordLookupHandle *)rh->proc_cls;
652   GNUNET_CRYPTO_hash(key,
653                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
654                      &zone);
655   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
656
657   rh->status = 0;
658   
659   if (name != NULL)
660   {
661     rh->status |= EXISTS;
662   }
663   
664   if (remaining_time.rel_value == 0)
665   {
666     rh->status |= EXPIRED;
667   }
668   
669   if (rd_count == 0)
670   {
671     /**
672      * Lookup terminated and no results
673      */
674     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
675                "Namestore lookup for %s terminated without results\n", name);
676     
677     
678
679     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
680                "Record %s unknown in namestore\n",
681                rh->name);
682     /**
683      * Our zone and no result? Cannot resolve TT
684      */
685     rh->proc(rh->proc_cls, rh, 0, NULL);
686     return;
687
688   }
689   else
690   {
691     
692     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
693                "Processing additional result %s from namestore\n", name);
694     int i;
695     for (i=0; i<rd_count;i++)
696     {
697       
698       if (rd[i].record_type != rlh->record_type)
699         continue;
700       
701       if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
702           == 0)
703       {
704         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This record is expired. Skipping\n");
705         continue;
706       }
707       
708       rh->answered++;
709       
710     }
711     
712     /**
713      * no answers found
714      */
715     if (rh->answered == 0)
716     {
717       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
718                  "No answers found. This is odd!\n");
719       rh->proc(rh->proc_cls, rh, 0, NULL);
720       return;
721     }
722     
723     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found %d answer(s) to query!\n",
724                rh->answered);
725
726     rh->proc(rh->proc_cls, rh, rd_count, rd);
727   }
728 }
729
730 /**
731  * The final phase of resolution.
732  * This is a name that is canonical and we do not have a delegation.
733  *
734  * @param rh the pending lookup
735  */
736 static void
737 resolve_record_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
738 {
739   struct RecordLookupHandle *rlh = (struct RecordLookupHandle *)rh->proc_cls;
740   /**
741    * Try to resolve this record in our namestore.
742    * The name to resolve is now in rh->authority_name
743    * since we tried to resolve it to an authority
744    * and failed.
745    **/
746   GNUNET_NAMESTORE_lookup_record(namestore_handle,
747                                  &rh->authority,
748                                  rh->name,
749                                  rlh->record_type,
750                                  &process_record_lookup_ns,
751                                  rh);
752
753 }
754
755
756 /**
757  * Handle timeout for DHT requests
758  *
759  * @param cls the request handle as closure
760  * @param tc the task context
761  */
762 static void
763 dht_authority_lookup_timeout(void *cls,
764                              const struct GNUNET_SCHEDULER_TaskContext *tc)
765 {
766   struct GNUNET_GNS_ResolverHandle *rh = cls;
767
768   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
769              "dht lookup for query %s timed out.\n",
770              rh->name);
771
772   GNUNET_DHT_get_stop (rh->get_handle);
773   if (strcmp(rh->name, "") == 0)
774   {
775     /*
776      * promote authority back to name and try to resolve record
777      */
778     strcpy(rh->name, rh->authority_name);
779   }
780   rh->proc(rh->proc_cls, rh, 0, NULL);
781 }
782
783 // Prototype
784 static void resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh);
785
786 /**
787  * Function called when we get a result from the dht
788  * for our query. Recursively tries to resolve PKEYs
789  * for name in DHT.
790  *
791  * @param cls the request handle
792  * @param exp lifetime
793  * @param key the key the record was stored under
794  * @param get_path get path
795  * @param get_path_length get path length
796  * @param put_path put path
797  * @param put_path_length put path length
798  * @param type the block type
799  * @param size the size of the record
800  * @param data the record data
801  */
802 static void
803 process_authority_dht_result(void* cls,
804                  struct GNUNET_TIME_Absolute exp,
805                  const GNUNET_HashCode * key,
806                  const struct GNUNET_PeerIdentity *get_path,
807                  unsigned int get_path_length,
808                  const struct GNUNET_PeerIdentity *put_path,
809                  unsigned int put_path_length,
810                  enum GNUNET_BLOCK_Type type,
811                  size_t size, const void *data)
812 {
813   struct GNUNET_GNS_ResolverHandle *rh;
814   struct GNSNameRecordBlock *nrb;
815   uint32_t num_records;
816   char* name = NULL;
817   char* rd_data = (char*) data;
818   int i;
819   int rd_size;
820   GNUNET_HashCode zone, name_hash;
821   
822   if (data == NULL)
823     return;
824   
825   //FIXME check expiration?
826   
827   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
828   nrb = (struct GNSNameRecordBlock*)data;
829   
830   /* stop dht lookup and timeout task */
831   GNUNET_DHT_get_stop (rh->get_handle);
832   GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);
833
834   rh->get_handle = NULL;
835   num_records = ntohl(nrb->rd_count);
836   name = (char*)&nrb[1];
837   {
838     struct GNUNET_NAMESTORE_RecordData rd[num_records];
839     
840     rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
841     rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
842   
843     if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
844                                                                rd_data,
845                                                                num_records,
846                                                                rd))
847     {
848       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
849       return;
850     }
851
852     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
853                "Got name: %s (wanted %s)\n", name, rh->authority_name);
854     for (i=0; i<num_records; i++)
855     {
856     
857       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
858                 "Got name: %s (wanted %s)\n", name, rh->authority_name);
859       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
860                  "Got type: %d (wanted %d)\n",
861                  rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
862       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
863                  "Got data length: %d\n", rd[i].data_size);
864       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
865                  "Got flag %d\n", rd[i].flags);
866
867       if ((strcmp(name, rh->authority_name) == 0) &&
868           (rd[i].record_type == GNUNET_GNS_RECORD_PKEY))
869       {
870         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Authority found in DHT\n");
871         rh->answered = 1;
872         memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
873         struct AuthorityChain *auth =
874           GNUNET_malloc(sizeof(struct AuthorityChain));
875         auth->zone = rh->authority;
876         auth->name = GNUNET_malloc(strlen(rh->authority_name)+1);
877         memset(auth->name, 0, strlen(rh->authority_name)+1);
878         strcpy(auth->name, rh->authority_name);
879         GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
880                                      rh->authority_chain_tail,
881                                      auth);
882       }
883
884     }
885
886
887     GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
888     GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
889
890     /* Save to namestore */
891     if (0 != GNUNET_CRYPTO_hash_cmp(&zone_hash, &zone))
892     {
893       GNUNET_NAMESTORE_record_put (namestore_handle,
894                                  &nrb->public_key,
895                                  name,
896                                  exp,
897                                  num_records,
898                                  rd,
899                                  &nrb->signature,
900                                  &on_namestore_record_put_result, //cont
901                                  NULL); //cls
902     }
903   }
904   
905   if (rh->answered)
906   {
907     rh->answered = 0;
908     /* delegate */
909     if (strcmp(rh->name, "") == 0)
910       rh->proc(rh->proc_cls, rh, 0, NULL);
911     else
912       resolve_delegation_from_dht(rh);
913     return;
914   }
915
916   /**
917    * should never get here unless false dht key/put
918    * block plugin should handle this
919    **/
920   
921   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DHT authority lookup error!\n");
922   GNUNET_break(0);
923 }
924
925
926 /**
927  * Process DHT lookup result for record.
928  *
929  * @param cls the closure
930  * @param rh resolver handle
931  * @param rd_count number of results (always 0)
932  * @param rd record data (always NULL)
933  */
934 static void
935 process_record_result_dht(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
936                        unsigned int rd_count,
937                        const struct GNUNET_NAMESTORE_RecordData *rd)
938 {
939   struct RecordLookupHandle* rlh;
940   rlh = (struct RecordLookupHandle*)cls;
941   if (rd_count == 0)
942   {
943     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
944                "No records for %s found in DHT. Aborting\n",
945                rh->name);
946     /* give up, cannot resolve */
947     rlh->proc(rlh->proc_cls, rh, 0, NULL);
948     //reply_to_dns(NULL, rh, 0, NULL);
949     return;
950   }
951
952   /* results found yay */
953   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
954              "Record resolved from namestore!");
955   rlh->proc(rlh->proc_cls, rh, rd_count, rd);
956   //reply_to_dns(NULL, rh, rd_count, rd);
957
958 }
959
960
961 /**
962  * Process namestore lookup result for record.
963  *
964  * @param cls the closure
965  * @param rh resolver handle
966  * @param rd_count number of results (always 0)
967  * @param rd record data (always NULL)
968  */
969 static void
970 process_record_result_ns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
971                        unsigned int rd_count,
972                        const struct GNUNET_NAMESTORE_RecordData *rd)
973 {
974   struct RecordLookupHandle* rlh;
975   rlh = (struct RecordLookupHandle*) cls;
976   if (rd_count == 0)
977   {
978     /* ns entry expired. try dht */
979     if (rh->status & (EXPIRED | !EXISTS))
980     {
981       rh->proc = &process_record_result_dht;
982       resolve_record_from_dht(rh);
983       return;
984     }
985     /* give up, cannot resolve */
986     rlh->proc(rlh->proc_cls, rh, 0, NULL);
987     //reply_to_dns(NULL, rh, 0, NULL);
988     return;
989   }
990
991   /* results found yay */
992   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
993              "Record resolved from namestore!");
994   rlh->proc(rlh->proc_cls, rh, rd_count, rd);
995   //reply_to_dns(NULL, rh, rd_count, rd);
996
997 }
998
999
1000 /**
1001  * Determine if this name is canonical.
1002  * i.e.
1003  * a.b.gnunet  = not canonical
1004  * a           = canonical
1005  *
1006  * @param name the name to test
1007  * @return 1 if canonical
1008  */
1009 static int
1010 is_canonical(char* name)
1011 {
1012   uint32_t len = strlen(name);
1013   int i;
1014
1015   for (i=0; i<len; i++)
1016   {
1017     if (*(name+i) == '.')
1018       return 0;
1019   }
1020   return 1;
1021 }
1022
1023 /**
1024  * Move one level up in the domain hierarchy and return the
1025  * passed top level domain.
1026  *
1027  * @param name the domain
1028  * @param dest the destination where the tld will be put
1029  */
1030 void
1031 pop_tld(char* name, char* dest)
1032 {
1033   uint32_t len;
1034
1035   if (is_canonical(name))
1036   {
1037     strcpy(dest, name);
1038     strcpy(name, "");
1039     return;
1040   }
1041
1042   for (len = strlen(name); len > 0; len--)
1043   {
1044     if (*(name+len) == '.')
1045       break;
1046   }
1047   
1048   //Was canonical?
1049   if (len == 0)
1050     return;
1051
1052   name[len] = '\0';
1053
1054   strcpy(dest, (name+len+1));
1055 }
1056
1057 /**
1058  * DHT resolution for delegation finished. Processing result.
1059  *
1060  * @param cls the closure
1061  * @param rh resolver handle
1062  * @param rd_count number of results (always 0)
1063  * @param rd record data (always NULL)
1064  */
1065 static void
1066 process_dht_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
1067                           unsigned int rd_count,
1068                           const struct GNUNET_NAMESTORE_RecordData *rd)
1069 {
1070   struct RecordLookupHandle* rlh;
1071   rlh = (struct RecordLookupHandle*) cls;
1072   
1073   if (strcmp(rh->name, "") == 0)
1074   {
1075     /* We resolved full name for delegation. resolving record */
1076     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1077       "Resolved full name for delegation via DHT. resolving record '' in ns\n");
1078     rh->proc = &process_record_result_ns;
1079     resolve_record_from_ns(rh);
1080     return;
1081   }
1082
1083   /**
1084    * we still have some left
1085    **/
1086   if (is_canonical(rh->name))
1087   {
1088     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1089                "Resolving canonical record %s in ns\n", rh->name);
1090     rh->proc = &process_record_result_ns;
1091     resolve_record_from_ns(rh);
1092     return;
1093   }
1094   /* give up, cannot resolve */
1095   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1096              "Cannot fully resolve delegation for %s via DHT!\n",
1097              rh->name);
1098   rlh->proc(rlh->proc_cls, rh, 0, NULL);
1099   //reply_to_dns(NULL, rh, 0, NULL);
1100 }
1101
1102
1103 /**
1104  * Start DHT lookup for a name -> PKEY (compare NS) record in
1105  * rh->authority's zone
1106  *
1107  * @param rh the pending gns query
1108  * @param name the name of the PKEY record
1109  */
1110 static void
1111 resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
1112 {
1113   uint32_t xquery;
1114   GNUNET_HashCode name_hash;
1115   GNUNET_HashCode lookup_key;
1116
1117   GNUNET_CRYPTO_hash(rh->authority_name,
1118                      strlen(rh->authority_name),
1119                      &name_hash);
1120   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
1121
1122   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1123                                                   &dht_authority_lookup_timeout,
1124                                                        rh);
1125
1126   xquery = htonl(GNUNET_GNS_RECORD_PKEY);
1127   
1128   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
1129                        DHT_OPERATION_TIMEOUT,
1130                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1131                        &lookup_key,
1132                        DHT_GNS_REPLICATION_LEVEL,
1133                        GNUNET_DHT_RO_NONE,
1134                        &xquery,
1135                        sizeof(xquery),
1136                        &process_authority_dht_result,
1137                        rh);
1138
1139 }
1140
1141
1142 /**
1143  * Namestore resolution for delegation finished. Processing result.
1144  *
1145  * @param cls the closure
1146  * @param rh resolver handle
1147  * @param rd_count number of results (always 0)
1148  * @param rd record data (always NULL)
1149  */
1150 static void
1151 process_ns_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
1152                           unsigned int rd_count,
1153                           const struct GNUNET_NAMESTORE_RecordData *rd)
1154 {
1155   struct RecordLookupHandle* rlh;
1156   rlh = (struct RecordLookupHandle*) cls;
1157   
1158   if (strcmp(rh->name, "") == 0)
1159   {
1160     /* We resolved full name for delegation. resolving record */
1161     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1162                "Resolved full name for delegation. resolving record ''\n");
1163     rh->proc = &process_record_result_ns;
1164     resolve_record_from_ns(rh);
1165     return;
1166   }
1167
1168   /**
1169    * we still have some left
1170    * check if ns entry is fresh
1171    **/
1172   if (rh->status & (EXISTS | !EXPIRED))
1173   {
1174     if (is_canonical(rh->name))
1175     {
1176       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1177                  "Resolving canonical record %s\n", rh->name);
1178       rh->proc = &process_record_result_ns;
1179       resolve_record_from_ns(rh);
1180     }
1181     else
1182     {
1183       /* give up, cannot resolve */
1184       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1185                  "Cannot fully resolve delegation for %s!\n",
1186                  rh->name);
1187       rlh->proc(rlh->proc_cls, rh, 0, NULL);
1188       //reply_to_dns(NULL, rh, 0, NULL);
1189     }
1190     return;
1191   }
1192   
1193   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1194              "Trying to resolve delegation for %s via DHT\n",
1195              rh->name);
1196   rh->proc = &process_dht_delegation_dns;
1197   resolve_delegation_from_dht(rh);
1198 }
1199
1200 //Prototype
1201 static void resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh);
1202
1203 /**
1204  * This is a callback function that should give us only PKEY
1205  * records. Used to query the namestore for the authority (PKEY)
1206  * for 'name'. It will recursively try to resolve the
1207  * authority for a given name from the namestore.
1208  *
1209  * @param cls the pending query
1210  * @param key the key of the zone we did the lookup
1211  * @param expiration expiration date of the record data set in the namestore
1212  * @param name the name for which we need an authority
1213  * @param rd_count the number of records with 'name'
1214  * @param rd the record data
1215  * @param signature the signature of the authority for the record data
1216  */
1217 static void
1218 process_authority_lookup_ns(void* cls,
1219                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1220                    struct GNUNET_TIME_Absolute expiration,
1221                    const char *name,
1222                    unsigned int rd_count,
1223                    const struct GNUNET_NAMESTORE_RecordData *rd,
1224                    const struct GNUNET_CRYPTO_RsaSignature *signature)
1225 {
1226   struct GNUNET_GNS_ResolverHandle *rh;
1227   struct GNUNET_TIME_Relative remaining_time;
1228   GNUNET_HashCode zone;
1229   char* new_name;
1230   
1231   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got %d records from authority lookup\n",
1232              rd_count);
1233
1234   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
1235   GNUNET_CRYPTO_hash(key,
1236                      sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1237                      &zone);
1238   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
1239   
1240   rh->status = 0;
1241   
1242   if (name != NULL)
1243   {
1244     rh->status |= EXISTS;
1245   }
1246   
1247   if (remaining_time.rel_value == 0)
1248   {
1249     rh->status |= EXPIRED;
1250   }
1251   
1252   /**
1253    * No authority found in namestore.
1254    */
1255   if (rd_count == 0)
1256   {
1257     /**
1258      * We did not find an authority in the namestore
1259      */
1260     
1261     /**
1262      * No PKEY in zone.
1263      * Promote this authority back to a name maybe it is
1264      * our record.
1265      */
1266     if (strcmp(rh->name, "") == 0)
1267     {
1268       /* simply promote back */
1269       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1270                  "Promoting %s back to name\n", rh->authority_name);
1271       strcpy(rh->name, rh->authority_name);
1272     }
1273     else
1274     {
1275       /* add back to existing name */
1276       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1277                  "Adding %s back to %s\n",
1278                  rh->authority_name, rh->name);
1279       new_name = GNUNET_malloc(strlen(rh->name)
1280                                + strlen(rh->authority_name) + 2);
1281       memset(new_name, 0, strlen(rh->name) + strlen(rh->authority_name) + 2);
1282       strcpy(new_name, rh->name);
1283       strcpy(new_name+strlen(new_name)+1, ".");
1284       strcpy(new_name+strlen(new_name)+2, rh->authority_name);
1285       GNUNET_free(rh->name);
1286       rh->name = new_name;
1287     }
1288     rh->proc(rh->proc_cls, rh, 0, NULL);
1289     return;
1290   }
1291
1292   //Note only 1 pkey should have been returned.. anything else would be strange
1293   /**
1294    * We found an authority that may be able to help us
1295    * move on with query
1296    */
1297   int i;
1298   for (i=0; i<rd_count;i++)
1299   {
1300   
1301     if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
1302       continue;
1303     
1304     if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
1305          == 0)
1306     {
1307       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This pkey is expired.\n");
1308       if (remaining_time.rel_value == 0)
1309       {
1310         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1311                    "This dht entry is expired.\n");
1312         rh->authority_chain_head->fresh = 0;
1313         rh->proc(rh->proc_cls, rh, 0, NULL);
1314         return;
1315       }
1316
1317       continue;
1318     }
1319
1320     /**
1321      * Resolve rest of query with new authority
1322      */
1323     GNUNET_assert(rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
1324     memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
1325     struct AuthorityChain *auth = GNUNET_malloc(sizeof(struct AuthorityChain));
1326     auth->zone = rh->authority;
1327     auth->name = GNUNET_malloc(strlen(rh->authority_name)+1);
1328     memset(auth->name, 0, strlen(rh->authority_name)+1);
1329     strcpy(auth->name, rh->authority_name);
1330     GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
1331                                  rh->authority_chain_tail,
1332                                  auth);
1333     
1334     /**
1335      * We are done with PKEY resolution if name is empty
1336      * else resolve again with new authority
1337      */
1338     if (strcmp(rh->name, "") == 0)
1339       rh->proc(rh->proc_cls, rh, 0, NULL);
1340     else
1341       resolve_delegation_from_ns(rh);
1342     return;
1343   }
1344     
1345   /**
1346    * no answers found
1347    */
1348   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1349              "Authority lookup successful but no PKEY... never get here\n");
1350   rh->proc(rh->proc_cls, rh, 0, NULL);
1351 }
1352
1353
1354 /**
1355  * Resolve the delegation chain for the request
1356  *
1357  * @param rh the resolver handle
1358  */
1359 static void
1360 resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
1361 {
1362   
1363   pop_tld(rh->name, rh->authority_name);
1364   GNUNET_NAMESTORE_lookup_record(namestore_handle,
1365                                  &rh->authority,
1366                                  rh->authority_name,
1367                                  GNUNET_GNS_RECORD_PKEY,
1368                                  &process_authority_lookup_ns,
1369                                  rh);
1370
1371 }
1372
1373 /**
1374  * Entry point for name resolution
1375  * Setup a new query and try to resolve
1376  *
1377  * @param request the request handle of the DNS request from a client
1378  * @param p the DNS query packet we received
1379  * @param q the DNS query we received parsed from p
1380  */
1381 static void
1382 start_resolution_from_dns(struct GNUNET_DNS_RequestHandle *request,
1383                           struct GNUNET_DNSPARSER_Packet *p,
1384                           struct GNUNET_DNSPARSER_Query *q)
1385 {
1386   struct GNUNET_GNS_ResolverHandle *rh;
1387   struct RecordLookupHandle* rlh;
1388   struct InterceptLookupHandle* ilh;
1389   
1390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1391               "Starting resolution for %s (type=%d)!\n",
1392               q->name, q->type);
1393   
1394   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
1395   rlh = GNUNET_malloc(sizeof(struct RecordLookupHandle));
1396   ilh = GNUNET_malloc(sizeof(struct InterceptLookupHandle));
1397   ilh->packet = p;
1398   ilh->query = q;
1399   ilh->request_handle = request;
1400   
1401   rh->authority = zone_hash;
1402
1403   rlh->record_type = q->type;
1404   rlh->name = q->name;
1405   rlh->proc = &reply_to_dns;
1406   rlh->proc_cls = ilh;
1407
1408   rh->proc_cls = rlh;
1409   
1410   rh->authority = zone_hash;
1411   rh->name = GNUNET_malloc(strlen(q->name)
1412                               - strlen(gnunet_tld) + 1);
1413   memset(rh->name, 0,
1414          strlen(q->name)-strlen(gnunet_tld) + 1);
1415   memcpy(rh->name, q->name,
1416          strlen(q->name)-strlen(gnunet_tld));
1417
1418   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
1419   
1420   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
1421   rh->authority_chain_head->prev = NULL;
1422   rh->authority_chain_head->next = NULL;
1423   rh->authority_chain_tail = rh->authority_chain_head;
1424   rh->authority_chain_head->zone = zone_hash;
1425
1426   /* Start resolution in our zone */
1427   rh->proc = &process_ns_delegation_dns;
1428   resolve_delegation_from_ns(rh);
1429 }
1430
1431
1432
1433 /**
1434  * The DNS request handler
1435  * Called for every incoming DNS request.
1436  *
1437  * @param cls closure
1438  * @param rh request handle to user for reply
1439  * @param request_length number of bytes in request
1440  * @param request udp payload of the DNS request
1441  */
1442 static void
1443 handle_dns_request(void *cls,
1444                    struct GNUNET_DNS_RequestHandle *rh,
1445                    size_t request_length,
1446                    const char *request)
1447 {
1448   struct GNUNET_DNSPARSER_Packet *p;
1449   int i;
1450   char *tldoffset;
1451
1452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hijacked a DNS request...processing\n");
1453   p = GNUNET_DNSPARSER_parse (request, request_length);
1454   
1455   if (NULL == p)
1456   {
1457     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1458                 "Received malformed DNS packet, leaving it untouched\n");
1459     GNUNET_DNS_request_forward (rh);
1460     GNUNET_DNSPARSER_free_packet (p);
1461     return;
1462   }
1463   
1464   /**
1465    * Check tld and decide if we or
1466    * legacy dns is responsible
1467    *
1468    * FIXME now in theory there could be more than 1 query in the request
1469    * but if this is case we get into trouble:
1470    * either we query the GNS or the DNS. We cannot do both!
1471    * So I suggest to either only allow a single query per request or
1472    * only allow GNS or DNS requests.
1473    * The way it is implemented here now is buggy and will lead to erratic
1474    * behaviour (if multiple queries are present).
1475    */
1476   if (p->num_queries == 0)
1477   {
1478     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1479                 "No Queries in DNS packet... forwarding\n");
1480     GNUNET_DNS_request_forward (rh);
1481     GNUNET_DNSPARSER_free_packet(p);
1482     return;
1483   }
1484
1485   if (p->num_queries > 1)
1486   {
1487     /* Note: We could also look for .gnunet */
1488     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1489                 ">1 queriy in DNS packet... odd. We only process #1\n");
1490   }
1491
1492   
1493   /**
1494    * Check for .gnunet
1495    */
1496   tldoffset = p->queries[0].name + strlen(p->queries[0].name) - 1;
1497   
1498   for (i=0; i<strlen(p->queries[0].name); i++)
1499   {
1500     if (*(tldoffset-i) == '.')
1501       break;
1502   }
1503   
1504   if ((i==strlen(gnunet_tld)-1) && (0 == strcmp(tldoffset-i, gnunet_tld)))
1505   {
1506     start_resolution_from_dns(rh, p, p->queries);
1507   }
1508   else
1509   {
1510     /**
1511      * This request does not concern us. Forward to real DNS.
1512      */
1513     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1514                "Request for %s is forwarded to DNS\n", p->queries[0].name);
1515     GNUNET_DNS_request_forward (rh);
1516     GNUNET_DNSPARSER_free_packet (p);
1517   }
1518
1519 }
1520
1521 /**
1522  * Method called periodicattluy that triggers
1523  * iteration over root zone
1524  *
1525  * @param cls closure
1526  * @param tc task context
1527  */
1528 static void
1529 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1530 {
1531   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
1532 }
1533
1534 /**
1535  * Continuation for DHT put
1536  *
1537  * @param cls closure
1538  * @param tc task context
1539  */
1540 static void
1541 record_dht_put(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1542 {
1543   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
1544 }
1545
1546 /* prototype */
1547 static void
1548 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1549
1550 /**
1551  * Function used to put all records successively into the DHT.
1552  *
1553  * @param cls the closure (NULL)
1554  * @param key the public key of the authority (ours)
1555  * @param expiration lifetime of the namestore entry
1556  * @param name the name of the records
1557  * @param rd_count the number of records in data
1558  * @param rd the record data
1559  * @param signature the signature for the record data
1560  */
1561 static void
1562 put_gns_record(void *cls,
1563                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1564                 struct GNUNET_TIME_Absolute expiration,
1565                 const char *name,
1566                 unsigned int rd_count,
1567                 const struct GNUNET_NAMESTORE_RecordData *rd,
1568                 const struct GNUNET_CRYPTO_RsaSignature *signature)
1569 {
1570   
1571   struct GNSNameRecordBlock *nrb;
1572   GNUNET_HashCode name_hash;
1573   GNUNET_HashCode xor_hash;
1574   struct GNUNET_CRYPTO_HashAsciiEncoded xor_hash_string;
1575   uint32_t rd_payload_length;
1576   char* nrb_data = NULL;
1577
1578   /* we're done */
1579   if (NULL == name)
1580   {
1581     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Zone iteration finished\n");
1582     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
1583     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start,
1584                                                    NULL);
1585     return;
1586   }
1587   
1588   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1589              "Putting records for %s into the DHT\n", name);
1590   
1591   rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
1592   
1593   nrb = GNUNET_malloc(rd_payload_length + strlen(name) + 1 
1594                       + sizeof(struct GNSNameRecordBlock));
1595   
1596   if (signature != NULL)
1597     nrb->signature = *signature;
1598   
1599   nrb->public_key = *key;
1600
1601   nrb->rd_count = htonl(rd_count);
1602   
1603   memset(&nrb[1], 0, strlen(name) + 1);
1604   memcpy(&nrb[1], name, strlen(name));
1605
1606   nrb_data = (char*)&nrb[1];
1607   nrb_data += strlen(name) + 1;
1608
1609   rd_payload_length += sizeof(struct GNSNameRecordBlock) +
1610     strlen(name) + 1;
1611
1612   if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
1613                                                 rd,
1614                                                 rd_payload_length,
1615                                                 nrb_data))
1616   {
1617     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Record serialization failed!\n");
1618     GNUNET_free(nrb);
1619     return;
1620     //FIXME what to do
1621   }
1622
1623
1624   /*
1625    * calculate DHT key: H(name) xor H(pubkey)
1626    */
1627   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
1628   GNUNET_CRYPTO_hash_xor(&zone_hash, &name_hash, &xor_hash);
1629   GNUNET_CRYPTO_hash_to_enc (&xor_hash, &xor_hash_string);
1630   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1631              "putting records for %s under key: %s with size %d\n",
1632              name, (char*)&xor_hash_string, rd_payload_length);
1633
1634   GNUNET_DHT_put (dht_handle, &xor_hash,
1635                   DHT_GNS_REPLICATION_LEVEL,
1636                   GNUNET_DHT_RO_NONE,
1637                   GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1638                   rd_payload_length,
1639                   (char*)nrb,
1640                   expiration,
1641                   DHT_OPERATION_TIMEOUT,
1642                   &record_dht_put,
1643                   NULL); //cls for cont
1644   
1645   num_public_records++;
1646
1647   /**
1648    * Reschedule periodic put
1649    */
1650   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (dht_update_interval,
1651                                 &update_zone_dht_next,
1652                                 NULL);
1653
1654   GNUNET_free(nrb);
1655
1656 }
1657
1658 /**
1659  * Periodically iterate over our zone and store everything in dht
1660  *
1661  * @param cls NULL
1662  * @param tc task context
1663  */
1664 static void
1665 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1666 {
1667   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting DHT zone update!\n");
1668   if (0 == num_public_records)
1669   {
1670     dht_update_interval = GNUNET_TIME_relative_multiply(
1671                                                       GNUNET_TIME_UNIT_SECONDS,
1672                                                       1);
1673   }
1674   else
1675   {
1676     dht_update_interval = GNUNET_TIME_relative_multiply(
1677                                                       GNUNET_TIME_UNIT_SECONDS,
1678                                                      (3600/num_public_records));
1679   }
1680   num_public_records = 0; //start counting again
1681   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
1682                                                           &zone_hash,
1683                                                           GNUNET_NAMESTORE_RF_AUTHORITY,
1684                                                           GNUNET_NAMESTORE_RF_PRIVATE,
1685                                                           &put_gns_record,
1686                                                           NULL);
1687 }
1688
1689 //Prototype
1690 static void send_shorten_response(const char* name,
1691                                   struct ClientShortenHandle *csh);
1692 static void
1693 process_shorten_pseu_lookup_ns(void *cls,
1694                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1695                  struct GNUNET_TIME_Absolute expire,
1696                  const char *name,
1697                  unsigned int rd_len,
1698                  const struct GNUNET_NAMESTORE_RecordData *rd,
1699                  const struct GNUNET_CRYPTO_RsaSignature *signature)
1700 {
1701   struct GNUNET_GNS_ResolverHandle *rh = 
1702     (struct GNUNET_GNS_ResolverHandle *)cls;
1703   struct GNUNET_TIME_Relative remaining_time;
1704
1705   GNUNET_TIME_absolute_get_remaining (expire);
1706   rh->status = 0;
1707   
1708   if (name != NULL)
1709   {
1710     rh->status |= EXISTS;
1711   }
1712   
1713   if (remaining_time.rel_value == 0)
1714   {
1715     rh->status |= EXPIRED;
1716   }
1717
1718   rh->proc(rh->proc_cls, rh, rd_len, rd);
1719 }
1720
1721
1722 /**
1723  * Start DHT lookup for a PSEUdonym record in
1724  * rh->authority's zone
1725  *
1726  * @param rh the pending gns query
1727  * @param name the name of the PKEY record
1728  */
1729 static void
1730 resolve_pseu_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
1731 {
1732   uint32_t xquery;
1733   GNUNET_HashCode name_hash;
1734   GNUNET_HashCode lookup_key;
1735
1736   //Empty string
1737   GNUNET_CRYPTO_hash("",
1738                      1,
1739                      &name_hash);
1740
1741   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
1742
1743   rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
1744                                                   &dht_lookup_timeout,
1745                                                   rh);
1746
1747   xquery = htonl(GNUNET_GNS_RECORD_PSEU);
1748   
1749   rh->get_handle = GNUNET_DHT_get_start(dht_handle,
1750                        DHT_OPERATION_TIMEOUT,
1751                        GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1752                        &lookup_key,
1753                        DHT_GNS_REPLICATION_LEVEL,
1754                        GNUNET_DHT_RO_NONE,
1755                        &xquery,
1756                        sizeof(xquery),
1757                        &process_authority_dht_result,
1758                        rh);
1759
1760 }
1761
1762 //Prototype
1763 static void
1764 handle_shorten_pseu_ns_result(void* cls,
1765                               struct GNUNET_GNS_ResolverHandle *rh,
1766                               uint32_t rd_count,
1767                               const struct GNUNET_NAMESTORE_RecordData *rd);
1768
1769 static void
1770 handle_shorten_zone_to_name(void *cls,
1771                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1772                  struct GNUNET_TIME_Absolute expire,
1773                  const char *name,
1774                  unsigned int rd_len,
1775                  const struct GNUNET_NAMESTORE_RecordData *rd,
1776                  const struct GNUNET_CRYPTO_RsaSignature *signature)
1777 {
1778   struct GNUNET_GNS_ResolverHandle *rh = 
1779     (struct GNUNET_GNS_ResolverHandle *)cls;
1780   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) rh->proc_cls;
1781
1782   char* result;
1783   size_t answer_len;
1784   
1785   /* we found a match in our own zone */
1786   if (rd_len != 0)
1787   {
1788     answer_len = strlen(rh->name) + strlen(name) + strlen(gnunet_tld) + 2;
1789     result = GNUNET_malloc(answer_len);
1790     memset(result, 0, answer_len);
1791     strcpy(result, rh->name);
1792     strcpy(result+strlen(rh->name), ".");
1793     strcpy(result+strlen(rh->name)+1, name);
1794     strcpy(result+strlen(rh->name)+strlen(name), gnunet_tld);
1795     
1796     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1797                "Sending shorten result %s\n", result);
1798
1799     send_shorten_response(result, csh);
1800     free_resolver_handle(rh);
1801     GNUNET_free(result);
1802   }
1803   else
1804   {
1805     /**
1806      * Nothing in our zone
1807      * check PSEU for this authority in namestore
1808      */
1809     rh->proc = &handle_shorten_pseu_ns_result;
1810     GNUNET_NAMESTORE_lookup_record(namestore_handle,
1811                                    &rh->authority_chain_head->zone,
1812                                    "",
1813                                    GNUNET_GNS_RECORD_PSEU,
1814                                    &process_shorten_pseu_lookup_ns,
1815                                    rh);
1816   }
1817 }
1818
1819 /**
1820  * Process result from namestore delegation lookup
1821  * for shorten operation
1822  *
1823  * @param cls the client shorten handle
1824  * @param rh the resolver handle
1825  * @param rd_count number of results (0)
1826  * @param rd data (NULL)
1827  */
1828 void
1829 handle_shorten_pseu_dht_result(void* cls,
1830                       struct GNUNET_GNS_ResolverHandle *rh,
1831                       uint32_t rd_len,
1832                       const struct GNUNET_NAMESTORE_RecordData *rd)
1833 {
1834   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1835   struct AuthorityChain *auth_chain;
1836   char* pseu;
1837   char* result;
1838   char* new_name;
1839   size_t answer_len;
1840   int i;
1841   
1842   /**
1843    * PSEU found
1844    */
1845   if (rd_len != 0)
1846   {
1847     for (i=0; i < rd_len; i++)
1848     {
1849       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1850       {
1851         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1852                    "Found PSEU %s\n", (char*) rd[i].data);
1853         break;
1854       }
1855     }
1856
1857     pseu = (char*) rd[i].data;
1858     answer_len = strlen(rh->name) + strlen(pseu) + strlen(gnunet_tld) + 2;
1859     result = GNUNET_malloc(answer_len);
1860     memset(result, 0, answer_len);
1861     strcpy(result, rh->name);
1862     strcpy(result+strlen(rh->name), ".");
1863     strcpy(result+strlen(rh->name)+1, pseu);
1864     strcpy(result+strlen(rh->name)+strlen(pseu), gnunet_tld);
1865     
1866     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1867                "Sending pseudonym shorten result %s\n", result);
1868     
1869     send_shorten_response(result, csh);
1870     free_resolver_handle(rh);
1871     GNUNET_free(result);
1872     return;
1873   }
1874   
1875   /**
1876    * No PSEU found.
1877    * continue with next authority
1878    * backtrack
1879    */
1880   auth_chain = rh->authority_chain_head;
1881
1882   if ((auth_chain->next->next == NULL) &&
1883       GNUNET_CRYPTO_hash_cmp(&auth_chain->next->zone, &zone_hash) == 0)
1884   {
1885     /**
1886      * Our zone is next
1887      */
1888     answer_len = strlen(rh->name) + strlen(auth_chain->name)
1889       + strlen(gnunet_tld) + 2;
1890
1891     result = GNUNET_malloc(answer_len);
1892     memset(result, 0, answer_len);
1893     strcpy(result, rh->name);
1894     strcpy(result+strlen(rh->name), ".");
1895     strcpy(result+strlen(rh->name)+1, auth_chain->name);
1896     strcpy(result+strlen(rh->name)+strlen(auth_chain->name)+1, gnunet_tld);
1897     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1898                "Sending non pseudonym shorten result %s\n", result);
1899     
1900     send_shorten_response(result, csh);
1901     free_resolver_handle(rh);
1902     GNUNET_free(result);
1903     return;
1904   }
1905
1906   /**
1907    * Continue with next authority
1908    */
1909   new_name = GNUNET_malloc(strlen(rh->name)+
1910                            strlen(auth_chain->name) + 2);
1911   memset(new_name, 0, strlen(rh->name)+
1912                       strlen(auth_chain->name) + 2);
1913   strcpy(new_name, rh->name);
1914   strcpy(new_name+strlen(rh->name)+1, ".");
1915   strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
1916   GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
1917                               rh->authority_chain_tail,
1918                               auth_chain);
1919   GNUNET_free(rh->name);
1920   rh->name = new_name;
1921   GNUNET_free(auth_chain->name);
1922   GNUNET_free(auth_chain);
1923   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
1924                                  &zone_hash,
1925                                  &rh->authority_chain_head->zone,
1926                                  &handle_shorten_zone_to_name,
1927                                  rh);
1928
1929 }
1930
1931
1932
1933 /**
1934  * Process result from namestore PSEU lookup
1935  * for shorten operation
1936  * FIXME do we need to check for own zone here?
1937  *
1938  * @param cls the client shorten handle
1939  * @param rh the resolver handle
1940  * @param rd_count number of results (0 if none found)
1941  * @param rd data (NULL if none found)
1942  */
1943 static void
1944 handle_shorten_pseu_ns_result(void* cls,
1945                       struct GNUNET_GNS_ResolverHandle *rh,
1946                       uint32_t rd_len,
1947                       const struct GNUNET_NAMESTORE_RecordData *rd)
1948 {
1949   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
1950   struct AuthorityChain *auth_chain;
1951   char* pseu;
1952   char* result;
1953   char* new_name;
1954   size_t answer_len;
1955   int i;
1956   
1957   /**
1958    * PSEU found
1959    */
1960   if (rd_len != 0)
1961   {
1962     for (i=0; i < rd_len; i++)
1963     {
1964       if (rd[i].record_type == GNUNET_GNS_RECORD_PSEU)
1965       {
1966         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1967                    "Found PSEU %s\n", (char*) rd[i].data);
1968         break;
1969       }
1970     }
1971     
1972     pseu = (char*) rd[i].data;
1973     answer_len = strlen(rh->name) + strlen(pseu) + strlen(gnunet_tld) + 2;
1974     result = GNUNET_malloc(answer_len);
1975     memset(result, 0, answer_len);
1976     strcpy(result, rh->name);
1977     strcpy(result+strlen(rh->name), ".");
1978     strcpy(result+strlen(rh->name)+1, pseu);
1979     strcpy(result+strlen(rh->name)+strlen(pseu)+1, gnunet_tld);
1980     
1981     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1982                "Sending shorten result %s\n", result);
1983     
1984     send_shorten_response(result, csh);
1985     free_resolver_handle(rh);
1986     GNUNET_free(result);
1987     return;
1988   }
1989   
1990   /**
1991    * No PSEU found. Ask DHT if expired.
1992    * Else contunue with next authority
1993    */
1994   if (rh->status & (EXISTS | !EXPIRED))
1995   {
1996     /**
1997      * backtrack
1998      */
1999     auth_chain = rh->authority_chain_head;
2000     new_name = GNUNET_malloc(strlen(rh->name)+
2001                              strlen(auth_chain->name) + 2);
2002     memset(new_name, 0, strlen(rh->name)+
2003                         strlen(auth_chain->name) + 2);
2004     strcpy(new_name, rh->name);
2005     strcpy(new_name+strlen(rh->name)+1, ".");
2006     strcpy(new_name+strlen(rh->name)+2, auth_chain->name);
2007     
2008     GNUNET_free(rh->name);
2009     rh->name = new_name;
2010     GNUNET_CONTAINER_DLL_remove(rh->authority_chain_head,
2011                                 rh->authority_chain_tail,
2012                                 auth_chain);
2013
2014     GNUNET_NAMESTORE_zone_to_name (namestore_handle,
2015                                    &zone_hash,
2016                                    &rh->authority_chain_head->zone,
2017                                    &handle_shorten_zone_to_name,
2018                                    rh);
2019     return;
2020   }
2021
2022   /**
2023    * Ask DHT
2024    */
2025   rh->authority = rh->authority_chain_head->zone;
2026   rh->proc = &handle_shorten_pseu_dht_result;
2027   resolve_pseu_from_dht(rh);
2028
2029 }
2030
2031
2032
2033 /**
2034  * Process result from namestore delegation lookup
2035  * for shorten operation
2036  *
2037  * @param cls the client shorten handle
2038  * @param rh the resolver handle
2039  * @param rd_count number of results (0)
2040  * @param rd data (NULL)
2041  */
2042 void
2043 handle_shorten_delegation_result(void* cls,
2044                       struct GNUNET_GNS_ResolverHandle *rh,
2045                       uint32_t rd_count,
2046                       const struct GNUNET_NAMESTORE_RecordData *rd)
2047 {
2048   struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
2049   struct AuthorityChain *auth_chain;
2050   char* result;
2051   size_t answer_len;
2052   
2053   /**
2054    * At this point rh->name contains the part of the name
2055    * that we do not have a PKEY in our namestore to resolve.
2056    * The authority chain in the resolver handle is now
2057    * useful to backtrack if needed
2058    */
2059   
2060   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2061              "PKEY resolved as far as possible in ns up to %s!\n", rh->name);
2062
2063   if (GNUNET_CRYPTO_hash_cmp(&rh->authority_chain_head->zone,
2064                              &zone_hash) == 0)
2065   {
2066     /**
2067      * This is our zone append .gnunet unless name is empty
2068      * (it shouldn't be, usually FIXME what happens if we
2069      * shorten to our zone to a "" record??)
2070      **/
2071     
2072     answer_len = strlen(rh->name) + strlen(gnunet_tld) + 2;
2073     result = GNUNET_malloc(answer_len);
2074     memset(result, 0, answer_len);
2075     strcpy(result, rh->name);
2076     strcpy(result+strlen(rh->name), ".");
2077     strcpy(result+strlen(rh->name)+1, gnunet_tld);
2078
2079     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2080                "Our zone: Sending name as shorten result %s\n", rh->name);
2081     
2082     send_shorten_response(rh->name, csh); //FIXME +.gnunet!
2083     free_resolver_handle(rh);
2084     GNUNET_free(csh->name);
2085     GNUNET_free(csh);
2086     GNUNET_free(result);
2087     return;
2088   }
2089   
2090   auth_chain = rh->authority_chain_head;
2091   /* backtrack authorities for pseu */
2092   GNUNET_NAMESTORE_zone_to_name (namestore_handle,
2093                                  &zone_hash, //ours
2094                                  &auth_chain->zone,
2095                                  &handle_shorten_zone_to_name,
2096                                  rh);
2097
2098 }
2099
2100 typedef void (*ShortenResponseProc) (void* cls, const char* name);
2101
2102 /**
2103  * Shorten a given name
2104  *
2105  * @param name the name to shorten
2106  * @param proc the processor to call when finished
2107  * @praram cls the closure to the processor
2108  */
2109 static void
2110 shorten_name(char* name, struct ClientShortenHandle* csh)
2111 {
2112
2113   struct GNUNET_GNS_ResolverHandle *rh;
2114   
2115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2116               "Starting resolution for %s (type=%d)!\n",
2117               name, GNUNET_GNS_RECORD_PKEY);
2118   
2119   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
2120   rh->authority = zone_hash;
2121   
2122   rh->name = GNUNET_malloc(strlen(name)
2123                               - strlen(gnunet_tld) + 1);
2124   memset(rh->name, 0,
2125          strlen(name)-strlen(gnunet_tld) + 1);
2126   memcpy(rh->name, name,
2127          strlen(name)-strlen(gnunet_tld));
2128
2129   csh->name = GNUNET_malloc(strlen(name)
2130                             - strlen(gnunet_tld) + 1);
2131   memset(rh->name, 0,
2132          strlen(name)-strlen(gnunet_tld) + 1);
2133   memcpy(rh->name, name,
2134          strlen(name)-strlen(gnunet_tld));
2135
2136   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
2137
2138   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
2139   rh->authority_chain_tail = rh->authority_chain_head;
2140   rh->authority_chain_head->zone = zone_hash;
2141   rh->proc = &handle_shorten_delegation_result;
2142   rh->proc_cls = (void*)csh;
2143
2144   /* Start delegation resolution in our namestore */
2145   resolve_delegation_from_ns(rh);
2146
2147 }
2148
2149 /**
2150  * Send shorten response back to client
2151  * FIXME this is without .gnunet!
2152  * 
2153  * @param cls the client handle in closure
2154  * @param name the shortened name result or NULL if cannot be shortened
2155  */
2156 static void
2157 send_shorten_response(const char* name, struct ClientShortenHandle *csh)
2158 {
2159   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %s\n",
2160               "SHORTEN_RESULT", name);
2161   struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
2162   
2163   if (name == NULL)
2164   {
2165     name = "";
2166   }
2167
2168   rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage)
2169                        + strlen(name) + 1);
2170   
2171   rmsg->id = csh->unique_id;
2172   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
2173   rmsg->header.size = 
2174     htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage) +
2175           strlen(name) + 1);
2176
2177   strcpy((char*)&rmsg[1], name);
2178
2179   GNUNET_SERVER_notification_context_unicast (nc, csh->client,
2180                               (const struct GNUNET_MessageHeader *) rmsg,
2181                               GNUNET_NO);
2182   GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
2183   
2184   GNUNET_free(rmsg);
2185   GNUNET_free(csh->name);
2186   GNUNET_free(csh);
2187
2188 }
2189
2190 /**
2191  * Handle a shorten message from the api
2192  *
2193  * @param cls the closure
2194  * @param client the client
2195  * @param message the message
2196  */
2197 static void handle_shorten(void *cls,
2198                            struct GNUNET_SERVER_Client * client,
2199                            const struct GNUNET_MessageHeader * message)
2200 {
2201   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");
2202
2203   size_t msg_size = 0;
2204   struct ClientShortenHandle *csh;
2205
2206   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientShortenMessage))
2207   {
2208     GNUNET_break_op (0);
2209     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2210     return;
2211   }
2212
2213   GNUNET_SERVER_notification_context_add (nc, client);
2214
2215   struct GNUNET_GNS_ClientShortenMessage *sh_msg =
2216     (struct GNUNET_GNS_ClientShortenMessage *) message;
2217   
2218   msg_size = ntohs(message->size);
2219
2220   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2221   {
2222     GNUNET_break_op (0);
2223     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2224     return;
2225   }
2226
2227   csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
2228   csh->client = client;
2229   csh->unique_id = sh_msg->id;
2230   
2231   shorten_name((char*)&sh_msg[1], csh);
2232
2233 }
2234
2235 /**
2236  * Reply to client with the result from our lookup.
2237  *
2238  * @param cls the closure (our client lookup handle)
2239  * @param rh the request handle of the lookup
2240  * @param rd_count the number of records
2241  * @param rd the record data
2242  */
2243 static void
2244 reply_to_client(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
2245                 uint32_t rd_count,
2246                 const struct GNUNET_NAMESTORE_RecordData *rd)
2247 {
2248   struct ClientLookupHandle* clh = (struct ClientLookupHandle*)cls;
2249   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
2250   size_t len;
2251   
2252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with %d results\n",
2253               "LOOKUP_RESULT", rd_count);
2254   
2255   len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
2256   rmsg = GNUNET_malloc(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
2257   
2258   rmsg->id = clh->unique_id;
2259   rmsg->rd_count = htonl(rd_count);
2260   rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
2261   rmsg->header.size = 
2262     htons(len+sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
2263
2264   GNUNET_NAMESTORE_records_serialize (rd_count, rd, len, (char*)&rmsg[1]);
2265   
2266   GNUNET_SERVER_notification_context_unicast (nc, clh->client,
2267                                 (const struct GNUNET_MessageHeader *) rmsg,
2268                                 GNUNET_NO);
2269   GNUNET_SERVER_receive_done (clh->client, GNUNET_OK);
2270   
2271   GNUNET_free(rh->proc_cls);
2272   free_resolver_handle(rh);
2273   GNUNET_free(rmsg);
2274   GNUNET_free(clh->name);
2275   GNUNET_free(clh);
2276
2277 }
2278
2279 /**
2280  * Lookup a given name
2281  *
2282  * @param name the name to looku[
2283  * @param clh the client lookup handle
2284  */
2285 static void
2286 lookup_name(char* name, struct ClientLookupHandle* clh)
2287 {
2288
2289   struct GNUNET_GNS_ResolverHandle *rh;
2290   struct RecordLookupHandle* rlh;
2291   
2292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2293               "Starting resolution for %s (type=%d)!\n",
2294               name, clh->type);
2295   
2296   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
2297   rlh = GNUNET_malloc(sizeof(struct RecordLookupHandle));
2298   
2299   rh->authority = zone_hash;
2300
2301   rlh->record_type = clh->type;
2302   rlh->name = clh->name;
2303   rlh->proc = &reply_to_client;
2304   rlh->proc_cls = clh;
2305
2306   rh->proc_cls = rlh;
2307   
2308   rh->name = GNUNET_malloc(strlen(name)
2309                               - strlen(gnunet_tld) + 1);
2310   memset(rh->name, 0,
2311          strlen(name)-strlen(gnunet_tld) + 1);
2312   memcpy(rh->name, name,
2313          strlen(name)-strlen(gnunet_tld));
2314
2315   rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);
2316   
2317   rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
2318   rh->authority_chain_head->prev = NULL;
2319   rh->authority_chain_head->next = NULL;
2320   rh->authority_chain_tail = rh->authority_chain_head;
2321   rh->authority_chain_head->zone = zone_hash;
2322
2323   /* Start resolution in our zone */
2324   rh->proc = &process_ns_delegation_dns; //FIXME rename
2325   resolve_delegation_from_ns(rh);
2326 }
2327
2328
2329 /**
2330  * Handle lookup requests from client
2331  *
2332  * @param cls the closure
2333  * @param client the client
2334  * @param message the message
2335  */
2336 static void
2337 handle_lookup(void *cls,
2338               struct GNUNET_SERVER_Client * client,
2339               const struct GNUNET_MessageHeader * message)
2340 {
2341   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "LOOKUP");
2342
2343   size_t msg_size = 0;
2344   struct ClientLookupHandle *clh;
2345
2346   if (ntohs (message->size) < sizeof (struct GNUNET_GNS_ClientLookupMessage))
2347   {
2348     GNUNET_break_op (0);
2349     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2350     return;
2351   }
2352
2353   GNUNET_SERVER_notification_context_add (nc, client);
2354
2355   struct GNUNET_GNS_ClientLookupMessage *sh_msg =
2356     (struct GNUNET_GNS_ClientLookupMessage *) message;
2357   
2358   msg_size = ntohs(message->size);
2359
2360   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2361   {
2362     GNUNET_break_op (0);
2363     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2364     return;
2365   }
2366
2367   clh = GNUNET_malloc(sizeof(struct ClientLookupHandle));
2368   clh->client = client;
2369   clh->name = GNUNET_malloc(strlen((char*)&sh_msg[1]) + 1);
2370   strcpy(clh->name, (char*)&sh_msg[1]);
2371   clh->unique_id = sh_msg->id;
2372   clh->type = ntohl(sh_msg->type);
2373   
2374   lookup_name((char*)&sh_msg[1], clh);
2375 }
2376
2377 /**
2378  * Process GNS requests.
2379  *
2380  * @param cls closure)
2381  * @param server the initialized server
2382  * @param c configuration to use
2383  */
2384 static void
2385 run (void *cls, struct GNUNET_SERVER_Handle *server,
2386      const struct GNUNET_CONFIGURATION_Handle *c)
2387 {
2388   
2389   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initializing GNS\n");
2390
2391   char* keyfile;
2392   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
2393
2394   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2395     {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
2396     {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0}
2397   };
2398
2399   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (c, "gns",
2400                                              "ZONEKEY", &keyfile))
2401   {
2402     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2403                 "No private key for root zone specified%s!\n", keyfile);
2404     GNUNET_SCHEDULER_shutdown(0);
2405     return;
2406   }
2407
2408   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2409   GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);
2410
2411   GNUNET_CRYPTO_hash(&pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2412                      &zone_hash);
2413   GNUNET_free(keyfile);
2414   
2415
2416   dns_handle = NULL;
2417   if (GNUNET_YES ==
2418       GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
2419                                             "HIJACK_DNS"))
2420   {
2421     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
2422                "DNS hijacking enabled... connecting to service.\n");
2423     /**
2424      * Do gnunet dns init here
2425      */
2426     dns_handle = GNUNET_DNS_connect(c,
2427                                     GNUNET_DNS_FLAG_PRE_RESOLUTION,
2428                                     &handle_dns_request, /* rh */
2429                                     NULL); /* Closure */
2430     if (NULL == dns_handle)
2431     {
2432       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2433                "Failed to connect to the dnsservice!\n");
2434     }
2435   }
2436
2437   
2438
2439   /**
2440    * handle to our local namestore
2441    */
2442   namestore_handle = GNUNET_NAMESTORE_connect(c);
2443
2444   if (NULL == namestore_handle)
2445   {
2446     //FIXME do error handling;
2447     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2448                "Failed to connect to the namestore!\n");
2449     GNUNET_SCHEDULER_shutdown(0);
2450     return;
2451   }
2452   
2453   /**
2454    * handle to the dht
2455    */
2456   dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg
2457
2458   if (NULL == dht_handle)
2459   {
2460     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
2461   }
2462
2463   //put_some_records(); //FIXME for testing
2464   
2465   /**
2466    * Schedule periodic put
2467    * for our records
2468    * We have roughly an hour for all records;
2469    */
2470   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
2471                                                       1);
2472   //zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
2473
2474   GNUNET_SERVER_add_handlers (server, handlers);
2475   
2476   //FIXME
2477   //GNUNET_SERVER_disconnect_notify (server,
2478   //                                 &client_disconnect_notification,
2479   //                                 NULL);
2480
2481   nc = GNUNET_SERVER_notification_context_create (server, 1);
2482
2483   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
2484                                 NULL);
2485 }
2486
2487
2488 /**
2489  * The main function for the GNS service.
2490  *
2491  * @param argc number of arguments from the command line
2492  * @param argv command line arguments
2493  * @return 0 ok, 1 on error
2494  */
2495 int
2496 main (int argc, char *const *argv)
2497 {
2498   int ret;
2499
2500   ret =
2501       (GNUNET_OK ==
2502        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
2503                            NULL)) ? 0 : 1;
2504   return ret;
2505 }
2506
2507 /* end of gnunet-service-gns.c */