aboutsummaryrefslogtreecommitdiff
path: root/src/gns/gnunet-service-gns.c
blob: ec4c792a68350c9a4d234a43fd2fdd3f0b5f7c19 (plain) (blame)
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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
/*
     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
 *    - 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 "block_gns.h"
#include "gns.h"

#define DHT_OPERATION_TIMEOUT  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
#define DHT_LOOKUP_TIMEOUT DHT_OPERATION_TIMEOUT
#define DHT_GNS_REPLICATION_LEVEL 5
#define MAX_DNS_LABEL_LENGTH 63

/* Ignore for now not used anyway and probably never will */
#define GNUNET_MESSAGE_TYPE_GNS_LOOKUP 23
#define GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT 24
#define GNUNET_MESSAGE_TYPE_GNS_SHORTEN 25
#define GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT 26


struct AuthorityChain
{
  struct AuthorityChain *prev;

  struct AuthorityChain *next;

  GNUNET_HashCode zone;

  /* was the ns entry fresh */
  int fresh;
};

struct GNUNET_GNS_ResolverHandle;

typedef void (*ResolutionResultProcessor) (void *cls,
                                  struct GNUNET_GNS_ResolverHandle *rh,
                                  uint32_t rd_count,
                                  const struct GNUNET_NAMESTORE_RecordData *rd);

enum ResolutionStatus
{
  EXISTS = 1,
  EXPIRED = 2
};

/**
 * Handle to a currenty pending resolution
 */
struct GNUNET_GNS_ResolverHandle
{
  /* The name to resolve */
  char *name;

  /* the request handle to reply to */
  struct GNUNET_DNS_RequestHandle *request_handle;
  
  /* the dns parser packet received */
  struct GNUNET_DNSPARSER_Packet *packet;
  
  /* the query parsed from the packet */

  struct GNUNET_DNSPARSER_Query *query;
  
  /* has this query been answered? how many matches */
  int answered;

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

  /* the name of the authoritative zone to query */
  char *authority_name;

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

  /* a handle for dht lookups. should be NULL if no lookups are in progress */
  struct GNUNET_DHT_GetHandle *get_handle;

  /* timeout task for dht lookups */
  GNUNET_SCHEDULER_TaskIdentifier dht_timeout_task;

  ResolutionResultProcessor proc;

  void* proc_cls;

  struct AuthorityChain *authority_chain_head;
  struct AuthorityChain *authority_chain_tail;

  enum ResolutionStatus status;

};

struct ClientShortenHandle
{
  struct GNUNET_SERVER_Client *client;
  uint64_t unique_id;
  GNUNET_HashCode key;
  char* name;
  uint32_t offset;
};

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

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

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

/**
 * Our handle to the namestore service
 * FIXME maybe need a second handle for iteration
 */
struct GNUNET_NAMESTORE_Handle *namestore_handle;

/**
 * Handle to iterate over our authoritative zone in namestore
 */
struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;

/**
 * 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";

/**
 * Useful for zone update for DHT put
 */
static int num_public_records =  3600;
struct GNUNET_TIME_Relative dht_update_interval;
GNUNET_SCHEDULER_TaskIdentifier zone_update_taskid = GNUNET_SCHEDULER_NO_TASK;

//static void resolve_name(struct GNUNET_GNS_ResolverHandle *rh);

/**
 * Reply to client with the result from our lookup.
 *
 * @param rh the request handle of the lookup
 * @param rd_count the number of records to return
 * @param rd the record data
 */
static void
reply_to_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh, uint32_t rd_count,
             const struct GNUNET_NAMESTORE_RecordData *rd)
{
  int i;
  size_t len;
  int ret;
  char *buf;
  struct GNUNET_DNSPARSER_Packet *packet = rh->packet;
  struct GNUNET_DNSPARSER_Record answer_records[rh->answered];
  struct GNUNET_DNSPARSER_Record additional_records[rd_count-(rh->answered)];
  packet->answers = answer_records;
  packet->additional_records = additional_records;
  
  /**
   * Put records in the DNS packet and modify it
   * to a response
   */
  len = sizeof(struct GNUNET_DNSPARSER_Record*);
  for (i=0; i < rd_count; i++)
  {
    
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Adding type %d to DNS response\n", rd[i].record_type);
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Name: %s\n", rh->name);
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "QName: %s\n", rh->query->name);
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Record %d/%d\n", i+1, rd_count);
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Record len %d\n", rd[i].data_size);
    
    if (rd[i].record_type == rh->query->type)
    {
      answer_records[i].name = rh->query->name;
      answer_records[i].type = rd[i].record_type;
      answer_records[i].data.raw.data_len = rd[i].data_size;
      answer_records[i].data.raw.data = (char*)rd[i].data;
      answer_records[i].expiration_time = rd[i].expiration;
      answer_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
    }
    else
    {
      additional_records[i].name = rh->query->name;
      additional_records[i].type = rd[i].record_type;
      additional_records[i].data.raw.data_len = rd[i].data_size;
      additional_records[i].data.raw.data = (char*)rd[i].data;
      additional_records[i].expiration_time = rd[i].expiration;
      additional_records[i].class = GNUNET_DNSPARSER_CLASS_INTERNET;//hmmn
    }
  }
  
  packet->num_answers = rh->answered;
  packet->num_additional_records = rd_count-(rh->answered);
  
  if (0 == GNUNET_CRYPTO_hash_cmp(&rh->authority, &zone_hash))
    packet->flags.authoritative_answer = 1;
  else
    packet->flags.authoritative_answer = 0;

  if (rd == NULL)
    packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NAME_ERROR;
  else
    packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR;
  
  packet->flags.query_or_response = 1;

  
  /**
   * Reply to DNS
   */
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Building DNS response\n");
  ret = GNUNET_DNSPARSER_pack (packet,
                               1024, /* FIXME magic from dns redirector */
                               &buf,
                               &len);
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Built DNS response! (ret=%d,len=%d)\n", ret, len);
  if (ret == GNUNET_OK)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Answering DNS request\n");
    GNUNET_DNS_request_answer(rh->request_handle,
                              len,
                              buf);
    //GNUNET_free(answer);
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Answered DNS request\n");
  }
  else
  {
    GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
               "Error building DNS response! (ret=%d)", ret);
  }

  GNUNET_free(rh->name);
  GNUNET_free(rh);
}


