aboutsummaryrefslogtreecommitdiff
path: root/src/gns/gnunet-service-gns.c
blob: 02613dbb1bdfc6ef1432d729ea7c9a542abe7f08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
/*
     This file is part of GNUnet.
     (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 3, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/

/**
 *
 * TODO:
 *    - Write xquery and block plugin
 *    - Think about mixed dns queries (.gnunet and .org)
 *    - (de-)serialisation of records/signature trees
 *    - The smaller FIXME issues all around
 *
 * @file gns/gnunet-service-gns.c
 * @brief GNUnet GNS service
 * @author Martin Schanzenbach
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_transport_service.h"
#include "gnunet_dns_service.h"
#include "gnunet_dnsparser_lib.h"
#include "gnunet_dht_service.h"
#include "gnunet_namestore_service.h"
#include "gnunet_gns_service.h"
#include "gns.h"

/* Ignore for now not used anyway and probably never will */
#define GNUNET_MESSAGE_TYPE_GNS_CLIENT_LOOKUP 23
#define GNUNET_MESSAGE_TYPE_GNS_CLIENT_RESULT 24

struct GNUNET_GNS_QueryRecordList
{
  /**
   * DLL
   */
  struct GNUNET_GNS_QueryRecordList * next;
  struct GNUNET_GNS_QueryRecordList * prev;

  struct GNUNET_DNSPARSER_Record * record;
};

/**
 * A result list for namestore queries
 */
struct GNUNET_GNS_PendingQuery
{
  /* the answer packet */
  struct GNUNET_DNSPARSER_Packet *answer;

  /* records to put into answer packet */
  struct GNUNET_GNS_QueryRecordList * records_head;
  struct GNUNET_GNS_QueryRecordList * records_tail;

  int num_records;
  int num_authority_records; //FIXME are all of our replies auth?
  
  char *original_name;
  char *name;

  uint16_t type;
  /* the dns request id */
  int id; // FIXME can handle->request_id also be used here?

  /* the request handle to reply to */
  struct GNUNET_DNS_RequestHandle *request_handle;

  /* hast this query been answered? */
  int answered;

  /* the authoritative zone to query */
  GNUNET_HashCode *authority;

  /* we have an authority in namestore that
   * may be able to resolve
   */
  int authority_found;
};


/**
 * Our handle to the DNS handler library
 */
struct GNUNET_DNS_Handle *dns_handle;

/**
 * Our handle to the DHT
 */
struct GNUNET_DHT_Handle *dht_handle;

struct GNUNET_TIME_Relative dht_update_interval;

/**
 * Our zone's private key
 */
struct GNUNET_CRYPTO_RsaPrivateKey *zone_key;

/**
 * Our handle to the namestore service
 */
struct GNUNET_NAMESTORE_Handle *namestore_handle;

/**
 * The configuration the GNS service is running with
 */
const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;

/**
 * Our notification context.
 */
static struct GNUNET_SERVER_NotificationContext *nc;

/**
 * Our zone hash
 */
GNUNET_HashCode zone_hash;

/**
 * Our tld. Maybe get from config file
 */
const char* gnunet_tld = ".gnunet";

/**
 * Task run during shutdown.
 *
 * @param cls unused
 * @param tc unused
 */
static void
shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GNUNET_DNS_disconnect(dns_handle);
  GNUNET_NAMESTORE_disconnect(namestore_handle, 0);
  GNUNET_DHT_disconnect(dht_handle);
}

/**
 * Function called when we get a result from the dht
 * for our query
 *
 * @param cls the query handle
 * @param exp lifetime
 * @param key the key the record was stored under
 * @param get_path get path
 * @param get_path_length get path length
 * @param put_path put path
 * @param put_path_length put path length
 * @param type the block type
 * @param size the size of the record
 * @param data the record data
 */
