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