-try to get keys form config
[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 /* Ignore for now not used anyway and probably never will */
43 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_LOOKUP 23
44 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_RESULT 24
45
46 /**
47  * A result list for namestore queries
48  */
49 struct GNUNET_GNS_ResolverHandle
50 {
51   /* The name to resolve */
52   char *name;
53
54   /* the request handle to reply to */
55   struct GNUNET_DNS_RequestHandle *request_handle;
56   
57   /* the dns parser packet received */
58   struct GNUNET_DNSPARSER_Packet *packet;
59   
60   /* the query parsed from the packet */
61
62   struct GNUNET_DNSPARSER_Query *query;
63   
64   /* has this query been answered? how many matches */
65   int answered;
66
67   /* the authoritative zone to query */
68   GNUNET_HashCode authority;
69
70   /**
71    * we have an authority in namestore that
72    * may be able to resolve
73    */
74   int authority_found;
75
76   /* a handle for dht lookups. should be NULL if no lookups are in progress */
77   struct GNUNET_DHT_GetHandle *get_handle;
78
79 };
80
81
82 /**
83  * Our handle to the DNS handler library
84  */
85 struct GNUNET_DNS_Handle *dns_handle;
86
87 /**
88  * Our handle to the DHT
89  */
90 struct GNUNET_DHT_Handle *dht_handle;
91
92 /**
93  * Our zone's private key
94  */
95 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
96
97 /**
98  * Our handle to the namestore service
99  * FIXME maybe need a second handle for iteration
100  */
101 struct GNUNET_NAMESTORE_Handle *namestore_handle;
102
103 /**
104  * Handle to iterate over our authoritative zone in namestore
105  */
106 struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
107
108 /**
109  * The configuration the GNS service is running with
110  */
111 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
112
113 /**
114  * Our notification context.
115  */
116 static struct GNUNET_SERVER_NotificationContext *nc;
117
118 /**
119  * Our zone hash
120  */
121 GNUNET_HashCode zone_hash;
122
123 /**
124  * Our tld. Maybe get from config file
125  */
126 const char* gnunet_tld = ".gnunet";
127
128 /**
129  * Useful for zone update for DHT put
130  */
131 static int num_public_records =  3600;
132 struct GNUNET_TIME_Relative dht_update_interval;
133 GNUNET_SCHEDULER_TaskIdentifier zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;
134
135 //Prototypes
136 void reply_to_dns(struct GNUNET_GNS_ResolverHandle *answer, uint32_t rd_count,
137                   const struct GNUNET_NAMESTORE_RecordData *rd);
138 void resolve_name(struct GNUNET_GNS_ResolverHandle *rh);
139
140 /**
141  * Task run during shutdown.
142  *
143  * @param cls unused
144  * @param tc unused
145  */
146 static void
147 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
148 {
149   //Kill zone task for it may make the scheduler hang
150   GNUNET_SCHEDULER_cancel(zone_update_taskid);
151   GNUNET_DNS_disconnect(dns_handle);
152   GNUNET_NAMESTORE_disconnect(namestore_handle, 0);
153   GNUNET_DHT_disconnect(dht_handle);
154 }
155
156 /**
157  * Callback when record data is put into namestore
158  *
159  * @param cls the closure
160  * @param success GNUNET_OK on success
161  * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
162  */
163 void
164 on_namestore_record_put_result(void *cls,
165                                int32_t success,
166                                const char *emsg)
167 {
168   if (GNUNET_NO == success)
169   {
170     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "records already in namestore\n");
171     return;
172   }
173   else if (GNUNET_YES == success)
174   {
175     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
176                "records successfully put in namestore\n");
177     return;
178   }
179
180   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
181              "Error putting records into namestore: %s\n", emsg);
182 }
183
184 /**
185  * Function called when we get a result from the dht
186  * for our query
187  *
188  * @param cls the request handle
189  * @param exp lifetime
190  * @param key the key the record was stored under
191  * @param get_path get path
192  * @param get_path_length get path length
193  * @param put_path put path
194  * @param put_path_length put path length
195  * @param type the block type
196  * @param size the size of the record
197  * @param data the record data
198  */
199 void
200 process_authority_dht_result(void* cls,
201                  struct GNUNET_TIME_Absolute exp,
202                  const GNUNET_HashCode * key,
203                  const struct GNUNET_PeerIdentity *get_path,
204                  unsigned int get_path_length,
205                  const struct GNUNET_PeerIdentity *put_path,
206                  unsigned int put_path_length,
207                  enum GNUNET_BLOCK_Type type,
208                  size_t size, const void *data)
209 {
210   struct GNUNET_GNS_ResolverHandle *rh;
211   struct GNSNameRecordBlock *nrb;
212   struct GNSRecordBlock *rb;
213   uint32_t num_records;
214   char* name = NULL;
215   int i;
216   GNUNET_HashCode zone, name_hash;
217   
218   //FIXME GNS block check
219
220   if (data == NULL)
221     return;
222   
223   //FIXME check expiration?
224   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
225   nrb = (struct GNSNameRecordBlock*)data;
226   
227   GNUNET_DHT_get_stop (rh->get_handle);
228   rh->get_handle = NULL;
229   num_records = ntohl(nrb->rd_count);
230   struct GNUNET_NAMESTORE_RecordData rd[num_records];
231   name = (char*)&nrb[1];
232   rb = (struct GNSRecordBlock *)(&nrb[1] + strlen(name));
233
234   for (i=0; i<num_records; i++)
235   {
236   
237     rd[i].record_type = ntohl(rb->type);
238     rd[i].data_size = ntohl(rb->data_length);
239     rd[i].data = &rb[1];
240     rd[i].expiration = GNUNET_TIME_absolute_ntoh(rb->expiration);
241     rd[i].flags = ntohs(rb->flags);
242     
243     if (strcmp(name, rh->query->name) &&
244         (rd[i].record_type == rh->query->type))
245     {
246       rh->answered = 1;
247     }
248
249   }
250
251   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
252   GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
253
254   //Save to namestore
255   GNUNET_NAMESTORE_record_put (namestore_handle,
256                                &nrb->public_key,
257                                name,
258                                exp,
259                                num_records,
260                                rd,
261                                &nrb->signature,
262                                &on_namestore_record_put_result, //cont
263                                NULL); //cls
264   
265   if (rh->answered)
266   {
267     rh->answered = 0;
268     rh->authority = zone;
269     resolve_name(rh);
270     return;
271   }
272   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "No authority in records\n");
273   reply_to_dns(rh, 0, NULL);
274 }
275
276 /**
277  * Start DHT lookup for a name -> PKEY (compare NS) record in
278  * query->authority's zone
279  *
280  * @param rh the pending gns query
281  * @param name the name of the PKEY record
282  */
283 void
284 resolve_authority_dht(struct GNUNET_GNS_ResolverHandle *rh, const char* name)
285 {
286   enum GNUNET_GNS_RecordType rtype = GNUNET_GNS_RECORD_PKEY;
287   struct GNUNET_TIME_Relative timeout;
288   GNUNET_HashCode name_hash;
289   GNUNET_HashCode lookup_key;
290
291   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
292   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
293
294   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);
295   
296   //FIXME how long to wait for results?
297   rh->get_handle = GNUNET_DHT_get_start(dht_handle, timeout,
298                        GNUNET_BLOCK_TYPE_TEST, //FIXME todo
299                        &lookup_key,
300                        5, //Replication level FIXME
301                        GNUNET_DHT_RO_NONE,
302                        &rtype, //xquery FIXME this is bad
303                        sizeof(GNUNET_GNS_RECORD_PKEY),
304                        &process_authority_dht_result,
305                        rh);
306
307 }
308
309 /**
310  * Function called when we get a result from the dht
311  * for our query
312  *
313  * @param cls the request handle
314  * @param exp lifetime
315  * @param key the key the record was stored under
316  * @param get_path get path
317  * @param get_path_length get path length
318  * @param put_path put path
319  * @param put_path_length put path length
320  * @param type the block type
321  * @param size the size of the record
322  * @param data the record data
323  */
324 void
325 process_name_dht_result(void* cls,
326                  struct GNUNET_TIME_Absolute exp,
327                  const GNUNET_HashCode * key,
328                  const struct GNUNET_PeerIdentity *get_path,
329                  unsigned int get_path_length,
330                  const struct GNUNET_PeerIdentity *put_path,
331                  unsigned int put_path_length,
332                  enum GNUNET_BLOCK_Type type,
333                  size_t size, const void *data)
334 {
335   struct GNUNET_GNS_ResolverHandle *rh;
336   struct GNSNameRecordBlock *nrb;
337   struct GNSRecordBlock *rb;
338   uint32_t num_records;
339   char* name = NULL;
340   int i;
341   GNUNET_HashCode zone, name_hash;
342
343   if (data == NULL)
344     return;
345
346   //FIXME maybe check expiration here, check block type
347   
348   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
349   nrb = (struct GNSNameRecordBlock*)data;
350
351   GNUNET_DHT_get_stop (rh->get_handle);
352   rh->get_handle = NULL;
353   num_records = ntohl(nrb->rd_count);
354   struct GNUNET_NAMESTORE_RecordData rd[num_records];
355
356   name = (char*)&nrb[1];
357   rb = (struct GNSRecordBlock*)(&nrb[1] + strlen(name));
358   
359   for (i=0; i<num_records; i++)
360   {
361     rd[i].record_type = ntohl(rb->type);
362     rd[i].data_size = ntohl(rb->data_length);
363     rd[i].data = (char*)&rb[1];
364     rd[i].expiration = GNUNET_TIME_absolute_ntoh(rb->expiration);
365     rd[i].flags = ntohs(rb->flags);
366     //FIXME class?
367     if (strcmp(name, rh->query->name) &&
368        (rd[i].record_type == rh->query->type))
369     {
370       rh->answered++;
371     }
372
373   }
374
375   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
376   GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
377   
378   //FIXME check pubkey against existing key in namestore?
379   //https://gnunet.org/bugs/view.php?id=2179
380
381   //Save to namestore
382   GNUNET_NAMESTORE_record_put (namestore_handle,
383                                &nrb->public_key,
384                                name,
385                                exp,
386                                num_records,
387                                rd,
388                                &nrb->signature,
389                                &on_namestore_record_put_result, //cont
390                                NULL); //cls
391   
392   if (rh->answered)
393     reply_to_dns(rh, num_records, rd);
394   else
395     reply_to_dns(rh, 0, NULL);
396
397 }
398
399 /**
400  * Start DHT lookup for a (name -> query->record_type) record in
401  * query->authority's zone
402  *
403  * @param rh the pending gns query context
404  * @param name the name to query record
405  */
406 void
407 resolve_name_dht(struct GNUNET_GNS_ResolverHandle *rh, const char* name)
408 {
409   struct GNUNET_TIME_Relative timeout;
410   GNUNET_HashCode name_hash;
411   GNUNET_HashCode lookup_key;
412
413   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
414   GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
415   
416
417   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);
418   
419   //FIXME how long to wait for results?
420   rh->get_handle = GNUNET_DHT_get_start(dht_handle, timeout,
421                        GNUNET_BLOCK_TYPE_TEST, //FIXME todo
422                        &lookup_key,
423                        5, //Replication level FIXME
424                        GNUNET_DHT_RO_NONE,
425                        &rh->query->type, //xquery
426                        sizeof(rh->query->type),
427                        &process_name_dht_result,
428                        rh);
429
430 }
431
432 //Prototype
433 void
434 resolve_name(struct GNUNET_GNS_ResolverHandle *rh);
435
436 /**
437  * This is a callback function that should give us only PKEY
438  * records. Used to query the namestore for the authority (PKEY)
439  * for 'name'
440  *
441  * @param cls the pending query
442  * @param key the key of the zone we did the lookup
443  * @param expiration expiration date of the record data set in the namestore
444  * @param name the name for which we need an authority
445  * @param rd_count the number of records with 'name'
446  * @param rd the record data
447  * @param signature the signature of the authority for the record data
448  */
449 void
450 process_authority_lookup(void* cls,
451                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
452                    struct GNUNET_TIME_Absolute expiration,
453                    const char *name,
454                    unsigned int rd_count,
455                    const struct GNUNET_NAMESTORE_RecordData *rd,
456                    const struct GNUNET_CRYPTO_RsaSignature *signature)
457 {
458   struct GNUNET_GNS_ResolverHandle *rh;
459   struct GNUNET_TIME_Relative remaining_time;
460   GNUNET_HashCode zone;
461
462   rh = (struct GNUNET_GNS_ResolverHandle *)cls;
463   GNUNET_CRYPTO_hash(key, GNUNET_CRYPTO_RSA_KEY_LENGTH, &zone);
464   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
465   
466   /**
467    * No authority found in namestore.
468    */
469   if (rd_count == 0)
470   {
471     /**
472      * We did not find an authority in the namestore
473      * _IF_ the current authoritative zone is us we cannot resolve
474      * _ELSE_ we can still check the _expired_ dht
475      */
476     if (0 != GNUNET_CRYPTO_hash_cmp(&zone, &zone_hash) &&
477         (remaining_time.rel_value == 0))
478     {
479       resolve_authority_dht(rh, name);
480       return;
481     }
482     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Authority unknown\n");
483     reply_to_dns(rh, 0, NULL);
484     return;
485   }
486
487   //Note only 1 pkey should have been returned.. anything else would be strange
488   /**
489    * We found an authority that may be able to help us
490    * move on with query
491    */
492   int i;
493   for (i=0; i<rd_count;i++)
494   {
495   
496     if (strcmp(name, rh->query->name) && rd[i].record_type
497         != GNUNET_GNS_RECORD_PKEY)
498       continue;
499     
500       if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
501           == 0)
502       {
503         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This pkey is expired.\n");
504         if (remaining_time.rel_value == 0)
505         {
506           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
507                      "This dht entry is expired. Refreshing\n");
508           resolve_authority_dht(rh, name);
509         }
510
511         continue;
512       }
513
514       GNUNET_assert(rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
515       GNUNET_CRYPTO_hash(rd[i].data, GNUNET_CRYPTO_RSA_KEY_LENGTH,
516                          &rh->authority);
517       resolve_name(rh);
518       return;
519       
520   }
521     
522   /**
523    * no answers found
524    */
525   
526   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
527              "Authority lookup successful but no PKEY... never get here?\n");
528   reply_to_dns(rh, 0, NULL);
529 }
530
531
532 /**
533  * Reply to client with the result from our lookup.
534  *
535  * @param rh the request handle of the lookup
536  * @param rd_count the number of records to return
537  * @param rd the record data
538  */
539 void
540 reply_to_dns(struct GNUNET_GNS_ResolverHandle *rh, uint32_t rd_count,
541              const struct GNUNET_NAMESTORE_RecordData *rd)
542 {
543   int i;
544   size_t len;
545   int ret;
546   char *buf;
547   struct GNUNET_DNSPARSER_Packet *packet = rh->packet;
548   struct GNUNET_DNSPARSER_Record answer_records[rh->answered];
549   struct GNUNET_DNSPARSER_Record additional_records[rd_count-(rh->answered)];
550   packet->answers = answer_records;
551   packet->additional_records = additional_records;
552   
553   len = sizeof(struct GNUNET_DNSPARSER_Record*);
554   for (i=0; i < rd_count; i++)
555   {
556     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
557                "Adding type %d to DNS response\n", rd[i].record_type);
558     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Name: %s\n", rh->name);
559     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "QName: %s\n", rh->query->name);
560     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Record %d/%d\n", i+1, rd_count);
561     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Record len %d\n", rd[i].data_size);
562     if (rd[i].record_type == rh->query->type)
563     {
564       answer_records[i].name = rh->query->name;
565       answer_records[i].type = rd[i].record_type;
566       answer_records[i].data.raw.data_len = rd[i].data_size;
567       answer_records[i].data.raw.data = (char*)rd[i].data;
568       answer_records[i].expiration_time = rd[i].expiration;
569       answer_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
570     }
571     else
572     {
573       additional_records[i].name = rh->query->name;
574       additional_records[i].type = rd[i].record_type;
575       additional_records[i].data.raw.data_len = rd[i].data_size;
576       additional_records[i].data.raw.data = (char*)rd[i].data;
577       additional_records[i].expiration_time = rd[i].expiration;
578       additional_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
579     }
580     //GNUNET_free(i->record); DO this later!
581   }
582   
583   packet->num_answers = rh->answered; //answer->num_records;
584   packet->num_additional_records = rd_count-(rh->answered);
585   
586   if (0 == GNUNET_CRYPTO_hash_cmp(&rh->authority, &zone_hash))
587     packet->flags.authoritative_answer = 1;
588   else
589    packet->flags.authoritative_answer = 0;
590
591   if (rd == NULL)
592     packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NAME_ERROR;
593   else
594     packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR;
595   
596   packet->flags.query_or_response = 1;
597
598   //FIXME this is silently discarded
599   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
600              "Building DNS response\n");
601   ret = GNUNET_DNSPARSER_pack (packet,
602                                1024, /* FIXME magic from dns redirector */
603                                &buf,
604                                &len);
605   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
606              "Built DNS response! (ret=%d,len=%d)\n", ret, len);
607   if (ret == GNUNET_OK)
608   {
609     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
610                "Answering DNS request\n");
611     GNUNET_DNS_request_answer(rh->request_handle,
612                               len,
613                               buf);
614     //GNUNET_free(answer);
615     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Answered DNS request\n");
616     //FIXME return code, free datastructures
617   }
618   else
619   {
620     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
621                "Error building DNS response! (ret=%d)", ret);
622   }
623
624   //FIXME into free_resolver(rh)
625   GNUNET_free(rh->name);
626   GNUNET_free(rh);
627 }
628
629
630 /**
631  * Namestore calls this function if we have an entry for this name.
632  * (or data=null to indicate the lookup has finished
633  *
634  * @param cls the pending query
635  * @param key the key of the zone we did the lookup
636  * @param expiration expiration date of the namestore entry
637  * @param name the name for which we need an authority
638  * @param rd_count the number of records with 'name'
639  * @param rd the record data
640  * @param signature the signature of the authority for the record data
641  */
642 static void
643 process_authoritative_result(void* cls,
644                   const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
645                   struct GNUNET_TIME_Absolute expiration,
646                   const char *name, unsigned int rd_count,
647                   const struct GNUNET_NAMESTORE_RecordData *rd,
648                   const struct GNUNET_CRYPTO_RsaSignature *signature)
649 {
650   struct GNUNET_GNS_ResolverHandle *rh;
651   struct GNUNET_TIME_Relative remaining_time;
652   GNUNET_HashCode zone;
653
654   rh = (struct GNUNET_GNS_ResolverHandle *) cls;
655   GNUNET_CRYPTO_hash(key, GNUNET_CRYPTO_RSA_KEY_LENGTH, &zone);
656   remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
657
658   //FIXME Handle results in rd
659
660   if (rd_count == 0)
661   {
662     /**
663      * Lookup terminated and no results
664      * -> DHT Phase unless data is recent
665      */
666     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
667                "Namestore lookup for %s terminated without results\n", name);
668     
669     /**
670      * if this is not our zone we cannot rely on the namestore to be
671      * complete. -> Query DHT
672      */
673     if (!GNUNET_CRYPTO_hash_cmp(&zone, &zone_hash))
674     {
675       if (remaining_time.rel_value == 0)
676       {
677         resolve_name_dht(rh, name);
678         return;
679       }
680       else
681       {
682         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
683                    "Record is still recent. No DHT lookup\n");
684       }
685     }
686
687     /**
688      * Our zone and no result? Cannot resolve TT
689      */
690     GNUNET_assert(rh->answered == 0);
691     reply_to_dns(rh, 0, NULL); //answered should be 0
692     return;
693
694   }
695   else
696   {
697     
698     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
699                "Processing additional result %s from namestore\n", name);
700     int i;
701     for (i=0; i<rd_count;i++)
702     {
703       
704       if (strcmp(name, rh->query->name) && rd[i].record_type != rh->query->type)
705         continue;
706       
707       if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
708           == 0)
709       {
710         //FIXME there is a catch here...
711         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This record is expired. Skipping\n");
712         continue;
713       }
714       
715       rh->answered++;
716       
717     }
718     
719     /**
720      * no answers found
721      * consult dht if expired
722      */
723     if ((remaining_time.rel_value == 0) && (rh->answered == 0))
724     {
725       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
726                  "This dht entry is old. Refreshing.\n");
727       resolve_name_dht(rh, name);
728       return;
729     }
730     
731     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Found %d answer(s) to query!\n",
732                rh->answered);
733
734     reply_to_dns(rh, rd_count, rd);
735   }
736 }
737
738 /**
739  * Determine if this name is canonical.
740  * i.e.
741  * a.b.gnunet  = not canonical
742  * a           = canonical
743  *
744  * @param name the name to test
745  * @return 1 if canonical
746  */
747 int
748 is_canonical(char* name)
749 {
750   uint32_t len = strlen(name);
751   int i;
752
753   for (i=0; i<len; i++)
754   {
755     if (*(name+i) == '.')
756       return 0;
757   }
758   return 1;
759 }
760
761 /**
762  * Move one level up in the domain hierarchy and return the
763  * passed top level domain.
764  *
765  * @param name the domain
766  * @return the tld
767  */
768 char* pop_tld(char* name)
769 {
770   uint32_t len;
771
772   if (is_canonical(name))
773     return NULL;
774
775   for (len = strlen(name); len > 0; len--)
776   {
777     if (*(name+len) == '.')
778       break;
779   }
780
781   if (len == 0)
782     return NULL; //Error
783
784   name[len] = '\0'; //terminate string
785
786   return (name+len+1);
787 }
788
789
790 /**
791  * The first phase of resolution.
792  * First check if the name is canonical.
793  * If it is then try to resolve directly.
794  * If not then first have to resolve the authoritative entities.
795  *
796  * @param rh the pending lookup
797  * @param zone the zone we are currently resolving in
798  */
799 void
800 resolve_name(struct GNUNET_GNS_ResolverHandle *rh)
801 {
802   if (is_canonical(rh->name))
803   {
804     //We only need to check this zone's ns
805     GNUNET_NAMESTORE_lookup_record(namestore_handle,
806                                &rh->authority,
807                                rh->name,
808                                rh->query->type,
809                                &process_authoritative_result,
810                                rh);
811   }
812   else
813   {
814     //We have to resolve the authoritative entity
815     char *new_authority = pop_tld(rh->name);
816     GNUNET_NAMESTORE_lookup_record(namestore_handle,
817                                  &rh->authority,
818                                  new_authority,
819                                  GNUNET_GNS_RECORD_PKEY,
820                                  &process_authority_lookup,
821                                  rh);
822   }
823 }
824
825 /**
826  * Entry point for name resolution
827  * Lookup local namestore of our zone.
828  *
829  * Setup a new query and try to resolve
830  *
831  * @param request the request handle of the DNS request from a client
832  * @param p the DNS query packet we received
833  * @param q the DNS query we received parsed from p
834  */
835 void
836 start_resolution(struct GNUNET_DNS_RequestHandle *request,
837                  struct GNUNET_DNSPARSER_Packet *p,
838                  struct GNUNET_DNSPARSER_Query *q)
839 {
840   struct GNUNET_GNS_ResolverHandle *rh;
841   
842   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting resolution for (%s)!\n",
843               q->name);
844   
845   rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
846   rh->packet = p;
847   rh->query = q;
848   rh->authority = zone_hash;
849   
850   //FIXME do not forget to free!!
851   rh->name = GNUNET_malloc(strlen(q->name)
852                               - strlen(gnunet_tld) + 1);
853   memset(rh->name, 0,
854          strlen(q->name)-strlen(gnunet_tld) + 1);
855   memcpy(rh->name, q->name,
856          strlen(q->name)-strlen(gnunet_tld));
857
858   rh->request_handle = request;
859
860   //Start resolution in our zone
861   resolve_name(rh);
862 }
863
864 /**
865  * The DNS request handler
866  * Called for every incoming DNS request.
867  *
868  * @param cls closure
869  * @param rh request handle to user for reply
870  * @param request_length number of bytes in request
871  * @param request udp payload of the DNS request
872  */
873 void
874 handle_dns_request(void *cls,
875                    struct GNUNET_DNS_RequestHandle *rh,
876                    size_t request_length,
877                    const char *request)
878 {
879   struct GNUNET_DNSPARSER_Packet *p;
880   char *tldoffset;
881
882   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Hijacked a DNS request...processing\n");
883   p = GNUNET_DNSPARSER_parse (request, request_length);
884   
885   if (NULL == p)
886   {
887     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
888                 "Received malformed DNS packet, leaving it untouched\n");
889     GNUNET_DNS_request_forward (rh);
890     return;
891   }
892   
893   /**
894    * Check tld and decide if we or
895    * legacy dns is responsible
896    *
897    * FIXME now in theory there could be more than 1 query in the request
898    * but if this is case we get into trouble:
899    * either we query the GNS or the DNS. We cannot do both!
900    * So I suggest to either only allow a single query per request or
901    * only allow GNS or DNS requests.
902    * The way it is implemented here now is buggy and will lead to erratic
903    * behaviour (if multiple queries are present).
904    */
905   if (p->num_queries == 0)
906   {
907     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
908                 "No Queries in DNS packet... forwarding\n");
909     GNUNET_DNS_request_forward (rh);
910   }
911
912   if (p->num_queries > 1)
913   {
914     //Note: We could also look for .gnunet
915     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
916                 ">1 queriy in DNS packet... odd. We only process #1\n");
917   }
918
919
920   tldoffset = p->queries[0].name + strlen(p->queries[0].name);
921
922   while ((*tldoffset) != '.')
923     tldoffset--;
924   
925   if (0 == strcmp(tldoffset, gnunet_tld))
926   {
927     start_resolution(rh, p, p->queries);
928   }
929   else
930   {
931     /**
932      * This request does not concern us. Forward to real DNS.
933      */
934     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
935                "Request for %s is forwarded to DNS\n", p->queries[0].name);
936     GNUNET_DNS_request_forward (rh);
937   }
938
939 }
940
941 /**
942  * test function that stores some data in the namestore
943  */
944 void
945 put_some_records(void)
946 {
947   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Populating namestore\n");
948   /* put a few records into namestore */
949   char* ipA = "1.2.3.4";
950   char* ipB = "5.6.7.8";
951   struct GNUNET_CRYPTO_RsaPrivateKey *bob_key = GNUNET_CRYPTO_rsa_key_create ();  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *bob;
952   bob = GNUNET_malloc(sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
953
954   GNUNET_CRYPTO_rsa_key_get_public (bob_key, bob);
955
956   GNUNET_HashCode *bob_zone = GNUNET_malloc(sizeof(GNUNET_HashCode));
957
958   GNUNET_CRYPTO_hash(bob, GNUNET_CRYPTO_RSA_KEY_LENGTH, bob_zone);
959
960   struct in_addr *alice = GNUNET_malloc(sizeof(struct in_addr));
961   struct in_addr *bob_web = GNUNET_malloc(sizeof(struct in_addr));
962   struct GNUNET_NAMESTORE_RecordData rda;
963   struct GNUNET_NAMESTORE_RecordData rdb;
964   struct GNUNET_NAMESTORE_RecordData rdb_web;
965
966   GNUNET_assert(1 == inet_pton (AF_INET, ipA, alice));
967   GNUNET_assert(1 == inet_pton (AF_INET, ipB, bob_web));
968
969   rda.data_size = sizeof(struct in_addr);
970   rdb_web.data_size = sizeof(struct in_addr);
971   rdb.data_size = sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded);
972   rda.data = alice;
973   rdb.data = bob;
974   rdb_web.data = bob_web;
975   rda.record_type = GNUNET_GNS_RECORD_TYPE_A;
976   rdb_web.record_type = GNUNET_GNS_RECORD_TYPE_A;
977   rdb.record_type = GNUNET_GNS_RECORD_PKEY;
978   rdb_web.expiration = GNUNET_TIME_absolute_get_forever ();
979   rda.expiration = GNUNET_TIME_absolute_get_forever ();
980   rdb.expiration = GNUNET_TIME_absolute_get_forever ();
981   
982   //alice.gnunet A IN 1.2.3.4
983   GNUNET_NAMESTORE_record_create (namestore_handle,
984                                zone_key,
985                                "alice",
986                                &rda,
987                                NULL,
988                                NULL);
989
990   //www.bob.gnunet A IN 5.6.7.8
991   GNUNET_NAMESTORE_record_create (namestore_handle,
992                                zone_key,
993                                "bob",
994                                &rdb,
995                                NULL,
996                                NULL);
997   GNUNET_NAMESTORE_record_put(namestore_handle,
998                               bob,
999                               "www",
1000                               GNUNET_TIME_absolute_get_forever (),
1001                               1,
1002                               &rdb_web,
1003                               NULL, //Signature
1004                               NULL, //Cont
1005                               NULL); //cls
1006 }
1007
1008 void
1009 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1010 {
1011   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
1012 }
1013
1014 /* prototype */
1015 static void
1016 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1017
1018 /**
1019  * Function used to put all records successively into the DHT.
1020  * FIXME bug here
1021  *
1022  * @param cls the closure (NULL)
1023  * @param key the public key of the authority (ours)
1024  * @param expiration lifetime of the namestore entry
1025  * @param name the name of the records
1026  * @param rd_count the number of records in data
1027  * @param rd the record data
1028  * @param signature the signature for the record data
1029  */
1030 void
1031 put_gns_record(void *cls,
1032                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
1033                 struct GNUNET_TIME_Absolute expiration,
1034                 const char *name,
1035                 unsigned int rd_count,
1036                 const struct GNUNET_NAMESTORE_RecordData *rd,
1037                 const struct GNUNET_CRYPTO_RsaSignature *signature)
1038 {
1039   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Putting records into the DHT\n");
1040   struct GNUNET_TIME_Relative timeout;
1041   struct GNSNameRecordBlock *nrb;
1042   struct GNSRecordBlock *rb;
1043   GNUNET_HashCode name_hash;
1044   GNUNET_HashCode xor_hash;
1045   int i;
1046   uint32_t rd_payload_length;
1047
1048   if (NULL == name) //We're done
1049   {
1050     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Zone iteration finished\n");
1051     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
1052     zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start,
1053                                                    NULL);
1054     return;
1055   }
1056   
1057   rd_payload_length = rd_count * sizeof(struct GNSRecordBlock);
1058   rd_payload_length += strlen(name) + sizeof(struct GNSNameRecordBlock);
1059   //Calculate payload size
1060   for (i=0; i<rd_count; i++)
1061   {
1062     rd_payload_length += rd[i].data_size;
1063   }
1064   
1065   nrb = GNUNET_malloc(rd_payload_length);
1066   
1067   if (signature != NULL)
1068     memcpy(&nrb->signature, signature,
1069          sizeof(struct GNUNET_CRYPTO_RsaSignature));
1070   //FIXME signature purpose
1071   memcpy(&nrb->public_key, key,
1072          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1073
1074   nrb->rd_count = htonl(rd_count);
1075
1076   memcpy(&nrb[1], name, strlen(name)); //FIXME is this 0 terminated??
1077
1078   rb = (struct GNSRecordBlock *)(&nrb[1]+strlen(name));
1079
1080   for (i=0; i<rd_count; i++)
1081   {
1082     rb->type = htonl(rd[i].record_type);
1083     rb->expiration = GNUNET_TIME_absolute_hton(rd[i].expiration);
1084     rb->data_length = htonl(rd[i].data_size);
1085     rb->flags = htonl(rd[i].flags);
1086     memcpy(&rb[1], rd[i].data, rd[i].data_size);
1087     rb = &rb[1] + rd[i].data_size;
1088   }
1089
1090   /**
1091    * FIXME magic number 20 move to config file
1092    */
1093   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);
1094   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
1095   GNUNET_CRYPTO_hash_xor(&zone_hash, &name_hash, &xor_hash);
1096   GNUNET_DHT_put (dht_handle, &xor_hash,
1097                   5, //replication level
1098                   GNUNET_DHT_RO_NONE,
1099                   GNUNET_BLOCK_TYPE_TEST, //FIXME todo block plugin
1100                   rd_payload_length,
1101                   (char*)nrb,
1102                   expiration,
1103                   timeout,
1104                   NULL, //FIXME continuation needed? success check? yes ofc
1105                   NULL); //cls for cont
1106   
1107   num_public_records++;
1108
1109   /**
1110    * Reschedule periodic put
1111    */
1112   zone_update_taskid = GNUNET_SCHEDULER_add_delayed (dht_update_interval,
1113                                 &update_zone_dht_next,
1114                                 NULL);
1115
1116 }
1117
1118 /**
1119  * Periodically iterate over our zone and store everything in dht
1120  *
1121  * @param cls NULL
1122  * @param tc task context
1123  */
1124 static void
1125 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1126 {
1127   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Update zone!\n");
1128   if (0 == num_public_records)
1129   {
1130     dht_update_interval = GNUNET_TIME_relative_multiply(
1131                                                       GNUNET_TIME_UNIT_SECONDS,
1132                                                       1);
1133   }
1134   else
1135   {
1136     dht_update_interval = GNUNET_TIME_relative_multiply(
1137                                                       GNUNET_TIME_UNIT_SECONDS,
1138                                                      (3600/num_public_records));
1139   }
1140   num_public_records = 0; //start counting again
1141   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
1142                                                           &zone_hash,
1143                                                           GNUNET_NAMESTORE_RF_AUTHORITY,
1144                                                           GNUNET_NAMESTORE_RF_PRIVATE,
1145                                                           &put_gns_record,
1146                                                           NULL);
1147 }
1148
1149 /**
1150  * Process GNS requests.
1151  *
1152  * @param cls closure
1153  * @param server the initialized server
1154  * @param c configuration to use
1155  */
1156 static void
1157 run (void *cls, struct GNUNET_SERVER_Handle *server,
1158      const struct GNUNET_CONFIGURATION_Handle *c)
1159 {
1160   
1161   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Init GNS\n");
1162   char* keyfile;
1163   //this always returns syserr
1164   if (GNUNET_SYSERR ==
1165       GNUNET_CONFIGURATION_get_value_string (c, "gns",
1166                                              "ZONEKEY", &keyfile));
1167   {
1168     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1169                 "No private key for root zone specified%s!\n", keyfile);
1170   }
1171   zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1172   //zone_key = GNUNET_CRYPTO_rsa_key_create ();
1173
1174   GNUNET_CRYPTO_hash(zone_key, GNUNET_CRYPTO_RSA_KEY_LENGTH,//FIXME is this ok?
1175                      &zone_hash);
1176   nc = GNUNET_SERVER_notification_context_create (server, 1);
1177
1178   /* FIXME - do some config parsing 
1179    *       - Maybe only hijack dns if option is set (HIJACK_DNS=1)
1180    */
1181
1182   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1183                                 NULL);
1184   /**
1185    * Do gnunet dns init here
1186    */
1187   dns_handle = GNUNET_DNS_connect(c,
1188                                   GNUNET_DNS_FLAG_PRE_RESOLUTION,
1189                                   &handle_dns_request, /* rh */
1190                                   NULL); /* Closure */
1191
1192   if (NULL == dns_handle)
1193   {
1194     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1195                "Failed to connect to the dnsservice!\n");
1196   }
1197
1198   /**
1199    * handle to our local namestore
1200    */
1201   namestore_handle = GNUNET_NAMESTORE_connect(c);
1202
1203   if (NULL == namestore_handle)
1204   {
1205     //FIXME do error handling;
1206     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1207                "Failed to connect to the namestore!\n");
1208   }
1209
1210   /**
1211    * handle to the dht
1212    */
1213   dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg
1214
1215   if (NULL == dht_handle)
1216   {
1217     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1218   }
1219
1220   put_some_records(); //FIXME for testing
1221   
1222   /**
1223    * Schedule periodic put
1224    * for our records
1225    * We have roughly an hour for all records;
1226    */
1227   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1228                                                       1); //FIXME from cfg
1229   zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);
1230   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "GNS Init done!\n");
1231
1232 }
1233
1234
1235 /**
1236  * The main function for the GNS service.
1237  *
1238  * @param argc number of arguments from the command line
1239  * @param argv command line arguments
1240  * @return 0 ok, 1 on error
1241  */
1242 int
1243 main (int argc, char *const *argv)
1244 {
1245   int ret;
1246
1247   ret =
1248       (GNUNET_OK ==
1249        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1250                            NULL)) ? 0 : 1;
1251   return ret;
1252 }
1253
1254 /* end of gnunet-service-gns.c */