void
process_authority_dht_result(void* cls,
                 struct GNUNET_TIME_Absolute exp,
                 const GNUNET_HashCode * key,
                 const struct GNUNET_PeerIdentity *get_path,
                 unsigned int get_path_length,
                 const struct GNUNET_PeerIdentity *put_path,
                 unsigned int put_path_length,
                 enum GNUNET_BLOCK_Type type,
                 size_t size, const void *data)
{
  if (data == NULL)
    return;

  /**
   * data is a serialized PKEY record (probably)
   * parse, put into namestore
   * namestore zone hash is in query.
   * Then adjust query->name and call resolve_name
   * with new zone (the one just received)
   *
   * query->authority = new_authority
   * resolve_name(query, new_authority);
   */
}

/**
 * Start DHT lookup for a name -> PKEY (compare NS) record in
 * query->authority's zone
 *
 * @param query the pending gns query
 * @param name the name of the PKEY record
 */
void
resolve_authority_dht(struct GNUNET_GNS_PendingQuery *query, const char* name)
{
  enum GNUNET_GNS_RecordType rtype = GNUNET_GNS_RECORD_PKEY;
  struct GNUNET_TIME_Relative timeout;
  GNUNET_HashCode name_hash;
  GNUNET_HashCode lookup_key;

  GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
  GNUNET_CRYPTO_hash_xor(&name_hash, query->authority, &lookup_key);

  timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);
  
  //FIXME how long to wait for results?
  GNUNET_DHT_get_start(dht_handle, timeout,
                       GNUNET_BLOCK_TYPE_TEST, //FIXME todo
                       &lookup_key,
                       5, //Replication level FIXME
                       GNUNET_DHT_RO_NONE,
                       &rtype, //xquery FIXME this is bad
                       sizeof(GNUNET_GNS_RECORD_PKEY),
                       &process_authority_dht_result,
                       query);

}

/**
 * Function called when we get a result from the dht
 * for our query
 *
 * @param cls the query handle
 * @param exp lifetime
 * @param key the key the record was stored under
 * @param get_path get path
 * @param get_path_length get path length
 * @param put_path put path
 * @param put_path_length put path length
 * @param type the block type
 * @param size the size of the record
 * @param data the record data
 */
void
process_name_dht_result(void* cls,
                 struct GNUNET_TIME_Absolute exp,
                 const GNUNET_HashCode * key,
                 const struct GNUNET_PeerIdentity *get_path,
                 unsigned int get_path_length,
                 const struct GNUNET_PeerIdentity *put_path,
                 unsigned int put_path_length,
                 enum GNUNET_BLOCK_Type type,
                 size_t size, const void *data)
{
  if (data == NULL)
    return;

  /**
   * data is a serialized GNS record of type
   * query->record_type. Parse and put into namestore
   * namestore zone hash is in query.
   * Check if record type and name match in query and reply
   * to dns!
   */
}

/**
 * Start DHT lookup for a (name -> query->record_type) record in
 * query->authority's zone
 *
 * @param query the pending gns query
 * @param name the name to query record
 */
void
resolve_name_dht(struct GNUNET_GNS_PendingQuery *query, const char* name)
{
  struct GNUNET_TIME_Relative timeout;
  GNUNET_HashCode name_hash;
  GNUNET_HashCode lookup_key;

  GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
  GNUNET_CRYPTO_hash_xor(&name_hash, query->authority, &lookup_key);

  timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);
  
  //FIXME how long to wait for results?
  GNUNET_DHT_get_start(dht_handle, timeout,
                       GNUNET_BLOCK_TYPE_TEST, //FIXME todo
                       &lookup_key,
                       5, //Replication level FIXME
                       GNUNET_DHT_RO_NONE,
                       &query->type, //xquery
                       sizeof(query->type),
                       &process_name_dht_result,
                       query);

}

//Prototype
void
resolve_name(struct GNUNET_GNS_PendingQuery *query, GNUNET_HashCode *zone);

/**
 * This is a callback function that should give us only PKEY
 * records. Used to query the namestore for the authority (PKEY)
 * for 'name'
 *
 * @param cls the pending query
 * @param zone our zone hash
 * @param name the name for which we need an authority
 * @param record_type the type of record (PKEY)
 * @param expiration expiration date of the record
 * @param flags namestore record flags
 * @param sig_loc the location of the record in the signature tree
 * @param size the size of the record
 * @param data the record data
 */
