-ns continuation
[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  *    - (de-)serialisation of records/signature trees
27  *    - The smaller FIXME issues all around
28  *
29  * @file gns/gnunet-service-gns.c
30  * @brief GNUnet GNS service
31  * @author Martin Schanzenbach
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_transport_service.h"
36 #include "gnunet_dns_service.h"
37 #include "gnunet_dnsparser_lib.h"
38 #include "gnunet_dht_service.h"
39 #include "gnunet_namestore_service.h"
40 #include "gnunet_gns_service.h"
41 #include "gns.h"
42
43 /* Ignore for now not used anyway and probably never will */
44 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_LOOKUP 23
45 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_RESULT 24
46
47 struct GNUNET_GNS_QueryRecordList
48 {
49   /**
50    * DLL
51    */
52   struct GNUNET_GNS_QueryRecordList * next;
53   struct GNUNET_GNS_QueryRecordList * prev;
54
55   struct GNUNET_NAMESTORE_RecordData * record;
56 };
57
58 /**
59  * A result list for namestore queries
60  */
61 struct GNUNET_GNS_PendingQuery
62 {
63   /* the answer packet */
64   struct GNUNET_DNSPARSER_Packet *answer;
65
66   /* records to put into answer packet */
67   struct GNUNET_GNS_QueryRecordList * records_head;
68   struct GNUNET_GNS_QueryRecordList * records_tail;
69
70   int num_records;
71   int num_authority_records; //FIXME are all of our replies auth?
72   
73   char *original_name;
74   char *name;
75
76   uint16_t type;
77   /* the dns request id */
78   int id; // FIXME can handle->request_id also be used here?
79
80   /* the request handle to reply to */
81   struct GNUNET_DNS_RequestHandle *request_handle;
82
83   /* hast this query been answered? */
84   int answered;
85
86   /* the authoritative zone to query */
87   GNUNET_HashCode *authority;
88
89   /* we have an authority in namestore that
90    * may be able to resolve
91    */
92   int authority_found;
93 };
94
95
96 /**
97  * Our handle to the DNS handler library
98  */
99 struct GNUNET_DNS_Handle *dns_handle;
100
101 /**
102  * Our handle to the DHT
103  */
104 struct GNUNET_DHT_Handle *dht_handle;
105
106 /**
107  * Our zone's private key
108  */
109 struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;
110
111 /**
112  * Our handle to the namestore service
113  */
114 struct GNUNET_NAMESTORE_Handle *namestore_handle;
115
116 struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
117
118 /**
119  * The configuration the GNS service is running with
120  */
121 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
122
123 /**
124  * Our notification context.
125  */
126 static struct GNUNET_SERVER_NotificationContext *nc;
127
128 /**
129  * Our zone hash
130  */
131 GNUNET_HashCode zone_hash;
132
133 /**
134  * Our tld. Maybe get from config file
135  */
136 const char* gnunet_tld = ".gnunet";
137
138 /**
139  * Useful for zone update for DHT put
140  */
141 static int num_public_records =  3600;
142 struct GNUNET_TIME_Relative dht_update_interval;
143
144
145 void reply_to_dns(struct GNUNET_GNS_PendingQuery *answer);
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);
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)
567 {
568   struct GNUNET_GNS_QueryRecordList *i;
569   struct GNUNET_DNSPARSER_Packet *packet;
570   struct GNUNET_DNSPARSER_Flags dnsflags;
571   int j;
572   size_t len;
573   int ret;
574   char *buf;
575   
576   packet = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Packet));
577   packet->answers =
578     GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record) * answer->num_records);
579   
580   len = sizeof(struct GNUNET_DNSPARSER_Record*);
581   j = 0;
582   for (i=answer->records_head; i != NULL; i=i->next)
583   {
584     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
585                "Adding type %d to DNS response\n", i->record->record_type);
586     //FIXME build proper dnsparser record! this will fail!
587     //memcpy(&packet->answers[j], 
588     //       i->record,
589     //       sizeof (struct GNUNET_DNSPARSER_Record));
590     GNUNET_free(i->record);
591     j++;
592   }
593   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "after memcpy\n");
594   /* FIXME how to handle auth, additional etc */
595   packet->num_answers = answer->num_records;
596   packet->num_authority_records = answer->num_authority_records;
597
598   dnsflags.authoritative_answer = 1;
599   dnsflags.opcode = GNUNET_DNSPARSER_OPCODE_QUERY;
600   dnsflags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR; //not sure
601   dnsflags.query_or_response = 1;
602   packet->flags = dnsflags;
603
604   packet->id = answer->id;
605   
606   //FIXME this is silently discarded
607   ret = GNUNET_DNSPARSER_pack (packet,
608                                1024, /* FIXME magic from dns redirector */
609                                &buf,
610                                &len);
611   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
612              "Built DNS response! (ret=%d)\n", ret);
613   if (ret == GNUNET_OK)
614   {
615     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
616                "Answering DNS request\n");
617     GNUNET_DNS_request_answer(answer->request_handle,
618                               len,
619                               buf);
620     //GNUNET_free(answer);
621     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Answered DNS request\n");
622     //FIXME return code, free datastructures
623   }
624   else
625   {
626     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
627                "Error building DNS response! (ret=%d)", ret);
628   }
629 }
630
631
632 /**
633  * Namestore calls this function if we have an entry for this name.
634  * (or data=null to indicate the lookup has finished)
635  *
636  * @param cls the pending query
637  * @param zone the zone of the lookup
638  * @param name the name looked up
639  * @param record_type the record type
640  * @param expiration lifetime of the record
641  * @param flags record flags
642  * @param sig_loc location of the record in the signature tree
643  * @param size the size of the record
644  * @param data the record data
645  */
646 static void
647 process_authoritative_result(void* cls,
648                   const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
649                   struct GNUNET_TIME_Absolute expiration,
650                   const char *name, unsigned int rd_count,
651                   const struct GNUNET_NAMESTORE_RecordData *rd,
652                   const struct GNUNET_CRYPTO_RsaSignature *signature)
653 {
654   struct GNUNET_GNS_PendingQuery *query;
655   struct GNUNET_GNS_QueryRecordList *qrecord;
656   struct GNUNET_NAMESTORE_RecordData *record;
657   GNUNET_HashCode zone;
658   query = (struct GNUNET_GNS_PendingQuery *) cls;
659   GNUNET_CRYPTO_hash(key, GNUNET_CRYPTO_RSA_KEY_LENGTH, &zone);
660
661   //FIXME Handle results in rd
662
663   if (rd_count == 0)
664   {
665     /**
666      * FIXME
667      * Lookup terminated and no results
668      * -> DHT Phase unless data is recent
669      */
670     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
671                "Namestore lookup terminated. without results\n");
672     
673     /**
674      * if this is not our zone we cannot rely on the namestore to be
675      * complete. -> Query DHT
676      */
677     if (!GNUNET_CRYPTO_hash_cmp(&zone, &zone_hash))
678     {
679       //FIXME if very recent dht lookup -> cannot resolve
680       resolve_name_dht(query, name);
681       return;
682     }
683
684     /**
685      * Our zone and no result? Cannot resolve TT
686      * FIXME modify query to say NX
687      */
688     GNUNET_assert(query->answered == 0);
689     reply_to_dns(query); //answered should be 0
690     return;
691
692   }
693   else
694   {
695     /**
696      * Record found
697      *
698      * FIXME Check record expiration and dht expiration
699      * consult dht if necessary
700      */
701     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
702                "Processing additional result %s from namestore\n", name);
703     int i;
704     for (i=0; i<rd_count;i++)
705     {
706       // A time will come when this has to be freed
707       qrecord = GNUNET_malloc(sizeof(struct GNUNET_GNS_QueryRecordList));
708       record = GNUNET_malloc(sizeof(struct GNUNET_NAMESTORE_RecordData));
709       qrecord->record = record;
710       
711       //fixme into gns_util
712       //parse_record(rd[i]->data, rd[i]->data_size, 0, record);
713       GNUNET_CONTAINER_DLL_insert(query->records_head,
714                                   query->records_tail,
715                                   qrecord);
716       query->num_records++;
717
718       //TODO really?
719       //we need to resolve to the original name in the end though...
720       //keep in mind. This can also be done later probably
721       //record->name = (char*)query->original_name;
722     }
723
724     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Found answer to query!\n");
725     query->answered = 1;
726
727     reply_to_dns(query);
728   }
729 }
730
731 /**
732  * Determine if this name is canonical.
733  * i.e.
734  * a.b.gnunet  = not canonical
735  * a           = canonical
736  *
737  * @param name the name to test
738  * @return 1 if canonical
739  */
740 int
741 is_canonical(char* name)
742 {
743   uint32_t len = strlen(name);
744   int i;
745
746   for (i=0; i<len; i++)
747   {
748     if (*(name+i) == '.')
749       return 0;
750   }
751   return 1;
752 }
753
754 /**
755  * Move one level up in the domain hierarchy and return the
756  * passed top level domain.
757  * FIXME this needs a better name
758  *
759  * @param name the domain
760  * @return the tld
761  */
762 char* pop_tld(char* name)
763 {
764   uint32_t len;
765
766   if (is_canonical(name))
767     return NULL;
768
769   for (len = strlen(name); len > 0; len--)
770   {
771     if (*(name+len) == '.')
772       break;
773   }
774
775   if (len == 0)
776     return NULL; //Error
777
778   name[len] = '\0'; //terminate string
779
780   return (name+len+1);
781 }
782
783
784 /**
785  * The first phase of resolution.
786  * First check if the name is canonical.
787  * If it is then try to resolve directly.
788  * If not then first have to resolve the authoritative entities.
789  *
790  * @param query the pending lookup
791  * @param zone the zone we are currently resolving in
792  */
793 void
794 resolve_name(struct GNUNET_GNS_PendingQuery *query, GNUNET_HashCode *zone)
795 {
796   if (is_canonical(query->name))
797   {
798     //We only need to check this zone's ns
799     GNUNET_NAMESTORE_lookup_record(namestore_handle,
800                                zone,
801                                query->name,
802                                query->type,
803                                &process_authoritative_result,
804                                query);
805   }
806   else
807   {
808     //We have to resolve the authoritative entity
809     char *new_authority = pop_tld(query->name);
810     GNUNET_NAMESTORE_lookup_record(namestore_handle,
811                                  zone,
812                                  new_authority,
813                                  GNUNET_GNS_RECORD_PKEY,
814                                  &process_authority_lookup,
815                                  query);
816   }
817 }
818
819 /**
820  * Entry point for name resolution
821  * Lookup local namestore of our zone.
822  *
823  * Setup a new query and try to resolve
824  *
825  * @param rh the request handle of the DNS request from a client
826  * @param name the name to look up
827  * @param id the id of the dns request (for the reply)
828  * @param type the record type to look for
829  */
830 void
831 start_resolution(struct GNUNET_DNS_RequestHandle *rh,
832                  char* name, uint16_t id, uint16_t type)
833 {
834   struct GNUNET_GNS_PendingQuery *query;
835   
836   //FIXME remove .gnunet here from name
837   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "This is .gnunet (%s)!\n", name);
838   query = GNUNET_malloc(sizeof (struct GNUNET_GNS_PendingQuery));
839   query->id = id;
840   query->original_name = name; //Full name of original query
841   
842   //FIXME do not forget to free!!
843   query->name = GNUNET_malloc(strlen(name)-strlen(gnunet_tld) + 1);
844   memset(query->name, 0, strlen(name)-strlen(gnunet_tld) + 1);
845   memcpy(query->name, name, strlen(name)-strlen(gnunet_tld));
846
847   query->type = type;
848   query->request_handle = rh;
849
850   //Start resolution in our zone
851   resolve_name(query, &zone_hash);
852 }
853
854 /**
855  * The DNS request handler
856  * Called for every incoming DNS request.
857  *
858  * @param cls closure
859  * @param rh request handle to user for reply
860  * @param request_length number of bytes in request
861  * @param request udp payload of the DNS request
862  */
863 void
864 handle_dns_request(void *cls,
865                    struct GNUNET_DNS_RequestHandle *rh,
866                    size_t request_length,
867                    const char *request)
868 {
869   struct GNUNET_DNSPARSER_Packet *p;
870   int i;
871   char *tldoffset;
872
873   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Hijacked a DNS request...processing\n");
874   p = GNUNET_DNSPARSER_parse (request, request_length);
875   
876   if (NULL == p)
877   {
878     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
879                 "Received malformed DNS packet, leaving it untouched\n");
880     GNUNET_DNS_request_forward (rh);
881     return;
882   }
883   
884   /**
885    * Check tld and decide if we or
886    * legacy dns is responsible
887    *
888    * FIXME now in theory there could be more than 1 query in the request
889    * but if this is case we get into trouble:
890    * either we query the GNS or the DNS. We cannot do both!
891    * So I suggest to either only allow a single query per request or
892    * only allow GNS or DNS requests.
893    * The way it is implemented here now is buggy and will lead to erratic
894    * behaviour (if multiple queries are present).
895    */
896   for (i=0;i<p->num_queries;i++)
897   {
898     tldoffset = p->queries[i].name + strlen(p->queries[i].name);
899
900     while ((*tldoffset) != '.')
901       tldoffset--;
902     
903     if (0 == strcmp(tldoffset, gnunet_tld))
904     {
905       start_resolution(rh, p->queries[i].name, p->id, p->queries[i].type);
906     }
907     else
908     {
909       /**
910        * This request does not concern us. Forward to real DNS.
911        */
912       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
913                  "Request for %s is forwarded to DNS\n", p->queries[i].name);
914       GNUNET_DNS_request_forward (rh);
915     }
916   }
917 }
918
919 /**
920  * test function that stores some data in the namestore
921  */
922 void
923 put_some_records(void)
924 {
925   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Populating namestore\n");
926   /* put a few records into namestore */
927   char* ipA = "1.2.3.4";
928   char* ipB = "5.6.7.8";
929   struct in_addr *alice = GNUNET_malloc(sizeof(struct in_addr));
930   struct in_addr *bob = GNUNET_malloc(sizeof(struct in_addr));
931   struct GNUNET_NAMESTORE_RecordData *rda;
932   struct GNUNET_NAMESTORE_RecordData *rdb;
933
934   rda = GNUNET_malloc(sizeof(struct GNUNET_NAMESTORE_RecordData));
935   rdb = GNUNET_malloc(sizeof(struct GNUNET_NAMESTORE_RecordData));
936   
937   GNUNET_assert(1 == inet_pton (AF_INET, ipA, alice));
938   GNUNET_assert(1 == inet_pton (AF_INET, ipB, bob));
939
940   rda->data_size = sizeof(struct in_addr);
941   rdb->data_size = sizeof(struct in_addr);
942   rda->data = alice;
943   rdb->data = bob;
944   rda->record_type = GNUNET_GNS_RECORD_TYPE_A;
945   rdb->record_type = GNUNET_GNS_RECORD_TYPE_A;
946   rda->expiration = GNUNET_TIME_absolute_get_forever ();
947   rdb->expiration = GNUNET_TIME_absolute_get_forever ();
948   
949   GNUNET_NAMESTORE_record_create (namestore_handle,
950                                zone_key,
951                                "alice",
952                                rda,
953                                NULL,
954                                NULL);
955   GNUNET_NAMESTORE_record_create (namestore_handle,
956                                zone_key,
957                                "bob",
958                                rdb,
959                                NULL,
960                                NULL);
961 }
962
963 void
964 update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
965 {
966   GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
967 }
968
969 /**
970  * Function used to put all records successively into the DHT.
971  *
972  * @param cls the closure (NULL)
973  * @param zone our root zone hash
974  * @param name the name of the record
975  * @param record_type the type of the record
976  * @param expiration lifetime of the record
977  * @param flags flags of the record
978  * @param sig_loc location of record in signature tree
979  * @param size size of the record
980  * @param record_data the record data
981  */
982 void
983 put_gns_record(void *cls,
984                 const const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
985                 struct GNUNET_TIME_Absolute expiration,
986                 const char *name,
987                 unsigned int rd_count,
988                 const struct GNUNET_NAMESTORE_RecordData *rd,
989                 const struct GNUNET_CRYPTO_RsaSignature *signature)
990 {
991   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Putting records into the DHT\n");
992   struct GNUNET_TIME_Relative timeout;
993   GNUNET_HashCode name_hash;
994   GNUNET_HashCode xor_hash;
995
996   if (NULL == name) //We're done
997   {
998     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
999     return;
1000   }
1001   /**
1002    * FIXME magic number 20 move to config file
1003    */
1004   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);
1005   GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
1006   GNUNET_CRYPTO_hash_xor(&zone_hash, &name_hash, &xor_hash);
1007   GNUNET_DHT_put (dht_handle, &xor_hash,
1008                   5, //replication level
1009                   GNUNET_DHT_RO_NONE,
1010                   GNUNET_BLOCK_TYPE_TEST, //FIXME todo block plugin
1011                   rd->data_size,
1012                   rd->data,
1013                   expiration,
1014                   timeout,
1015                   NULL, //FIXME continuation needed? success check? yes ofc
1016                   NULL); //cls for cont
1017
1018   /**
1019    * Reschedule periodic put
1020    */
1021   GNUNET_SCHEDULER_add_delayed (dht_update_interval,
1022                                 &update_zone_dht_next,
1023                                 NULL);
1024
1025 }
1026
1027 /**
1028  * Periodically iterate over our zone and store everything in dht
1029  *
1030  * @param cls NULL
1031  * @param tc task context
1032  */
1033 static void
1034 update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1035 {
1036   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Update zone!\n");
1037   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1038                                                      (3600/num_public_records));
1039   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
1040                                                           &zone_hash,
1041                                                           GNUNET_NAMESTORE_RF_AUTHORITY,
1042                                                           GNUNET_NAMESTORE_RF_PRIVATE,
1043                                                           &put_gns_record,
1044                                                           NULL);
1045 }
1046
1047 /**
1048  * Process GNS requests.
1049  *
1050  * @param cls closure
1051  * @param server the initialized server
1052  * @param c configuration to use
1053  */
1054 static void
1055 run (void *cls, struct GNUNET_SERVER_Handle *server,
1056      const struct GNUNET_CONFIGURATION_Handle *c)
1057 {
1058   
1059   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Init GNS\n");
1060   zone_key = GNUNET_CRYPTO_rsa_key_create ();
1061
1062   GNUNET_CRYPTO_hash(zone_key, GNUNET_CRYPTO_RSA_KEY_LENGTH,//FIXME is this ok?
1063                      &zone_hash);
1064   nc = GNUNET_SERVER_notification_context_create (server, 1);
1065
1066   /* FIXME - do some config parsing 
1067    *       - Maybe only hijack dns if option is set (HIJACK_DNS=1)
1068    */
1069
1070   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1071                                 NULL);
1072   /**
1073    * Do gnunet dns init here
1074    */
1075   dns_handle = GNUNET_DNS_connect(c,
1076                                   GNUNET_DNS_FLAG_PRE_RESOLUTION,
1077                                   &handle_dns_request, /* rh */
1078                                   NULL); /* Closure */
1079
1080   if (NULL == dns_handle)
1081   {
1082     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1083                "Failed to connect to the dnsservice!\n");
1084   }
1085
1086   /**
1087    * handle to our local namestore
1088    */
1089   namestore_handle = GNUNET_NAMESTORE_connect(c);
1090
1091   if (NULL == namestore_handle)
1092   {
1093     //FIXME do error handling;
1094     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1095                "Failed to connect to the namestore!\n");
1096   }
1097
1098   /**
1099    * handle to the dht
1100    */
1101   dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg
1102
1103   if (NULL == dht_handle)
1104   {
1105     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
1106   }
1107
1108   put_some_records(); //FIXME for testing
1109   
1110   /**
1111    * Schedule periodic put
1112    * for our records
1113    * We have roughly an hour for all records;
1114    */
1115   dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
1116                                                       60); //FIXME from cfg
1117   GNUNET_SCHEDULER_add_delayed (dht_update_interval,
1118                                 &update_zone_dht_start,
1119                                 NULL);
1120   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "GNS Init done!\n");
1121
1122 }
1123
1124
1125 /**
1126  * The main function for the GNS service.
1127  *
1128  * @param argc number of arguments from the command line
1129  * @param argv command line arguments
1130  * @return 0 ok, 1 on error
1131  */
1132 int
1133 main (int argc, char *const *argv)
1134 {
1135   int ret;
1136
1137   ret =
1138       (GNUNET_OK ==
1139        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1140                            NULL)) ? 0 : 1;
1141   return ret;
1142 }
1143
1144 /* end of gnunet-service-gns.c */