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