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