/**
 * Task run during shutdown.
 *
 * @param cls unused
 * @param tc unused
 */
static void
shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  /* Kill zone task for it may make the scheduler hang */
  if (zone_update_taskid)
    GNUNET_SCHEDULER_cancel(zone_update_taskid);

  GNUNET_DNS_disconnect(dns_handle);
  GNUNET_NAMESTORE_disconnect(namestore_handle, 1);
  GNUNET_DHT_disconnect(dht_handle);
}

/**
 * Callback when record data is put into namestore
 *
 * @param cls the closure
 * @param success GNUNET_OK on success
 * @param emsg the error message. NULL if SUCCESS==GNUNET_OK
 */
void
on_namestore_record_put_result(void *cls,
                               int32_t success,
                               const char *emsg)
{
  if (GNUNET_NO == success)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "records already in namestore\n");
    return;
  }
  else if (GNUNET_YES == success)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "records successfully put in namestore\n");
    return;
  }

  GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
             "Error putting records into namestore: %s\n", emsg);
}

/**
 * Handle timeout for DHT requests
 *
 * @param cls the request handle as closure
 * @param tc the task context
 */
static void
dht_lookup_timeout(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_GNS_ResolverHandle *rh = cls;

  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "dht lookup for query %s (type=%d) timed out.\n",
             rh->name, rh->query->type);

  GNUNET_DHT_get_stop (rh->get_handle);
  rh->proc(rh->proc_cls, rh, 0, NULL);
}



/**
 * Function called when we get a result from the dht
 * for our query
 *
 * @param cls the request 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
 */
static void
process_record_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)
{
  struct GNUNET_GNS_ResolverHandle *rh;
  struct GNSNameRecordBlock *nrb;
  uint32_t num_records;
  char* name = NULL;
  char* rd_data = (char*)data;
  int i;
  int rd_size;
  
  GNUNET_HashCode zone, name_hash;
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "got dht result (size=%d)\n", size);
  
  if (data == NULL)
    return;

  //FIXME maybe check expiration here, check block type
  
  rh = (struct GNUNET_GNS_ResolverHandle *)cls;
  nrb = (struct GNSNameRecordBlock*)data;
  
  /* stop lookup and timeout task */
  GNUNET_DHT_get_stop (rh->get_handle);
  GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);
  
  rh->get_handle = NULL;
  name = (char*)&nrb[1];
  num_records = ntohl(nrb->rd_count);
  {
    struct GNUNET_NAMESTORE_RecordData rd[num_records];

    rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
    rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
  
    if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
                                                               rd_data,
                                                               num_records,
                                                               rd))
    {
      GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
      return;
    }

    for (i=0; i<num_records; i++)
    {
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Got name: %s (wanted %s)\n", name, rh->name);
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Got type: %d (wanted %d)\n",
               rd[i].record_type, rh->query->type);
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Got data length: %d\n", rd[i].data_size);
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Got flag %d\n", rd[i].flags);
    
     if ((strcmp(name, rh->name) == 0) &&
         (rd[i].record_type == rh->query->type))
      {
        rh->answered++;
      }

    }

    GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
    GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);
  
    /**
     * FIXME check pubkey against existing key in namestore?
     * https://gnunet.org/bugs/view.php?id=2179
     */

    /* Save to namestore */
    GNUNET_NAMESTORE_record_put (namestore_handle,
                                 &nrb->public_key,
                                 name,
                                 exp,
                                 num_records,
                                 rd,
                                 &nrb->signature,
                                 &on_namestore_record_put_result, //cont
                                 NULL); //cls
  
    if (rh->answered)
      rh->proc(rh->proc_cls, rh, num_records, rd);
    else
      rh->proc(rh->proc_cls, rh, 0, NULL);
  }

}


/**
 * Start DHT lookup for a (name -> query->record_type) record in
 * query->authority's zone
 *
 * @param rh the pending gns query context
 * @param name the name to query record
 */
static void
resolve_record_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
{
  uint32_t xquery;
  GNUNET_HashCode name_hash;
  GNUNET_HashCode lookup_key;
  struct GNUNET_CRYPTO_HashAsciiEncoded lookup_key_string;

  GNUNET_CRYPTO_hash(rh->name, strlen(rh->name), &name_hash);
  GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);
  GNUNET_CRYPTO_hash_to_enc (&lookup_key, &lookup_key_string);
  
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "starting dht lookup for %s with key: %s\n",
             rh->name, (char*)&lookup_key_string);

  rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed(DHT_LOOKUP_TIMEOUT,
                                                      &dht_lookup_timeout, rh);

  xquery = htonl(rh->query->type);
  rh->get_handle = GNUNET_DHT_get_start(dht_handle, 
                       DHT_OPERATION_TIMEOUT,
                       GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
                       &lookup_key,
                       DHT_GNS_REPLICATION_LEVEL,
                       GNUNET_DHT_RO_NONE,
                       &xquery, 
                       sizeof(xquery),
                       &process_record_dht_result,
                       rh);

}


