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