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