/**
 * Namestore calls this function if we have record for this name.
 * (or with rd_count=0 to indicate no matches)
 *
 * @param cls the pending query
 * @param key the key of the zone we did the lookup
 * @param expiration expiration date of the namestore entry
 * @param name the name for which we need an authority
 * @param rd_count the number of records with 'name'
 * @param rd the record data
 * @param signature the signature of the authority for the record data
 */
static void
process_record_lookup_ns(void* cls,
                  const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
                  struct GNUNET_TIME_Absolute expiration,
                  const char *name, unsigned int rd_count,
                  const struct GNUNET_NAMESTORE_RecordData *rd,
                  const struct GNUNET_CRYPTO_RsaSignature *signature)
{
  struct GNUNET_GNS_ResolverHandle *rh;
  struct GNUNET_TIME_Relative remaining_time;
  GNUNET_HashCode zone;

  rh = (struct GNUNET_GNS_ResolverHandle *) cls;
  GNUNET_CRYPTO_hash(key,
                     sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
                     &zone);
  remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);

  rh->status = 0;
  
  if (name != NULL)
  {
    rh->status |= EXISTS;
  }
  
  if (remaining_time.rel_value == 0)
  {
    rh->status |= EXPIRED;
  }
  
  if (rd_count == 0)
  {
    /**
     * Lookup terminated and no results
     */
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Namestore lookup for %s terminated without results\n", name);
    
    

    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Record %s unknown in namestore\n",
               rh->name);
    /**
     * Our zone and no result? Cannot resolve TT
     */
    rh->proc(rh->proc_cls, rh, 0, NULL);
    return;

  }
  else
  {
    
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Processing additional result %s from namestore\n", name);
    int i;
    for (i=0; i<rd_count;i++)
    {
      
      if (rd[i].record_type != rh->query->type)
        continue;
      
      if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
          == 0)
      {
        GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This record is expired. Skipping\n");
        continue;
      }
      
      rh->answered++;
      
    }
    
    /**
     * no answers found
     */
    if (rh->answered == 0)
    {
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
                 "No answers found. This is odd!\n");
      rh->proc(rh->proc_cls, rh, 0, NULL);
      return;
    }
    
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found %d answer(s) to query!\n",
               rh->answered);

    rh->proc(rh->proc_cls, rh, rd_count, rd);
  }
}

/**
 * The final phase of resolution.
 * This is a name that is canonical and we do not have a delegation.
 *
 * @param rh the pending lookup
 */
static void
resolve_record_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
{
  
  /**
   * Try to resolve this record in our namestore.
   * The name to resolve is now in rh->authority_name
   * since we tried to resolve it to an authority
   * and failed.
   **/
  GNUNET_NAMESTORE_lookup_record(namestore_handle,
                                 &rh->authority,
                                 rh->name,
                                 rh->query->type,
                                 &process_record_lookup_ns,
                                 rh);

}


/**
 * Handle timeout for DHT requests
 *
 * @param cls the request handle as closure
 * @param tc the task context
 */
static void
dht_authority_lookup_timeout(void *cls,
                             const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_GNS_ResolverHandle *rh = cls;

  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "dht lookup for query %s (type=%d) timed out.\n",
             rh->name, rh->query->type);

  GNUNET_DHT_get_stop (rh->get_handle);
  if (strcmp(rh->name, "") == 0)
  {
    /*
     * promote authority back to name and try to resolve record
     */
    strcpy(rh->name, rh->authority_name);
  }
  rh->proc(rh->proc_cls, rh, 0, NULL);
}

// Prototype
static void resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh);

/**
 * Function called when we get a result from the dht
 * for our query
 *
 * @param cls the request 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
 */
