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