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