static 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)
{
  struct GNUNET_GNS_ResolverHandle *rh;
  struct GNSNameRecordBlock *nrb;
  uint32_t num_records;
  char* name = NULL;
  char* rd_data = (char*) data;
  int i;
  int rd_size;
  GNUNET_HashCode zone, name_hash;
  
  if (data == NULL)
    return;
  
  //FIXME check expiration?
  
  rh = (struct GNUNET_GNS_ResolverHandle *)cls;
  nrb = (struct GNSNameRecordBlock*)data;
  
  /* stop dht lookup and timeout task */
  GNUNET_DHT_get_stop (rh->get_handle);
  GNUNET_SCHEDULER_cancel(rh->dht_timeout_task);

  rh->get_handle = NULL;
  num_records = ntohl(nrb->rd_count);
  name = (char*)&nrb[1];
  {
    struct GNUNET_NAMESTORE_RecordData rd[num_records];
    
    rd_data += strlen(name) + 1 + sizeof(struct GNSNameRecordBlock);
    rd_size = size - strlen(name) - 1 - sizeof(struct GNSNameRecordBlock);
  
    if (GNUNET_SYSERR == GNUNET_NAMESTORE_records_deserialize (rd_size,
                                                               rd_data,
                                                               num_records,
                                                               rd))
    {
      GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error deserializing data!\n");
      return;
    }

    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Got name: %s (wanted %s)\n", name, rh->authority_name);
    for (i=0; i<num_records; i++)
    {
    
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                "Got name: %s (wanted %s)\n", name, rh->authority_name);
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                 "Got type: %d (wanted %d)\n",
                 rd[i].record_type, GNUNET_GNS_RECORD_PKEY);
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                 "Got data length: %d\n", rd[i].data_size);
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                 "Got flag %d\n", rd[i].flags);

      if ((strcmp(name, rh->authority_name) == 0) &&
          (rd[i].record_type == GNUNET_GNS_RECORD_PKEY))
      {
        GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Authority found in DHT\n");
        rh->answered = 1;
        memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
        struct AuthorityChain *auth =
          GNUNET_malloc(sizeof(struct AuthorityChain));
        auth->zone = rh->authority;
        GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
                                     rh->authority_chain_tail,
                                     auth);
      }

    }


    GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
    GNUNET_CRYPTO_hash_xor(key, &name_hash, &zone);

    /* Save to namestore */
    if (0 != GNUNET_CRYPTO_hash_cmp(&zone_hash, &zone))
    {
      GNUNET_NAMESTORE_record_put (namestore_handle,
                                 &nrb->public_key,
                                 name,
                                 exp,
                                 num_records,
                                 rd,
                                 &nrb->signature,
                                 &on_namestore_record_put_result, //cont
                                 NULL); //cls
    }
  }
  
  if (rh->answered)
  {
    rh->answered = 0;
    /* delegate */
    if (strcmp(rh->name, "") == 0)
      rh->proc(rh->proc_cls, rh, 0, NULL);
    else
      resolve_delegation_from_dht(rh);
    return;
  }

  /* resolve never get here, should timeout??*/
  
  
  if (strcmp(rh->name, "") == 0)
  {
    /* promote authority back to name */
    strcpy(rh->name, rh->authority_name);
  }
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No authority in records\n");
  rh->proc(rh->proc_cls, rh, 0, NULL);
}


/**
 * DHT lookup result for record.
 *
 * @param cls the closure
 * @param rh resolver handle
 * @param rd_count number of results (always 0)
 * @param rd record data (always NULL)
 */
static void
process_record_result_dht(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
                       unsigned int rd_count,
                       const struct GNUNET_NAMESTORE_RecordData *rd)
{
  if (rd_count == 0)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "No records for %s found in DHT. Aborting\n",
               rh->name);
    /* give up, cannot resolve */
    reply_to_dns(NULL, rh, 0, NULL);
    return;
  }

  /* results found yay */
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Record resolved from namestore!");
  reply_to_dns(NULL, rh, rd_count, rd);

}


/**
 * Namestore lookup result for record.
 *
 * @param cls the closure
 * @param rh resolver handle
 * @param rd_count number of results (always 0)
 * @param rd record data (always NULL)
 */
static void
process_record_result_ns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
                       unsigned int rd_count,
                       const struct GNUNET_NAMESTORE_RecordData *rd)
{
  if (rd_count == 0)
  {
    /* ns entry expired. try dht */
    if (rh->status & (EXPIRED | !EXISTS))
    {
      rh->proc = &process_record_result_dht;
      resolve_record_from_dht(rh);
      return;
    }
    /* give up, cannot resolve */
    reply_to_dns(NULL, rh, 0, NULL);
    return;
  }

  /* results found yay */
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Record resolved from namestore!");
  reply_to_dns(NULL, rh, rd_count, rd);

}


/**
 * 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
 */
static 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.
 *
 * @param name the domain
 * @param dest the destination where the tld will be put
 */
void
pop_tld(char* name, char* dest)
{
  uint32_t len;

  if (is_canonical(name))
  {
    strcpy(dest, name);
    strcpy(name, "");
    return;
  }

  for (len = strlen(name); len > 0; len--)
  {
    if (*(name+len) == '.')
      break;
  }
  
  //Was canonical?
  if (len == 0)
    return;

  name[len] = '\0';

  strcpy(dest, (name+len+1));
}

/**
 * Namestore resolution for delegation finished. Processing result.
 *
 * @param cls the closure
 * @param rh resolver handle
 * @param rd_count number of results (always 0)
 * @param rd record data (always NULL)
 */
static void
process_dht_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
                          unsigned int rd_count,
                          const struct GNUNET_NAMESTORE_RecordData *rd)
{
  if (strcmp(rh->name, "") == 0)
  {
    /* We resolved full name for delegation. resolving record */
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
      "Resolved full name for delegation via DHT. resolving record '' in ns\n");
    rh->proc = &process_record_result_ns;
    resolve_record_from_ns(rh);
    return;
  }

  /**
   * we still have some left
   **/
  if (is_canonical(rh->name))
  {
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Resolving canonical record %s in ns\n", rh->name);
    rh->proc = &process_record_result_ns;
    resolve_record_from_ns(rh);
    return;
  }
  /* give up, cannot resolve */
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Cannot fully resolve delegation for %s via DHT!\n",
             rh->name);
  reply_to_dns(NULL, rh, 0, NULL);
}


/**
 * Start DHT lookup for a name -> PKEY (compare NS) record in
 * rh->authority's zone
 *
 * @param rh the pending gns query
 * @param name the name of the PKEY record
 */