void
process_authority_lookup(void* cls, const GNUNET_HashCode *zone,
                   const char *name, uint32_t record_type,
                   struct GNUNET_TIME_Absolute expiration,
                   enum GNUNET_NAMESTORE_RecordFlags flags,
                   const struct GNUNET_NAMESTORE_SignatureLocation *sig_loc,
                   size_t size, const void *data)
{
  struct GNUNET_GNS_PendingQuery *query;

  query = (struct GNUNET_GNS_PendingQuery *)cls;
  
  /**
   * No authority found in namestore.
   */
  if (NULL == data)
  {
    if (query->authority_found)
    {
      query->authority_found = 0;
      resolve_name(query, query->authority);
      return;
    }

    /**
     * We did not find an authority in the namestore
     * _IF_ the current authoritative zone is us.
     * we cannot resolve
     * _ELSE_ we cannot still check the dht
     */
    if (GNUNET_CRYPTO_hash_cmp(zone, &zone_hash))
    {
      GNUNET_log(GNUNET_ERROR_TYPE_INFO, "NX record\n");
      //FIXME return NX answer
      return;
    }

    resolve_authority_dht(query, name);
    return;
  }
  
  /**
   * We found an authority that may be able to help us
   * move on with query
   */
  query->authority_found = 1;
  GNUNET_HashCode *key = (GNUNET_HashCode*) data; //FIXME i assume this works
  query->authority = key;
  
}


/**
 * Reply to client with the result from our lookup.
 *
 * @param answer the pending query used in the lookup
 */
void
reply_to_dns(struct GNUNET_GNS_PendingQuery *answer)
{
  struct GNUNET_GNS_QueryRecordList *i;
  struct GNUNET_DNSPARSER_Packet *packet;
  struct GNUNET_DNSPARSER_Flags dnsflags;
  int j;
  size_t len;
  int ret;
  char *buf;
  
  packet = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Packet));
  packet->answers =
    GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record) * answer->num_records);
  
  len = sizeof(struct GNUNET_DNSPARSER_Record*);
  j = 0;
  for (i=answer->records_head; i != NULL; i=i->next)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_INFO,
               "Adding %s to DNS response\n", i->record->name);
    memcpy(&packet->answers[j], 
           i->record,
           sizeof (struct GNUNET_DNSPARSER_Record));
    GNUNET_free(i->record);
    j++;
  }
  GNUNET_log(GNUNET_ERROR_TYPE_INFO, "after memcpy\n");
  /* FIXME how to handle auth, additional etc */
  packet->num_answers = answer->num_records;
  packet->num_authority_records = answer->num_authority_records;

  dnsflags.authoritative_answer = 1;
  dnsflags.opcode = GNUNET_DNSPARSER_OPCODE_QUERY;
  dnsflags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR; //not sure
  dnsflags.query_or_response = 1;
  packet->flags = dnsflags;

  packet->id = answer->id;
  
  //FIXME this is silently discarded
  ret = GNUNET_DNSPARSER_pack (packet,
                               1024, /* FIXME magic from dns redirector */
                               &buf,
                               &len);
  GNUNET_log(GNUNET_ERROR_TYPE_INFO,
             "Built DNS response! (ret=%d)\n", ret);
  if (ret == GNUNET_OK)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_INFO,
               "Answering DNS request\n");
    //GNUNET_DNS_request_answer(answer->request_handle,
    //                          len,
     //                         buf);
    GNUNET_free(answer);
    GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Answered DNS request\n");
    //FIXME return code, free datastructures
  }
  else
  {
    GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
               "Error building DNS response! (ret=%d)", ret);
  }
}


/**
 * Namestore calls this function if we have an entry for this name.
 * (or data=null to indicate the lookup has finished)
 *
 * @param cls the pending query
 * @param zone the zone of the lookup
 * @param name the name looked up
 * @param record_type the record type
 * @param expiration lifetime of the record
 * @param flags record flags
 * @param sig_loc location of the record in the signature tree
 * @param size the size of the record
 * @param data the record data
 */
