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