static void
resolve_delegation_from_dht(struct GNUNET_GNS_ResolverHandle *rh)
{
  uint32_t xquery;
  GNUNET_HashCode name_hash;
  GNUNET_HashCode lookup_key;

  GNUNET_CRYPTO_hash(rh->authority_name,
                     strlen(rh->authority_name),
                     &name_hash);
  GNUNET_CRYPTO_hash_xor(&name_hash, &rh->authority, &lookup_key);

  rh->dht_timeout_task = GNUNET_SCHEDULER_add_delayed (DHT_LOOKUP_TIMEOUT,
                                                  &dht_authority_lookup_timeout,
                                                       rh);

  xquery = htonl(GNUNET_GNS_RECORD_PKEY);
  //FIXME how long to wait for results?
  rh->get_handle = GNUNET_DHT_get_start(dht_handle,
                       DHT_OPERATION_TIMEOUT,
                       GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
                       &lookup_key,
                       DHT_GNS_REPLICATION_LEVEL,
                       GNUNET_DHT_RO_NONE,
                       NULL,
                       sizeof(xquery),
                       &process_authority_dht_result,
                       rh);

}


/**
 * Namestore resolution for delegation finished. Processing result.
 *
 * @param cls the closure
 * @param rh resolver handle
 * @param rd_count number of results (always 0)
 * @param rd record data (always NULL)
 */
static void
process_ns_delegation_dns(void* cls, struct GNUNET_GNS_ResolverHandle *rh,
                          unsigned int rd_count,
                          const struct GNUNET_NAMESTORE_RecordData *rd)
{
  if (strcmp(rh->name, "") == 0)
  {
    /* We resolved full name for delegation. resolving record */
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Resolved full name for delegation. resolving record ''\n");
    rh->proc = &process_record_result_ns;
    resolve_record_from_ns(rh);
    return;
  }

  /**
   * we still have some left
   * check if ns entry is fresh
   **/
  if (rh->status & (EXISTS | !EXPIRED))
  {
    if (is_canonical(rh->name))
    {
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                 "Resolving canonical record %s\n", rh->name);
      rh->proc = &process_record_result_ns;
      resolve_record_from_ns(rh);
    }
    else
    {
      /* give up, cannot resolve */
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                 "Cannot fully resolve delegation for %s!\n",
                 rh->name);
      reply_to_dns(NULL, rh, 0, NULL);
    }
    return;
  }
  
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Trying to resolve delegation for %s via DHT\n",
             rh->name);
  rh->proc = &process_dht_delegation_dns;
  resolve_delegation_from_dht(rh);
}

//Prototype
static void resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh);

/**
 * 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 key the key of the zone we did the lookup
 * @param expiration expiration date of the record data set in the namestore
 * @param name the name for which we need an authority
 * @param rd_count the number of records with 'name'
 * @param rd the record data
 * @param signature the signature of the authority for the record data
 */
static void
process_authority_lookup_ns(void* cls,
                   const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
                   struct GNUNET_TIME_Absolute expiration,
                   const char *name,
                   unsigned int rd_count,
                   const struct GNUNET_NAMESTORE_RecordData *rd,
                   const struct GNUNET_CRYPTO_RsaSignature *signature)
{
  struct GNUNET_GNS_ResolverHandle *rh;
  struct GNUNET_TIME_Relative remaining_time;
  GNUNET_HashCode zone;
  char* new_name;
  
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got %d records from authority lookup\n",
             rd_count);

  rh = (struct GNUNET_GNS_ResolverHandle *)cls;
  GNUNET_CRYPTO_hash(key,
                     sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
                     &zone);
  remaining_time = GNUNET_TIME_absolute_get_remaining (expiration);
  
  rh->status = 0;
  
  if (name != NULL)
  {
    rh->status |= EXISTS;
  }
  
  if (remaining_time.rel_value == 0)
  {
    rh->status |= EXPIRED;
  }
  
  /**
   * No authority found in namestore.
   */
  if (rd_count == 0)
  {
    /**
     * We did not find an authority in the namestore
     */
    
    /**
     * No PKEY in zone.
     * Promote this authority back to a name maybe it is
     * our record.
     */
    if (strcmp(rh->name, "") == 0)
    {
      /* simply promote back */
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                 "Promoting %s back to name\n", rh->authority_name);
      strcpy(rh->name, rh->authority_name);
    }
    else
    {
      /* add back to existing name */
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                 "Adding %s back to %s\n",
                 rh->authority_name, rh->name);
      new_name = GNUNET_malloc(strlen(rh->name)
                               + strlen(rh->authority_name) + 2);
      memset(new_name, 0, strlen(rh->name) + strlen(rh->authority_name) + 2);
      strcpy(new_name, rh->name);
      strcpy(new_name+strlen(new_name)+1, ".");
      strcpy(new_name+strlen(new_name)+2, rh->authority_name);
      GNUNET_free(rh->name);
      rh->name = new_name;
    }
    rh->proc(rh->proc_cls, rh, 0, NULL);
    return;
  }

  //Note only 1 pkey should have been returned.. anything else would be strange
  /**
   * We found an authority that may be able to help us
   * move on with query
   */
  int i;
  for (i=0; i<rd_count;i++)
  {
  
    if (rd[i].record_type != GNUNET_GNS_RECORD_PKEY)
      continue;
    
    if ((GNUNET_TIME_absolute_get_remaining (rd[i].expiration)).rel_value
         == 0)
    {
      GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "This pkey is expired.\n");
      if (remaining_time.rel_value == 0)
      {
        GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
                   "This dht entry is expired.\n");
        rh->authority_chain_head->fresh = 0;
        rh->proc(rh->proc_cls, rh, 0, NULL);
        return;
      }

      continue;
    }

    /**
     * Resolve rest of query with new authority
     */
    GNUNET_assert(rd[i].record_type == GNUNET_GNS_RECORD_PKEY);
    memcpy(&rh->authority, rd[i].data, sizeof(GNUNET_HashCode));
    struct AuthorityChain *auth = GNUNET_malloc(sizeof(struct AuthorityChain));
    auth->zone = rh->authority;
    GNUNET_CONTAINER_DLL_insert (rh->authority_chain_head,
                                 rh->authority_chain_tail,
                                 auth);

    if (strcmp(rh->name, "") == 0)
      rh->proc(rh->proc_cls, rh, 0, NULL);
    else
      resolve_delegation_from_ns(rh);
    return;
  }
    
  /**
   * no answers found
   */
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Authority lookup successful but no PKEY... never get here\n");
  rh->proc(rh->proc_cls, rh, 0, NULL);
}