static void
process_authoritative_result(void* cls, const GNUNET_HashCode *zone,
                  const char *name, uint32_t record_type,
                  struct GNUNET_TIME_Absolute expiration,
                  enum GNUNET_NAMESTORE_RecordFlags flags,
                  const struct GNUNET_NAMESTORE_SignatureLocation *sig_loc,
                  size_t size, const void *data)
{
  struct GNUNET_GNS_PendingQuery *query;
  struct GNUNET_GNS_QueryRecordList *qrecord;
  struct GNUNET_DNSPARSER_Record *record;
  query = (struct GNUNET_GNS_PendingQuery *) cls;


  if (NULL == data)
  {
    /**
     * FIXME
     * Lookup terminated
     * Do we have what we need to answer?
     * If not -> DHT Phase
     * if full_name == next_name and not anwered we cannot resolve
     */
    GNUNET_log(GNUNET_ERROR_TYPE_INFO,
               "Namestore lookup terminated. (answered=%d)", query->answered);
    if (query->answered)
    {
      reply_to_dns(query);
      return;
    }

    /**
     * if this is not our zone we cannot rely on the namestore to be
     * complete. -> Query DHT
     */
    if (!GNUNET_CRYPTO_hash_cmp(zone, &zone_hash))
    {
      //FIXME todo
      resolve_name_dht(query, name);
      return;
    }

    /**
     * Our zone and no result? Cannot resolve TT
     * FIXME modify query to say NX
     */
    return;

  }
  else
  {
    /**
     * Record found
     */
    GNUNET_log(GNUNET_ERROR_TYPE_INFO,
               "Processing additional result for %s from namestore\n", name);

    qrecord = GNUNET_malloc(sizeof(struct GNUNET_GNS_QueryRecordList));
    record = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record));
    qrecord->record = record;

    record->name = (char*)query->original_name;

    /**
     * FIXME for gns records this requires the dnsparser to be modified!
     * or use RAW. But RAW data need serialization!
     * maybe store record data appropriately in namestore to avoid a
     * huge switch statement?
     */
    if (record_type == GNUNET_DNSPARSER_TYPE_A)
    {
      record->data.raw.data = (char*)data;
      record->data.raw.data_len = size;
    }
    record->expiration_time = expiration;
    record->type = record_type;
    record->class = GNUNET_DNSPARSER_CLASS_INTERNET; /* srsly? */
    
    //FIXME authoritative answer if we find a result in namestore
    if (flags == GNUNET_NAMESTORE_RF_AUTHORITY)
    {
      //query->num_authority_records++;
    }
    
    /**
     * This seems to take into account that the result could
     * be different in name and or record type...
     * but to me this does not make sense
     */
    GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Found answer to query!\n");
    query->answered = 1;

    query->num_records++;

    /**
     * FIXME watch for leaks
     * properly free pendingquery when the time comes
     */
    GNUNET_CONTAINER_DLL_insert(query->records_head,
                                query->records_tail,
                                qrecord);
  }
}

/**
 * Determine if this name is canonical.
 * i.e.
 * a.b.gnunet  = not canonical
 * a           = canonical
 *
 * @param name the name to test
 * @return 1 if canonical
 */
int
is_canonical(char* name)
{
  uint32_t len = strlen(name);
  int i;

  for (i=0; i<len; i++)
  {
    if (*(name+i) == '.')
      return 0;
  }
  return 1;
}

/**
 * Move one level up in the domain hierarchy and return the
 * passed top level domain.
 * FIXME this needs a better name
 *
 * @param name the domain
 * @return the tld
 */
char* move_up(char* name)
{
  uint32_t len;

  if (is_canonical(name))
    return NULL;

  for (len = strlen(name); len > 0; len--)
  {
    if (*(name+len) == '.')
      break;
  }

  if (len == 0)
    return NULL; //Error

  name[len] = '\0'; //terminate string

  return (name+len+1);
}


