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