/**
 * The first phase of resolution.
 * First check if the name is canonical.
 * If it is then try to resolve directly.
 * If not then we first have to resolve the authoritative entities.
 *
 * @param rh the pending lookup
 */
/*static void
resolve_name(struct GNUNET_GNS_ResolverHandle *rh)
{
  
  pop_tld(rh->name, rh->authority_name);
  GNUNET_NAMESTORE_lookup_record(namestore_handle,
                                 &rh->authority,
                                 rh->authority_name,
                                 GNUNET_GNS_RECORD_PKEY,
                                 &process_authority_lookup,
                                 rh);

}*/



static void
resolve_delegation_from_ns(struct GNUNET_GNS_ResolverHandle *rh)
{
  
  /**
   * Try to resolve this name to a delegation.
   **/
  pop_tld(rh->name, rh->authority_name);
  GNUNET_NAMESTORE_lookup_record(namestore_handle,
                                 &rh->authority,
                                 rh->authority_name,
                                 GNUNET_GNS_RECORD_PKEY,
                                 &process_authority_lookup_ns,
                                 rh);

}

/**
 * Entry point for name resolution
 * Setup a new query and try to resolve
 *
 * @param request the request handle of the DNS request from a client
 * @param p the DNS query packet we received
 * @param q the DNS query we received parsed from p
 */
static void
start_resolution_from_dns(struct GNUNET_DNS_RequestHandle *request,
                          struct GNUNET_DNSPARSER_Packet *p,
                          struct GNUNET_DNSPARSER_Query *q)
{
  struct GNUNET_GNS_ResolverHandle *rh;
  
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Starting resolution for %s (type=%d)!\n",
              q->name, q->type);
  
  rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
  rh->packet = p;
  rh->query = q;
  rh->authority = zone_hash;
  
  
  rh->name = GNUNET_malloc(strlen(q->name)
                              - strlen(gnunet_tld) + 1);
  memset(rh->name, 0,
         strlen(q->name)-strlen(gnunet_tld) + 1);
  memcpy(rh->name, q->name,
         strlen(q->name)-strlen(gnunet_tld));

  rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);

  rh->request_handle = request;

  rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
  rh->authority_chain_tail = rh->authority_chain_head;
  rh->authority_chain_head->zone = zone_hash;

  /* Start resolution in our zone */
  rh->proc = &process_ns_delegation_dns;
  resolve_delegation_from_ns(rh);
  //resolve_name(rh);
}

/**
 * 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
 */
static void
handle_dns_request(void *cls,
                   struct GNUNET_DNS_RequestHandle *rh,
                   size_t request_length,
                   const char *request)
{
  struct GNUNET_DNSPARSER_Packet *p;
  char *tldoffset;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hijacked a DNS request...processing\n");
  p = GNUNET_DNSPARSER_parse (request, request_length);
  
  if (NULL == p)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "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).
   */
  if (p->num_queries == 0)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "No Queries in DNS packet... forwarding\n");
    GNUNET_DNS_request_forward (rh);
  }

  if (p->num_queries > 1)
  {
    /* Note: We could also look for .gnunet */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                ">1 queriy in DNS packet... odd. We only process #1\n");
  }

  
  /**
   * Check for .gnunet
   */
  tldoffset = p->queries[0].name + strlen(p->queries[0].name);

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

}

/**
 * Method called periodicattluy that triggers
 * iteration over root zone
 *
 * @param cls closure
 * @param tc task context
 */
static void
update_zone_dht_next(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GNUNET_NAMESTORE_zone_iterator_next(namestore_iter);
}

/**
 * Continuation for DHT put
 *
 * @param cls closure
 * @param tc task context
 */
static void
record_dht_put(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "put request transmitted\n");
}

/* prototype */
static void
update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);

/**
 * Function used to put all records successively into the DHT.
 *
 * @param cls the closure (NULL)
 * @param key the public key of the authority (ours)
 * @param expiration lifetime of the namestore entry
 * @param name the name of the records
 * @param rd_count the number of records in data
 * @param rd the record data
 * @param signature the signature for the record data
 */