/**
 * The first phase of resolution.
 * First check if the name is canonical.
 * If it is then try to resolve directly.
 * If not then first have to resolve the authoritative entities.
 *
 * @param query the pending lookup
 * @param zone the zone we are currently resolving in
 */
void
resolve_name(struct GNUNET_GNS_PendingQuery *query, GNUNET_HashCode *zone)
{
  if (is_canonical(query->name))
  {
    //We only need to check this zone's ns
    GNUNET_NAMESTORE_lookup_name(namestore_handle,
                               zone,
                               query->name,
                               query->type,
                               &process_authoritative_result,
                               query);
  }
  else
  {
    //We have to resolve the authoritative entity
    char *new_authority = move_up(query->name);
    GNUNET_NAMESTORE_lookup_name(namestore_handle,
                                 zone,
                                 new_authority,
                                 GNUNET_GNS_RECORD_PKEY,
                                 &process_authority_lookup,
                                 query);
  }
}

/**
 * Entry point for name resolution
 * Lookup local namestore of our zone.
 *
 * Setup a new query and try to resolve
 *
 * @param rh the request handle of the DNS request from a client
 * @param name the name to look up
 * @param id the id of the dns request (for the reply)
 * @param type the record type to look for
 */
void
start_resolution(struct GNUNET_DNS_RequestHandle *rh,
                 char* name, uint16_t id, uint16_t type)
{
  struct GNUNET_GNS_PendingQuery *query;
  
  //FIXME remove .gnunet here from name
  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "This is .gnunet (%s)!\n", name);
  query = GNUNET_malloc(sizeof (struct GNUNET_GNS_PendingQuery));
  query->id = id;
  query->original_name = name; //Full name of original query
  
  //FIXME do not forget to free!!
  query->name = GNUNET_malloc(strlen(name)-strlen(gnunet_tld) + 1);
  memset(query->name, 0, strlen(name)-strlen(gnunet_tld) + 1);
  memcpy(query->name, name, strlen(name)-strlen(gnunet_tld));

  query->type = type;
  query->request_handle = rh;

  //Start resolution in our zone
  resolve_name(query, &zone_hash);
}

/**
 * The DNS request handler
 * Called for every incoming DNS request.
 *
 * @param cls closure
 * @param rh request handle to user for reply
 * @param request_length number of bytes in request
 * @param request udp payload of the DNS request
 */
void
handle_dns_request(void *cls,
                   struct GNUNET_DNS_RequestHandle *rh,
                   size_t request_length,
                   const char *request)
{
  struct GNUNET_DNSPARSER_Packet *p;
  int i;
  char *tldoffset;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Hijacked a DNS request...processing\n");
  p = GNUNET_DNSPARSER_parse (request, request_length);
  
  if (NULL == p)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Received malformed DNS packet, leaving it untouched\n");
    GNUNET_DNS_request_forward (rh);
    return;
  }
  
  /**
   * Check tld and decide if we or
   * legacy dns is responsible
   *
   * FIXME now in theory there could be more than 1 query in the request
   * but if this is case we get into trouble:
   * either we query the GNS or the DNS. We cannot do both!
   * So I suggest to either only allow a single query per request or
   * only allow GNS or DNS requests.
   * The way it is implemented here now is buggy and will lead to erratic
   * behaviour (if multiple queries are present).
   */
  for (i=0;i<p->num_queries;i++)
  {
    tldoffset = p->queries[i].name + strlen(p->queries[i].name);

    while ((*tldoffset) != '.')
      tldoffset--;
    
    if (0 == strcmp(tldoffset, gnunet_tld))
    {
      start_resolution(rh, p->queries[i].name, p->id, p->queries[i].type);
    }
    else
    {
      /**
       * This request does not concern us. Forward to real DNS.
       */
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
                 "Request for %s is forwarded to DNS\n", p->queries[i].name);
      GNUNET_DNS_request_forward (rh);
    }
  }
}

/**
 * test function that stores some data in the namestore
 */
