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