static void
put_gns_record(void *cls,
                const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *key,
                struct GNUNET_TIME_Absolute expiration,
                const char *name,
                unsigned int rd_count,
                const struct GNUNET_NAMESTORE_RecordData *rd,
                const struct GNUNET_CRYPTO_RsaSignature *signature)
{
  
  struct GNSNameRecordBlock *nrb;
  GNUNET_HashCode name_hash;
  GNUNET_HashCode xor_hash;
  struct GNUNET_CRYPTO_HashAsciiEncoded xor_hash_string;
  uint32_t rd_payload_length;
  char* nrb_data = NULL;

  /* we're done */
  if (NULL == name)
  {
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Zone iteration finished\n");
    GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
    zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start,
                                                   NULL);
    return;
  }
  
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Putting records for %s into the DHT\n", name);
  
  rd_payload_length = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
  
  nrb = GNUNET_malloc(rd_payload_length + strlen(name) + 1 
                      + sizeof(struct GNSNameRecordBlock));
  
  if (signature != NULL)
    nrb->signature = *signature;
  
  nrb->public_key = *key;

  nrb->rd_count = htonl(rd_count);
  
  memset(&nrb[1], 0, strlen(name) + 1);
  memcpy(&nrb[1], name, strlen(name));

  nrb_data = (char*)&nrb[1];
  nrb_data += strlen(name) + 1;

  rd_payload_length += sizeof(struct GNSNameRecordBlock) +
    strlen(name) + 1;

  if (-1 == GNUNET_NAMESTORE_records_serialize (rd_count,
                                                rd,
                                                rd_payload_length,
                                                nrb_data))
  {
    GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Record serialization failed!\n");
    return;
    //FIXME what to do
  }


  /*
   * calculate DHT key: H(name) xor H(pubkey)
   */
  GNUNET_CRYPTO_hash(name, strlen(name), &name_hash);
  GNUNET_CRYPTO_hash_xor(&zone_hash, &name_hash, &xor_hash);
  GNUNET_CRYPTO_hash_to_enc (&xor_hash, &xor_hash_string);
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "putting records for %s under key: %s with size %d\n",
             name, (char*)&xor_hash_string, rd_payload_length);

  GNUNET_DHT_put (dht_handle, &xor_hash,
                  DHT_GNS_REPLICATION_LEVEL,
                  GNUNET_DHT_RO_NONE,
                  GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
                  rd_payload_length,
                  (char*)nrb,
                  expiration,
                  DHT_OPERATION_TIMEOUT,
                  &record_dht_put,
                  NULL); //cls for cont
  
  num_public_records++;

  /**
   * Reschedule periodic put
   */
  zone_update_taskid = GNUNET_SCHEDULER_add_delayed (dht_update_interval,
                                &update_zone_dht_next,
                                NULL);

}

/**
 * Periodically iterate over our zone and store everything in dht
 *
 * @param cls NULL
 * @param tc task context
 */
static void
update_zone_dht_start(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting DHT zone update!\n");
  if (0 == num_public_records)
  {
    dht_update_interval = GNUNET_TIME_relative_multiply(
                                                      GNUNET_TIME_UNIT_SECONDS,
                                                      1);
  }
  else
  {
    dht_update_interval = GNUNET_TIME_relative_multiply(
                                                      GNUNET_TIME_UNIT_SECONDS,
                                                     (3600/num_public_records));
  }
  num_public_records = 0; //start counting again
  namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
                                                          &zone_hash,
                                                          GNUNET_NAMESTORE_RF_AUTHORITY,
                                                          GNUNET_NAMESTORE_RF_PRIVATE,
                                                          &put_gns_record,
                                                          NULL);
}

//Prototype
static void send_shorten_response(const char* name,
                                  struct ClientShortenHandle *csh);

void
handle_local_zone_to_name(void *cls,
                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
                 struct GNUNET_TIME_Absolute expire,
                 const char *name,
                 unsigned int rd_len,
                 const struct GNUNET_NAMESTORE_RecordData *rd,
                 const struct GNUNET_CRYPTO_RsaSignature *signature)
{
  struct GNUNET_GNS_ResolverHandle *rh = 
    (struct GNUNET_GNS_ResolverHandle *)cls;
  struct ClientShortenHandle* csh = (struct ClientShortenHandle*) rh->proc_cls;
  /* we found a match in our own zone */
  if (rd_len != 0)
  {
    send_shorten_response(name, csh);
    //FIXME free, add .gnunet
  }
  else
  {
    
  }
}

void
handle_shorten_result(void* cls,
                      struct GNUNET_GNS_ResolverHandle *rh,
                      uint32_t rd_count,
                      const struct GNUNET_NAMESTORE_RecordData *rd)
{
  struct ClientShortenHandle* csh = (struct ClientShortenHandle*) cls;
  struct AuthorityChain *auth_chain;
  
  /**
   * Couldn't completely resolve
   * Search authority chain
   */
  
  if (rd_count == 0)
  {
    /* Nothing we can do. That name is unknown */
    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "PKEY for %s unknown!\n", csh->name);
    if (GNUNET_CRYPTO_hash_cmp(&rh->authority_chain_head->zone,
                               &zone_hash) == 0)
    {
      /* either we can shorten completely or we don't know this name */
      if (rh->authority_chain_head->next == NULL)
        send_shorten_response('\0', csh);
      else
        send_shorten_response(rh->name, csh); //FIXME +.gnunet!
      //FIXME free
      return;
    }
    csh->offset++;
    auth_chain = rh->authority_chain_head;
    /* backtrack authorities for pseu */
    GNUNET_NAMESTORE_zone_to_name (namestore_handle,
                                   &zone_hash, //ours
                                   &auth_chain->zone,
                                   &handle_local_zone_to_name,
                                   rh);
  }
  else /* we can use the result directly */
  {
    /* First check local namestore for name */
    /* Then try dht/namestore for PSEU */
  }


}

typedef void (*ShortenResponseProc) (void* cls, const char* name);

/**
 * Shorten a given name
 *
 * @param name the name to shorten
 * @param proc the processor to call when finished
 * @praram cls the closure to the processor
 */