void
put_some_records(void)
{
  GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Populating namestore\n");
  /* put a few records into namestore */
  char* ipA = "1.2.3.4";
  char* ipB = "5.6.7.8";
  struct in_addr *alice = GNUNET_malloc(sizeof(struct in_addr));
  struct in_addr *bob = GNUNET_malloc(sizeof(struct in_addr));
  GNUNET_assert(1 == inet_pton (AF_INET, ipA, alice));
  GNUNET_assert(1 == inet_pton (AF_INET, ipB, bob));
  GNUNET_NAMESTORE_record_put (namestore_handle,
                               &zone_hash,
                               "alice",
                               GNUNET_GNS_RECORD_TYPE_A,
                               GNUNET_TIME_absolute_get_forever(),
                               GNUNET_NAMESTORE_RF_AUTHORITY,
                               NULL, //sig loc
                               sizeof(struct in_addr),
                               alice,
                               NULL,
                               NULL);
  GNUNET_NAMESTORE_record_put (namestore_handle,
                               &zone_hash,
                               "bob",
                               GNUNET_GNS_RECORD_TYPE_A,
                               GNUNET_TIME_absolute_get_forever(),
                               GNUNET_NAMESTORE_RF_AUTHORITY,
                               NULL, //sig loc
                               sizeof(struct in_addr),
                               bob,
                               NULL,
                               NULL);
}

//Prototype... needed in put function
static void
update_zone_dht(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);

/**
 * Function used to put all records successively into the DHT.
 * FIXME also serializes records. maybe do this somewhere else...
 * FIXME don't store private records (maybe zone transfer does this)
 *
 * @param cls the closure (NULL)
 * @param zone our root zone hash
 * @param name the name of the record
 * @param record_type the type of the record
 * @param expiration lifetime of the record
 * @param flags flags of the record
 * @param sig_loc location of record in signature tree
 * @param size size of the record
 * @param record_data the record data
 */
void
put_gns_record(void *cls, const GNUNET_HashCode *zone, const char *name,
               uint32_t record_type, struct GNUNET_TIME_Absolute expiration,
               enum GNUNET_NAMESTORE_RecordFlags flags,
               const struct GNUNET_NAMESTORE_SignatureLocation *sig_loc,
               size_t size, const void *record_data)
{
  GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Putting a record into the DHT\n");
  struct GNUNET_TIME_Relative timeout;

  char* data;
  char* data_ptr;
  struct GNUNET_TIME_AbsoluteNBO exp_nbo;
  exp_nbo = GNUNET_TIME_absolute_hton (expiration);
  uint32_t namelen = htonl(strlen(name));
  uint16_t flags_nbo = htons(flags);
  uint64_t offset = GNUNET_htonll(sig_loc->offset);
  uint32_t depth = htonl(sig_loc->depth);
  uint32_t revision = htonl(sig_loc->revision);
  GNUNET_HashCode name_hash;
  GNUNET_HashCode xor_hash;

  /**
   * I guess this can be done prettier
   * FIXME extract into function, maybe even into different file
   */
  size_t record_len = sizeof(size_t) + sizeof(uint32_t) +
    sizeof(uint16_t) +
    sizeof(struct GNUNET_NAMESTORE_SignatureLocation) +
    sizeof(uint32_t) + strlen(name) + size;
  
  record_type = htonl(record_type);

  data = GNUNET_malloc(record_len);
  
  /* -_- */
  data_ptr = data;
  memcpy(data_ptr, &namelen, sizeof(size_t));
  data_ptr += sizeof(size_t);

  memcpy(data_ptr, name, namelen);
  data_ptr += namelen;
  
  memcpy(data_ptr, &record_type, sizeof(uint32_t));
  data_ptr += sizeof(uint32_t);

  memcpy(data_ptr, &exp_nbo, sizeof(struct GNUNET_TIME_AbsoluteNBO));
  data_ptr += sizeof(struct GNUNET_TIME_AbsoluteNBO);

  memcpy(data_ptr, &flags_nbo, sizeof(uint16_t));
  data_ptr += sizeof(uint16_t);

  memcpy(data_ptr, &offset, sizeof(uint64_t));
  data_ptr += sizeof(uint64_t);

  memcpy(data_ptr, &depth, sizeof(uint32_t));
  data_ptr += sizeof(uint32_t);
  
  memcpy(data_ptr, &revision, sizeof(uint32_t));
  data_ptr += sizeof(uint32_t);

  memcpy(data_ptr, &size, sizeof(uint32_t));
  data_ptr += sizeof(uint32_t);

  /**
   * FIXME note that this only works with raw data in nbo
   * write helper function that converts properly and returns buffer
   */
  memcpy(data_ptr, record_data, size);
  data_ptr += size;
  /*Doing this made me sad...*/

  /**
   * FIXME magic number 20 move to config file
   */
  timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20);

  GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
  GNUNET_CRYPTO_hash_xor(&zone_hash, &name_hash, &xor_hash);
  GNUNET_DHT_put (dht_handle, &xor_hash,
                  5, //replication level
                  GNUNET_DHT_RO_NONE,
                  GNUNET_BLOCK_TYPE_TEST, //FIXME todo block plugin
                  (data_ptr-data),
                  data,
                  expiration, //FIXME from record makes sense? is absolute?
                  timeout,
                  NULL, //FIXME continuation needed? success check? yes ofc
                  NULL); //cls for cont

  /**
   * Reschedule periodic put
   */
  GNUNET_SCHEDULER_add_delayed (dht_update_interval,
                                &update_zone_dht,
                                NULL);

}

