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