static void
shorten_name(char* name, struct ClientShortenHandle* csh)
{

  struct GNUNET_GNS_ResolverHandle *rh;
  
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Starting resolution for %s (type=%d)!\n",
              name, GNUNET_GNS_RECORD_PKEY);
  
  rh = GNUNET_malloc(sizeof (struct GNUNET_GNS_ResolverHandle));
  rh->authority = zone_hash;
  
  rh->name = GNUNET_malloc(strlen(name)
                              - strlen(gnunet_tld) + 1);
  memset(rh->name, 0,
         strlen(name)-strlen(gnunet_tld) + 1);
  memcpy(rh->name, name,
         strlen(name)-strlen(gnunet_tld));

  csh->name = GNUNET_malloc(strlen(name)
                            - strlen(gnunet_tld) + 1);
  memset(rh->name, 0,
         strlen(name)-strlen(gnunet_tld) + 1);
  memcpy(rh->name, name,
         strlen(name)-strlen(gnunet_tld));

  rh->authority_name = GNUNET_malloc(sizeof(char)*MAX_DNS_LABEL_LENGTH);

  rh->authority_chain_head = GNUNET_malloc(sizeof(struct AuthorityChain));
  rh->authority_chain_tail = rh->authority_chain_head;
  rh->authority_chain_head->zone = zone_hash;
  rh->proc = handle_shorten_result;
  rh->proc_cls = (void*)csh;

  /* Start resolution in our zone */
  //resolve_name(rh);

}

/**
 * Send shorten response back to client
 * FIXME this is without .gnunet!
 * 
 * @param cls the client handle in closure
 * @param name the shortened name result or NULL if cannot be shortened
 */
static void
send_shorten_response(const char* name, struct ClientShortenHandle *csh)
{
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n",
              "SHORTEN_RESULT");
  struct GNUNET_GNS_ClientShortenResultMessage *rmsg;
  
  if (name == NULL)
  {
    name = '\0';
  }

  rmsg = GNUNET_malloc(sizeof(struct GNUNET_GNS_ClientShortenResultMessage *)
                       + strlen(name));
  
  rmsg->unique_id = csh->unique_id;
  rmsg->key = csh->key;
  rmsg->header.type = htons(GNUNET_MESSAGE_TYPE_GNS_SHORTEN_RESULT);
  rmsg->header.size = 
    htons(sizeof(struct GNUNET_GNS_ClientShortenResultMessage *) +
          strlen(name));

  strcpy((char*)&rmsg[1], name);

  GNUNET_SERVER_notification_context_unicast (nc, csh->client,
                              (const struct GNUNET_MessageHeader *) &rmsg,
                              GNUNET_NO);

  GNUNET_SERVER_receive_done (csh->client, GNUNET_OK);
  
  GNUNET_free(csh);
  GNUNET_free(rmsg);

}

/**
 * Handle a shorten message from the api
 *
 * @param cls the closure
 * @param client the client
 * @param message the message
 */
static void handle_shorten(void *cls,
                           struct GNUNET_SERVER_Client * client,
                           const struct GNUNET_MessageHeader * message)
{
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "SHORTEN");

  size_t msg_size = 0;
  struct ClientShortenHandle *csh;

  if (ntohs (message->size) != sizeof (struct GNUNET_GNS_ClientShortenMessage))
  {
    GNUNET_break_op (0);
    GNUNET_SERVER_receive_done (client, GNUNET_OK);
    return;
  }

  struct GNUNET_GNS_ClientShortenMessage *sh_msg =
    (struct GNUNET_GNS_ClientShortenMessage *) message;
  
  msg_size = ntohs(message->size);

  if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
  {
    GNUNET_break_op (0);
    GNUNET_SERVER_receive_done (client, GNUNET_OK);
    return;
  }

  csh = GNUNET_malloc(sizeof(struct ClientShortenHandle));
  csh->client = client;
  csh->unique_id = sh_msg->unique_id;
  csh->key = sh_msg->key;
  
  //Offset in original name
  csh->offset = 0;
  

  shorten_name((char*)&sh_msg[1], csh);

}

/**
 * TODO
 */
static void
handle_lookup(void *cls,
              struct GNUNET_SERVER_Client * client,
              const struct GNUNET_MessageHeader * message)
{
}

/**
 * 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_DEBUG, "Initializing GNS\n");

  char* keyfile;
  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;

  static const struct GNUNET_SERVER_MessageHandler handlers[] = {
    {&handle_shorten, NULL, GNUNET_MESSAGE_TYPE_GNS_SHORTEN, 0},
    {&handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0}
  };

  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (c, "gns",
                                             "ZONEKEY", &keyfile))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "No private key for root zone specified%s!\n", keyfile);
    GNUNET_SCHEDULER_shutdown(0);
    return;
  }

  zone_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
  GNUNET_CRYPTO_rsa_key_get_public (zone_key, &pkey);

  GNUNET_CRYPTO_hash(&pkey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
                     &zone_hash);
  

  if (GNUNET_YES ==
      GNUNET_CONFIGURATION_get_value_yesno (c, "gns",
                                            "HIJACK_DNS"))
  {
    GNUNET_log(GNUNET_ERROR_TYPE_INFO,
               "DNS hijacking enabled... connecting to service.\n");
    /**
     * 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");
    GNUNET_SCHEDULER_shutdown(0);
    return;
  }
  
  /**
   * 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
   * We have roughly an hour for all records;
   */
  dht_update_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
                                                      1);
  //zone_update_taskid = GNUNET_SCHEDULER_add_now (&update_zone_dht_start, NULL);

  GNUNET_SERVER_add_handlers (server, handlers);
  
  //FIXME
  //GNUNET_SERVER_disconnect_notify (server,
  //                                 &client_disconnect_notification,
  //                                 NULL);

  nc = GNUNET_SERVER_notification_context_create (server, 1);

  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
                                NULL);
}


/**
 * 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 */