/**
 * Periodically iterate over our zone and store everything in dht
 *
 * @param cls NULL
 * @param tc task context
 */
static void
update_zone_dht(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Update zone!\n");
  GNUNET_NAMESTORE_zone_transfer (namestore_handle, &zone_hash,
                                  &put_gns_record,
                                  NULL);
}

/**
 * Process GNS requests.
 *
 * @param cls closure
 * @param server the initialized server
 * @param c configuration to use
 */
static void
run (void *cls, struct GNUNET_SERVER_Handle *server,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  
  GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Init GNS\n");
  zone_key = GNUNET_CRYPTO_rsa_key_create ();

  GNUNET_CRYPTO_hash(zone_key, GNUNET_CRYPTO_RSA_KEY_LENGTH,//FIXME is this ok?
                     &zone_hash);
  nc = GNUNET_SERVER_notification_context_create (server, 1);

  /* FIXME - do some config parsing 
   *       - Maybe only hijack dns if option is set (HIJACK_DNS=1)
   */

  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
                                NULL);
  /**
   * Do gnunet dns init here
   */
  dns_handle = GNUNET_DNS_connect(c,
                                  GNUNET_DNS_FLAG_PRE_RESOLUTION,
                                  &handle_dns_request, /* rh */
                                  NULL); /* Closure */

  if (NULL == dns_handle)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
               "Failed to connect to the dnsservice!\n");
  }

  /**
   * handle to our local namestore
   */
  namestore_handle = GNUNET_NAMESTORE_connect(c);

  if (NULL == namestore_handle)
  {
    //FIXME do error handling;
    GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
               "Failed to connect to the namestore!\n");
  }

  /**
   * handle to the dht
   */
  dht_handle = GNUNET_DHT_connect(c, 1); //FIXME get ht_len from cfg

  if (NULL == dht_handle)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not connect to DHT!\n");
  }

  put_some_records(); //FIXME for testing
  
  /**
   * Schedule periodic put
   * for our records
   */
  dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
                                                      60); //FIXME from cfg
  GNUNET_SCHEDULER_add_delayed (dht_update_interval,
                                &update_zone_dht,
                                NULL);
  GNUNET_log(GNUNET_ERROR_TYPE_INFO, "GNS Init done!\n");

}


/**
 * The main function for the GNS service.
 *
 * @param argc number of arguments from the command line
 * @param argv command line arguments
 * @return 0 ok, 1 on error
 */
int
main (int argc, char *const *argv)
{
  int ret;

  ret =
      (GNUNET_OK ==
       GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
                           NULL)) ? 0 : 1;
  return ret;
}

/* end of gnunet-service-gns.c */